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