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