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