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