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