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