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