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