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