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