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