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