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