45189272feb0be1a231e302e641719ffd59607fa
[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  *
36  * \ingroup channel_drivers
37  *
38  */
39
40
41 #include <stdio.h>
42 #include <ctype.h>
43 #include <string.h>
44 #include <unistd.h>
45 #include <sys/socket.h>
46 #include <sys/ioctl.h>
47 #include <net/if.h>
48 #include <errno.h>
49 #include <stdlib.h>
50 #include <fcntl.h>
51 #include <netdb.h>
52 #include <signal.h>
53 #include <sys/signal.h>
54 #include <netinet/in.h>
55 #include <netinet/in_systm.h>
56 #include <arpa/inet.h>
57 #include <netinet/ip.h>
58 #include <regex.h>
59
60 #include "asterisk.h"
61
62 ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
63
64 #include "asterisk/lock.h"
65 #include "asterisk/channel.h"
66 #include "asterisk/config.h"
67 #include "asterisk/logger.h"
68 #include "asterisk/module.h"
69 #include "asterisk/pbx.h"
70 #include "asterisk/options.h"
71 #include "asterisk/lock.h"
72 #include "asterisk/sched.h"
73 #include "asterisk/io.h"
74 #include "asterisk/rtp.h"
75 #include "asterisk/acl.h"
76 #include "asterisk/manager.h"
77 #include "asterisk/callerid.h"
78 #include "asterisk/cli.h"
79 #include "asterisk/app.h"
80 #include "asterisk/musiconhold.h"
81 #include "asterisk/dsp.h"
82 #include "asterisk/features.h"
83 #include "asterisk/acl.h"
84 #include "asterisk/srv.h"
85 #include "asterisk/astdb.h"
86 #include "asterisk/causes.h"
87 #include "asterisk/utils.h"
88 #include "asterisk/file.h"
89 #include "asterisk/astobj.h"
90 #include "asterisk/dnsmgr.h"
91 #include "asterisk/devicestate.h"
92 #include "asterisk/linkedlists.h"
93 #include "asterisk/stringfields.h"
94 #include "asterisk/monitor.h"
95
96 #ifdef OSP_SUPPORT
97 #include "asterisk/astosp.h"
98 #endif
99
100 #ifndef FALSE
101 #define FALSE   0
102 #endif
103
104 #ifndef TRUE
105 #define TRUE 1
106 #endif
107
108  
109 #define VIDEO_CODEC_MASK        0x1fc0000 /*!< Video codecs from H.261 thru AST_FORMAT_MAX_VIDEO */
110 #ifndef IPTOS_MINCOST
111 #define IPTOS_MINCOST           0x02
112 #endif
113
114 /* #define VOCAL_DATA_HACK */
115
116 #define DEFAULT_DEFAULT_EXPIRY  120
117 #define DEFAULT_MIN_EXPIRY      60
118 #define DEFAULT_MAX_EXPIRY      3600
119 #define DEFAULT_REGISTRATION_TIMEOUT    20
120 #define DEFAULT_MAX_FORWARDS    "70"
121
122 /* guard limit must be larger than guard secs */
123 /* guard min must be < 1000, and should be >= 250 */
124 #define EXPIRY_GUARD_SECS       15              /*!< How long before expiry do we reregister */
125 #define EXPIRY_GUARD_LIMIT      30              /*!< Below here, we use EXPIRY_GUARD_PCT instead of 
126                                                   EXPIRY_GUARD_SECS */
127 #define EXPIRY_GUARD_MIN        500             /*!< This is the minimum guard time applied. If 
128                                                   GUARD_PCT turns out to be lower than this, it 
129                                                    will use this time instead.
130                                                    This is in milliseconds. */
131 #define EXPIRY_GUARD_PCT        0.20            /*!< Percentage of expires timeout to use when 
132                                                    below EXPIRY_GUARD_LIMIT */
133 #define DEFAULT_EXPIRY 900                      /*!< Expire slowly */
134
135 static int min_expiry = DEFAULT_MIN_EXPIRY;     /*!< Minimum accepted registration time */
136 static int max_expiry = DEFAULT_MAX_EXPIRY;     /*!< Maximum accepted registration time */
137 static int default_expiry = DEFAULT_DEFAULT_EXPIRY;
138 static int expiry = DEFAULT_EXPIRY;
139
140 #ifndef MAX
141 #define MAX(a,b) ((a) > (b) ? (a) : (b))
142 #endif
143
144 #define CALLERID_UNKNOWN        "Unknown"
145
146 #define DEFAULT_MAXMS           2000            /*!< Qualification: Must be faster than 2 seconds by default */
147 #define DEFAULT_FREQ_OK         60 * 1000       /*!< Qualification: How often to check for the host to be up */
148 #define DEFAULT_FREQ_NOTOK      10 * 1000       /*!< Qualification: How often to check, if the host is down... */
149
150 #define DEFAULT_RETRANS         1000            /*!< How frequently to retransmit Default: 2 * 500 ms in RFC 3261 */
151 #define MAX_RETRANS             6               /*!< Try only 6 times for retransmissions, a total of 7 transmissions */
152 #define MAX_AUTHTRIES           3               /*!< Try authentication three times, then fail */
153
154 #define SIP_MAX_HEADERS         64                      /*!< Max amount of SIP headers to read */
155 #define SIP_MAX_LINES           64                      /*!< Max amount of lines in SIP attachment (like SDP) */
156 #define SIP_MAX_PACKET          4096    /*!< Also from RFC 3261 (2543), should sub headers tho */
157
158
159 static const char desc[] = "Session Initiation Protocol (SIP)";
160 static const char config[] = "sip.conf";
161 static const char notify_config[] = "sip_notify.conf";
162 static int usecnt = 0;
163
164
165 #define RTP     1
166 #define NO_RTP  0
167
168 /* Do _NOT_ make any changes to this enum, or the array following it;
169    if you think you are doing the right thing, you are probably
170    not doing the right thing. If you think there are changes
171    needed, get someone else to review them first _before_
172    submitting a patch. If these two lists do not match properly
173    bad things will happen.
174 */
175
176 enum xmittype {
177         XMIT_CRITICAL = 2,              /*!< Transmit critical SIP message reliably, with re-transmits.
178                                                         If it fails, it's critical and will cause a teardown of the session */
179         XMIT_RELIABLE = 1,              /*!< Transmit SIP message reliably, with re-transmits */
180         XMIT_UNRELIABLE = 0,            /*!< Transmit SIP message without bothering with re-transmits */
181 };
182
183 enum subscriptiontype { 
184         NONE = 0,
185         TIMEOUT,
186         XPIDF_XML,
187         DIALOG_INFO_XML,
188         CPIM_PIDF_XML,
189         PIDF_XML,
190         MWI_NOTIFICATION
191 };
192
193 static const struct cfsubscription_types {
194         enum subscriptiontype type;
195         const char * const event;
196         const char * const mediatype;
197         const char * const text;
198 } subscription_types[] = {
199         { NONE,            "-",        "unknown",                    "unknown" },
200         /* IETF draft: draft-ietf-sipping-dialog-package-05.txt */
201         { DIALOG_INFO_XML, "dialog",   "application/dialog-info+xml", "dialog-info+xml" },
202         { CPIM_PIDF_XML,   "presence", "application/cpim-pidf+xml",   "cpim-pidf+xml" },  /* RFC 3863 */
203         { PIDF_XML,        "presence", "application/pidf+xml",        "pidf+xml" },       /* RFC 3863 */
204         { XPIDF_XML,       "presence", "application/xpidf+xml",       "xpidf+xml" },       /* Pre-RFC 3863 with MS additions */
205         { MWI_NOTIFICATION,     "message-summary", "application/simple-message-summary", "mwi" } /* Mailbox notification */
206 };
207
208 enum sipmethod {
209         SIP_UNKNOWN,
210         SIP_RESPONSE,
211         SIP_REGISTER,
212         SIP_OPTIONS,
213         SIP_NOTIFY,
214         SIP_INVITE,
215         SIP_ACK,
216         SIP_PRACK,
217         SIP_BYE,
218         SIP_REFER,
219         SIP_SUBSCRIBE,
220         SIP_MESSAGE,
221         SIP_UPDATE,
222         SIP_INFO,
223         SIP_CANCEL,
224         SIP_PUBLISH,
225 } sip_method_list;
226
227 enum sip_auth_type {
228         PROXY_AUTH,
229         WWW_AUTH,
230 };
231
232 /* States for outbound registrations (with register= lines in sip.conf */
233 enum sipregistrystate {
234         REG_STATE_UNREGISTERED = 0,     /*!< We are not registred */
235         REG_STATE_REGSENT,      /*!< Registration request sent */
236         REG_STATE_AUTHSENT,     /*!< We have tried to authenticate */
237         REG_STATE_REGISTERED,   /*!< Registred and done */
238         REG_STATE_REJECTED,     /*!< Registration rejected */
239         REG_STATE_TIMEOUT,      /*!< Registration timed out */
240         REG_STATE_NOAUTH,       /*!< We have no accepted credentials */
241         REG_STATE_FAILED,       /*!< Registration failed after several tries */
242 };
243
244
245 /*! XXX Note that sip_methods[i].id == i must hold or the code breaks */
246 static const struct  cfsip_methods { 
247         enum sipmethod id;
248         int need_rtp;           /*!< when this is the 'primary' use for a pvt structure, does it need RTP? */
249         char * const text;
250 } sip_methods[] = {
251         { SIP_UNKNOWN,   RTP,    "-UNKNOWN-" },
252         { SIP_RESPONSE,  NO_RTP, "SIP/2.0" },
253         { SIP_REGISTER,  NO_RTP, "REGISTER" },
254         { SIP_OPTIONS,   NO_RTP, "OPTIONS" },
255         { SIP_NOTIFY,    NO_RTP, "NOTIFY" },
256         { SIP_INVITE,    RTP,    "INVITE" },
257         { SIP_ACK,       NO_RTP, "ACK" },
258         { SIP_PRACK,     NO_RTP, "PRACK" },
259         { SIP_BYE,       NO_RTP, "BYE" },
260         { SIP_REFER,     NO_RTP, "REFER" },
261         { SIP_SUBSCRIBE, NO_RTP, "SUBSCRIBE" },
262         { SIP_MESSAGE,   NO_RTP, "MESSAGE" },
263         { SIP_UPDATE,    NO_RTP, "UPDATE" },
264         { SIP_INFO,      NO_RTP, "INFO" },
265         { SIP_CANCEL,    NO_RTP, "CANCEL" },
266         { SIP_PUBLISH,   NO_RTP, "PUBLISH" }
267 };
268
269 /*! \brief Structure for conversion between compressed SIP and "normal" SIP */
270 static const struct cfalias {
271         char * const fullname;
272         char * const shortname;
273 } aliases[] = {
274         { "Content-Type", "c" },
275         { "Content-Encoding", "e" },
276         { "From", "f" },
277         { "Call-ID", "i" },
278         { "Contact", "m" },
279         { "Content-Length", "l" },
280         { "Subject", "s" },
281         { "To", "t" },
282         { "Supported", "k" },
283         { "Refer-To", "r" },
284         { "Referred-By", "b" },
285         { "Allow-Events", "u" },
286         { "Event", "o" },
287         { "Via", "v" },
288         { "Accept-Contact", "a" },
289         { "Reject-Contact", "j" },
290         { "Request-Disposition", "d" },
291         { "Session-Expires", "x" },
292 };
293
294 /*!  Define SIP option tags, used in Require: and Supported: headers 
295         We need to be aware of these properties in the phones to use 
296         the replace: header. We should not do that without knowing
297         that the other end supports it... 
298         This is nothing we can configure, we learn by the dialog
299         Supported: header on the REGISTER (peer) or the INVITE
300         (other devices)
301         We are not using many of these today, but will in the future.
302         This is documented in RFC 3261
303 */
304 #define SUPPORTED               1
305 #define NOT_SUPPORTED           0
306
307 #define SIP_OPT_REPLACES        (1 << 0)
308 #define SIP_OPT_100REL          (1 << 1)
309 #define SIP_OPT_TIMER           (1 << 2)
310 #define SIP_OPT_EARLY_SESSION   (1 << 3)
311 #define SIP_OPT_JOIN            (1 << 4)
312 #define SIP_OPT_PATH            (1 << 5)
313 #define SIP_OPT_PREF            (1 << 6)
314 #define SIP_OPT_PRECONDITION    (1 << 7)
315 #define SIP_OPT_PRIVACY         (1 << 8)
316 #define SIP_OPT_SDP_ANAT        (1 << 9)
317 #define SIP_OPT_SEC_AGREE       (1 << 10)
318 #define SIP_OPT_EVENTLIST       (1 << 11)
319 #define SIP_OPT_GRUU            (1 << 12)
320 #define SIP_OPT_TARGET_DIALOG   (1 << 13)
321
322 /*! \brief List of well-known SIP options. If we get this in a require,
323    we should check the list and answer accordingly. */
324 static const struct cfsip_options {
325         int id;                 /*!< Bitmap ID */
326         int supported;          /*!< Supported by Asterisk ? */
327         char * const text;      /*!< Text id, as in standard */
328 } sip_options[] = {
329         /* Replaces: header for transfer */
330         { SIP_OPT_REPLACES,     SUPPORTED,      "replaces" },   
331         /* RFC3262: PRACK 100% reliability */
332         { SIP_OPT_100REL,       NOT_SUPPORTED,  "100rel" },     
333         /* SIP Session Timers */
334         { SIP_OPT_TIMER,        NOT_SUPPORTED,  "timer" },
335         /* RFC3959: SIP Early session support */
336         { SIP_OPT_EARLY_SESSION, NOT_SUPPORTED, "early-session" },
337         /* SIP Join header support */
338         { SIP_OPT_JOIN,         NOT_SUPPORTED,  "join" },
339         /* RFC3327: Path support */
340         { SIP_OPT_PATH,         NOT_SUPPORTED,  "path" },
341         /* RFC3840: Callee preferences */
342         { SIP_OPT_PREF,         NOT_SUPPORTED,  "pref" },
343         /* RFC3312: Precondition support */
344         { SIP_OPT_PRECONDITION, NOT_SUPPORTED,  "precondition" },
345         /* RFC3323: Privacy with proxies*/
346         { SIP_OPT_PRIVACY,      NOT_SUPPORTED,  "privacy" },
347         /* RFC4092: Usage of the SDP ANAT Semantics in the SIP */
348         { SIP_OPT_SDP_ANAT,     NOT_SUPPORTED,  "sdp-anat" },
349         /* RFC3329: Security agreement mechanism */
350         { SIP_OPT_SEC_AGREE,    NOT_SUPPORTED,  "sec_agree" },
351         /* SIMPLE events:  draft-ietf-simple-event-list-07.txt */
352         { SIP_OPT_EVENTLIST,    NOT_SUPPORTED,  "eventlist" },
353         /* GRUU: Globally Routable User Agent URI's */
354         { SIP_OPT_GRUU,         NOT_SUPPORTED,  "gruu" },
355         /* Target-dialog: draft-ietf-sip-target-dialog-00.txt */
356         { SIP_OPT_TARGET_DIALOG,NOT_SUPPORTED,  "target-dialog" },
357 };
358
359
360 /*! \brief SIP Methods we support */
361 #define ALLOWED_METHODS "INVITE, ACK, CANCEL, OPTIONS, BYE, REFER, SUBSCRIBE, NOTIFY"
362
363 /*! \brief SIP Extensions we support */
364 #define SUPPORTED_EXTENSIONS "replaces" 
365
366
367 /* Default values, set and reset in reload_config before reading configuration */
368 /* These are default values in the source. There are other recommended values in the
369    sip.conf.sample for new installations. These may differ to keep backwards compatibility,
370    yet encouraging new behaviour on new installations 
371  */
372 #define DEFAULT_SIP_PORT        5060    /*!< From RFC 3261 (former 2543) */
373 #define DEFAULT_CONTEXT         "default"
374 #define DEFAULT_MUSICCLASS      "default"
375 #define DEFAULT_VMEXTEN         "asterisk"
376 #define DEFAULT_CALLERID        "asterisk"
377 #define DEFAULT_NOTIFYMIME      "application/simple-message-summary"
378 #define DEFAULT_MWITIME         10
379 #define DEFAULT_ALLOWGUEST      TRUE
380 #define DEFAULT_SRVLOOKUP       FALSE           /*!< Recommended setting is ON */
381 #define DEFAULT_COMPACTHEADERS  FALSE
382 #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. */
383 #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. */
384 #define DEFAULT_TOS_VIDEO       0               /*!< Video packets should be marked as DSCP AF41, but the default is 0 to be compatible with previous versions. */
385 #define DEFAULT_ALLOW_EXT_DOM   TRUE
386 #define DEFAULT_REALM           "asterisk"
387 #define DEFAULT_NOTIFYRINGING   TRUE
388 #define DEFAULT_PEDANTIC        FALSE
389 #define DEFAULT_AUTOCREATEPEER  FALSE
390 #define DEFAULT_QUALIFY         FALSE
391 #define DEFAULT_T1MIN           100             /*!< 100 MS for minimal roundtrip time */
392 #define DEFAULT_MAX_CALL_BITRATE (384)          /*!< Max bitrate for video */
393 #ifndef DEFAULT_USERAGENT
394 #define DEFAULT_USERAGENT "Asterisk PBX"        /*!< Default Useragent: header unless re-defined in sip.conf */
395 #endif
396
397
398 /* Default setttings are used as a channel setting and as a default when
399    configuring devices */
400 static char default_context[AST_MAX_CONTEXT];
401 static char default_subscribecontext[AST_MAX_CONTEXT];
402 static char default_language[MAX_LANGUAGE];
403 static char default_callerid[AST_MAX_EXTENSION];
404 static char default_fromdomain[AST_MAX_EXTENSION];
405 static char default_notifymime[AST_MAX_EXTENSION];
406 static int default_qualify;             /*!< Default Qualify= setting */
407 static char default_vmexten[AST_MAX_EXTENSION];
408 static char default_musicclass[MAX_MUSICCLASS];         /*!< Global music on hold class */
409 static int default_maxcallbitrate;      /*!< Maximum bitrate for call */
410 static struct ast_codec_pref default_prefs;             /*!< Default codec prefs */
411
412 /* Global settings only apply to the channel */
413 static int global_rtautoclear;
414 static int global_notifyringing;        /*!< Send notifications on ringing */
415 static int srvlookup;                   /*!< SRV Lookup on or off. Default is off, RFC behavior is on */
416 static int pedanticsipchecking;         /*!< Extra checking ?  Default off */
417 static int autocreatepeer;              /*!< Auto creation of peers at registration? Default off. */
418 static int global_relaxdtmf;                    /*!< Relax DTMF */
419 static int global_rtptimeout;           /*!< Time out call if no RTP */
420 static int global_rtpholdtimeout;
421 static int global_rtpkeepalive;         /*!< Send RTP keepalives */
422 static int global_reg_timeout;  
423 static int global_regattempts_max;      /*!< Registration attempts before giving up */
424 static int global_allowguest;           /*!< allow unauthenticated users/peers to connect? */
425 static int global_allowsubscribe;       /*!< Flag for disabling ALL subscriptions, this is FALSE only if all peers are FALSE 
426                                             the global setting is in globals_flags[1] */
427 static int global_mwitime;              /*!< Time between MWI checks for peers */
428 static int global_tos_sip;              /*!< IP type of service for SIP packets */
429 static int global_tos_audio;            /*!< IP type of service for audio RTP packets */
430 static int global_tos_video;            /*!< IP type of service for video RTP packets */
431 static int compactheaders;              /*!< send compact sip headers */
432 static int recordhistory;               /*!< Record SIP history. Off by default */
433 static int dumphistory;                 /*!< Dump history to verbose before destroying SIP dialog */
434 static char global_realm[MAXHOSTNAMELEN];               /*!< Default realm */
435 static char global_regcontext[AST_MAX_CONTEXT];         /*!< Context for auto-extensions */
436 static char global_useragent[AST_MAX_EXTENSION];        /*!< Useragent for the SIP channel */
437 static int allow_external_domains;      /*!< Accept calls to external SIP domains? */
438 static int global_callevents;           /*!< Whether we send manager events or not */
439 static int global_t1min;                /*!< T1 roundtrip time minimum */
440
441 /*! \brief Codecs that we support by default: */
442 static int global_capability = AST_FORMAT_ULAW | AST_FORMAT_ALAW | AST_FORMAT_GSM | AST_FORMAT_H263;
443 static int noncodeccapability = AST_RTP_DTMF;
444
445 /* Object counters */
446 static int suserobjs = 0;               /*!< Static users */
447 static int ruserobjs = 0;               /*!< Realtime users */
448 static int speerobjs = 0;               /*!< Statis peers */
449 static int rpeerobjs = 0;               /*!< Realtime peers */
450 static int apeerobjs = 0;               /*!< Autocreated peer objects */
451 static int regobjs = 0;                 /*!< Registry objects */
452
453 static struct ast_flags global_flags[2] = {{0}};        /*!< global SIP_ flags */
454
455 AST_MUTEX_DEFINE_STATIC(usecnt_lock);
456
457 AST_MUTEX_DEFINE_STATIC(rand_lock);                     /*!< Lock for thread-safe random generator */
458
459 /*! \brief Protect the SIP dialog list (of sip_pvt's) */
460 AST_MUTEX_DEFINE_STATIC(iflock);
461
462 /*! \brief Protect the monitoring thread, so only one process can kill or start it, and not
463    when it's doing something critical. */
464 AST_MUTEX_DEFINE_STATIC(netlock);
465
466 AST_MUTEX_DEFINE_STATIC(monlock);
467
468 AST_MUTEX_DEFINE_STATIC(sip_reload_lock);
469
470 /*! \brief This is the thread for the monitor which checks for input on the channels
471    which are not currently in use.  */
472 static pthread_t monitor_thread = AST_PTHREADT_NULL;
473
474 static int sip_reloading = FALSE;                       /*!< Flag for avoiding multiple reloads at the same time */
475 static enum channelreloadreason sip_reloadreason;       /*!< Reason for last reload/load of configuration */
476
477 static struct sched_context *sched;     /*!< The scheduling context */
478 static struct io_context *io;           /*!< The IO context */
479
480 #define DEC_CALL_LIMIT  0
481 #define INC_CALL_LIMIT  1
482
483
484 /*! \brief sip_request: The data grabbed from the UDP socket */
485 struct sip_request {
486         char *rlPart1;          /*!< SIP Method Name or "SIP/2.0" protocol version */
487         char *rlPart2;          /*!< The Request URI or Response Status */
488         int len;                /*!< Length */
489         int headers;            /*!< # of SIP Headers */
490         int method;             /*!< Method of this request */
491         char *header[SIP_MAX_HEADERS];
492         int lines;              /*!< SDP Content */
493         char *line[SIP_MAX_LINES];
494         char data[SIP_MAX_PACKET];
495         int debug;              /*!< Debug flag for this packet */
496         unsigned int flags;     /*!< SIP_PKT Flags for this packet */
497 };
498
499 /*! \brief structure used in transfers */
500 struct sip_dual {
501         struct ast_channel *chan1;
502         struct ast_channel *chan2;
503         struct sip_request req;
504 };
505
506 struct sip_pkt;
507
508 /*! \brief Parameters to the transmit_invite function */
509 struct sip_invite_param {
510         const char *distinctive_ring;   /*!< Distinctive ring header */
511         const char *osptoken;           /*!< OSP token for this call */
512         int addsipheaders;      /*!< Add extra SIP headers */
513         const char *uri_options;        /*!< URI options to add to the URI */
514         const char *vxml_url;           /*!< VXML url for Cisco phones */
515         char *auth;             /*!< Authentication */
516         char *authheader;       /*!< Auth header */
517         enum sip_auth_type auth_type;   /*!< Authentication type */
518 };
519
520 /*! \brief Structure to save routing information for a SIP session */
521 struct sip_route {
522         struct sip_route *next;
523         char hop[0];
524 };
525
526 /*! \brief Modes for SIP domain handling in the PBX */
527 enum domain_mode {
528         SIP_DOMAIN_AUTO,        /*!< This domain is auto-configured */
529         SIP_DOMAIN_CONFIG,      /*!< This domain is from configuration */
530 };
531
532 struct domain {
533         char domain[MAXHOSTNAMELEN];            /*!< SIP domain we are responsible for */
534         char context[AST_MAX_EXTENSION];        /*!< Incoming context for this domain */
535         enum domain_mode mode;                  /*!< How did we find this domain? */
536         AST_LIST_ENTRY(domain) list;            /*!< List mechanics */
537 };
538
539 static AST_LIST_HEAD_STATIC(domain_list, domain);       /*!< The SIP domain list */
540
541
542 /*! \brief sip_history: Structure for saving transactions within a SIP dialog */
543 struct sip_history {
544         AST_LIST_ENTRY(sip_history) list;
545         char event[0];  /* actually more, depending on needs */
546 };
547
548 AST_LIST_HEAD_NOLOCK(sip_history_head, sip_history); /*!< history list, entry in sip_pvt */
549
550 /*! \brief sip_auth: Creadentials for authentication to other SIP services */
551 struct sip_auth {
552         char realm[AST_MAX_EXTENSION];  /*!< Realm in which these credentials are valid */
553         char username[256];             /*!< Username */
554         char secret[256];               /*!< Secret */
555         char md5secret[256];            /*!< MD5Secret */
556         struct sip_auth *next;          /*!< Next auth structure in list */
557 };
558
559 /*--- Various flags for the flags field in the pvt structure 
560  Peer only flags should be set in PAGE2 below
561 */
562 #define SIP_ALREADYGONE         (1 << 0)        /*!< Whether or not we've already been destroyed by our peer */
563 #define SIP_NEEDDESTROY         (1 << 1)        /*!< if we need to be destroyed */
564 #define SIP_NOVIDEO             (1 << 2)        /*!< Didn't get video in invite, don't offer */
565 #define SIP_RINGING             (1 << 3)        /*!< Have sent 180 ringing */
566 #define SIP_PROGRESS_SENT       (1 << 4)        /*!< Have sent 183 message progress */
567 #define SIP_NEEDREINVITE        (1 << 5)        /*!< Do we need to send another reinvite? */
568 #define SIP_PENDINGBYE          (1 << 6)        /*!< Need to send bye after we ack? */
569 #define SIP_GOTREFER            (1 << 7)        /*!< Got a refer? */
570 #define SIP_PROMISCREDIR        (1 << 8)        /*!< Promiscuous redirection */
571 #define SIP_TRUSTRPID           (1 << 9)        /*!< Trust RPID headers? */
572 #define SIP_USEREQPHONE         (1 << 10)       /*!< Add user=phone to numeric URI. Default off */
573 #define SIP_REALTIME            (1 << 11)       /*!< Flag for realtime users */
574 #define SIP_USECLIENTCODE       (1 << 12)       /*!< Trust X-ClientCode info message */
575 #define SIP_OUTGOING            (1 << 13)       /*!< Is this an outgoing call? */
576 #define SIP_FREEBIT             (1 << 14)       /*!< Free for session-related use */
577 #define SIP_FREEBIT3            (1 << 15)       /*!< Free for session-related use */
578 #define SIP_DTMF                (3 << 16)       /*!< DTMF Support: four settings, uses two bits */
579 #define SIP_DTMF_RFC2833        (0 << 16)       /*!< DTMF Support: RTP DTMF - "rfc2833" */
580 #define SIP_DTMF_INBAND         (1 << 16)       /*!< DTMF Support: Inband audio, only for ULAW/ALAW - "inband" */
581 #define SIP_DTMF_INFO           (2 << 16)       /*!< DTMF Support: SIP Info messages - "info" */
582 #define SIP_DTMF_AUTO           (3 << 16)       /*!< DTMF Support: AUTO switch between rfc2833 and in-band DTMF */
583 /* NAT settings */
584 #define SIP_NAT                 (3 << 18)       /*!< four settings, uses two bits */
585 #define SIP_NAT_NEVER           (0 << 18)       /*!< No nat support */
586 #define SIP_NAT_RFC3581         (1 << 18)
587 #define SIP_NAT_ROUTE           (2 << 18)
588 #define SIP_NAT_ALWAYS          (3 << 18)
589 /* re-INVITE related settings */
590 #define SIP_REINVITE            (3 << 20)       /*!< two bits used */
591 #define SIP_CAN_REINVITE        (1 << 20)       /*!< allow peers to be reinvited to send media directly p2p */
592 #define SIP_REINVITE_UPDATE     (2 << 20)       /*!< use UPDATE (RFC3311) when reinviting this peer */
593 /* "insecure" settings */
594 #define SIP_INSECURE_PORT       (1 << 22)       /*!< don't require matching port for incoming requests */
595 #define SIP_INSECURE_INVITE     (1 << 23)       /*!< don't require authentication for incoming INVITEs */
596 /* Sending PROGRESS in-band settings */
597 #define SIP_PROG_INBAND         (3 << 24)       /*!< three settings, uses two bits */
598 #define SIP_PROG_INBAND_NEVER   (0 << 24)
599 #define SIP_PROG_INBAND_NO      (1 << 24)
600 #define SIP_PROG_INBAND_YES     (2 << 24)
601 /* Open Settlement Protocol authentication */
602 #define SIP_OSPAUTH             (3 << 26)       /*!< four settings, uses two bits */
603 #define SIP_OSPAUTH_NO          (0 << 26)
604 #define SIP_OSPAUTH_GATEWAY     (1 << 26)
605 #define SIP_OSPAUTH_PROXY       (2 << 26)
606 #define SIP_OSPAUTH_EXCLUSIVE   (3 << 26)
607 /* Call states */
608 #define SIP_CALL_ONHOLD         (1 << 28)        
609 #define SIP_CALL_LIMIT          (1 << 29)
610 /* Remote Party-ID Support */
611 #define SIP_SENDRPID            (1 << 30)
612 /* Did this connection increment the counter of in-use calls? */
613 #define SIP_INC_COUNT           (1 << 31)
614
615 #define SIP_FLAGS_TO_COPY \
616         (SIP_PROMISCREDIR | SIP_TRUSTRPID | SIP_SENDRPID | SIP_DTMF | SIP_REINVITE | \
617          SIP_PROG_INBAND | SIP_OSPAUTH | SIP_USECLIENTCODE | SIP_NAT | \
618          SIP_USEREQPHONE | SIP_INSECURE_PORT | SIP_INSECURE_INVITE)
619
620 /* a new page of flags for peers */
621 #define SIP_PAGE2_RTCACHEFRIENDS        (1 << 0)
622 #define SIP_PAGE2_RTUPDATE              (1 << 1)
623 #define SIP_PAGE2_RTAUTOCLEAR           (1 << 2)
624 #define SIP_PAGE2_IGNOREREGEXPIRE       (1 << 3)
625 #define SIP_PAGE2_RT_FROMCONTACT        (1 << 4)
626 #define SIP_PAGE2_DEBUG                 (3 << 5)
627 #define SIP_PAGE2_DEBUG_CONFIG          (1 << 5)
628 #define SIP_PAGE2_DEBUG_CONSOLE         (1 << 6)
629 #define SIP_PAGE2_DYNAMIC               (1 << 7)        /*!< Dynamic Peers register with Asterisk */
630 #define SIP_PAGE2_SELFDESTRUCT          (1 << 8)        /*!< Automatic peers need to destruct themselves */
631 #define SIP_PAGE2_VIDEOSUPPORT          (1 << 9)
632 #define SIP_PAGE2_ALLOWSUBSCRIBE        (1 << 10)       /*!< Allow subscriptions from this peer? */
633 #define SIP_PAGE2_ALLOWOVERLAP          (1 << 11)       /*!< Allow overlap dialing ? */
634 #define SIP_PAGE2_SUBSCRIBEMWIONLY      (1 << 12)       /*!< Only issue MWI notification if subscribed to */
635
636
637 #define SIP_PAGE2_FLAGS_TO_COPY \
638         (SIP_PAGE2_ALLOWSUBSCRIBE | SIP_PAGE2_ALLOWOVERLAP | SIP_PAGE2_VIDEOSUPPORT)
639
640 /* SIP packet flags */
641 #define SIP_PKT_DEBUG           (1 << 0)        /*!< Debug this packet */
642 #define SIP_PKT_WITH_TOTAG      (1 << 1)        /*!< This packet has a to-tag */
643
644 #define sipdebug                ast_test_flag(&global_flags[1], SIP_PAGE2_DEBUG)
645 #define sipdebug_config         ast_test_flag(&global_flags[1], SIP_PAGE2_DEBUG_CONFIG)
646 #define sipdebug_console        ast_test_flag(&global_flags[1], SIP_PAGE2_DEBUG_CONSOLE)
647
648 /*! \brief sip_pvt: PVT structures are used for each SIP dialog, ie. a call, a registration, a subscribe  */
649 static struct sip_pvt {
650         ast_mutex_t lock;                       /*!< Dialog private lock */
651         int method;                             /*!< SIP method that opened this dialog */
652         AST_DECLARE_STRING_FIELDS(
653                 AST_STRING_FIELD(callid);       /*!< Global CallID */
654                 AST_STRING_FIELD(randdata);     /*!< Random data */
655                 AST_STRING_FIELD(accountcode);  /*!< Account code */
656                 AST_STRING_FIELD(realm);        /*!< Authorization realm */
657                 AST_STRING_FIELD(nonce);        /*!< Authorization nonce */
658                 AST_STRING_FIELD(opaque);       /*!< Opaque nonsense */
659                 AST_STRING_FIELD(qop);          /*!< Quality of Protection, since SIP wasn't complicated enough yet. */
660                 AST_STRING_FIELD(domain);       /*!< Authorization domain */
661                 AST_STRING_FIELD(refer_to);     /*!< Place to store REFER-TO extension */
662                 AST_STRING_FIELD(referred_by);  /*!< Place to store REFERRED-BY extension */
663                 AST_STRING_FIELD(refer_contact);/*!< Place to store Contact info from a REFER extension */
664                 AST_STRING_FIELD(from);         /*!< The From: header */
665                 AST_STRING_FIELD(useragent);    /*!< User agent in SIP request */
666                 AST_STRING_FIELD(exten);        /*!< Extension where to start */
667                 AST_STRING_FIELD(context);      /*!< Context for this call */
668                 AST_STRING_FIELD(subscribecontext); /*!< Subscribecontext */
669                 AST_STRING_FIELD(fromdomain);   /*!< Domain to show in the from field */
670                 AST_STRING_FIELD(fromuser);     /*!< User to show in the user field */
671                 AST_STRING_FIELD(fromname);     /*!< Name to show in the user field */
672                 AST_STRING_FIELD(tohost);       /*!< Host we should put in the "to" field */
673                 AST_STRING_FIELD(language);     /*!< Default language for this call */
674                 AST_STRING_FIELD(musicclass);   /*!< Music on Hold class */
675                 AST_STRING_FIELD(rdnis);        /*!< Referring DNIS */
676                 AST_STRING_FIELD(theirtag);     /*!< Their tag */
677                 AST_STRING_FIELD(username);     /*!< [user] name */
678                 AST_STRING_FIELD(peername);     /*!< [peer] name, not set if [user] */
679                 AST_STRING_FIELD(authname);     /*!< Who we use for authentication */
680                 AST_STRING_FIELD(uri);          /*!< Original requested URI */
681                 AST_STRING_FIELD(okcontacturi); /*!< URI from the 200 OK on INVITE */
682                 AST_STRING_FIELD(peersecret);   /*!< Password */
683                 AST_STRING_FIELD(peermd5secret);
684                 AST_STRING_FIELD(cid_num);      /*!< Caller*ID */
685                 AST_STRING_FIELD(cid_name);     /*!< Caller*ID */
686                 AST_STRING_FIELD(via);          /*!< Via: header */
687                 AST_STRING_FIELD(fullcontact);  /*!< The Contact: that the UA registers with us */
688                 AST_STRING_FIELD(our_contact);  /*!< Our contact header */
689                 AST_STRING_FIELD(rpid);         /*!< Our RPID header */
690                 AST_STRING_FIELD(rpid_from);    /*!< Our RPID From header */
691         );
692         struct ast_codec_pref prefs;            /*!< codec prefs */
693         unsigned int ocseq;                     /*!< Current outgoing seqno */
694         unsigned int icseq;                     /*!< Current incoming seqno */
695         ast_group_t callgroup;                  /*!< Call group */
696         ast_group_t pickupgroup;                /*!< Pickup group */
697         int lastinvite;                         /*!< Last Cseq of invite */
698         struct ast_flags flags[2];              /*!< SIP_ flags */
699         int timer_t1;                           /*!< SIP timer T1, ms rtt */
700         unsigned int sipoptions;                /*!< Supported SIP sipoptions on the other end */
701         int capability;                         /*!< Special capability (codec) */
702         int jointcapability;                    /*!< Supported capability at both ends (codecs ) */
703         int peercapability;                     /*!< Supported peer capability */
704         int prefcodec;                          /*!< Preferred codec (outbound only) */
705         int noncodeccapability;
706         int maxcallbitrate;                     /*!< Maximum Call Bitrate for Video Calls */    
707         int callingpres;                        /*!< Calling presentation */
708         int authtries;                          /*!< Times we've tried to authenticate */
709         int expiry;                             /*!< How long we take to expire */
710         int branch;                             /*!< One random number */
711         char tag[11];                           /*!< Another random number */
712         int sessionid;                          /*!< SDP Session ID */
713         int sessionversion;                     /*!< SDP Session Version */
714         struct sockaddr_in sa;                  /*!< Our peer */
715         struct sockaddr_in redirip;             /*!< Where our RTP should be going if not to us */
716         struct sockaddr_in vredirip;            /*!< Where our Video RTP should be going if not to us */
717         int redircodecs;                        /*!< Redirect codecs */
718         struct sockaddr_in recv;                /*!< Received as */
719         struct in_addr ourip;                   /*!< Our IP */
720         struct ast_channel *owner;              /*!< Who owns us */
721         struct sip_pvt *refer_call;             /*!< Call we are referring */
722         struct sip_route *route;                /*!< Head of linked list of routing steps (fm Record-Route) */
723         int route_persistant;                   /*!< Is this the "real" route? */
724         struct sip_auth *peerauth;              /*!< Realm authentication */
725         int noncecount;                         /*!< Nonce-count */
726         char lastmsg[256];                      /*!< Last Message sent/received */
727         int amaflags;                           /*!< AMA Flags */
728         int pendinginvite;                      /*!< Any pending invite */
729 #ifdef OSP_SUPPORT
730         int osphandle;                          /*!< OSP Handle for call */
731         time_t ospstart;                        /*!< OSP Start time */
732         unsigned int osptimelimit;              /*!< OSP call duration limit */
733 #endif
734         struct sip_request initreq;             /*!< Initial request that opened the SIP dialog */
735         
736         int maxtime;                            /*!< Max time for first response */
737         int initid;                             /*!< Auto-congest ID if appropriate */
738         int autokillid;                         /*!< Auto-kill ID */
739         time_t lastrtprx;                       /*!< Last RTP received */
740         time_t lastrtptx;                       /*!< Last RTP sent */
741         int rtptimeout;                         /*!< RTP timeout time */
742         int rtpholdtimeout;                     /*!< RTP timeout when on hold */
743         int rtpkeepalive;                       /*!< Send RTP packets for keepalive */
744         enum subscriptiontype subscribed;       /*!< Is this dialog a subscription?  */
745         int stateid;
746         int laststate;                          /*!< Last known extension state */
747         int dialogver;
748         
749         struct ast_dsp *vad;                    /*!< Voice Activation Detection dsp */
750         
751         struct sip_peer *relatedpeer;           /*!< If this dialog is related to a peer, which one 
752                                                         Used in peerpoke, mwi subscriptions */
753         struct sip_registry *registry;          /*!< If this is a REGISTER dialog, to which registry */
754         struct ast_rtp *rtp;                    /*!< RTP Session */
755         struct ast_rtp *vrtp;                   /*!< Video RTP session */
756         struct sip_pkt *packets;                /*!< Packets scheduled for re-transmission */
757         struct sip_history_head *history;       /*!< History of this SIP dialog */
758         struct ast_variable *chanvars;          /*!< Channel variables to set for call */
759         struct sip_pvt *next;                   /*!< Next dialog in chain */
760         struct sip_invite_param *options;       /*!< Options for INVITE */
761 } *iflist = NULL;
762
763 #define FLAG_RESPONSE (1 << 0)
764 #define FLAG_FATAL (1 << 1)
765
766 /*! \brief sip packet - read in sipsock_read(), transmitted in send_request() */
767 struct sip_pkt {
768         struct sip_pkt *next;                   /*!< Next packet */
769         int retrans;                            /*!< Retransmission number */
770         int method;                             /*!< SIP method for this packet */
771         int seqno;                              /*!< Sequence number */
772         unsigned int flags;                     /*!< non-zero if this is a response packet (e.g. 200 OK) */
773         struct sip_pvt *owner;                  /*!< Owner AST call */
774         int retransid;                          /*!< Retransmission ID */
775         int timer_a;                            /*!< SIP timer A, retransmission timer */
776         int timer_t1;                           /*!< SIP Timer T1, estimated RTT or 500 ms */
777         int packetlen;                          /*!< Length of packet */
778         char data[0];
779 };      
780
781 /*! \brief Structure for SIP user data. User's place calls to us */
782 struct sip_user {
783         /* Users who can access various contexts */
784         ASTOBJ_COMPONENTS(struct sip_user);
785         char secret[80];                /*!< Password */
786         char md5secret[80];             /*!< Password in md5 */
787         char context[AST_MAX_CONTEXT];  /*!< Default context for incoming calls */
788         char subscribecontext[AST_MAX_CONTEXT]; /* Default context for subscriptions */
789         char cid_num[80];               /*!< Caller ID num */
790         char cid_name[80];              /*!< Caller ID name */
791         char accountcode[AST_MAX_ACCOUNT_CODE]; /* Account code */
792         char language[MAX_LANGUAGE];    /*!< Default language for this user */
793         char musicclass[MAX_MUSICCLASS];/*!< Music on Hold class */
794         char useragent[256];            /*!< User agent in SIP request */
795         struct ast_codec_pref prefs;    /*!< codec prefs */
796         ast_group_t callgroup;          /*!< Call group */
797         ast_group_t pickupgroup;        /*!< Pickup Group */
798         unsigned int sipoptions;        /*!< Supported SIP options */
799         struct ast_flags flags[2];      /*!< SIP_ flags */
800         int amaflags;                   /*!< AMA flags for billing */
801         int callingpres;                /*!< Calling id presentation */
802         int capability;                 /*!< Codec capability */
803         int inUse;                      /*!< Number of calls in use */
804         int call_limit;                 /*!< Limit of concurrent calls */
805         struct ast_ha *ha;              /*!< ACL setting */
806         struct ast_variable *chanvars;  /*!< Variables to set for channel created by user */
807         int maxcallbitrate;             /*!< Maximum Bitrate for a video call */
808 };
809
810 /*! \brief Structure for SIP peer data, we place calls to peers if registered  or fixed IP address (host) */
811 struct sip_peer {
812         ASTOBJ_COMPONENTS(struct sip_peer);     /*!< name, refcount, objflags,  object pointers */
813                                         /*!< peer->name is the unique name of this object */
814         char secret[80];                /*!< Password */
815         char md5secret[80];             /*!< Password in MD5 */
816         struct sip_auth *auth;          /*!< Realm authentication list */
817         char context[AST_MAX_CONTEXT];  /*!< Default context for incoming calls */
818         char subscribecontext[AST_MAX_CONTEXT]; /*!< Default context for subscriptions */
819         char username[80];              /*!< Temporary username until registration */ 
820         char accountcode[AST_MAX_ACCOUNT_CODE]; /*!< Account code */
821         int amaflags;                   /*!< AMA Flags (for billing) */
822         char tohost[MAXHOSTNAMELEN];    /*!< If not dynamic, IP address */
823         char regexten[AST_MAX_EXTENSION]; /*!< Extension to register (if regcontext is used) */
824         char fromuser[80];              /*!< From: user when calling this peer */
825         char fromdomain[MAXHOSTNAMELEN];        /*!< From: domain when calling this peer */
826         char fullcontact[256];          /*!< Contact registered with us (not in sip.conf) */
827         char cid_num[80];               /*!< Caller ID num */
828         char cid_name[80];              /*!< Caller ID name */
829         int callingpres;                /*!< Calling id presentation */
830         int inUse;                      /*!< Number of calls in use */
831         int call_limit;                 /*!< Limit of concurrent calls */
832         char vmexten[AST_MAX_EXTENSION]; /*!< Dialplan extension for MWI notify message*/
833         char mailbox[AST_MAX_EXTENSION]; /*!< Mailbox setting for MWI checks */
834         char language[MAX_LANGUAGE];    /*!<  Default language for prompts */
835         char musicclass[MAX_MUSICCLASS];/*!<  Music on Hold class */
836         char useragent[256];            /*!<  User agent in SIP request (saved from registration) */
837         struct ast_codec_pref prefs;    /*!<  codec prefs */
838         int lastmsgssent;
839         time_t  lastmsgcheck;           /*!<  Last time we checked for MWI */
840         unsigned int sipoptions;        /*!<  Supported SIP options */
841         struct ast_flags flags[2];      /*!<  SIP_ flags */
842         int expire;                     /*!<  When to expire this peer registration */
843         int capability;                 /*!<  Codec capability */
844         int rtptimeout;                 /*!<  RTP timeout */
845         int rtpholdtimeout;             /*!<  RTP Hold Timeout */
846         int rtpkeepalive;               /*!<  Send RTP packets for keepalive */
847         ast_group_t callgroup;          /*!<  Call group */
848         ast_group_t pickupgroup;        /*!<  Pickup group */
849         struct ast_dnsmgr_entry *dnsmgr;/*!<  DNS refresh manager for peer */
850         struct sockaddr_in addr;        /*!<  IP address of peer */
851         int maxcallbitrate;             /*!< Maximum Bitrate for a video call */
852         
853         /* Qualification */
854         struct sip_pvt *call;           /*!<  Call pointer */
855         int pokeexpire;                 /*!<  When to expire poke (qualify= checking) */
856         int lastms;                     /*!<  How long last response took (in ms), or -1 for no response */
857         int maxms;                      /*!<  Max ms we will accept for the host to be up, 0 to not monitor */
858         struct timeval ps;              /*!<  Ping send time */
859         
860         struct sockaddr_in defaddr;     /*!<  Default IP address, used until registration */
861         struct ast_ha *ha;              /*!<  Access control list */
862         struct ast_variable *chanvars;  /*!<  Variables to set for channel created by user */
863         struct sip_pvt *mwipvt;         /*!<  Subscription for MWI */
864         int lastmsg;
865 };
866
867
868
869 /*! \brief Registrations with other SIP proxies */
870 struct sip_registry {
871         ASTOBJ_COMPONENTS_FULL(struct sip_registry,1,1);
872         AST_DECLARE_STRING_FIELDS(
873                 AST_STRING_FIELD(callid);       /*!< Global Call-ID */
874                 AST_STRING_FIELD(realm);        /*!< Authorization realm */
875                 AST_STRING_FIELD(nonce);        /*!< Authorization nonce */
876                 AST_STRING_FIELD(opaque);       /*!< Opaque nonsense */
877                 AST_STRING_FIELD(qop);          /*!< Quality of Protection, since SIP wasn't complicated enough yet. */
878                 AST_STRING_FIELD(domain);       /*!< Authorization domain */
879                 AST_STRING_FIELD(username);     /*!< Who we are registering as */
880                 AST_STRING_FIELD(authuser);     /*!< Who we *authenticate* as */
881                 AST_STRING_FIELD(hostname);     /*!< Domain or host we register to */
882                 AST_STRING_FIELD(secret);       /*!< Password in clear text */  
883                 AST_STRING_FIELD(md5secret);    /*!< Password in md5 */
884                 AST_STRING_FIELD(contact);      /*!< Contact extension */
885                 AST_STRING_FIELD(random);
886         );
887         int portno;                     /*!<  Optional port override */
888         int expire;                     /*!< Sched ID of expiration */
889         int regattempts;                /*!< Number of attempts (since the last success) */
890         int timeout;                    /*!< sched id of sip_reg_timeout */
891         int refresh;                    /*!< How often to refresh */
892         struct sip_pvt *call;           /*!< create a sip_pvt structure for each outbound "registration dialog" in progress */
893         enum sipregistrystate regstate; /*!< Registration state (see above) */
894         int callid_valid;               /*!< 0 means we haven't chosen callid for this registry yet. */
895         unsigned int ocseq;             /*!< Sequence number we got to for REGISTERs for this registry */
896         struct sockaddr_in us;          /*!< Who the server thinks we are */
897         int noncecount;                 /*!< Nonce-count */
898         char lastmsg[256];              /*!< Last Message sent/received */
899 };
900
901 /* --- Linked lists of various objects --------*/
902
903 /*! \brief  The user list: Users and friends */
904 static struct ast_user_list {
905         ASTOBJ_CONTAINER_COMPONENTS(struct sip_user);
906 } userl;
907
908 /*! \brief  The peer list: Peers and Friends */
909 static struct ast_peer_list {
910         ASTOBJ_CONTAINER_COMPONENTS(struct sip_peer);
911 } peerl;
912
913 /*! \brief  The register list: Other SIP proxys we register with and place calls to */
914 static struct ast_register_list {
915         ASTOBJ_CONTAINER_COMPONENTS(struct sip_registry);
916         int recheck;
917 } regl;
918
919 /*! \todo Move the sip_auth list to AST_LIST */
920 static struct sip_auth *authl = NULL;           /*!< Authentication list for realm authentication */
921
922
923 /* --- Sockets and networking --------------*/
924 static int sipsock  = -1;                       /*!< Main socket for SIP network communication */
925 static struct sockaddr_in bindaddr = { 0, };    /*!< The address we bind to */
926 static struct sockaddr_in externip;             /*!< External IP address if we are behind NAT */
927 static char externhost[MAXHOSTNAMELEN];         /*!< External host name (possibly with dynamic DNS and DHCP */
928 static time_t externexpire = 0;                 /*!< Expiration counter for re-resolving external host name in dynamic DNS */
929 static int externrefresh = 10;
930 static struct ast_ha *localaddr;                /*!< List of local networks, on the same side of NAT as this Asterisk */
931 static struct in_addr __ourip;
932 static struct sockaddr_in outboundproxyip;
933 static int ourport;
934 static struct sockaddr_in debugaddr;
935
936 struct ast_config *notify_types;                /*!< The list of manual NOTIFY types we know how to send */
937
938
939
940 /*---------------------------- Forward declarations of functions in chan_sip.c */
941 static int transmit_response(struct sip_pvt *p, char *msg, struct sip_request *req);
942 static int transmit_response_with_sdp(struct sip_pvt *p, char *msg, struct sip_request *req, enum xmittype reliable);
943 static int transmit_response_with_unsupported(struct sip_pvt *p, char *msg, struct sip_request *req, char *unsupported);
944 static int transmit_response_with_auth(struct sip_pvt *p, const char *msg, struct sip_request *req, const char *rand, enum xmittype reliable, const char *header, int stale);
945 static int transmit_request(struct sip_pvt *p, int sipmethod, int inc, enum xmittype reliable, int newbranch);
946 static int transmit_request_with_auth(struct sip_pvt *p, int sipmethod, int inc, enum xmittype reliable, int newbranch);
947 static int transmit_invite(struct sip_pvt *p, int sipmethod, int sendsdp, int init);
948 static int transmit_reinvite_with_sdp(struct sip_pvt *p);
949 static int transmit_info_with_digit(struct sip_pvt *p, char digit);
950 static int transmit_info_with_vidupdate(struct sip_pvt *p);
951 static int transmit_message_with_text(struct sip_pvt *p, const char *text);
952 static int transmit_refer(struct sip_pvt *p, const char *dest);
953 static int sip_sipredirect(struct sip_pvt *p, const char *dest);
954 static struct sip_peer *temp_peer(const char *name);
955 static int do_proxy_auth(struct sip_pvt *p, struct sip_request *req, char *header, char *respheader, int sipmethod, int init);
956 static void free_old_route(struct sip_route *route);
957 static int build_reply_digest(struct sip_pvt *p, int method, char *digest, int digest_len);
958 static int update_call_counter(struct sip_pvt *fup, int event);
959 static struct sip_peer *build_peer(const char *name, struct ast_variable *v, int realtime);
960 static struct sip_user *build_user(const char *name, struct ast_variable *v, int realtime);
961 static int sip_do_reload(enum channelreloadreason reason);
962 static int expire_register(void *data);
963 static struct ast_channel *sip_request_call(const char *type, int format, void *data, int *cause);
964 static int sip_devicestate(void *data);
965 static int sip_sendtext(struct ast_channel *ast, const char *text);
966 static int sip_call(struct ast_channel *ast, char *dest, int timeout);
967 static int sip_hangup(struct ast_channel *ast);
968 static int sip_answer(struct ast_channel *ast);
969 static struct ast_frame *sip_read(struct ast_channel *ast);
970 static int sip_write(struct ast_channel *ast, struct ast_frame *frame);
971 static int sip_indicate(struct ast_channel *ast, int condition);
972 static int sip_transfer(struct ast_channel *ast, const char *dest);
973 static int sip_fixup(struct ast_channel *oldchan, struct ast_channel *newchan);
974 static int sip_senddigit(struct ast_channel *ast, char digit);
975 static int clear_realm_authentication(struct sip_auth *authlist);       /* Clear realm authentication list (at reload) */
976 static struct sip_auth *add_realm_authentication(struct sip_auth *authlist, char *configuration, int lineno);   /* Add realm authentication in list */
977 static struct sip_auth *find_realm_authentication(struct sip_auth *authlist, const char *realm);        /* Find authentication for a specific realm */
978 static int check_auth(struct sip_pvt *p, struct sip_request *req, const char *username,
979                 const char *secret, const char *md5secret, int sipmethod,
980                 char *uri, enum xmittype reliable, int ignore);
981 static int check_sip_domain(const char *domain, char *context, size_t len); /* Check if domain is one of our local domains */
982 static void append_date(struct sip_request *req);       /* Append date to SIP packet */
983 static int determine_firstline_parts(struct sip_request *req);
984 static void sip_dump_history(struct sip_pvt *dialog);   /* Dump history to LOG_DEBUG at end of dialog, before destroying data */
985 static const struct cfsubscription_types *find_subscription_type(enum subscriptiontype subtype);
986 static int transmit_state_notify(struct sip_pvt *p, int state, int full);
987 static char *gettag(struct sip_request *req, char *header, char *tagbuf, int tagbufsize);
988 static int find_sip_method(char *msg);
989 static unsigned int parse_sip_options(struct sip_pvt *pvt, char *supported);
990 static void sip_destroy(struct sip_pvt *p);
991 static void sip_destroy_peer(struct sip_peer *peer);
992 static void sip_destroy_user(struct sip_user *user);
993 static void parse_request(struct sip_request *req);
994 static char *get_header(struct sip_request *req, const char *name);
995 static void copy_request(struct sip_request *dst,struct sip_request *src);
996 static int transmit_response_reliable(struct sip_pvt *p, char *msg, struct sip_request *req);
997 static int transmit_register(struct sip_registry *r, int sipmethod, char *auth, char *authheader);
998 static int sip_poke_peer(struct sip_peer *peer);
999 static int __sip_do_register(struct sip_registry *r);
1000 static int restart_monitor(void);
1001 static void set_peer_defaults(struct sip_peer *peer);
1002 static struct sip_peer *temp_peer(const char *name);
1003 static int sip_send_mwi_to_peer(struct sip_peer *peer);
1004 static int sip_scheddestroy(struct sip_pvt *p, int ms);
1005
1006
1007 /*----- RTP interface functions */
1008 static int sip_set_rtp_peer(struct ast_channel *chan, struct ast_rtp *rtp, struct ast_rtp *vrtp, int codecs, int nat_active);
1009 static struct ast_rtp *sip_get_rtp_peer(struct ast_channel *chan);
1010 static struct ast_rtp *sip_get_vrtp_peer(struct ast_channel *chan);
1011 static int sip_get_codec(struct ast_channel *chan);
1012
1013 /*! \brief Definition of this channel for PBX channel registration */
1014 static const struct ast_channel_tech sip_tech = {
1015         .type = "SIP",
1016         .description = "Session Initiation Protocol (SIP)",
1017         .capabilities = ((AST_FORMAT_MAX_AUDIO << 1) - 1),
1018         .properties = AST_CHAN_TP_WANTSJITTER,
1019         .requester = sip_request_call,
1020         .devicestate = sip_devicestate,
1021         .call = sip_call,
1022         .hangup = sip_hangup,
1023         .answer = sip_answer,
1024         .read = sip_read,
1025         .write = sip_write,
1026         .write_video = sip_write,
1027         .indicate = sip_indicate,
1028         .transfer = sip_transfer,
1029         .fixup = sip_fixup,
1030         .send_digit = sip_senddigit,
1031         .bridge = ast_rtp_bridge,
1032         .send_text = sip_sendtext,
1033 };
1034
1035 /*! \brief Interface structure with callbacks used to connect to RTP module */
1036 static struct ast_rtp_protocol sip_rtp = {
1037         type: "SIP",
1038         get_rtp_info: sip_get_rtp_peer,
1039         get_vrtp_info: sip_get_vrtp_peer,
1040         set_rtp_peer: sip_set_rtp_peer,
1041         get_codec: sip_get_codec,
1042 };
1043
1044
1045 /*!
1046   \brief Thread-safe random number generator
1047   \return a random number
1048
1049   This function uses a mutex lock to guarantee that no
1050   two threads will receive the same random number.
1051  */
1052 static force_inline int thread_safe_rand(void)
1053 {
1054         int val;
1055
1056         ast_mutex_lock(&rand_lock);
1057         val = rand();
1058         ast_mutex_unlock(&rand_lock);
1059         
1060         return val;
1061 }
1062
1063 /*! \brief Find SIP method from header
1064  * Strictly speaking, SIP methods are case SENSITIVE, but we don't check 
1065  * following Jon Postel's rule: Be gentle in what you accept, strict with what you send */
1066 static int find_sip_method(char *msg)
1067 {
1068         int i, res = 0;
1069         
1070         if (ast_strlen_zero(msg))
1071                 return 0;
1072
1073         for (i = 1; (i < (sizeof(sip_methods) / sizeof(sip_methods[0]))) && !res; i++) {
1074                 if (!strcasecmp(sip_methods[i].text, msg)) 
1075                         res = sip_methods[i].id;
1076         }
1077         return res;
1078 }
1079
1080 /*! \brief Parse supported header in incoming packet */
1081 static unsigned int parse_sip_options(struct sip_pvt *pvt, char *supported)
1082 {
1083         char *next = NULL;
1084         char *sep = NULL;
1085         char *temp = ast_strdupa(supported);
1086         int i;
1087         unsigned int profile = 0;
1088
1089         if (ast_strlen_zero(supported) )
1090                 return 0;
1091
1092         if (option_debug > 2 && sipdebug)
1093                 ast_log(LOG_DEBUG, "Begin: parsing SIP \"Supported: %s\"\n", supported);
1094
1095         next = temp;
1096         while (next) {
1097                 char res=0;
1098                 if ( (sep = strchr(next, ',')) != NULL) {
1099                         *sep = '\0';
1100                         sep++;
1101                 }
1102                 while (*next == ' ')    /* Skip spaces */
1103                         next++;
1104                 if (option_debug > 2 && sipdebug)
1105                         ast_log(LOG_DEBUG, "Found SIP option: -%s-\n", next);
1106                 for (i=0; (i < (sizeof(sip_options) / sizeof(sip_options[0]))) && !res; i++) {
1107                         if (!strcasecmp(next, sip_options[i].text)) {
1108                                 profile |= sip_options[i].id;
1109                                 res = 1;
1110                                 if (option_debug > 2 && sipdebug)
1111                                         ast_log(LOG_DEBUG, "Matched SIP option: %s\n", next);
1112                         }
1113                 }
1114                 if (!res) 
1115                         if (option_debug > 2 && sipdebug)
1116                                 ast_log(LOG_DEBUG, "Found no match for SIP option: %s (Please file bug report!)\n", next);
1117                 next = sep;
1118         }
1119         if (pvt) {
1120                 pvt->sipoptions = profile;
1121                 if (option_debug)
1122                         ast_log(LOG_DEBUG, "* SIP extension value: %d for call %s\n", profile, pvt->callid);
1123         }
1124         return profile;
1125 }
1126
1127 /*! \brief See if we pass debug IP filter */
1128 static inline int sip_debug_test_addr(struct sockaddr_in *addr) 
1129 {
1130         if (!sipdebug)
1131                 return 0;
1132         if (debugaddr.sin_addr.s_addr) {
1133                 if (((ntohs(debugaddr.sin_port) != 0)
1134                         && (debugaddr.sin_port != addr->sin_port))
1135                         || (debugaddr.sin_addr.s_addr != addr->sin_addr.s_addr))
1136                         return 0;
1137         }
1138         return 1;
1139 }
1140
1141 /*! \brief Test PVT for debugging output */
1142 static inline int sip_debug_test_pvt(struct sip_pvt *p) 
1143 {
1144         if (!sipdebug)
1145                 return 0;
1146         return sip_debug_test_addr(ast_test_flag(&p->flags[0], SIP_NAT_ROUTE) ? &p->recv : &p->sa);
1147 }
1148
1149
1150 /*! \brief Transmit SIP message */
1151 static int __sip_xmit(struct sip_pvt *p, char *data, int len)
1152 {
1153         int res;
1154         char iabuf[INET_ADDRSTRLEN];
1155
1156         if (ast_test_flag(&p->flags[0], SIP_NAT_ROUTE))
1157                 res=sendto(sipsock, data, len, 0, (struct sockaddr *)&p->recv, sizeof(struct sockaddr_in));
1158         else
1159                 res=sendto(sipsock, data, len, 0, (struct sockaddr *)&p->sa, sizeof(struct sockaddr_in));
1160
1161         if (res != len) {
1162                 ast_log(LOG_WARNING, "sip_xmit of %p (len %d) to %s:%d returned %d: %s\n", data, len, ast_inet_ntoa(iabuf, sizeof(iabuf), p->sa.sin_addr), ntohs(p->sa.sin_port), res, strerror(errno));
1163         }
1164         return res;
1165 }
1166
1167
1168 /*! \brief Build a Via header for a request */
1169 static void build_via(struct sip_pvt *p)
1170 {
1171         char iabuf[INET_ADDRSTRLEN];
1172         /* Work around buggy UNIDEN UIP200 firmware */
1173         const char *rport = ast_test_flag(&p->flags[0], SIP_NAT) & SIP_NAT_RFC3581 ? ";rport" : "";
1174
1175         /* z9hG4bK is a magic cookie.  See RFC 3261 section 8.1.1.7 */
1176         ast_string_field_build(p, via, "SIP/2.0/UDP %s:%d;branch=z9hG4bK%08x%s",
1177                          ast_inet_ntoa(iabuf, sizeof(iabuf), p->ourip), ourport, p->branch, rport);
1178 }
1179
1180 /*! \brief NAT fix - decide which IP address to use for ASterisk server?
1181  * Only used for outbound registrations */
1182 static int ast_sip_ouraddrfor(struct in_addr *them, struct in_addr *us)
1183 {
1184         /*
1185          * Using the localaddr structure built up with localnet statements
1186          * apply it to their address to see if we need to substitute our
1187          * externip or can get away with our internal bindaddr
1188          */
1189         struct sockaddr_in theirs;
1190         theirs.sin_addr = *them;
1191
1192         if (localaddr && externip.sin_addr.s_addr &&
1193            ast_apply_ha(localaddr, &theirs)) {
1194                 if (externexpire && (time(NULL) >= externexpire)) {
1195                         struct ast_hostent ahp;
1196                         struct hostent *hp;
1197
1198                         time(&externexpire);
1199                         externexpire += externrefresh;
1200                         if ((hp = ast_gethostbyname(externhost, &ahp))) {
1201                                 memcpy(&externip.sin_addr, hp->h_addr, sizeof(externip.sin_addr));
1202                         } else
1203                                 ast_log(LOG_NOTICE, "Warning: Re-lookup of '%s' failed!\n", externhost);
1204                 }
1205                 memcpy(us, &externip.sin_addr, sizeof(struct in_addr));
1206                 if (option_debug) {
1207                         char iabuf[INET_ADDRSTRLEN];
1208                         ast_inet_ntoa(iabuf, sizeof(iabuf), *(struct in_addr *)&them->s_addr);
1209                 
1210                         ast_log(LOG_DEBUG, "Target address %s is not local, substituting externip\n", iabuf);
1211                 }
1212         } else if (bindaddr.sin_addr.s_addr)
1213                 memcpy(us, &bindaddr.sin_addr, sizeof(struct in_addr));
1214         else
1215                 return ast_ouraddrfor(them, us);
1216         return 0;
1217 }
1218
1219 /*! \brief Append to SIP dialog history 
1220         \return Always returns 0 */
1221 #define append_history(p, event, fmt , args... )        append_history_full(p, "%-15s " fmt, event, ## args)
1222
1223 static int append_history_full(struct sip_pvt *p, const char *fmt, ...)
1224         __attribute__ ((format (printf, 2, 3)));
1225
1226 /*! \brief Append to SIP dialog history with arg list  */
1227 static void append_history_va(struct sip_pvt *p, const char *fmt, va_list ap)
1228 {
1229         char buf[80], *c = buf; /* max history length */
1230         struct sip_history *hist;
1231         int l;
1232
1233         vsnprintf(buf, sizeof(buf), fmt, ap);
1234         strsep(&c, "\r\n"); /* Trim up everything after \r or \n */
1235         l = strlen(buf) + 1;
1236         if (!(hist = ast_calloc(1, sizeof(*hist) + l)))
1237                 return;
1238         if (!p->history && !(p->history = ast_calloc(1, sizeof(*p->history)))) {
1239                 free(hist);
1240                 return;
1241         }
1242         memcpy(hist->event, buf, l);
1243         AST_LIST_INSERT_TAIL(p->history, hist, list);
1244 }
1245
1246 /*! \brief Append to SIP dialog history with arg list  */
1247 static int append_history_full(struct sip_pvt *p, const char *fmt, ...)
1248 {
1249         va_list ap;
1250
1251         if (!recordhistory || !p)
1252                 return 0;
1253         va_start(ap, fmt);
1254         append_history_va(p, fmt, ap);
1255         va_end(ap);
1256
1257         return 0;
1258 }
1259
1260 /*! \brief Retransmit SIP message if no answer */
1261 static int retrans_pkt(void *data)
1262 {
1263         struct sip_pkt *pkt=data, *prev, *cur = NULL;
1264         char iabuf[INET_ADDRSTRLEN];
1265         int reschedule = DEFAULT_RETRANS;
1266
1267         /* Lock channel */
1268         ast_mutex_lock(&pkt->owner->lock);
1269
1270         if (pkt->retrans < MAX_RETRANS) {
1271                 pkt->retrans++;
1272                 if (!pkt->timer_t1) {   /* Re-schedule using timer_a and timer_t1 */
1273                         if (sipdebug && option_debug > 3)
1274                                 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);
1275                 } else {
1276                         int siptimer_a;
1277
1278                         if (sipdebug && option_debug > 3)
1279                                 ast_log(LOG_DEBUG, "SIP TIMER: Rescheduling retransmission #%d (%d) %s - %d\n", pkt->retransid, pkt->retrans, sip_methods[pkt->method].text, pkt->method);
1280                         if (!pkt->timer_a)
1281                                 pkt->timer_a = 2 ;
1282                         else
1283                                 pkt->timer_a = 2 * pkt->timer_a;
1284  
1285                         /* For non-invites, a maximum of 4 secs */
1286                         siptimer_a = pkt->timer_t1 * pkt->timer_a;      /* Double each time */
1287                         if (pkt->method != SIP_INVITE && siptimer_a > 4000)
1288                                 siptimer_a = 4000;
1289                 
1290                         /* Reschedule re-transmit */
1291                         reschedule = siptimer_a;
1292                         if (option_debug > 3)
1293                                 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);
1294                 } 
1295
1296                 if (pkt->owner && sip_debug_test_pvt(pkt->owner)) {
1297                         if (ast_test_flag(&pkt->owner->flags[0], SIP_NAT_ROUTE))
1298                                 ast_verbose("Retransmitting #%d (NAT) to %s:%d:\n%s\n---\n", pkt->retrans, ast_inet_ntoa(iabuf, sizeof(iabuf), pkt->owner->recv.sin_addr), ntohs(pkt->owner->recv.sin_port), pkt->data);
1299                         else
1300                                 ast_verbose("Retransmitting #%d (no NAT) to %s:%d:\n%s\n---\n", pkt->retrans, ast_inet_ntoa(iabuf, sizeof(iabuf), pkt->owner->sa.sin_addr), ntohs(pkt->owner->sa.sin_port), pkt->data);
1301                 }
1302
1303                 append_history(pkt->owner, "ReTx", "%d %s", reschedule, pkt->data);
1304                 __sip_xmit(pkt->owner, pkt->data, pkt->packetlen);
1305                 ast_mutex_unlock(&pkt->owner->lock);
1306                 return  reschedule;
1307         } 
1308         /* Too many retries */
1309         if (pkt->owner && pkt->method != SIP_OPTIONS) {
1310                 if (ast_test_flag(pkt, FLAG_FATAL) || sipdebug) /* Tell us if it's critical or if we're debugging */
1311                         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");
1312         } else {
1313                 if ((pkt->method == SIP_OPTIONS) && sipdebug)
1314                         ast_log(LOG_WARNING, "Cancelling retransmit of OPTIONs (call id %s) \n", pkt->owner->callid);
1315         }
1316         append_history(pkt->owner, "MaxRetries", "%s", (ast_test_flag(pkt, FLAG_FATAL)) ? "(Critical)" : "(Non-critical)");
1317                 
1318         pkt->retransid = -1;
1319
1320         if (ast_test_flag(pkt, FLAG_FATAL)) {
1321                 while(pkt->owner->owner && ast_mutex_trylock(&pkt->owner->owner->lock)) {
1322                         ast_mutex_unlock(&pkt->owner->lock);
1323                         usleep(1);
1324                         ast_mutex_lock(&pkt->owner->lock);
1325                 }
1326                 if (pkt->owner->owner) {
1327                         ast_set_flag(&pkt->owner->flags[0], SIP_ALREADYGONE);
1328                         ast_log(LOG_WARNING, "Hanging up call %s - no reply to our critical packet.\n", pkt->owner->callid);
1329                         ast_queue_hangup(pkt->owner->owner);
1330                         ast_mutex_unlock(&pkt->owner->owner->lock);
1331                 } else {
1332                         /* If no channel owner, destroy now */
1333                         ast_set_flag(&pkt->owner->flags[0], SIP_NEEDDESTROY);   
1334                 }
1335         }
1336         /* In any case, go ahead and remove the packet */
1337         prev = NULL;
1338         cur = pkt->owner->packets;
1339         while(cur) {
1340                 if (cur == pkt)
1341                         break;
1342                 prev = cur;
1343                 cur = cur->next;
1344         }
1345         if (cur) {
1346                 if (prev)
1347                         prev->next = cur->next;
1348                 else
1349                         pkt->owner->packets = cur->next;
1350                 ast_mutex_unlock(&pkt->owner->lock);
1351                 free(cur);
1352                 pkt = NULL;
1353         } else
1354                 ast_log(LOG_WARNING, "Weird, couldn't find packet owner!\n");
1355         if (pkt)
1356                 ast_mutex_unlock(&pkt->owner->lock);
1357         return 0;
1358 }
1359
1360 /*! \brief Transmit packet with retransmits 
1361         \return 0 on success, -1 on failure to allocate packet 
1362 */
1363 static int __sip_reliable_xmit(struct sip_pvt *p, int seqno, int resp, char *data, int len, int fatal, int sipmethod)
1364 {
1365         struct sip_pkt *pkt;
1366         int siptimer_a = DEFAULT_RETRANS;
1367
1368         if (!(pkt = ast_calloc(1, sizeof(*pkt) + len + 1)))
1369                 return -1;
1370         memcpy(pkt->data, data, len);
1371         pkt->method = sipmethod;
1372         pkt->packetlen = len;
1373         pkt->next = p->packets;
1374         pkt->owner = p;
1375         pkt->seqno = seqno;
1376         pkt->flags = resp;
1377         pkt->data[len] = '\0';
1378         pkt->timer_t1 = p->timer_t1;    /* Set SIP timer T1 */
1379         if (fatal)
1380                 ast_set_flag(pkt, FLAG_FATAL);
1381
1382         if (pkt->timer_t1)
1383                 siptimer_a = pkt->timer_t1 * 2;
1384
1385         /* Schedule retransmission */
1386         pkt->retransid = ast_sched_add_variable(sched, siptimer_a, retrans_pkt, pkt, 1);
1387         if (option_debug > 3 && sipdebug)
1388                 ast_log(LOG_DEBUG, "*** SIP TIMER: Initalizing retransmit timer on packet: Id  #%d\n", pkt->retransid);
1389         pkt->next = p->packets;
1390         p->packets = pkt;
1391
1392         __sip_xmit(pkt->owner, pkt->data, pkt->packetlen);      /* Send packet */
1393         if (sipmethod == SIP_INVITE) {
1394                 /* Note this is a pending invite */
1395                 p->pendinginvite = seqno;
1396         }
1397         return 0;
1398 }
1399
1400 /*! \brief Kill a SIP dialog (called by scheduler) */
1401 static int __sip_autodestruct(void *data)
1402 {
1403         struct sip_pvt *p = data;
1404
1405         /* If this is a subscription, tell the phone that we got a timeout */
1406         if (p->subscribed) {
1407                 p->subscribed = TIMEOUT;
1408                 transmit_state_notify(p, AST_EXTENSION_DEACTIVATED, 1); /* Send last notification */
1409                 p->subscribed = NONE;
1410                 append_history(p, "Subscribestatus", "timeout");
1411                 if (option_debug > 2)
1412                         ast_log(LOG_DEBUG, "Re-scheduled destruction of SIP subsription %s\n", p->callid ? p->callid : "<unknown>");
1413                 return 10000;   /* Reschedule this destruction so that we know that it's gone */
1414         }
1415
1416         /* Reset schedule ID */
1417         p->autokillid = -1;
1418
1419         if (option_debug)
1420                 ast_log(LOG_DEBUG, "Auto destroying call '%s'\n", p->callid);
1421         append_history(p, "AutoDestroy", "");
1422         if (p->owner) {
1423                 ast_log(LOG_WARNING, "Autodestruct on dialog '%s' with owner in place (Method: %s)\n", p->callid, sip_methods[p->method].text);
1424                 ast_queue_hangup(p->owner);
1425         } else {
1426                 sip_destroy(p);
1427         }
1428         return 0;
1429 }
1430
1431 /*! \brief Schedule destruction of SIP call */
1432 static int sip_scheddestroy(struct sip_pvt *p, int ms)
1433 {
1434         if (sip_debug_test_pvt(p))
1435                 ast_verbose("Scheduling destruction of SIP dialog '%s' in %d ms (Method: %s)\n", p->callid, ms, sip_methods[p->method].text);
1436         if (recordhistory)
1437                 append_history(p, "SchedDestroy", "%d ms", ms);
1438
1439         if (p->autokillid > -1)
1440                 ast_sched_del(sched, p->autokillid);
1441         p->autokillid = ast_sched_add(sched, ms, __sip_autodestruct, p);
1442         return 0;
1443 }
1444
1445 /*! \brief Cancel destruction of SIP dialog */
1446 static int sip_cancel_destroy(struct sip_pvt *p)
1447 {
1448         if (p->autokillid > -1)
1449                 ast_sched_del(sched, p->autokillid);
1450         append_history(p, "CancelDestroy", "");
1451         p->autokillid = -1;
1452         return 0;
1453 }
1454
1455 /*! \brief Acknowledges receipt of a packet and stops retransmission */
1456 static int __sip_ack(struct sip_pvt *p, int seqno, int resp, int sipmethod)
1457 {
1458         struct sip_pkt *cur, *prev = NULL;
1459         int res = -1;
1460
1461         /* Just in case... */
1462         char *msg;
1463
1464         msg = sip_methods[sipmethod].text;
1465
1466         ast_mutex_lock(&p->lock);
1467         cur = p->packets;
1468         while(cur) {
1469                 if ((cur->seqno == seqno) && ((ast_test_flag(cur, FLAG_RESPONSE)) == resp) &&
1470                         ((ast_test_flag(cur, FLAG_RESPONSE)) || 
1471                          (!strncasecmp(msg, cur->data, strlen(msg)) && (cur->data[strlen(msg)] < 33)))) {
1472                         if (!resp && (seqno == p->pendinginvite)) {
1473                                 ast_log(LOG_DEBUG, "Acked pending invite %d\n", p->pendinginvite);
1474                                 p->pendinginvite = 0;
1475                         }
1476                         /* this is our baby */
1477                         if (prev)
1478                                 prev->next = cur->next;
1479                         else
1480                                 p->packets = cur->next;
1481                         if (cur->retransid > -1) {
1482                                 if (sipdebug && option_debug > 3)
1483                                         ast_log(LOG_DEBUG, "** SIP TIMER: Cancelling retransmit of packet (reply received) Retransid #%d\n", cur->retransid);
1484                                 ast_sched_del(sched, cur->retransid);
1485                         }
1486                         free(cur);
1487                         res = 0;
1488                         break;
1489                 }
1490                 prev = cur;
1491                 cur = cur->next;
1492         }
1493         ast_mutex_unlock(&p->lock);
1494         if (option_debug)
1495                 ast_log(LOG_DEBUG, "Stopping retransmission on '%s' of %s %d: Match %s\n", p->callid, resp ? "Response" : "Request", seqno, res ? "Not Found" : "Found");
1496         return res;
1497 }
1498
1499 /*! \brief Pretend to ack all packets */
1500 static int __sip_pretend_ack(struct sip_pvt *p)
1501 {
1502         struct sip_pkt *cur=NULL;
1503
1504         while(p->packets) {
1505                 if (cur == p->packets) {
1506                         ast_log(LOG_WARNING, "Have a packet that doesn't want to give up! %s\n", sip_methods[cur->method].text);
1507                         return -1;
1508                 }
1509                 cur = p->packets;
1510                 if (cur->method)
1511                         __sip_ack(p, p->packets->seqno, (ast_test_flag(p->packets, FLAG_RESPONSE)), cur->method);
1512                 else {  /* Unknown packet type */
1513                         char *c;
1514                         char method[128];
1515
1516                         ast_copy_string(method, p->packets->data, sizeof(method));
1517                         c = ast_skip_blanks(method); /* XXX what ? */
1518                         *c = '\0';
1519                         __sip_ack(p, p->packets->seqno, (ast_test_flag(p->packets, FLAG_RESPONSE)), find_sip_method(method));
1520                 }
1521         }
1522         return 0;
1523 }
1524
1525 /*! \brief Acks receipt of packet, keep it around (used for provisional responses) */
1526 static int __sip_semi_ack(struct sip_pvt *p, int seqno, int resp, int sipmethod)
1527 {
1528         struct sip_pkt *cur;
1529         int res = -1;
1530         char *msg = sip_methods[sipmethod].text;
1531
1532         cur = p->packets;
1533         while(cur) {
1534                 if ((cur->seqno == seqno) && ((ast_test_flag(cur, FLAG_RESPONSE)) == resp) &&
1535                         ((ast_test_flag(cur, FLAG_RESPONSE)) || 
1536                          (!strncasecmp(msg, cur->data, strlen(msg)) && (cur->data[strlen(msg)] < 33)))) {
1537                         /* this is our baby */
1538                         if (cur->retransid > -1) {
1539                                 if (option_debug > 3 && sipdebug)
1540                                         ast_log(LOG_DEBUG, "*** SIP TIMER: Cancelling retransmission #%d - %s (got response)\n", cur->retransid, msg);
1541                                 ast_sched_del(sched, cur->retransid);
1542                         }
1543                         cur->retransid = -1;
1544                         res = 0;
1545                         break;
1546                 }
1547                 cur = cur->next;
1548         }
1549         if (option_debug)
1550                 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");
1551         return res;
1552 }
1553
1554
1555 /*! \brief Copy SIP request, parse it */
1556 static void parse_copy(struct sip_request *dst, struct sip_request *src)
1557 {
1558         memset(dst, 0, sizeof(*dst));
1559         memcpy(dst->data, src->data, sizeof(dst->data));
1560         dst->len = src->len;
1561         parse_request(dst);
1562 }
1563
1564 /*! \brief Transmit response on SIP request*/
1565 static int send_response(struct sip_pvt *p, struct sip_request *req, enum xmittype reliable, int seqno)
1566 {
1567         int res;
1568
1569         if (sip_debug_test_pvt(p)) {
1570                 char iabuf[INET_ADDRSTRLEN];
1571                 if (ast_test_flag(&p->flags[0], SIP_NAT_ROUTE))
1572                         ast_verbose("%sTransmitting (NAT) to %s:%d:\n%s\n---\n", reliable ? "Reliably " : "", ast_inet_ntoa(iabuf, sizeof(iabuf), p->recv.sin_addr), ntohs(p->recv.sin_port), req->data);
1573                 else
1574                         ast_verbose("%sTransmitting (no NAT) to %s:%d:\n%s\n---\n", reliable ? "Reliably " : "", ast_inet_ntoa(iabuf, sizeof(iabuf), p->sa.sin_addr), ntohs(p->sa.sin_port), req->data);
1575         }
1576         if (recordhistory) {
1577                 struct sip_request tmp;
1578                 parse_copy(&tmp, req);
1579                 append_history(p, reliable ? "TxRespRel" : "TxResp", "%s / %s", tmp.data, get_header(&tmp, "CSeq"));
1580         }
1581         res = (reliable) ?
1582                 __sip_reliable_xmit(p, seqno, 1, req->data, req->len, (reliable == XMIT_CRITICAL), req->method) :
1583                 __sip_xmit(p, req->data, req->len);
1584         if (res > 0)
1585                 return 0;
1586         return res;
1587 }
1588
1589 /*! \brief Send SIP Request to the other part of the dialogue */
1590 static int send_request(struct sip_pvt *p, struct sip_request *req, enum xmittype reliable, int seqno)
1591 {
1592         int res;
1593
1594         if (sip_debug_test_pvt(p)) {
1595                 char iabuf[INET_ADDRSTRLEN];
1596                 if (ast_test_flag(&p->flags[0], SIP_NAT_ROUTE))
1597                         ast_verbose("%sTransmitting (NAT) to %s:%d:\n%s\n---\n", reliable ? "Reliably " : "", ast_inet_ntoa(iabuf, sizeof(iabuf), p->recv.sin_addr), ntohs(p->recv.sin_port), req->data);
1598                 else
1599                         ast_verbose("%sTransmitting (no NAT) to %s:%d:\n%s\n---\n", reliable ? "Reliably " : "", ast_inet_ntoa(iabuf, sizeof(iabuf), p->sa.sin_addr), ntohs(p->sa.sin_port), req->data);
1600         }
1601         if (recordhistory) {
1602                 struct sip_request tmp;
1603                 parse_copy(&tmp, req);
1604                 append_history(p, reliable ? "TxReqRel" : "TxReq", "%s / %s", tmp.data, get_header(&tmp, "CSeq"));
1605         }
1606         res = (reliable) ?
1607                 __sip_reliable_xmit(p, seqno, 0, req->data, req->len, (reliable > 1), req->method) :
1608                 __sip_xmit(p, req->data, req->len);
1609         return res;
1610 }
1611
1612 /*! \brief Pick out text in brackets from character string
1613         \return pointer to terminated stripped string
1614         \param tmp input string that will be modified */
1615 static char *get_in_brackets(char *tmp)
1616 {
1617         char *parse;
1618         char *first_quote;
1619         char *first_bracket;
1620         char *second_bracket;
1621         char last_char;
1622
1623         parse = tmp;
1624         while (1) {
1625                 first_quote = strchr(parse, '"');
1626                 first_bracket = strchr(parse, '<');
1627                 if (first_quote && first_bracket && (first_quote < first_bracket)) {
1628                         last_char = '\0';
1629                         for (parse = first_quote + 1; *parse; parse++) {
1630                                 if ((*parse == '"') && (last_char != '\\'))
1631                                         break;
1632                                 last_char = *parse;
1633                         }
1634                         if (!*parse) {
1635                                 ast_log(LOG_WARNING, "No closing quote found in '%s'\n", tmp);
1636                                 return tmp;
1637                         }
1638                         parse++;
1639                         continue;
1640                 }
1641                 if (first_bracket) {
1642                         second_bracket = strchr(first_bracket + 1, '>');
1643                         if (second_bracket) {
1644                                 *second_bracket = '\0';
1645                                 return first_bracket + 1;
1646                         } else {
1647                                 ast_log(LOG_WARNING, "No closing bracket found in '%s'\n", tmp);
1648                                 return tmp;
1649                         }
1650                 }
1651                 return tmp;
1652         }
1653 }
1654
1655 /*! \brief Send SIP MESSAGE text within a call
1656         Called from PBX core sendtext() application */
1657 static int sip_sendtext(struct ast_channel *ast, const char *text)
1658 {
1659         struct sip_pvt *p = ast->tech_pvt;
1660         int debug = sip_debug_test_pvt(p);
1661
1662         if (debug)
1663                 ast_verbose("Sending text %s on %s\n", text, ast->name);
1664         if (!p)
1665                 return -1;
1666         if (ast_strlen_zero(text))
1667                 return 0;
1668         if (debug)
1669                 ast_verbose("Really sending text %s on %s\n", text, ast->name);
1670         transmit_message_with_text(p, text);
1671         return 0;       
1672 }
1673
1674 /*! \brief Update peer object in realtime storage */
1675 static void realtime_update_peer(const char *peername, struct sockaddr_in *sin, const char *username, const char *fullcontact, int expirey)
1676 {
1677         char port[10];
1678         char ipaddr[20];
1679         char regseconds[20];
1680         time_t nowtime;
1681         
1682         time(&nowtime);
1683         nowtime += expirey;
1684         snprintf(regseconds, sizeof(regseconds), "%d", (int)nowtime);   /* Expiration time */
1685         ast_inet_ntoa(ipaddr, sizeof(ipaddr), sin->sin_addr);
1686         snprintf(port, sizeof(port), "%d", ntohs(sin->sin_port));
1687         
1688         if (fullcontact)
1689                 ast_update_realtime("sippeers", "name", peername, "ipaddr", ipaddr, "port", port, "regseconds", regseconds, "username", username, "fullcontact", fullcontact, NULL);
1690         else
1691                 ast_update_realtime("sippeers", "name", peername, "ipaddr", ipaddr, "port", port, "regseconds", regseconds, "username", username, NULL);
1692 }
1693
1694 /*! \brief Automatically add peer extension to dial plan */
1695 static void register_peer_exten(struct sip_peer *peer, int onoff)
1696 {
1697         char multi[256];
1698         char *stringp, *ext;
1699         if (!ast_strlen_zero(global_regcontext)) {
1700
1701                 ast_copy_string(multi, S_OR(peer->regexten, peer->name), sizeof(multi));
1702                 stringp = multi;
1703                 while((ext = strsep(&stringp, "&"))) {
1704                         if (onoff)
1705                                 ast_add_extension(global_regcontext, 1, ext, 1, NULL, NULL, "Noop",
1706                                                   ast_strdup(peer->name), free, "SIP");
1707                         else
1708                                 ast_context_remove_extension(global_regcontext, ext, 1, NULL);
1709                 }
1710         }
1711 }
1712
1713 /*! \brief Destroy peer object from memory */
1714 static void sip_destroy_peer(struct sip_peer *peer)
1715 {
1716         if (option_debug > 2)
1717                 ast_log(LOG_DEBUG, "Destroying SIP peer %s\n", peer->name);
1718
1719         /* Delete it, it needs to disappear */
1720         if (peer->call)
1721                 sip_destroy(peer->call);
1722
1723         if (peer->mwipvt) {     /* We have an active subscription, delete it */
1724                 sip_destroy(peer->mwipvt);
1725         }
1726
1727         if (peer->chanvars) {
1728                 ast_variables_destroy(peer->chanvars);
1729                 peer->chanvars = NULL;
1730         }
1731         if (peer->expire > -1)
1732                 ast_sched_del(sched, peer->expire);
1733         if (peer->pokeexpire > -1)
1734                 ast_sched_del(sched, peer->pokeexpire);
1735         register_peer_exten(peer, FALSE);
1736         ast_free_ha(peer->ha);
1737         if (ast_test_flag(&peer->flags[1], SIP_PAGE2_SELFDESTRUCT))
1738                 apeerobjs--;
1739         else if (ast_test_flag(&peer->flags[0], SIP_REALTIME))
1740                 rpeerobjs--;
1741         else
1742                 speerobjs--;
1743         clear_realm_authentication(peer->auth);
1744         peer->auth = (struct sip_auth *) NULL;
1745         if (peer->dnsmgr)
1746                 ast_dnsmgr_release(peer->dnsmgr);
1747         free(peer);
1748 }
1749
1750 /*! \brief Update peer data in database (if used) */
1751 static void update_peer(struct sip_peer *p, int expiry)
1752 {
1753         int rtcachefriends = ast_test_flag(&p->flags[1], SIP_PAGE2_RTCACHEFRIENDS);
1754         if (ast_test_flag(&global_flags[1], SIP_PAGE2_RTUPDATE) &&
1755             (ast_test_flag(&p->flags[0], SIP_REALTIME) || rtcachefriends)) {
1756                 realtime_update_peer(p->name, &p->addr, p->username, rtcachefriends ? p->fullcontact : NULL, expiry);
1757         }
1758 }
1759
1760
1761 /*! \brief  realtime_peer: Get peer from realtime storage
1762  * Checks the "sippeers" realtime family from extconfig.conf 
1763  * \todo Consider adding check of port address when matching here to follow the same
1764  *      algorithm as for static peers. Will we break anything by adding that?
1765 */
1766 static struct sip_peer *realtime_peer(const char *peername, struct sockaddr_in *sin)
1767 {
1768         struct sip_peer *peer = NULL;
1769         struct ast_variable *var;
1770         struct ast_variable *tmp;
1771         char *newpeername = (char *) peername;
1772         char iabuf[80];
1773
1774         /* First check on peer name */
1775         if (newpeername) 
1776                 var = ast_load_realtime("sippeers", "name", peername, NULL);
1777         else if (sin) { /* Then check on IP address for dynamic peers */
1778                 ast_inet_ntoa(iabuf, sizeof(iabuf), sin->sin_addr);
1779                 var = ast_load_realtime("sippeers", "host", iabuf, NULL);       /* First check for fixed IP hosts */
1780                 if (!var)
1781                         var = ast_load_realtime("sippeers", "ipaddr", iabuf, NULL);     /* Then check for registred hosts */
1782         
1783         } else
1784                 return NULL;
1785
1786         if (!var)
1787                 return NULL;
1788
1789         for (tmp = var; tmp; tmp = tmp->next) {
1790                 /* If this is type=user, then skip this object. */
1791                 if (!strcasecmp(tmp->name, "type") &&
1792                     !strcasecmp(tmp->value, "user")) {
1793                         ast_variables_destroy(var);
1794                         return NULL;
1795                 } else if (!newpeername && !strcasecmp(tmp->name, "name")) {
1796                         newpeername = tmp->value;
1797                 }
1798         }
1799         
1800         if (!newpeername) {     /* Did not find peer in realtime */
1801                 ast_log(LOG_WARNING, "Cannot Determine peer name ip=%s\n", iabuf);
1802                 ast_variables_destroy(var);
1803                 return (struct sip_peer *) NULL;
1804         }
1805
1806         /* Peer found in realtime, now build it in memory */
1807         peer = build_peer(newpeername, var, !ast_test_flag(&global_flags[1], SIP_PAGE2_RTCACHEFRIENDS));
1808         if (!peer) {
1809                 ast_variables_destroy(var);
1810                 return (struct sip_peer *) NULL;
1811         }
1812
1813         if (ast_test_flag(&global_flags[1], SIP_PAGE2_RTCACHEFRIENDS)) {
1814                 /* Cache peer */
1815                 ast_copy_flags(&peer->flags[1],&global_flags[1], SIP_PAGE2_RTAUTOCLEAR|SIP_PAGE2_RTCACHEFRIENDS);
1816                 if (ast_test_flag(&global_flags[1], SIP_PAGE2_RTAUTOCLEAR)) {
1817                         if (peer->expire > -1) {
1818                                 ast_sched_del(sched, peer->expire);
1819                         }
1820                         peer->expire = ast_sched_add(sched, (global_rtautoclear) * 1000, expire_register, (void *)peer);
1821                 }
1822                 ASTOBJ_CONTAINER_LINK(&peerl,peer);
1823         } else {
1824                 ast_set_flag(&peer->flags[0], SIP_REALTIME);
1825         }
1826         ast_variables_destroy(var);
1827
1828         return peer;
1829 }
1830
1831 /*! \brief Support routine for find_peer */
1832 static int sip_addrcmp(char *name, struct sockaddr_in *sin)
1833 {
1834         /* We know name is the first field, so we can cast */
1835         struct sip_peer *p = (struct sip_peer *) name;
1836         return  !(!inaddrcmp(&p->addr, sin) || 
1837                                         (ast_test_flag(&p->flags[0], SIP_INSECURE_PORT) &&
1838                                         (p->addr.sin_addr.s_addr == sin->sin_addr.s_addr)));
1839 }
1840
1841 /*! \brief Locate peer by name or ip address 
1842  *      This is used on incoming SIP message to find matching peer on ip
1843         or outgoing message to find matching peer on name */
1844 static struct sip_peer *find_peer(const char *peer, struct sockaddr_in *sin, int realtime)
1845 {
1846         struct sip_peer *p = NULL;
1847
1848         if (peer)
1849                 p = ASTOBJ_CONTAINER_FIND(&peerl, peer);
1850         else
1851                 p = ASTOBJ_CONTAINER_FIND_FULL(&peerl, sin, name, sip_addr_hashfunc, 1, sip_addrcmp);
1852
1853         if (!p && realtime) {
1854                 p = realtime_peer(peer, sin);
1855         }
1856         return p;
1857 }
1858
1859 /*! \brief Remove user object from in-memory storage */
1860 static void sip_destroy_user(struct sip_user *user)
1861 {
1862         if (option_debug > 2)
1863                 ast_log(LOG_DEBUG, "Destroying user object from memory: %s\n", user->name);
1864         ast_free_ha(user->ha);
1865         if (user->chanvars) {
1866                 ast_variables_destroy(user->chanvars);
1867                 user->chanvars = NULL;
1868         }
1869         if (ast_test_flag(&user->flags[0], SIP_REALTIME))
1870                 ruserobjs--;
1871         else
1872                 suserobjs--;
1873         free(user);
1874 }
1875
1876 /*! \brief Load user from realtime storage
1877  * Loads user from "sipusers" category in realtime (extconfig.conf)
1878  * Users are matched on From: user name (the domain in skipped) */
1879 static struct sip_user *realtime_user(const char *username)
1880 {
1881         struct ast_variable *var;
1882         struct ast_variable *tmp;
1883         struct sip_user *user = NULL;
1884
1885         var = ast_load_realtime("sipusers", "name", username, NULL);
1886
1887         if (!var)
1888                 return NULL;
1889
1890         for (tmp = var; tmp; tmp = tmp->next) {
1891                 if (!strcasecmp(tmp->name, "type") &&
1892                         !strcasecmp(tmp->value, "peer")) {
1893                         ast_variables_destroy(var);
1894                         return NULL;
1895                 }
1896         }
1897
1898         user = build_user(username, var, !ast_test_flag(&global_flags[1], SIP_PAGE2_RTCACHEFRIENDS));
1899         
1900         if (!user) {    /* No user found */
1901                 ast_variables_destroy(var);
1902                 return NULL;
1903         }
1904
1905         if (ast_test_flag(&global_flags[1], SIP_PAGE2_RTCACHEFRIENDS)) {
1906                 ast_set_flag(&user->flags[1], SIP_PAGE2_RTCACHEFRIENDS);
1907                 suserobjs++;
1908                 ASTOBJ_CONTAINER_LINK(&userl,user);
1909         } else {
1910                 /* Move counter from s to r... */
1911                 suserobjs--;
1912                 ruserobjs++;
1913                 ast_set_flag(&user->flags[0], SIP_REALTIME);
1914         }
1915         ast_variables_destroy(var);
1916         return user;
1917 }
1918
1919 /*! \brief Locate user by name 
1920  * Locates user by name (From: sip uri user name part) first
1921  * from in-memory list (static configuration) then from 
1922  * realtime storage (defined in extconfig.conf) */
1923 static struct sip_user *find_user(const char *name, int realtime)
1924 {
1925         struct sip_user *u = NULL;
1926         u = ASTOBJ_CONTAINER_FIND(&userl,name);
1927         if (!u && realtime) {
1928                 u = realtime_user(name);
1929         }
1930         return u;
1931 }
1932
1933 /*! \brief Create address structure from peer reference */
1934 static int create_addr_from_peer(struct sip_pvt *r, struct sip_peer *peer)
1935 {
1936         if ((peer->addr.sin_addr.s_addr || peer->defaddr.sin_addr.s_addr) &&
1937             (!peer->maxms || ((peer->lastms >= 0)  && (peer->lastms <= peer->maxms)))) {
1938                 if (peer->addr.sin_addr.s_addr) {
1939                         r->sa.sin_family = peer->addr.sin_family;
1940                         r->sa.sin_addr = peer->addr.sin_addr;
1941                         r->sa.sin_port = peer->addr.sin_port;
1942                 } else {
1943                         r->sa.sin_family = peer->defaddr.sin_family;
1944                         r->sa.sin_addr = peer->defaddr.sin_addr;
1945                         r->sa.sin_port = peer->defaddr.sin_port;
1946                 }
1947                 memcpy(&r->recv, &r->sa, sizeof(r->recv));
1948         } else {
1949                 return -1;
1950         }
1951
1952         ast_copy_flags(&r->flags[0], &peer->flags[0], SIP_FLAGS_TO_COPY);
1953         ast_copy_flags(&r->flags[1], &peer->flags[1], SIP_PAGE2_FLAGS_TO_COPY);
1954         r->capability = peer->capability;
1955         if (!ast_test_flag(&r->flags[1], SIP_PAGE2_VIDEOSUPPORT) && r->vrtp) {
1956                 ast_rtp_destroy(r->vrtp);
1957                 r->vrtp = NULL;
1958         }
1959         r->prefs = peer->prefs;
1960         if (r->rtp) {
1961                 if (option_debug)
1962                         ast_log(LOG_DEBUG, "Setting NAT on RTP to %d\n", (ast_test_flag(&r->flags[0], SIP_NAT) & SIP_NAT_ROUTE));
1963                 ast_rtp_setnat(r->rtp, (ast_test_flag(&r->flags[0], SIP_NAT) & SIP_NAT_ROUTE));
1964         }
1965         if (r->vrtp) {
1966                 if (option_debug)
1967                         ast_log(LOG_DEBUG, "Setting NAT on VRTP to %d\n", (ast_test_flag(&r->flags[0], SIP_NAT) & SIP_NAT_ROUTE));
1968                 ast_rtp_setnat(r->vrtp, (ast_test_flag(&r->flags[0], SIP_NAT) & SIP_NAT_ROUTE));
1969         }
1970         ast_string_field_set(r, peername, peer->username);
1971         ast_string_field_set(r, authname, peer->username);
1972         ast_string_field_set(r, username, peer->username);
1973         ast_string_field_set(r, peersecret, peer->secret);
1974         ast_string_field_set(r, peermd5secret, peer->md5secret);
1975         ast_string_field_set(r, tohost, peer->tohost);
1976         ast_string_field_set(r, fullcontact, peer->fullcontact);
1977         if (!r->initreq.headers && !ast_strlen_zero(peer->fromdomain)) {
1978                 char *tmpcall;
1979                 char *c;
1980                 tmpcall = ast_strdupa(r->callid);
1981                 if (tmpcall) {
1982                         c = strchr(tmpcall, '@');
1983                         if (c) {
1984                                 *c = '\0';
1985                                 ast_string_field_build(r, callid, "%s@%s", tmpcall, peer->fromdomain);
1986                         }
1987                 }
1988         }
1989         if (ast_strlen_zero(r->tohost)) {
1990                 char iabuf[INET_ADDRSTRLEN];
1991
1992                 ast_inet_ntoa(iabuf, sizeof(iabuf),  peer->addr.sin_addr.s_addr ? peer->addr.sin_addr : peer->defaddr.sin_addr);
1993
1994                 ast_string_field_set(r, tohost, iabuf);
1995         }
1996         if (!ast_strlen_zero(peer->fromdomain))
1997                 ast_string_field_set(r, fromdomain, peer->fromdomain);
1998         if (!ast_strlen_zero(peer->fromuser))
1999                 ast_string_field_set(r, fromuser, peer->fromuser);
2000         r->maxtime = peer->maxms;
2001         r->callgroup = peer->callgroup;
2002         r->pickupgroup = peer->pickupgroup;
2003         /* Set timer T1 to RTT for this peer (if known by qualify=) */
2004         /* Minimum is settable or default to 100 ms */
2005         if (peer->maxms && peer->lastms)
2006                 r->timer_t1 = peer->lastms < global_t1min ? global_t1min : peer->lastms;
2007         if ((ast_test_flag(&r->flags[0], SIP_DTMF) == SIP_DTMF_RFC2833) ||
2008             (ast_test_flag(&r->flags[0], SIP_DTMF) == SIP_DTMF_AUTO))
2009                 r->noncodeccapability |= AST_RTP_DTMF;
2010         else
2011                 r->noncodeccapability &= ~AST_RTP_DTMF;
2012         ast_string_field_set(r, context, peer->context);
2013         r->rtptimeout = peer->rtptimeout;
2014         r->rtpholdtimeout = peer->rtpholdtimeout;
2015         r->rtpkeepalive = peer->rtpkeepalive;
2016         if (peer->call_limit)
2017                 ast_set_flag(&r->flags[0], SIP_CALL_LIMIT);
2018         r->maxcallbitrate = peer->maxcallbitrate;
2019         
2020         return 0;
2021 }
2022
2023 /*! \brief create address structure from peer name
2024  *      Or, if peer not found, find it in the global DNS 
2025  *      returns TRUE (-1) on failure, FALSE on success */
2026 static int create_addr(struct sip_pvt *dialog, const char *opeer)
2027 {
2028         struct hostent *hp;
2029         struct ast_hostent ahp;
2030         struct sip_peer *p;
2031         int found=0;
2032         char *port;
2033         int portno;
2034         char host[MAXHOSTNAMELEN], *hostn;
2035         char peer[256];
2036
2037         ast_copy_string(peer, opeer, sizeof(peer));
2038         port = strchr(peer, ':');
2039         if (port) {
2040                 *port = '\0';
2041                 port++;
2042         }
2043         dialog->sa.sin_family = AF_INET;
2044         dialog->timer_t1 = 500; /* Default SIP retransmission timer T1 (RFC 3261) */
2045         p = find_peer(peer, NULL, 1);
2046
2047         if (p) {
2048                 found++;
2049                 if (create_addr_from_peer(dialog, p))
2050                         ASTOBJ_UNREF(p, sip_destroy_peer);
2051         }
2052         if (!p) {
2053                 if (found)
2054                         return -1;
2055
2056                 hostn = peer;
2057                 if (port)
2058                         portno = atoi(port);
2059                 else
2060                         portno = DEFAULT_SIP_PORT;
2061                 if (srvlookup) {
2062                         char service[MAXHOSTNAMELEN];
2063                         int tportno;
2064                         int ret;
2065                         snprintf(service, sizeof(service), "_sip._udp.%s", peer);
2066                         ret = ast_get_srv(NULL, host, sizeof(host), &tportno, service);
2067                         if (ret > 0) {
2068                                 hostn = host;
2069                                 portno = tportno;
2070                         }
2071                 }
2072                 hp = ast_gethostbyname(hostn, &ahp);
2073                 if (hp) {
2074                         ast_string_field_set(dialog, tohost, peer);
2075                         memcpy(&dialog->sa.sin_addr, hp->h_addr, sizeof(dialog->sa.sin_addr));
2076                         dialog->sa.sin_port = htons(portno);
2077                         memcpy(&dialog->recv, &dialog->sa, sizeof(dialog->recv));
2078                         return 0;
2079                 } else {
2080                         ast_log(LOG_WARNING, "No such host: %s\n", peer);
2081                         return -1;
2082                 }
2083         } else {
2084                 ASTOBJ_UNREF(p, sip_destroy_peer);
2085                 return 0;
2086         }
2087 }
2088
2089 /*! \brief Scheduled congestion on a call */
2090 static int auto_congest(void *nothing)
2091 {
2092         struct sip_pvt *p = nothing;
2093
2094         ast_mutex_lock(&p->lock);
2095         p->initid = -1;
2096         if (p->owner) {
2097                 if (!ast_mutex_trylock(&p->owner->lock)) {
2098                         ast_log(LOG_NOTICE, "Auto-congesting %s\n", p->owner->name);
2099                         ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
2100                         ast_mutex_unlock(&p->owner->lock);
2101                 }
2102         }
2103         ast_mutex_unlock(&p->lock);
2104         return 0;
2105 }
2106
2107
2108
2109
2110 /*! \brief Initiate SIP call from PBX 
2111  *      used from the dial() application      */
2112 static int sip_call(struct ast_channel *ast, char *dest, int timeout)
2113 {
2114         int res;
2115         struct sip_pvt *p;
2116 #ifdef OSP_SUPPORT
2117         const char *osphandle = NULL;
2118 #endif  
2119         struct varshead *headp;
2120         struct ast_var_t *current;
2121         
2122         p = ast->tech_pvt;
2123         if ((ast->_state != AST_STATE_DOWN) && (ast->_state != AST_STATE_RESERVED)) {
2124                 ast_log(LOG_WARNING, "sip_call called on %s, neither down nor reserved\n", ast->name);
2125                 return -1;
2126         }
2127
2128         /* Check whether there is vxml_url, distinctive ring variables */
2129         headp=&ast->varshead;
2130         AST_LIST_TRAVERSE(headp,current,entries) {
2131                 /* Check whether there is a VXML_URL variable */
2132                 if (!p->options->vxml_url && !strcasecmp(ast_var_name(current), "VXML_URL")) {
2133                         p->options->vxml_url = ast_var_value(current);
2134                 } else if (!p->options->uri_options && !strcasecmp(ast_var_name(current), "SIP_URI_OPTIONS")) {
2135                         p->options->uri_options = ast_var_value(current);
2136                 } else if (!p->options->distinctive_ring && !strcasecmp(ast_var_name(current), "ALERT_INFO")) {
2137                         /* Check whether there is a ALERT_INFO variable */
2138                         p->options->distinctive_ring = ast_var_value(current);
2139                 } else if (!p->options->addsipheaders && !strncasecmp(ast_var_name(current), "SIPADDHEADER", strlen("SIPADDHEADER"))) {
2140                         /* Check whether there is a variable with a name starting with SIPADDHEADER */
2141                         p->options->addsipheaders = 1;
2142                 }
2143
2144                 
2145 #ifdef OSP_SUPPORT
2146                 else if (!p->options->osptoken && !strcasecmp(ast_var_name(current), "OSPTOKEN")) {
2147                         p->options->osptoken = ast_var_value(current);
2148                 } else if (!osphandle && !strcasecmp(ast_var_name(current), "OSPHANDLE")) {
2149                         osphandle = ast_var_value(current);
2150                 }
2151 #endif
2152         }
2153         
2154         res = 0;
2155         ast_set_flag(&p->flags[0], SIP_OUTGOING);
2156 #ifdef OSP_SUPPORT
2157         if (!p->options->osptoken || !osphandle || (sscanf(osphandle, "%d", &p->osphandle) != 1)) {
2158                 /* Force Disable OSP support */
2159                 if (option_debug)
2160                         ast_log(LOG_DEBUG, "Disabling OSP support for this call. osptoken = %s, osphandle = %s\n", p->options->osptoken, osphandle);
2161                 p->options->osptoken = NULL;
2162                 osphandle = NULL;
2163                 p->osphandle = -1;
2164         }
2165 #endif
2166         ast_log(LOG_DEBUG, "Outgoing Call for %s\n", p->username);
2167         res = update_call_counter(p, INC_CALL_LIMIT);
2168         if ( res != -1 ) {
2169                 p->callingpres = ast->cid.cid_pres;
2170                 p->jointcapability = p->capability;
2171                 transmit_invite(p, SIP_INVITE, 1, 2);
2172                 if (p->maxtime) {
2173                         /* Initialize auto-congest time */
2174                         p->initid = ast_sched_add(sched, p->maxtime * 4, auto_congest, p);
2175                 }
2176         }
2177         return res;
2178 }
2179
2180 /*! \brief Destroy registry object
2181         Objects created with the register= statement in static configuration */
2182 static void sip_registry_destroy(struct sip_registry *reg)
2183 {
2184         /* Really delete */
2185         if (option_debug > 2)
2186                 ast_log(LOG_DEBUG, "Destroying registry entry for %s@%s\n", reg->username, reg->hostname);
2187
2188         if (reg->call) {
2189                 /* Clear registry before destroying to ensure
2190                    we don't get reentered trying to grab the registry lock */
2191                 reg->call->registry = NULL;
2192                 if (option_debug > 2)
2193                         ast_log(LOG_DEBUG, "Destroying active SIP dialog for registry %s@%s\n", reg->username, reg->hostname);
2194                 sip_destroy(reg->call);
2195         }
2196         if (reg->expire > -1)
2197                 ast_sched_del(sched, reg->expire);
2198         if (reg->timeout > -1)
2199                 ast_sched_del(sched, reg->timeout);
2200         ast_string_field_free_all(reg);
2201         regobjs--;
2202         free(reg);
2203         
2204 }
2205
2206 /*! \brief Execute destrucion of SIP dialog structure, release memory */
2207 static void __sip_destroy(struct sip_pvt *p, int lockowner)
2208 {
2209         struct sip_pvt *cur, *prev = NULL;
2210         struct sip_pkt *cp;
2211
2212         if (sip_debug_test_pvt(p) || option_debug > 2)
2213                 ast_verbose("Really destroying SIP dialog '%s' Method: %s\n", p->callid, sip_methods[p->method].text);
2214
2215         /* Remove link from peer to subscription of MWI */
2216         if (p->relatedpeer && p->relatedpeer->mwipvt)
2217                 p->relatedpeer->mwipvt = (struct sip_pvt *) NULL;
2218
2219         if (dumphistory)
2220                 sip_dump_history(p);
2221
2222         if (p->options)
2223                 free(p->options);
2224
2225         if (p->stateid > -1)
2226                 ast_extension_state_del(p->stateid, NULL);
2227         if (p->initid > -1)
2228                 ast_sched_del(sched, p->initid);
2229         if (p->autokillid > -1)
2230                 ast_sched_del(sched, p->autokillid);
2231
2232         if (p->rtp) {
2233                 ast_rtp_destroy(p->rtp);
2234         }
2235         if (p->vrtp) {
2236                 ast_rtp_destroy(p->vrtp);
2237         }
2238         if (p->route) {
2239                 free_old_route(p->route);
2240                 p->route = NULL;
2241         }
2242         if (p->registry) {
2243                 if (p->registry->call == p)
2244                         p->registry->call = NULL;
2245                 ASTOBJ_UNREF(p->registry, sip_registry_destroy);
2246         }
2247
2248         /* Unlink us from the owner if we have one */
2249         if (p->owner) {
2250                 if (lockowner)
2251                         ast_mutex_lock(&p->owner->lock);
2252                 if (option_debug)
2253                         ast_log(LOG_DEBUG, "Detaching from %s\n", p->owner->name);
2254                 p->owner->tech_pvt = NULL;
2255                 if (lockowner)
2256                         ast_mutex_unlock(&p->owner->lock);
2257         }
2258         /* Clear history */
2259         if (p->history) {
2260                 while(!AST_LIST_EMPTY(p->history)) {
2261                         struct sip_history *hist = AST_LIST_FIRST(p->history);
2262                         AST_LIST_REMOVE_HEAD(p->history, list);
2263                         free(hist);
2264                 }
2265                 free(p->history);
2266                 p->history = NULL;
2267         }
2268
2269         cur = iflist;
2270         while(cur) {
2271                 if (cur == p) {
2272                         if (prev)
2273                                 prev->next = cur->next;
2274                         else
2275                                 iflist = cur->next;
2276                         break;
2277                 }
2278                 prev = cur;
2279                 cur = cur->next;
2280         }
2281         if (!cur) {
2282                 ast_log(LOG_WARNING, "Trying to destroy \"%s\", not found in dialog list?!?! \n", p->callid);
2283                 return;
2284         } 
2285         if (p->initid > -1)
2286                 ast_sched_del(sched, p->initid);
2287
2288         /* remove all current packets in this dialog */
2289         while((cp = p->packets)) {
2290                 p->packets = p->packets->next;
2291                 if (cp->retransid > -1) {
2292                         ast_sched_del(sched, cp->retransid);
2293                 }
2294                 free(cp);
2295         }
2296         if (p->chanvars) {
2297                 ast_variables_destroy(p->chanvars);
2298                 p->chanvars = NULL;
2299         }
2300         ast_mutex_destroy(&p->lock);
2301
2302         ast_string_field_free_all(p);
2303
2304         free(p);
2305 }
2306
2307 /*! \brief  update_call_counter: Handle call_limit for SIP users 
2308  * Setting a call-limit will cause calls above the limit not to be accepted.
2309  *
2310  * Remember that for a type=friend, there's one limit for the user and
2311  * another for the peer, not a combined call limit.
2312  * This will cause unexpected behaviour in subscriptions, since a "friend"
2313  * is *two* devices in Asterisk, not one.
2314  *
2315  * Thought: For realtime, we should propably update storage with inuse counter... 
2316  *
2317  * \return 0 if call is ok (no call limit, below treshold)
2318  *      -1 on rejection of call
2319  *              
2320  */
2321 static int update_call_counter(struct sip_pvt *fup, int event)
2322 {
2323         char name[256];
2324         int *inuse, *call_limit;
2325         int outgoing = ast_test_flag(&fup->flags[0], SIP_OUTGOING);
2326         struct sip_user *u = NULL;
2327         struct sip_peer *p = NULL;
2328
2329         if (option_debug > 2)
2330                 ast_log(LOG_DEBUG, "Updating call counter for %s call\n", outgoing ? "outgoing" : "incoming");
2331         /* Test if we need to check call limits, in order to avoid 
2332            realtime lookups if we do not need it */
2333         if (!ast_test_flag(&fup->flags[0], SIP_CALL_LIMIT))
2334                 return 0;
2335
2336         ast_copy_string(name, fup->username, sizeof(name));
2337
2338         /* Check the list of users */
2339         if (!outgoing)  /* Only check users for incoming calls */
2340                 u = find_user(name, 1);
2341
2342         if (u) {
2343                 inuse = &u->inUse;
2344                 call_limit = &u->call_limit;
2345                 p = NULL;
2346         } else {
2347                 /* Try to find peer */
2348                 if (!p)
2349                         p = find_peer(fup->peername, NULL, 1);
2350                 if (p) {
2351                         inuse = &p->inUse;
2352                         call_limit = &p->call_limit;
2353                         ast_copy_string(name, fup->peername, sizeof(name));
2354                 } else {
2355                         if (option_debug > 1)
2356                                 ast_log(LOG_DEBUG, "%s is not a local user, no call limit\n", name);
2357                         return 0;
2358                 }
2359         }
2360         switch(event) {
2361                 /* incoming and outgoing affects the inUse counter */
2362                 case DEC_CALL_LIMIT:
2363                         if ( *inuse > 0 ) {
2364                                 if (ast_test_flag(&fup->flags[0], SIP_INC_COUNT))
2365                                         (*inuse)--;
2366                         } else {
2367                                 *inuse = 0;
2368                         }
2369                         if (option_debug > 1 || sipdebug) {
2370                                 ast_log(LOG_DEBUG, "Call %s %s '%s' removed from call limit %d\n", outgoing ? "to" : "from", u ? "user":"peer", name, *call_limit);
2371                         }
2372                         break;
2373                 case INC_CALL_LIMIT:
2374                         if (*call_limit > 0 ) {
2375                                 if (*inuse >= *call_limit) {
2376                                         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);
2377                                         if (u)
2378                                                 ASTOBJ_UNREF(u, sip_destroy_user);
2379                                         else
2380                                                 ASTOBJ_UNREF(p, sip_destroy_peer);
2381                                         return -1; 
2382                                 }
2383                         }
2384                         (*inuse)++;
2385                         ast_set_flag(&fup->flags[0], SIP_INC_COUNT);
2386                         if (option_debug > 1 || sipdebug) {
2387                                 ast_log(LOG_DEBUG, "Call %s %s '%s' is %d out of %d\n", outgoing ? "to" : "from", u ? "user":"peer", name, *inuse, *call_limit);
2388                         }
2389                         break;
2390                 default:
2391                         ast_log(LOG_ERROR, "update_call_counter(%s, %d) called with no event!\n", name, event);
2392         }
2393         if (u)
2394                 ASTOBJ_UNREF(u, sip_destroy_user);
2395         else
2396                 ASTOBJ_UNREF(p, sip_destroy_peer);
2397         return 0;
2398 }
2399
2400 /*! \brief Destroy SIP call structure */
2401 static void sip_destroy(struct sip_pvt *p)
2402 {
2403         ast_mutex_lock(&iflock);
2404         if (option_debug > 2)
2405                 ast_log(LOG_DEBUG, "Destroying SIP dialog %s\n", p->callid);
2406         __sip_destroy(p, 1);
2407         ast_mutex_unlock(&iflock);
2408 }
2409
2410 /*! \brief Convert SIP hangup causes to Asterisk hangup causes */
2411 static int hangup_sip2cause(int cause)
2412 {
2413         /* Possible values taken from causes.h */
2414
2415         switch(cause) {
2416                 case 401:       /* Unauthorized */
2417                         return AST_CAUSE_CALL_REJECTED;
2418                 case 403:       /* Not found */
2419                         return AST_CAUSE_CALL_REJECTED;
2420                 case 404:       /* Not found */
2421                         return AST_CAUSE_UNALLOCATED;
2422                 case 405:       /* Method not allowed */
2423                         return AST_CAUSE_INTERWORKING;
2424                 case 407:       /* Proxy authentication required */
2425                         return AST_CAUSE_CALL_REJECTED;
2426                 case 408:       /* No reaction */
2427                         return AST_CAUSE_NO_USER_RESPONSE;
2428                 case 409:       /* Conflict */
2429                         return AST_CAUSE_NORMAL_TEMPORARY_FAILURE;
2430                 case 410:       /* Gone */
2431                         return AST_CAUSE_UNALLOCATED;
2432                 case 411:       /* Length required */
2433                         return AST_CAUSE_INTERWORKING;
2434                 case 413:       /* Request entity too large */
2435                         return AST_CAUSE_INTERWORKING;
2436                 case 414:       /* Request URI too large */
2437                         return AST_CAUSE_INTERWORKING;
2438                 case 415:       /* Unsupported media type */
2439                         return AST_CAUSE_INTERWORKING;
2440                 case 420:       /* Bad extension */
2441                         return AST_CAUSE_NO_ROUTE_DESTINATION;
2442                 case 480:       /* No answer */
2443                         return AST_CAUSE_FAILURE;
2444                 case 481:       /* No answer */
2445                         return AST_CAUSE_INTERWORKING;
2446                 case 482:       /* Loop detected */
2447                         return AST_CAUSE_INTERWORKING;
2448                 case 483:       /* Too many hops */
2449                         return AST_CAUSE_NO_ANSWER;
2450                 case 484:       /* Address incomplete */
2451                         return AST_CAUSE_INVALID_NUMBER_FORMAT;
2452                 case 485:       /* Ambigous */
2453                         return AST_CAUSE_UNALLOCATED;
2454                 case 486:       /* Busy everywhere */
2455                         return AST_CAUSE_BUSY;
2456                 case 487:       /* Request terminated */
2457                         return AST_CAUSE_INTERWORKING;
2458                 case 488:       /* No codecs approved */
2459                         return AST_CAUSE_BEARERCAPABILITY_NOTAVAIL;
2460                 case 491:       /* Request pending */
2461                         return AST_CAUSE_INTERWORKING;
2462                 case 493:       /* Undecipherable */
2463                         return AST_CAUSE_INTERWORKING;
2464                 case 500:       /* Server internal failure */
2465                         return AST_CAUSE_FAILURE;
2466                 case 501:       /* Call rejected */
2467                         return AST_CAUSE_FACILITY_REJECTED;
2468                 case 502:       
2469                         return AST_CAUSE_DESTINATION_OUT_OF_ORDER;
2470                 case 503:       /* Service unavailable */
2471                         return AST_CAUSE_CONGESTION;
2472                 case 504:       /* Gateway timeout */
2473                         return AST_CAUSE_RECOVERY_ON_TIMER_EXPIRE;
2474                 case 505:       /* SIP version not supported */
2475                         return AST_CAUSE_INTERWORKING;
2476                 case 600:       /* Busy everywhere */
2477                         return AST_CAUSE_USER_BUSY;
2478                 case 603:       /* Decline */
2479                         return AST_CAUSE_CALL_REJECTED;
2480                 case 604:       /* Does not exist anywhere */
2481                         return AST_CAUSE_UNALLOCATED;
2482                 case 606:       /* Not acceptable */
2483                         return AST_CAUSE_BEARERCAPABILITY_NOTAVAIL;
2484                 default:
2485                         return AST_CAUSE_NORMAL;
2486         }
2487         /* Never reached */
2488         return 0;
2489 }
2490
2491 /*! \brief Convert Asterisk hangup causes to SIP codes 
2492 \verbatim
2493  Possible values from causes.h
2494         AST_CAUSE_NOTDEFINED    AST_CAUSE_NORMAL        AST_CAUSE_BUSY
2495         AST_CAUSE_FAILURE       AST_CAUSE_CONGESTION    AST_CAUSE_UNALLOCATED
2496
2497         In addition to these, a lot of PRI codes is defined in causes.h 
2498         ...should we take care of them too ?
2499         
2500         Quote RFC 3398
2501
2502    ISUP Cause value                        SIP response
2503    ----------------                        ------------
2504    1  unallocated number                   404 Not Found
2505    2  no route to network                  404 Not found
2506    3  no route to destination              404 Not found
2507    16 normal call clearing                 --- (*)
2508    17 user busy                            486 Busy here
2509    18 no user responding                   408 Request Timeout
2510    19 no answer from the user              480 Temporarily unavailable
2511    20 subscriber absent                    480 Temporarily unavailable
2512    21 call rejected                        403 Forbidden (+)
2513    22 number changed (w/o diagnostic)      410 Gone
2514    22 number changed (w/ diagnostic)       301 Moved Permanently
2515    23 redirection to new destination       410 Gone
2516    26 non-selected user clearing           404 Not Found (=)
2517    27 destination out of order             502 Bad Gateway
2518    28 address incomplete                   484 Address incomplete
2519    29 facility rejected                    501 Not implemented
2520    31 normal unspecified                   480 Temporarily unavailable
2521 \endverbatim
2522 */
2523 static char *hangup_cause2sip(int cause)
2524 {
2525         switch(cause)
2526         {
2527                 case AST_CAUSE_UNALLOCATED:             /* 1 */
2528                 case AST_CAUSE_NO_ROUTE_DESTINATION:    /* 3 IAX2: Can't find extension in context */
2529                 case AST_CAUSE_NO_ROUTE_TRANSIT_NET:    /* 2 */
2530                         return "404 Not Found";
2531                 case AST_CAUSE_CONGESTION:              /* 34 */
2532                 case AST_CAUSE_SWITCH_CONGESTION:       /* 42 */
2533                         return "503 Service Unavailable";
2534                 case AST_CAUSE_NO_USER_RESPONSE:        /* 18 */
2535                         return "408 Request Timeout";
2536                 case AST_CAUSE_NO_ANSWER:               /* 19 */
2537                         return "480 Temporarily unavailable";
2538                 case AST_CAUSE_CALL_REJECTED:           /* 21 */
2539                         return "403 Forbidden";
2540                 case AST_CAUSE_NUMBER_CHANGED:          /* 22 */
2541                         return "410 Gone";
2542                 case AST_CAUSE_NORMAL_UNSPECIFIED:      /* 31 */
2543                         return "480 Temporarily unavailable";
2544                 case AST_CAUSE_INVALID_NUMBER_FORMAT:
2545                         return "484 Address incomplete";
2546                 case AST_CAUSE_USER_BUSY:
2547                         return "486 Busy here";
2548                 case AST_CAUSE_FAILURE:
2549                         return "500 Server internal failure";
2550                 case AST_CAUSE_FACILITY_REJECTED:       /* 29 */
2551                         return "501 Not Implemented";
2552                 case AST_CAUSE_CHAN_NOT_IMPLEMENTED:
2553                         return "503 Service Unavailable";
2554                 /* Used in chan_iax2 */
2555                 case AST_CAUSE_DESTINATION_OUT_OF_ORDER:
2556                         return "502 Bad Gateway";
2557                 case AST_CAUSE_BEARERCAPABILITY_NOTAVAIL:       /* Can't find codec to connect to host */
2558                         return "488 Not Acceptable Here";
2559                         
2560                 case AST_CAUSE_NOTDEFINED:
2561                 default:
2562                         ast_log(LOG_DEBUG, "AST hangup cause %d (no match found in SIP)\n", cause);
2563                         return NULL;
2564         }
2565
2566         /* Never reached */
2567         return 0;
2568 }
2569
2570
2571 /*! \brief  sip_hangup: Hangup SIP call
2572  * Part of PBX interface, called from ast_hangup */
2573 static int sip_hangup(struct ast_channel *ast)
2574 {
2575         struct sip_pvt *p = ast->tech_pvt;
2576         int needcancel = FALSE;
2577         struct ast_flags locflags = {0};
2578
2579         if (!p) {
2580                 ast_log(LOG_DEBUG, "Asked to hangup channel that was not connected\n");
2581                 return 0;
2582         }
2583         if (option_debug && sipdebug)
2584                 ast_log(LOG_DEBUG, "Hangup call %s, SIP callid %s)\n", ast->name, p->callid);
2585
2586         ast_mutex_lock(&p->lock);
2587 #ifdef OSP_SUPPORT
2588         if ((p->osphandle > -1) && (ast->_state == AST_STATE_UP)) {
2589                 ast_osp_terminate(p->osphandle, AST_CAUSE_NORMAL, p->ospstart, time(NULL) - p->ospstart);
2590         }
2591 #endif  
2592         if (option_debug && sipdebug)
2593                 ast_log(LOG_DEBUG, "update_call_counter(%s) - decrement call limit counter on hangup\n", p->username);
2594         update_call_counter(p, DEC_CALL_LIMIT);
2595         /* Determine how to disconnect */
2596         if (p->owner != ast) {
2597                 ast_log(LOG_WARNING, "Huh?  We aren't the owner? Can't hangup call.\n");
2598                 ast_mutex_unlock(&p->lock);
2599                 return 0;
2600         }
2601         /* If the call is not UP, we need to send CANCEL instead of BYE */
2602         if (ast->_state != AST_STATE_UP)
2603                 needcancel = TRUE;
2604
2605         /* Disconnect */
2606         p = ast->tech_pvt;
2607         if (p->vad)
2608                 ast_dsp_free(p->vad);
2609
2610         p->owner = NULL;
2611         ast->tech_pvt = NULL;
2612
2613         ast_mutex_lock(&usecnt_lock);
2614         usecnt--;
2615         ast_mutex_unlock(&usecnt_lock);
2616         ast_update_use_count();
2617
2618         ast_set_flag(&locflags, SIP_NEEDDESTROY);       
2619
2620         /* Start the process if it's not already started */
2621         if (!ast_test_flag(&p->flags[0], SIP_ALREADYGONE) && !ast_strlen_zero(p->initreq.data)) {
2622                 if (needcancel) {       /* Outgoing call, not up */
2623                         if (ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
2624                                 /* stop retransmitting an INVITE that has not received a response */
2625                                 __sip_pretend_ack(p);
2626
2627                                 /* Send a new request: CANCEL */
2628                                 transmit_request_with_auth(p, SIP_CANCEL, p->ocseq, XMIT_RELIABLE, 0);
2629                                 /* Actually don't destroy us yet, wait for the 487 on our original 
2630                                    INVITE, but do set an autodestruct just in case we never get it. */
2631                                 ast_clear_flag(&locflags, SIP_NEEDDESTROY);
2632
2633                                 sip_scheddestroy(p, 32000);
2634                                 if ( p->initid != -1 ) {
2635                                         /* channel still up - reverse dec of inUse counter
2636                                            only if the channel is not auto-congested */
2637                                         update_call_counter(p, INC_CALL_LIMIT);
2638                                 }
2639                         } else {        /* Incoming call, not up */
2640                                 char *res;
2641                                 if (ast->hangupcause && ((res = hangup_cause2sip(ast->hangupcause)))) {
2642                                         transmit_response_reliable(p, res, &p->initreq);
2643                                 } else 
2644                                         transmit_response_reliable(p, "603 Declined", &p->initreq);
2645                         }
2646                 } else {        /* Call is in UP state, send BYE */
2647                         if (!p->pendinginvite) {
2648                                 /* Send a hangup */
2649                                 transmit_request_with_auth(p, SIP_BYE, 0, XMIT_RELIABLE, 1);
2650                         } else {
2651                                 /* Note we will need a BYE when this all settles out
2652                                    but we can't send one while we have "INVITE" outstanding. */
2653                                 ast_set_flag(&p->flags[0], SIP_PENDINGBYE);     
2654                                 ast_clear_flag(&p->flags[0], SIP_NEEDREINVITE); 
2655                         }
2656                 }
2657         }
2658         ast_copy_flags(&p->flags[0], &locflags, SIP_NEEDDESTROY);       
2659         ast_mutex_unlock(&p->lock);
2660         return 0;
2661 }
2662
2663 /*! \brief Try setting codec suggested by the SIP_CODEC channel variable */
2664 static void try_suggested_sip_codec(struct sip_pvt *p)
2665 {
2666         int fmt;
2667         const char *codec;
2668
2669         codec = pbx_builtin_getvar_helper(p->owner, "SIP_CODEC");
2670         if (!codec) 
2671                 return;
2672
2673         fmt = ast_getformatbyname(codec);
2674         if (fmt) {
2675                 ast_log(LOG_NOTICE, "Changing codec to '%s' for this call because of ${SIP_CODEC) variable\n", codec);
2676                 if (p->jointcapability & fmt) {
2677                         p->jointcapability &= fmt;
2678                         p->capability &= fmt;
2679                 } else
2680                         ast_log(LOG_NOTICE, "Ignoring ${SIP_CODEC} variable because it is not shared by both ends.\n");
2681         } else
2682                 ast_log(LOG_NOTICE, "Ignoring ${SIP_CODEC} variable because of unrecognized/not configured codec (check allow/disallow in sip.conf): %s\n", codec);
2683         return; 
2684 }
2685
2686 /*! \brief  sip_answer: Answer SIP call , send 200 OK on Invite 
2687  * Part of PBX interface */
2688 static int sip_answer(struct ast_channel *ast)
2689 {
2690         int res = 0;
2691         struct sip_pvt *p = ast->tech_pvt;
2692
2693         ast_mutex_lock(&p->lock);
2694         if (ast->_state != AST_STATE_UP) {
2695 #ifdef OSP_SUPPORT      
2696                 time(&p->ospstart);
2697 #endif
2698                 try_suggested_sip_codec(p);     
2699
2700                 ast_setstate(ast, AST_STATE_UP);
2701                 if (option_debug)
2702                         ast_log(LOG_DEBUG, "SIP answering channel: %s\n", ast->name);
2703                 res = transmit_response_with_sdp(p, "200 OK", &p->initreq, XMIT_RELIABLE);
2704         }
2705         ast_mutex_unlock(&p->lock);
2706         return res;
2707 }
2708
2709 /*! \brief Send frame to media channel (rtp) */
2710 static int sip_write(struct ast_channel *ast, struct ast_frame *frame)
2711 {
2712         struct sip_pvt *p = ast->tech_pvt;
2713         int res = 0;
2714
2715         switch (frame->frametype) {
2716         case AST_FRAME_VOICE:
2717                 if (!(frame->subclass & ast->nativeformats)) {
2718                         ast_log(LOG_WARNING, "Asked to transmit frame type %d, while native formats is %d (read/write = %d/%d)\n",
2719                                 frame->subclass, ast->nativeformats, ast->readformat, ast->writeformat);
2720                         return 0;
2721                 }
2722                 if (p) {
2723                         ast_mutex_lock(&p->lock);
2724                         if (p->rtp) {
2725                                 /* If channel is not up, activate early media session */
2726                                 if ((ast->_state != AST_STATE_UP) &&
2727                                     !ast_test_flag(&p->flags[0], SIP_PROGRESS_SENT) &&
2728                                     !ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
2729                                         transmit_response_with_sdp(p, "183 Session Progress", &p->initreq, XMIT_UNRELIABLE);
2730                                         ast_set_flag(&p->flags[0], SIP_PROGRESS_SENT);  
2731                                 }
2732                                 time(&p->lastrtptx);
2733                                 res =  ast_rtp_write(p->rtp, frame);
2734                         }
2735                         ast_mutex_unlock(&p->lock);
2736                 }
2737                 break;
2738         case AST_FRAME_VIDEO:
2739                 if (p) {
2740                         ast_mutex_lock(&p->lock);
2741                         if (p->vrtp) {
2742                                 /* Activate video early media */
2743                                 if ((ast->_state != AST_STATE_UP) &&
2744                                     !ast_test_flag(&p->flags[0], SIP_PROGRESS_SENT) &&
2745                                     !ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
2746                                         transmit_response_with_sdp(p, "183 Session Progress", &p->initreq, XMIT_UNRELIABLE);
2747                                         ast_set_flag(&p->flags[0], SIP_PROGRESS_SENT);  
2748                                 }
2749                                 time(&p->lastrtptx);
2750                                 res =  ast_rtp_write(p->vrtp, frame);
2751                         }
2752                         ast_mutex_unlock(&p->lock);
2753                 }
2754                 break;
2755         case AST_FRAME_IMAGE:
2756                 return 0;
2757                 break;
2758         default: 
2759                 ast_log(LOG_WARNING, "Can't send %d type frames with SIP write\n", frame->frametype);
2760                 return 0;
2761         }
2762
2763         return res;
2764 }
2765
2766 /*! \brief  sip_fixup: Fix up a channel:  If a channel is consumed, this is called.
2767         Basically update any ->owner links */
2768 static int sip_fixup(struct ast_channel *oldchan, struct ast_channel *newchan)
2769 {
2770         struct sip_pvt *p = newchan->tech_pvt;
2771         ast_mutex_lock(&p->lock);
2772         if (p->owner != oldchan) {
2773                 ast_log(LOG_WARNING, "old channel wasn't %p but was %p\n", oldchan, p->owner);
2774                 ast_mutex_unlock(&p->lock);
2775                 return -1;
2776         }
2777         p->owner = newchan;
2778         ast_mutex_unlock(&p->lock);
2779         return 0;
2780 }
2781
2782 /*! \brief Send DTMF character on SIP channel
2783         within one call, we're able to transmit in many methods simultaneously */
2784 static int sip_senddigit(struct ast_channel *ast, char digit)
2785 {
2786         struct sip_pvt *p = ast->tech_pvt;
2787         int res = 0;
2788
2789         ast_mutex_lock(&p->lock);
2790         switch (ast_test_flag(&p->flags[0], SIP_DTMF)) {
2791         case SIP_DTMF_INFO:
2792                 transmit_info_with_digit(p, digit);
2793                 break;
2794         case SIP_DTMF_RFC2833:
2795                 if (p->rtp)
2796                         ast_rtp_senddigit(p->rtp, digit);
2797                 break;
2798         case SIP_DTMF_INBAND:
2799                 res = -1;
2800                 break;
2801         }
2802         ast_mutex_unlock(&p->lock);
2803         return res;
2804 }
2805
2806 /*! \brief Transfer SIP call */
2807 static int sip_transfer(struct ast_channel *ast, const char *dest)
2808 {
2809         struct sip_pvt *p = ast->tech_pvt;
2810         int res;
2811
2812         ast_mutex_lock(&p->lock);
2813         if (ast->_state == AST_STATE_RING)
2814                 res = sip_sipredirect(p, dest);
2815         else
2816                 res = transmit_refer(p, dest);
2817         ast_mutex_unlock(&p->lock);
2818         return res;
2819 }
2820
2821 /*! \brief Play indication to user 
2822  * With SIP a lot of indications is sent as messages, letting the device play
2823    the indication - busy signal, congestion etc 
2824    \return -1 to force ast_indicate to send indication in audio, 0 if SIP can handle the indication by sending a message
2825 */
2826 static int sip_indicate(struct ast_channel *ast, int condition)
2827 {
2828         struct sip_pvt *p = ast->tech_pvt;
2829         int res = 0;
2830
2831         ast_mutex_lock(&p->lock);
2832         switch(condition) {
2833         case AST_CONTROL_RINGING:
2834                 if (ast->_state == AST_STATE_RING) {
2835                         if (!ast_test_flag(&p->flags[0], SIP_PROGRESS_SENT) ||
2836                             (ast_test_flag(&p->flags[0], SIP_PROG_INBAND) == SIP_PROG_INBAND_NEVER)) {                          
2837                                 /* Send 180 ringing if out-of-band seems reasonable */
2838                                 transmit_response(p, "180 Ringing", &p->initreq);
2839                                 ast_set_flag(&p->flags[0], SIP_RINGING);
2840                                 if (ast_test_flag(&p->flags[0], SIP_PROG_INBAND) != SIP_PROG_INBAND_YES)
2841                                         break;
2842                         } else {
2843                                 /* Well, if it's not reasonable, just send in-band */
2844                         }
2845                 }
2846                 res = -1;
2847                 break;
2848         case AST_CONTROL_BUSY:
2849                 if (ast->_state != AST_STATE_UP) {
2850                         transmit_response(p, "486 Busy Here", &p->initreq);
2851                         ast_set_flag(&p->flags[0], SIP_ALREADYGONE);    
2852                         ast_softhangup_nolock(ast, AST_SOFTHANGUP_DEV);
2853                         break;
2854                 }
2855                 res = -1;
2856                 break;
2857         case AST_CONTROL_CONGESTION:
2858                 if (ast->_state != AST_STATE_UP) {
2859                         transmit_response(p, "503 Service Unavailable", &p->initreq);
2860                         ast_set_flag(&p->flags[0], SIP_ALREADYGONE);    
2861                         ast_softhangup_nolock(ast, AST_SOFTHANGUP_DEV);
2862                         break;
2863                 }
2864                 res = -1;
2865                 break;
2866         case AST_CONTROL_PROCEEDING:
2867                 if ((ast->_state != AST_STATE_UP) &&
2868                     !ast_test_flag(&p->flags[0], SIP_PROGRESS_SENT) &&
2869                     !ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
2870                         transmit_response(p, "100 Trying", &p->initreq);
2871                         break;
2872                 }
2873                 res = -1;
2874                 break;
2875         case AST_CONTROL_PROGRESS:
2876                 if ((ast->_state != AST_STATE_UP) &&
2877                     !ast_test_flag(&p->flags[0], SIP_PROGRESS_SENT) &&
2878                     !ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
2879                         transmit_response_with_sdp(p, "183 Session Progress", &p->initreq, XMIT_UNRELIABLE);
2880                         ast_set_flag(&p->flags[0], SIP_PROGRESS_SENT);  
2881                         break;
2882                 }
2883                 res = -1;
2884                 break;
2885         case AST_CONTROL_HOLD:  /* The other part of the bridge are put on hold */
2886                 if (sipdebug)
2887                         ast_log(LOG_DEBUG, "Bridged channel now on hold - %s\n", p->callid);
2888                 res = -1;
2889                 break;
2890         case AST_CONTROL_UNHOLD:        /* The other part of the bridge are back from hold */
2891                 if (sipdebug)
2892                         ast_log(LOG_DEBUG, "Bridged channel is back from hold, let's talk! : %s\n", p->callid);
2893                 res = -1;
2894                 break;
2895         case AST_CONTROL_VIDUPDATE:     /* Request a video frame update */
2896                 if (p->vrtp && !ast_test_flag(&p->flags[0], SIP_NOVIDEO)) {
2897                         transmit_info_with_vidupdate(p);
2898                         /* ast_rtcp_send_h261fur(p->vrtp); */
2899                         res = 0;
2900                 } else
2901                         res = -1;
2902                 break;
2903         case -1:
2904                 res = -1;
2905                 break;
2906         default:
2907                 ast_log(LOG_WARNING, "Don't know how to indicate condition %d\n", condition);
2908                 res = -1;
2909                 break;
2910         }
2911         ast_mutex_unlock(&p->lock);
2912         return res;
2913 }
2914
2915
2916
2917 /*! \brief Initiate a call in the SIP channel
2918         called from sip_request_call (calls from the pbx ) */
2919 static struct ast_channel *sip_new(struct sip_pvt *i, int state, const char *title)
2920 {
2921         struct ast_channel *tmp;
2922         struct ast_variable *v = NULL;
2923         int fmt;
2924         int what;
2925 #ifdef OSP_SUPPORT
2926         char iabuf[INET_ADDRSTRLEN];
2927         char peer[MAXHOSTNAMELEN];
2928 #endif  
2929         
2930         ast_mutex_unlock(&i->lock);
2931         /* Don't hold a sip pvt lock while we allocate a channel */
2932         tmp = ast_channel_alloc(1);
2933         ast_mutex_lock(&i->lock);
2934         if (!tmp) {
2935                 ast_log(LOG_WARNING, "Unable to allocate SIP channel structure\n");
2936                 return NULL;
2937         }
2938         tmp->tech = &sip_tech;
2939         /* Select our native format based on codec preference until we receive
2940            something from another device to the contrary. */
2941         if (i->jointcapability)
2942                 what = i->jointcapability;
2943         else if (i->capability)
2944                 what = i->capability;
2945         else
2946                 what = global_capability;
2947         tmp->nativeformats = ast_codec_choose(&i->prefs, what, 1) | (i->jointcapability & AST_FORMAT_VIDEO_MASK);
2948         fmt = ast_best_codec(tmp->nativeformats);
2949
2950         if (title)
2951                 ast_string_field_build(tmp, name, "SIP/%s-%04x", title, thread_safe_rand() & 0xffff);
2952         else if (strchr(i->fromdomain,':'))
2953                 ast_string_field_build(tmp, name, "SIP/%s-%08x", strchr(i->fromdomain,':')+1, (int)(long)(i));
2954         else
2955                 ast_string_field_build(tmp, name, "SIP/%s-%08x", i->fromdomain, (int)(long)(i));
2956
2957         if (ast_test_flag(&i->flags[0], SIP_DTMF) ==  SIP_DTMF_INBAND) {
2958                 i->vad = ast_dsp_new();
2959                 ast_dsp_set_features(i->vad, DSP_FEATURE_DTMF_DETECT);
2960                 if (global_relaxdtmf)
2961                         ast_dsp_digitmode(i->vad, DSP_DIGITMODE_DTMF | DSP_DIGITMODE_RELAXDTMF);
2962         }
2963         if (i->rtp) {
2964                 tmp->fds[0] = ast_rtp_fd(i->rtp);
2965                 tmp->fds[1] = ast_rtcp_fd(i->rtp);
2966         }
2967         if (i->vrtp) {
2968                 tmp->fds[2] = ast_rtp_fd(i->vrtp);
2969                 tmp->fds[3] = ast_rtcp_fd(i->vrtp);
2970         }
2971         if (state == AST_STATE_RING)
2972                 tmp->rings = 1;
2973         tmp->adsicpe = AST_ADSI_UNAVAILABLE;
2974         tmp->writeformat = fmt;
2975         tmp->rawwriteformat = fmt;
2976         tmp->readformat = fmt;
2977         tmp->rawreadformat = fmt;
2978         tmp->tech_pvt = i;
2979
2980         tmp->callgroup = i->callgroup;
2981         tmp->pickupgroup = i->pickupgroup;
2982         tmp->cid.cid_pres = i->callingpres;
2983         if (!ast_strlen_zero(i->accountcode))
2984                 ast_string_field_set(tmp, accountcode, i->accountcode);
2985         if (i->amaflags)
2986                 tmp->amaflags = i->amaflags;
2987         if (!ast_strlen_zero(i->language))
2988                 ast_string_field_set(tmp, language, i->language);
2989         if (!ast_strlen_zero(i->musicclass))
2990                 ast_string_field_set(tmp, musicclass, i->musicclass);
2991         i->owner = tmp;
2992         ast_mutex_lock(&usecnt_lock);
2993         usecnt++;
2994         ast_mutex_unlock(&usecnt_lock);
2995         ast_copy_string(tmp->context, i->context, sizeof(tmp->context));
2996         ast_copy_string(tmp->exten, i->exten, sizeof(tmp->exten));
2997         if (!ast_strlen_zero(i->cid_num)) 
2998                 tmp->cid.cid_num = ast_strdup(i->cid_num);
2999         if (!ast_strlen_zero(i->cid_name))
3000                 tmp->cid.cid_name = ast_strdup(i->cid_name);
3001         if (!ast_strlen_zero(i->rdnis))
3002                 tmp->cid.cid_rdnis = ast_strdup(i->rdnis);
3003         if (!ast_strlen_zero(i->exten) && strcmp(i->exten, "s"))
3004                 tmp->cid.cid_dnid = ast_strdup(i->exten);
3005         tmp->priority = 1;
3006         if (!ast_strlen_zero(i->uri)) {
3007                 pbx_builtin_setvar_helper(tmp, "SIPURI", i->uri);
3008         }
3009         if (!ast_strlen_zero(i->domain)) {
3010                 pbx_builtin_setvar_helper(tmp, "SIPDOMAIN", i->domain);
3011         }
3012         if (!ast_strlen_zero(i->useragent)) {
3013                 pbx_builtin_setvar_helper(tmp, "SIPUSERAGENT", i->useragent);
3014         }
3015         if (!ast_strlen_zero(i->callid)) {
3016                 pbx_builtin_setvar_helper(tmp, "SIPCALLID", i->callid);
3017         }
3018 #ifdef OSP_SUPPORT
3019         snprintf(peer, sizeof(peer), "[%s]:%d", ast_inet_ntoa(iabuf, sizeof(iabuf), i->sa.sin_addr), ntohs(i->sa.sin_port));
3020         pbx_builtin_setvar_helper(tmp, "OSPPEER", peer);
3021 #endif
3022         ast_setstate(tmp, state);
3023         if (state != AST_STATE_DOWN) {
3024                 if (ast_pbx_start(tmp)) {
3025                         ast_log(LOG_WARNING, "Unable to start PBX on %s\n", tmp->name);
3026                         tmp->hangupcause = AST_CAUSE_SWITCH_CONGESTION;
3027                         ast_hangup(tmp);
3028                         tmp = NULL;
3029                 }
3030         }
3031         /* Set channel variables for this call from configuration */
3032         for (v = i->chanvars ; v ; v = v->next)
3033                 pbx_builtin_setvar_helper(tmp,v->name,v->value);
3034                                 
3035         return tmp;
3036 }
3037
3038 /*! \brief Reads one line of SIP message body */
3039 static char* get_sdp_by_line(char* line, char *name, int nameLen)
3040 {
3041         if (strncasecmp(line, name, nameLen) == 0 && line[nameLen] == '=') {
3042                 return ast_skip_blanks(line + nameLen + 1);
3043         }
3044         return "";
3045 }
3046
3047 /*! \brief Gets all kind of SIP message bodies, including SDP,
3048    but the name wrongly applies _only_ sdp */
3049 static char *get_sdp(struct sip_request *req, char *name) 
3050 {
3051         int x;
3052         int len = strlen(name);
3053         char *r;
3054
3055         for (x = 0; x < req->lines; x++) {
3056                 r = get_sdp_by_line(req->line[x], name, len);
3057                 if (r[0] != '\0')
3058                         return r;
3059         }
3060         return "";
3061 }
3062
3063
3064 static void sdpLineNum_iterator_init(int* iterator) 
3065 {
3066         *iterator = 0;
3067 }
3068
3069 static char* get_sdp_iterate(int* iterator,
3070                              struct sip_request *req, char *name)
3071 {
3072         int len = strlen(name);
3073         char *r;
3074
3075         while (*iterator < req->lines) {
3076                 r = get_sdp_by_line(req->line[(*iterator)++], name, len);
3077                 if (r[0] != '\0')
3078                         return r;
3079         }
3080         return "";
3081 }
3082
3083 static char *find_alias(const char *name, char *_default)
3084 {
3085         int x;
3086         for (x=0;x<sizeof(aliases) / sizeof(aliases[0]); x++) 
3087                 if (!strcasecmp(aliases[x].fullname, name))
3088                         return aliases[x].shortname;
3089         return _default;
3090 }
3091
3092 static char *__get_header(struct sip_request *req, const char *name, int *start)
3093 {
3094         int pass;
3095
3096         /*
3097          * Technically you can place arbitrary whitespace both before and after the ':' in
3098          * a header, although RFC3261 clearly says you shouldn't before, and place just
3099          * one afterwards.  If you shouldn't do it, what absolute idiot decided it was 
3100          * a good idea to say you can do it, and if you can do it, why in the hell would.
3101          * you say you shouldn't.
3102          * Anyways, pedanticsipchecking controls whether we allow spaces before ':',
3103          * and we always allow spaces after that for compatibility.
3104          */
3105         for (pass = 0; name && pass < 2;pass++) {
3106                 int x, len = strlen(name);
3107                 for (x=*start; x<req->headers; x++) {
3108                         if (!strncasecmp(req->header[x], name, len)) {
3109                                 char *r = req->header[x] + len; /* skip name */
3110                                 if (pedanticsipchecking)
3111                                         r = ast_skip_blanks(r);
3112
3113                                 if (*r == ':') {
3114                                         *start = x+1;
3115                                         return ast_skip_blanks(r+1);
3116                                 }
3117                         }
3118                 }
3119                 if (pass == 0) /* Try aliases */
3120                         name = find_alias(name, NULL);
3121         }
3122
3123         /* Don't return NULL, so get_header is always a valid pointer */
3124         return "";
3125 }
3126
3127 /*! \brief Get header from SIP request */
3128 static char *get_header(struct sip_request *req, const char *name)
3129 {
3130         int start = 0;
3131         return __get_header(req, name, &start);
3132 }
3133
3134 /*! \brief Read RTP from network */
3135 static struct ast_frame *sip_rtp_read(struct ast_channel *ast, struct sip_pvt *p)
3136 {
3137         /* Retrieve audio/etc from channel.  Assumes p->lock is already held. */
3138         struct ast_frame *f;
3139         
3140         if (!p->rtp) {
3141                 /* We have no RTP allocated for this channel */
3142                 return &ast_null_frame;
3143         }
3144
3145         switch(ast->fdno) {
3146         case 0:
3147                 f = ast_rtp_read(p->rtp);       /* RTP Audio */
3148                 break;
3149         case 1:
3150                 f = ast_rtcp_read(p->rtp);      /* RTCP Control Channel */
3151                 break;
3152         case 2:
3153                 f = ast_rtp_read(p->vrtp);      /* RTP Video */
3154                 break;
3155         case 3:
3156                 f = ast_rtcp_read(p->vrtp);     /* RTCP Control Channel for video */
3157                 break;
3158         default:
3159                 f = &ast_null_frame;
3160         }
3161         /* Don't forward RFC2833 if we're not supposed to */
3162         if (f && (f->frametype == AST_FRAME_DTMF) &&
3163             (ast_test_flag(&p->flags[0], SIP_DTMF) != SIP_DTMF_RFC2833))
3164                 return &ast_null_frame;
3165
3166         if (p->owner) {
3167                 /* We already hold the channel lock */
3168                 if (f->frametype == AST_FRAME_VOICE) {
3169                         if (f->subclass != (p->owner->nativeformats & AST_FORMAT_AUDIO_MASK)) {
3170                                 if (option_debug)
3171                                         ast_log(LOG_DEBUG, "Oooh, format changed to %d\n", f->subclass);
3172                                 p->owner->nativeformats = (p->owner->nativeformats & AST_FORMAT_VIDEO_MASK) | f->subclass;
3173                                 ast_set_read_format(p->owner, p->owner->readformat);
3174                                 ast_set_write_format(p->owner, p->owner->writeformat);
3175                         }
3176                         if ((ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_INBAND) && p->vad) {
3177                                 f = ast_dsp_process(p->owner, p->vad, f);
3178                                 if (option_debug && f && (f->frametype == AST_FRAME_DTMF)) 
3179                                         ast_log(LOG_DEBUG, "* Detected inband DTMF '%c'\n", f->subclass);
3180                         }
3181                 }
3182         }
3183         return f;
3184 }
3185
3186 /*! \brief Read SIP RTP from channel */
3187 static struct ast_frame *sip_read(struct ast_channel *ast)
3188 {
3189         struct ast_frame *fr;
3190         struct sip_pvt *p = ast->tech_pvt;
3191
3192         ast_mutex_lock(&p->lock);
3193         fr = sip_rtp_read(ast, p);
3194         time(&p->lastrtprx);
3195         ast_mutex_unlock(&p->lock);
3196         return fr;
3197 }
3198
3199
3200 /*! \brief Generate 32 byte random string for callid's etc */
3201 static char *generate_random_string(char *buf, size_t size)
3202 {
3203         int val[4];
3204         int x;
3205
3206         for (x=0; x<4; x++)
3207                 val[x] = thread_safe_rand();
3208         snprintf(buf, size, "%08x%08x%08x%08x", val[0], val[1], val[2], val[3]);
3209
3210         return buf;
3211 }
3212
3213 /*! \brief Build SIP Call-ID value for a non-REGISTER transaction */
3214 static void build_callid_pvt(struct sip_pvt *pvt)
3215 {
3216         char iabuf[INET_ADDRSTRLEN];
3217         char buf[33];
3218
3219         const char *host = S_OR(pvt->fromdomain, ast_inet_ntoa(iabuf, sizeof(iabuf), pvt->ourip));
3220         
3221         ast_string_field_build(pvt, callid, "%s@%s", generate_random_string(buf, sizeof(buf)), host);
3222
3223 }
3224
3225 /*! \brief Build SIP Call-ID value for a REGISTER transaction */
3226 static void build_callid_registry(struct sip_registry *reg, struct in_addr ourip, const char *fromdomain)
3227 {
3228         char iabuf[INET_ADDRSTRLEN];
3229         char buf[33];
3230
3231         const char *host = S_OR(fromdomain, ast_inet_ntoa(iabuf, sizeof(iabuf), ourip));
3232
3233         ast_string_field_build(reg, callid, "%s@%s", generate_random_string(buf, sizeof(buf)), host);
3234 }
3235
3236 /*! \brief Make our SIP dialog tag */
3237 static void make_our_tag(char *tagbuf, size_t len)
3238 {
3239         snprintf(tagbuf, len, "as%08x", thread_safe_rand());
3240 }
3241
3242 /*! \brief Allocate SIP_PVT structure and set defaults */
3243 static struct sip_pvt *sip_alloc(ast_string_field callid, struct sockaddr_in *sin,
3244                                  int useglobal_nat, const int intended_method)
3245 {
3246         struct sip_pvt *p;
3247
3248         if (!(p = ast_calloc(1, sizeof(*p))))
3249                 return NULL;
3250
3251         if (ast_string_field_init(p, 512)) {
3252                 free(p);
3253                 return NULL;
3254         }
3255
3256         ast_mutex_init(&p->lock);
3257
3258         p->method = intended_method;
3259         p->initid = -1;
3260         p->autokillid = -1;
3261         p->subscribed = NONE;
3262         p->stateid = -1;
3263         p->prefs = default_prefs;               /* Set default codecs for this call */
3264
3265         if (intended_method != SIP_OPTIONS)     /* Peerpoke has it's own system */
3266                 p->timer_t1 = 500;      /* Default SIP retransmission timer T1 (RFC 3261) */
3267 #ifdef OSP_SUPPORT
3268         p->osphandle = -1;
3269         p->osptimelimit = 0;
3270 #endif  
3271         if (sin) {
3272                 memcpy(&p->sa, sin, sizeof(p->sa));
3273                 if (ast_sip_ouraddrfor(&p->sa.sin_addr,&p->ourip))
3274                         memcpy(&p->ourip, &__ourip, sizeof(p->ourip));
3275         } else {
3276                 memcpy(&p->ourip, &__ourip, sizeof(p->ourip));
3277         }
3278         
3279         ast_copy_flags(&p->flags[0], &global_flags[0], SIP_FLAGS_TO_COPY);
3280         ast_copy_flags(&p->flags[1], &global_flags[1], SIP_PAGE2_FLAGS_TO_COPY);
3281
3282         p->branch = thread_safe_rand(); 
3283         make_our_tag(p->tag, sizeof(p->tag));
3284         /* Start with 101 instead of 1 */
3285         p->ocseq = 101;
3286
3287         if (sip_methods[intended_method].need_rtp) {
3288                 p->rtp = ast_rtp_new_with_bindaddr(sched, io, 1, 0, bindaddr.sin_addr);
3289                 if (ast_test_flag(&p->flags[1], SIP_PAGE2_VIDEOSUPPORT))
3290                         p->vrtp = ast_rtp_new_with_bindaddr(sched, io, 1, 0, bindaddr.sin_addr);
3291                 if (!p->rtp || (ast_test_flag(&p->flags[1], SIP_PAGE2_VIDEOSUPPORT) && !p->vrtp)) {
3292                         ast_log(LOG_WARNING, "Unable to create RTP audio %s session: %s\n",
3293                                 ast_test_flag(&p->flags[1], SIP_PAGE2_VIDEOSUPPORT) ? "and video" : "", strerror(errno));
3294                         ast_mutex_destroy(&p->lock);
3295                         if (p->chanvars) {
3296                                 ast_variables_destroy(p->chanvars);
3297                                 p->chanvars = NULL;
3298                         }
3299                         free(p);
3300                         return NULL;
3301                 }
3302                 ast_rtp_settos(p->rtp, global_tos_audio);
3303                 if (p->vrtp)
3304                         ast_rtp_settos(p->vrtp, global_tos_video);
3305                 p->rtptimeout = global_rtptimeout;
3306                 p->rtpholdtimeout = global_rtpholdtimeout;
3307                 p->rtpkeepalive = global_rtpkeepalive;
3308                 p->maxcallbitrate = default_maxcallbitrate;
3309         }
3310
3311         if (useglobal_nat && sin) {
3312                 /* Setup NAT structure according to global settings if we have an address */
3313                 ast_copy_flags(&p->flags[0], &global_flags[0], SIP_NAT);
3314                 memcpy(&p->recv, sin, sizeof(p->recv));
3315                 if (p->rtp)
3316                         ast_rtp_setnat(p->rtp, ast_test_flag(&p->flags[0], SIP_NAT_ROUTE));
3317                 if (p->vrtp)
3318                         ast_rtp_setnat(p->vrtp, ast_test_flag(&p->flags[0], SIP_NAT_ROUTE));
3319         }
3320
3321         if (p->method != SIP_REGISTER)
3322                 ast_string_field_set(p, fromdomain, default_fromdomain);
3323         build_via(p);
3324         if (!callid)
3325                 build_callid_pvt(p);
3326         else
3327                 ast_string_field_set(p, callid, callid);
3328         /* Assign default music on hold class */
3329         ast_string_field_set(p, musicclass, default_musicclass);
3330         p->capability = global_capability;
3331         if ((ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_RFC2833) ||
3332             (ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_AUTO))
3333                 p->noncodeccapability |= AST_RTP_DTMF;
3334         ast_string_field_set(p, context, default_context);
3335
3336         /* Add to active dialog list */
3337         ast_mutex_lock(&iflock);
3338         p->next = iflist;
3339         iflist = p;
3340         ast_mutex_unlock(&iflock);
3341         if (option_debug)
3342                 ast_log(LOG_DEBUG, "Allocating new SIP dialog for %s - %s (%s)\n", callid ? callid : "(No Call-ID)", sip_methods[intended_method].text, p->rtp ? "With RTP" : "No RTP");
3343         return p;
3344 }
3345
3346 /*! \brief Connect incoming SIP message to current dialog or create new dialog structure
3347         Called by handle_request, sipsock_read */
3348 static struct sip_pvt *find_call(struct sip_request *req, struct sockaddr_in *sin, const int intended_method)
3349 {
3350         struct sip_pvt *p;
3351         char *callid;
3352         char *tag = "";
3353         char totag[128];
3354         char fromtag[128];
3355
3356         callid = get_header(req, "Call-ID");
3357
3358         if (pedanticsipchecking) {
3359                 /* In principle Call-ID's uniquely identify a call, but with a forking SIP proxy
3360                    we need more to identify a branch - so we have to check branch, from
3361                    and to tags to identify a call leg.
3362                    For Asterisk to behave correctly, you need to turn on pedanticsipchecking
3363                    in sip.conf
3364                    */
3365                 if (gettag(req, "To", totag, sizeof(totag)))
3366                         ast_set_flag(req, SIP_PKT_WITH_TOTAG);  /* Used in handle_request/response */
3367                 gettag(req, "From", fromtag, sizeof(fromtag));
3368
3369                 if (req->method == SIP_RESPONSE)
3370                         tag = totag;
3371                 else
3372                         tag = fromtag;
3373                         
3374
3375                 if (option_debug > 4 )
3376                         ast_log(LOG_DEBUG, "= Looking for  Call ID: %s (Checking %s) --From tag %s --To-tag %s  \n", callid, req->method==SIP_RESPONSE ? "To" : "From", fromtag, totag);
3377         }
3378
3379         ast_mutex_lock(&iflock);
3380         p = iflist;
3381         while(p) {      /* In pedantic, we do not want packets with bad syntax to be connected to a PVT */
3382                 int found = FALSE;
3383                 if (req->method == SIP_REGISTER)
3384                         found = (!strcmp(p->callid, callid));
3385                 else 
3386                         found = (!strcmp(p->callid, callid) && 
3387                         (!pedanticsipchecking || !tag || ast_strlen_zero(p->theirtag) || !strcmp(p->theirtag, tag))) ;
3388
3389                 if (option_debug > 4)
3390                         ast_log(LOG_DEBUG, "= %s Their Call ID: %s Their Tag %s Our tag: %s\n", found ? "Found" : "No match", p->callid, p->theirtag, p->tag);
3391
3392                 /* If we get a new request within an existing to-tag - check the to tag as well */
3393                 if (pedanticsipchecking && found  && req->method != SIP_RESPONSE) {     /* SIP Request */
3394                         if (p->tag[0] == '\0' && totag[0]) {
3395                                 /* We have no to tag, but they have. Wrong dialog */
3396                                 found = FALSE;
3397                         } else if (totag[0]) {                  /* Both have tags, compare them */
3398                                 if (strcmp(totag, p->tag)) {
3399                                         found = FALSE;          /* This is not our packet */
3400                                 }
3401                         }
3402                         if (!found && option_debug > 4)
3403                                 ast_log(LOG_DEBUG, "= Being pedantic: This is not our match on request: Call ID: %s Ourtag <null> Totag %s Method %s\n", p->callid, totag, sip_methods[req->method].text);
3404                 }
3405
3406
3407                 if (found) {
3408                         /* Found the call */
3409                         ast_mutex_lock(&p->lock);
3410                         ast_mutex_unlock(&iflock);
3411                         return p;
3412                 }
3413                 p = p->next;
3414         }
3415         ast_mutex_unlock(&iflock);
3416         p = sip_alloc(callid, sin, 1, intended_method);
3417         if (p)
3418                 ast_mutex_lock(&p->lock);
3419         return p;
3420 }
3421
3422 /*! \brief Parse register=> line in sip.conf and add to registry */
3423 static int sip_register(char *value, int lineno)
3424 {
3425         struct sip_registry *reg;
3426         char copy[256];
3427         char *username=NULL, *hostname=NULL, *secret=NULL, *authuser=NULL;
3428         char *porta=NULL;
3429         char *contact=NULL;
3430         char *stringp=NULL;
3431         
3432         if (!value)
3433                 return -1;
3434         ast_copy_string(copy, value, sizeof(copy));
3435         stringp=copy;
3436         username = stringp;
3437         hostname = strrchr(stringp, '@');
3438         if (hostname) {
3439                 *hostname = '\0';
3440                 hostname++;
3441         }
3442         if (ast_strlen_zero(username) || ast_strlen_zero(hostname)) {
3443                 ast_log(LOG_WARNING, "Format for registration is user[:secret[:authuser]]@host[:port][/contact] at line %d\n", lineno);
3444                 return -1;
3445         }
3446         stringp = username;
3447         username = strsep(&stringp, ":");
3448         if (username) {
3449                 secret = strsep(&stringp, ":");
3450                 if (secret) 
3451                         authuser = strsep(&stringp, ":");
3452         }
3453         stringp = hostname;
3454         hostname = strsep(&stringp, "/");
3455         if (hostname) 
3456                 contact = strsep(&stringp, "/");
3457         if (ast_strlen_zero(contact))
3458                 contact = "s";
3459         stringp=hostname;
3460         hostname = strsep(&stringp, ":");
3461         porta = strsep(&stringp, ":");
3462         
3463         if (porta && !atoi(porta)) {
3464                 ast_log(LOG_WARNING, "%s is not a valid port number at line %d\n", porta, lineno);
3465                 return -1;
3466         }
3467         if (!(reg = ast_calloc(1, sizeof(*reg)))) {
3468                 ast_log(LOG_ERROR, "Out of memory. Can't allocate SIP registry entry\n");
3469                 return -1;
3470         }
3471
3472         if (ast_string_field_init(reg, 256)) {
3473                 ast_log(LOG_ERROR, "Out of memory. Can't allocate SIP registry strings\n");
3474                 free(reg);
3475                 return -1;
3476         }
3477
3478         regobjs++;
3479         ASTOBJ_INIT(reg);
3480         ast_string_field_set(reg, contact, contact);
3481         if (username)
3482                 ast_string_field_set(reg, username, username);
3483         if (hostname)
3484                 ast_string_field_set(reg, hostname, hostname);
3485         if (authuser)
3486                 ast_string_field_set(reg, authuser, authuser);
3487         if (secret)
3488                 ast_string_field_set(reg, secret, secret);
3489         reg->expire = -1;
3490         reg->timeout =  -1;
3491         reg->refresh = default_expiry;
3492         reg->portno = porta ? atoi(porta) : 0;
3493         reg->callid_valid = FALSE;
3494         reg->ocseq = 101;
3495         ASTOBJ_CONTAINER_LINK(&regl, reg);      /* Add the new registry entry to the list */
3496         ASTOBJ_UNREF(reg,sip_registry_destroy);
3497         return 0;
3498 }
3499
3500 /*! \brief  Parse multiline SIP headers into one header
3501         This is enabled if pedanticsipchecking is enabled */
3502 static int lws2sws(char *msgbuf, int len)