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