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