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