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