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