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