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