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