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