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