30a40a0dfb483c2f352f3dff58457fa689cacd53
[asterisk/asterisk.git] / channels / chan_sip.c
1 /*
2  * Asterisk -- A telephony toolkit for Linux.
3  *
4  * Implementation of Session Initiation Protocol
5  * 
6  * Copyright (C) 1999, Mark Spencer
7  *
8  * Mark Spencer <markster@linux-support.net>
9  *
10  * This program is free software, distributed under the terms of
11  * the GNU General Public License
12  */
13
14 #include <stdio.h>
15 #include <ctype.h>
16 #include <pthread.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/parking.h>
38 #include <asterisk/acl.h>
39 #include <asterisk/srv.h>
40 #include <asterisk/astdb.h>
41 #include <asterisk/causes.h>
42 #include <sys/socket.h>
43 #include <sys/ioctl.h>
44 #include <net/if.h>
45 #include <errno.h>
46 #include <unistd.h>
47 #include <stdlib.h>
48 #include <fcntl.h>
49 #include <netdb.h>
50 #include <arpa/inet.h>
51 #include <pthread.h>
52 #include <signal.h>
53 #include <sys/signal.h>
54 #include <netinet/in_systm.h>
55 #include <netinet/ip.h>
56
57 #ifdef SIP_MYSQL_FRIENDS
58 #define MYSQL_FRIENDS
59 #include <mysql/mysql.h>
60 #endif
61
62 #define VIDEO_CODEC_MASK        0x1fc0000 /* Video codecs from H.261 thru AST_FORMAT_MAX_VIDEO */
63 #ifndef IPTOS_MINCOST
64 #define IPTOS_MINCOST 0x02
65 #endif
66
67 /* #define VOCAL_DATA_HACK */
68
69 #define SIPDUMPER
70 #define DEFAULT_DEFAULT_EXPIRY  120
71 #define DEFAULT_MAX_EXPIRY      3600
72
73 /* guard limit must be larger than guard secs */
74 /* guard min must be < 1000, and should be >= 250 */
75 #define EXPIRY_GUARD_SECS       15      /* How long before expiry do we reregister */
76 #define EXPIRY_GUARD_LIMIT      30      /* Below here, we use EXPIRY_GUARD_PCT instead of EXPIRY_GUARD_SECS */
77 #define EXPIRY_GUARD_MIN        500     /* This is the minimum guard time applied. If GUARD_PCT turns out
78                                         to be lower than this, it will use this time instead. This is in
79                                         milliseconds. */
80 #define EXPIRY_GUARD_PCT        0.20    /* Percentage of expires timeout to use when below EXPIRY_GUARD_LIMIT */
81
82 #ifndef MAX
83 #define MAX(a,b) ((a) > (b) ? (a) : (b))
84 #endif
85
86 #define CALLERID_UNKNOWN        "Unknown"
87
88 #define SIP_DTMF_RFC2833        (1 << 0)
89 #define SIP_DTMF_INBAND         (1 << 1)
90 #define SIP_DTMF_INFO           (1 << 2)
91
92 static int max_expiry = DEFAULT_MAX_EXPIRY;
93 static int default_expiry = DEFAULT_DEFAULT_EXPIRY;
94
95 #define DEFAULT_MAXMS           2000            /* Must be faster than 2 seconds by default */
96 #define DEFAULT_FREQ_OK         60 * 1000               /* How often to check for the host to be up */
97 #define DEFAULT_FREQ_NOTOK      10 * 1000               /* How often to check, if the host is down... */
98
99 #define DEFAULT_RETRANS         1000                    /* How frequently to retransmit */
100 #define MAX_RETRANS                     5                               /* Try only 5 times for retransmissions */
101
102 #ifdef MYSQL_FRIENDS
103 static ast_mutex_t mysqllock = AST_MUTEX_INITIALIZER;
104 static MYSQL *mysql;
105 static char mydbuser[80];
106 static char mydbpass[80];
107 static char mydbhost[80];
108 static char mydbname[80];
109 #endif
110
111                                                         /* SIP Debug            */
112 #define DEBUG_READ      0                               /* Recieved data        */
113 #define DEBUG_SEND      1                               /* Transmit data        */
114
115 static char *desc = "Session Initiation Protocol (SIP)";
116 static char *type = "SIP";
117 static char *tdesc = "Session Initiation Protocol (SIP)";
118 static char *config = "sip.conf";
119
120 #define DEFAULT_SIP_PORT        5060    /* From RFC 2543 */
121 #define SIP_MAX_PACKET  1500            /* Also from RFC 2543, should sub headers tho */
122
123 #define ALLOWED_METHODS "INVITE, ACK, CANCEL, OPTIONS, BYE, REFER"
124
125 static char context[AST_MAX_EXTENSION] = "default";
126
127 static char language[MAX_LANGUAGE] = "";
128
129 static char callerid[AST_MAX_EXTENSION] = "asterisk";
130
131 static char fromdomain[AST_MAX_EXTENSION] = "";
132
133 static char notifymime[AST_MAX_EXTENSION] = "application/simple-message-summary";
134
135 static int srvlookup = 0;
136
137 static int pedanticsipchecking = 0;
138
139 static int autocreatepeer = 0;
140
141 static int relaxdtmf = 0;
142
143 static int usecnt =0;
144 static ast_mutex_t usecnt_lock = AST_MUTEX_INITIALIZER;
145
146 /* Protect the interface list (of sip_pvt's) */
147 static ast_mutex_t iflock = AST_MUTEX_INITIALIZER;
148
149 /* Protect the monitoring thread, so only one process can kill or start it, and not
150    when it's doing something critical. */
151 static ast_mutex_t netlock = AST_MUTEX_INITIALIZER;
152
153 static ast_mutex_t monlock = AST_MUTEX_INITIALIZER;
154
155 /* This is the thread for the monitor which checks for input on the channels
156    which are not currently in use.  */
157 static pthread_t monitor_thread = AST_PTHREADT_NULL;
158
159 static int restart_monitor(void);
160
161 /* Codecs that we support by default: */
162 static int capability = AST_FORMAT_ULAW | AST_FORMAT_ALAW | AST_FORMAT_GSM | AST_FORMAT_H263;
163 static int noncodeccapability = AST_RTP_DTMF;
164
165 static char ourhost[256];
166 static struct in_addr __ourip;
167 static int ourport;
168
169 static int sipdebug = 0;
170 static struct sockaddr_in debugaddr;
171
172 static int tos = 0;
173
174 static int videosupport = 0;
175
176 static int globaldtmfmode = SIP_DTMF_RFC2833;
177
178 /* Expire slowly */
179 static int expiry = 900;
180
181 static struct sched_context *sched;
182 static struct io_context *io;
183 /* The private structures of the  sip channels are linked for
184    selecting outgoing channels */
185    
186 #define SIP_MAX_HEADERS         64
187 #define SIP_MAX_LINES           64
188
189 #define DEC_IN_USE      0
190 #define INC_IN_USE      1
191 #define DEC_OUT_USE     2
192 #define INC_OUT_USE     3
193
194 static struct sip_codec_pref {
195         int codec;
196         struct sip_codec_pref *next;
197 } *prefs;
198
199 struct sip_request {
200   char *rlPart1; /* SIP Method Name or "SIP/2.0" protocol version */
201   char *rlPart2; /* The Request URI or Response Status */
202         int len;
203         int headers;                                    /* SIP Headers */
204         char *header[SIP_MAX_HEADERS];
205         int lines;                                              /* SDP Content */
206         char *line[SIP_MAX_LINES];
207         char data[SIP_MAX_PACKET];
208 };
209
210 struct sip_pkt;
211
212 struct sip_route {
213         struct sip_route *next;
214         char hop[0];
215 };
216
217 static struct sip_pvt {
218         ast_mutex_t lock;                               /* Channel private lock */
219         char callid[80];                                        /* Global CallID */
220         char randdata[80];      /* Random data */
221         unsigned int ocseq;                                     /* Current outgoing seqno */
222         unsigned int icseq;                                     /* Current incoming seqno */
223         unsigned int callgroup;
224         unsigned int pickupgroup;
225         int lastinvite;                                         /* Last Cseq of invite */
226         int alreadygone;                                        /* Whether or not we've already been destroyed by or peer */
227         int needdestroy;                                        /* if we need to be destroyed */
228         int capability;                                         /* Special capability */
229         int jointcapability;                            /* Supported capability at both ends */
230         int prefcodec;                                          /* Preferred codec (outbound only) */
231         int noncodeccapability;
232         int outgoing;                                           /* Outgoing or incoming call? */
233         int authtries;                                          /* Times we've tried to authenticate */
234         int insecure;                                           /* Don't check source port/ip */
235         int expiry;                                             /* How long we take to expire */
236         int branch;                                                     /* One random number */
237         int canreinvite;                                        /* Do we support reinvite */
238         int ringing;                                            /* Have sent 180 ringing */
239         int progress;                                           /* Have sent 183 message progress */
240         int tag;                                                        /* Another random number */
241         int nat;                                                        /* Whether to try to support NAT */
242         int sessionid;                                          /* SDP Session ID */
243         int sessionversion;                                     /* SDP Session Version */
244         struct sockaddr_in sa;                          /* Our peer */
245         struct sockaddr_in redirip;                     /* Where our RTP should be going if not to us */
246         struct sockaddr_in vredirip;            /* Where our Video RTP should be going if not to us */
247         struct sockaddr_in recv;                        /* Received as */
248         struct in_addr ourip;                           /* Our IP */
249         struct ast_channel *owner;                      /* Who owns us */
250         char exten[AST_MAX_EXTENSION];          /* Extention where to start */
251         char refer_to[AST_MAX_EXTENSION];       /* Place to store REFER-TO extension */
252         char referred_by[AST_MAX_EXTENSION];/* Place to store REFERRED-BY extension */
253         char refer_contact[AST_MAX_EXTENSION];/* Place to store Contact info from a REFER extension */
254         struct sip_pvt *refer_call;                     /* Call we are referring */
255         struct sip_route *route;                        /* Head of linked list of routing steps (fm Record-Route) */
256         char remote_party_id[256];
257         char from[256];
258         char context[AST_MAX_EXTENSION];
259         char fromdomain[AST_MAX_EXTENSION];     /* Domain to show in the from field */
260         char fromuser[AST_MAX_EXTENSION];       /* Domain to show in the user field */
261         char tohost[AST_MAX_EXTENSION];         /* Host we should put in the "to" field */
262         char language[MAX_LANGUAGE];
263         char rdnis[256];                                /* Referring DNIS */
264         char theirtag[256];                             /* Their tag */
265         char username[256];
266         char peername[256];
267         char authname[256];                             /* Who we use for authentication */
268         char uri[256];                                  /* Original requested URI */
269         char peersecret[256];
270         char peermd5secret[256];
271         char callerid[256];                                     /* Caller*ID */
272         int restrictcid;                        /* hide presentation from remote user */
273         char via[256];
274         char accountcode[20];                           /* Account code */
275         char our_contact[256];                          /* Our contact header */
276         char realm[256];                                /* Authorization realm */
277         char nonce[256];                                /* Authorization nonce */
278         char opaque[256];                               /* Opaque nonsense */
279         char qop[80];                           /* Quality of Protection, since SIP wasn't complicated enough yet. */
280         char domain[256];                               /* Authorization nonce */
281         char lastmsg[256];                              /* Last Message sent/received */
282         int amaflags;                                           /* AMA Flags */
283         int pendinginvite;                                      /* Any pending invite */
284         int pendingbye;                                         /* Need to send bye after we ack? */
285         int gotrefer;                                           /* Got a refer? */
286         struct sip_request initreq;                     /* Initial request */
287         
288         int maxtime;                                            /* Max time for first response */
289         int initid;                                                     /* Auto-congest ID if appropriate */
290         int autokillid;                                         /* Auto-kill ID */
291
292         int subscribed;
293         int stateid;
294         int dialogver;
295         
296         int dtmfmode;
297         struct ast_dsp *vad;
298         
299         struct sip_peer *peerpoke;                      /* If this calls is to poke a peer, which one */
300         struct sip_registry *registry;                  /* If this is a REGISTER call, to which registry */
301         struct ast_rtp *rtp;                            /* RTP Session */
302         struct ast_rtp *vrtp;                           /* Video RTP session */
303         struct sip_pkt *packets;                        /* Packets scheduled for re-transmission */
304         struct sip_pvt *next;
305 } *iflist = NULL;
306
307 #define FLAG_RESPONSE (1 << 0)
308 #define FLAG_FATAL (1 << 1)
309
310 struct sip_pkt {
311         struct sip_pkt *next;                           /* Next packet */
312         int retrans;                                            /* Retransmission number */
313         int seqno;                                                      /* Sequence number */
314         int flags;                                                      /* non-zero if this is a response packet (e.g. 200 OK) */
315         struct sip_pvt *owner;                          /* Owner call */
316         int retransid;                                          /* Retransmission ID */
317         int packetlen;                                          /* Length of packet */
318         char data[0];
319 };      
320
321 struct sip_user {
322         /* Users who can access various contexts */
323         char name[80];
324         char secret[80];
325         char md5secret[80];
326         char context[80];
327         char callerid[80];
328         char methods[80];
329         char accountcode[20];
330         char language[MAX_LANGUAGE];
331         unsigned int callgroup;
332         unsigned int pickupgroup;
333         int nat;
334         int hascallerid;
335         int amaflags;
336         int insecure;
337         int canreinvite;
338         int capability;
339         int dtmfmode;
340         int inUse;
341         int incominglimit;
342         int outUse;
343         int outgoinglimit;
344         int restrictcid;
345         struct ast_ha *ha;
346         struct sip_user *next;
347 };
348
349 struct sip_peer {
350         char name[80];
351         char secret[80];
352         char md5secret[80];
353         char context[80];               /* JK02: peers need context too to allow parking etc */
354         char methods[80];
355         char username[80];
356         char tohost[80];
357         char fromuser[80];
358         char fromdomain[80];
359         char mailbox[AST_MAX_EXTENSION];
360         int lastmsgssent;
361         time_t  lastmsgcheck;
362         int dynamic;
363         int expire;
364         int expiry;
365         int capability;
366         int insecure;
367         int nat;
368         int canreinvite;
369         unsigned int callgroup;
370         unsigned int pickupgroup;
371         int dtmfmode;
372         struct sockaddr_in addr;
373         struct in_addr mask;
374
375         /* Qualification */
376         struct sip_pvt *call;           /* Call pointer */
377         int pokeexpire;                         /* When to expire poke */
378         int lastms;                                     /* How long last response took (in ms), or -1 for no response */
379         int maxms;                                      /* Max ms we will accept for the host to be up, 0 to not monitor */
380         struct timeval ps;                      /* Ping send time */
381         
382         struct sockaddr_in defaddr;
383         struct ast_ha *ha;
384         int delme;
385         int selfdestruct;
386         int lastmsg;
387         int temponly;
388         struct sip_peer *next;
389 };
390
391 static ast_mutex_t sip_reload_lock = AST_MUTEX_INITIALIZER;
392 static int sip_reloading = 0;
393
394 #define REG_STATE_UNREGISTERED 0
395 #define REG_STATE_REGSENT          1
396 #define REG_STATE_AUTHSENT         2
397 #define REG_STATE_REGISTERED   3
398 #define REG_STATE_REJECTED         4
399 #define REG_STATE_TIMEOUT          5
400 #define REG_STATE_NOAUTH           6
401
402 struct sip_registry {
403         struct sockaddr_in addr;                /* Who we connect to for registration purposes */
404         char username[80];                              /* Who we are registering as */
405         char authuser[80];                              /* Who we *authenticate* as */
406         char hostname[80];
407         char secret[80];                        /* Password or key name in []'s */      
408         char md5secret[80];
409         char contact[80];                       /* Contact extension */
410         char random[80];
411         int expire;                                     /* Sched ID of expiration */
412         int timeout;                                    /* sched id of sip_reg_timeout */
413         int refresh;                                    /* How often to refresh */
414         struct sip_pvt *call;                           /* create a sip_pvt structure for each outbound "registration call" in progress */
415         int regstate;
416         int callid_valid;               /* 0 means we haven't chosen callid for this registry yet. */
417         char callid[80];                /* Global CallID for this registry */
418         unsigned int ocseq;             /* Sequence number we got to for REGISTERs for this registry */
419         struct sockaddr_in us;                  /* Who the server thinks we are */
420         struct sip_registry *next;
421 };
422
423 static struct ast_user_list {
424         struct sip_user *users;
425         ast_mutex_t lock;
426 } userl = { NULL, AST_MUTEX_INITIALIZER };
427
428 static struct ast_peer_list {
429         struct sip_peer *peers;
430         ast_mutex_t lock;
431 } peerl = { NULL, AST_MUTEX_INITIALIZER };
432
433 static struct ast_register_list {
434         struct sip_registry *registrations;
435         ast_mutex_t lock;
436         int recheck;
437 } regl = { NULL, AST_MUTEX_INITIALIZER };
438
439
440 #define REINVITE_INVITE         1
441 #define REINVITE_UPDATE         2
442
443 static int __sip_do_register(struct sip_registry *r);
444
445 static int sipsock  = -1;
446 static int globalnat = 0;
447 static int globalcanreinvite = REINVITE_INVITE;
448
449
450 static struct sockaddr_in bindaddr;
451 static struct sockaddr_in localnet;
452 static struct sockaddr_in localmask;
453 static struct sockaddr_in externip;
454
455 static struct ast_frame  *sip_read(struct ast_channel *ast);
456 static int transmit_response(struct sip_pvt *p, char *msg, struct sip_request *req);
457 static int transmit_response_with_sdp(struct sip_pvt *p, char *msg, struct sip_request *req, int retrans);
458 static int transmit_response_with_auth(struct sip_pvt *p, char *msg, struct sip_request *req, char *rand, int reliable);
459 static int transmit_request(struct sip_pvt *p, char *msg, int inc, int reliable, int newbranch);
460 static int transmit_request_with_auth(struct sip_pvt *p, char *msg, int inc, int reliable, int newbranch);
461 static int transmit_invite(struct sip_pvt *p, char *msg, int sendsdp, char *auth, char *authheader, char *vxml_url,char *distinctive_ring, int init);
462 static int transmit_reinvite_with_sdp(struct sip_pvt *p, struct ast_rtp *rtp, struct ast_rtp *vrtp);
463 static int transmit_info_with_digit(struct sip_pvt *p, char digit);
464 static int transmit_message_with_text(struct sip_pvt *p, char *text);
465 static int transmit_refer(struct sip_pvt *p, char *dest);
466 static struct sip_peer *temp_peer(char *name);
467 static int do_proxy_auth(struct sip_pvt *p, struct sip_request *req, char *header, char *respheader, char *msg, int init);
468 /* static char *getsipuri(char *header); */
469 static void free_old_route(struct sip_route *route);
470 static int build_reply_digest(struct sip_pvt *p, char *orig_header, char *digest, int digest_len);
471 static int update_user_counter(struct sip_pvt *fup, int event);
472 static void prune_peers(void);
473 static int sip_do_reload(void);
474 static int sip_debug_test_addr(struct sockaddr_in *addr);
475 static int sip_debug_test_pvt(struct sip_pvt *p);
476
477 static int __sip_xmit(struct sip_pvt *p, char *data, int len)
478 {
479         int res;
480         if (p->nat)
481             res=sendto(sipsock, data, len, 0, (struct sockaddr *)&p->recv, sizeof(struct sockaddr_in));
482         else
483             res=sendto(sipsock, data, len, 0, (struct sockaddr *)&p->sa, sizeof(struct sockaddr_in));
484         if (res != len) {
485                 ast_log(LOG_WARNING, "sip_xmit of %p (len %d) to %s returned %d: %s\n", data, len, inet_ntoa(p->sa.sin_addr), res, strerror(errno));
486         }
487         return res;
488 }
489
490 static void sip_destroy(struct sip_pvt *p);
491
492 static int ast_sip_ouraddrfor(struct in_addr *them, struct in_addr *us)
493 {
494         /*
495           check to see if them is contained in our localnet/mask,
496           if not, use our externip for us, otherwise use the 
497           real internal address in bindaddr
498          */
499         if (localnet.sin_addr.s_addr && externip.sin_addr.s_addr &&
500             ((htonl(them->s_addr) & htonl(localnet.sin_addr.s_addr)) != htonl(localnet.sin_addr.s_addr)))
501                 memcpy(us, &externip.sin_addr, sizeof(struct in_addr));
502         else if (bindaddr.sin_addr.s_addr)
503                 memcpy(us, &bindaddr.sin_addr, sizeof(struct in_addr));
504         else
505                 return ast_ouraddrfor(them, us);
506         return 0;
507 }
508
509 static int retrans_pkt(void *data)
510 {
511         struct sip_pkt *pkt=data;
512         int res = 0;
513         ast_mutex_lock(&pkt->owner->lock);
514         if (pkt->retrans < MAX_RETRANS) {
515                 pkt->retrans++;
516                 if (sip_debug_test_pvt(pkt->owner)) {
517                         if (pkt->owner->nat)
518                                 ast_verbose("Retransmitting #%d (NAT):\n%s\n to %s:%d\n", pkt->retrans, pkt->data, inet_ntoa(pkt->owner->recv.sin_addr), ntohs(pkt->owner->recv.sin_port));
519                         else
520                                 ast_verbose("Retransmitting #%d (no NAT):\n%s\n to %s:%d\n", pkt->retrans, pkt->data, inet_ntoa(pkt->owner->sa.sin_addr), ntohs(pkt->owner->sa.sin_port));
521                 }
522                 __sip_xmit(pkt->owner, pkt->data, pkt->packetlen);
523                 res = 1;
524         } else {
525                 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");
526                 pkt->retransid = -1;
527                 if (pkt->flags & FLAG_FATAL) {
528                         while(pkt->owner->owner && ast_mutex_trylock(&pkt->owner->owner->lock)) {
529                                 ast_mutex_unlock(&pkt->owner->lock);
530                                 usleep(1);
531                                 ast_mutex_lock(&pkt->owner->lock);
532                         }
533                         if (pkt->owner->owner) {
534                                 /* XXX Potential deadlocK?? XXX */
535                                 ast_queue_hangup(pkt->owner->owner);
536                                 ast_mutex_unlock(&pkt->owner->owner->lock);
537                         } else {
538                                 /* If no owner, destroy now */
539                                 pkt->owner->needdestroy = 1;
540                         }
541                 } else {
542                         /* Okay, it's not fatal, just continue.  XXX If we were nice, we'd free it now, rather than wait for the
543                            end of the call XXX */
544                 }
545         }
546         if (pkt)
547                 ast_mutex_unlock(&pkt->owner->lock);
548         return res;
549 }
550
551 static int __sip_reliable_xmit(struct sip_pvt *p, int seqno, int resp, char *data, int len, int fatal)
552 {
553         struct sip_pkt *pkt;
554         pkt = malloc(sizeof(struct sip_pkt) + len);
555         if (!pkt)
556                 return -1;
557         memset(pkt, 0, sizeof(struct sip_pkt));
558         memcpy(pkt->data, data, len);
559         pkt->packetlen = len;
560         pkt->next = p->packets;
561         pkt->owner = p;
562         pkt->seqno = seqno;
563         pkt->flags = resp;
564         if (fatal)
565                 pkt->flags |= FLAG_FATAL;
566         /* Schedule retransmission */
567         pkt->retransid = ast_sched_add(sched, DEFAULT_RETRANS, retrans_pkt, pkt);
568         pkt->next = p->packets;
569         p->packets = pkt;
570         __sip_xmit(pkt->owner, pkt->data, pkt->packetlen);
571         if (!strncasecmp(pkt->data, "INVITE", 6)) {
572                 /* Note this is a pending invite */
573                 p->pendinginvite = seqno;
574         }
575         return 0;
576 }
577
578 static int __sip_autodestruct(void *data)
579 {
580         struct sip_pvt *p = data;
581         p->autokillid = -1;
582         ast_log(LOG_DEBUG, "Auto destroying call '%s'\n", p->callid);
583         if (p->owner) {
584                 ast_log(LOG_WARNING, "Autodestruct on call '%s' with owner in place\n", p->callid);
585                 ast_queue_hangup(p->owner);
586         } else {
587                 sip_destroy(p);
588         }
589         return 0;
590 }
591
592 static int sip_scheddestroy(struct sip_pvt *p, int ms)
593 {
594         if (sip_debug_test_pvt(p))
595                 ast_verbose("Scheduling destruction of call '%s' in %d ms\n", p->callid, ms);
596         if (p->autokillid > -1)
597                 ast_sched_del(sched, p->autokillid);
598         p->autokillid = ast_sched_add(sched, ms, __sip_autodestruct, p);
599         return 0;
600 }
601
602 static int sip_cancel_destroy(struct sip_pvt *p)
603 {
604         if (p->autokillid > -1)
605                 ast_sched_del(sched, p->autokillid);
606         p->autokillid = -1;
607         return 0;
608 }
609
610 static int __sip_ack(struct sip_pvt *p, int seqno, int resp)
611 {
612         struct sip_pkt *cur, *prev = NULL;
613         int res = -1;
614         int resetinvite = 0;
615         cur = p->packets;
616         while(cur) {
617                 if ((cur->seqno == seqno) && ((cur->flags & FLAG_RESPONSE) == resp)) {
618                         if (!resp && (seqno == p->pendinginvite)) {
619                                 ast_log(LOG_DEBUG, "Acked pending invite %d\n", p->pendinginvite);
620                                 p->pendinginvite = 0;
621                                 resetinvite = 1;
622                         }
623                         /* this is our baby */
624                         if (prev)
625                                 prev->next = cur->next;
626                         else
627                                 p->packets = cur->next;
628                         if (cur->retransid > -1)
629                                 ast_sched_del(sched, cur->retransid);
630                         free(cur);
631                         res = 0;
632                         break;
633                 }
634                 prev = cur;
635                 cur = cur->next;
636         }
637         ast_log(LOG_DEBUG, "Stopping retransmission on '%s' of %s %d: %s\n", p->callid, resp ? "Response" : "Request", seqno, res ? "Not Found" : "Found");
638         return res;
639 }
640
641 static int __sip_semi_ack(struct sip_pvt *p, int seqno, int resp)
642 {
643         struct sip_pkt *cur;
644         int res = -1;
645         cur = p->packets;
646         while(cur) {
647                 if ((cur->seqno == seqno) && ((cur->flags & FLAG_RESPONSE) == resp)) {
648                         /* this is our baby */
649                         if (cur->retransid > -1)
650                                 ast_sched_del(sched, cur->retransid);
651                         cur->retransid = -1;
652                         res = 0;
653                         break;
654                 }
655                 cur = cur->next;
656         }
657         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");
658         return res;
659 }
660
661 static int send_response(struct sip_pvt *p, struct sip_request *req, int reliable, int seqno)
662 {
663         int res;
664         if (sip_debug_test_pvt(p)) {
665                 if (p->nat)
666                         ast_verbose("%sTransmitting (NAT):\n%s\n to %s:%d\n", reliable ? "Reliably " : "", req->data, inet_ntoa(p->recv.sin_addr), ntohs(p->recv.sin_port));
667                 else
668                         ast_verbose("%sTransmitting (no NAT):\n%s\n to %s:%d\n", reliable ? "Reliably " : "", req->data, inet_ntoa(p->sa.sin_addr), ntohs(p->sa.sin_port));
669         }
670         if (reliable)
671                 res = __sip_reliable_xmit(p, seqno, 1, req->data, req->len, (reliable > 1));
672         else
673                 res = __sip_xmit(p, req->data, req->len);
674         if (res > 0)
675                 res = 0;
676         return res;
677 }
678
679 static int send_request(struct sip_pvt *p, struct sip_request *req, int reliable, int seqno)
680 {
681         int res;
682         if (sip_debug_test_pvt(p)) {
683                 if (p->nat)
684                         ast_verbose("%sTransmitting:\n%s (NAT) to %s:%d\n", reliable ? "Reliably " : "", req->data, inet_ntoa(p->recv.sin_addr), ntohs(p->recv.sin_port));
685                 else
686                         ast_verbose("%sTransmitting:\n%s (no NAT) to %s:%d\n", reliable ? "Reliably " : "", req->data, inet_ntoa(p->sa.sin_addr), ntohs(p->sa.sin_port));
687         }
688         if (reliable)
689                 res = __sip_reliable_xmit(p, seqno, 0, req->data, req->len, (reliable > 1));
690         else
691                 res = __sip_xmit(p, req->data, req->len);
692         return res;
693 }
694
695 static char *ditch_braces(char *tmp)
696 {
697         char *c = tmp;
698         char *n;
699         if ((n = strchr(tmp, '<')) ) {
700                 c = n + 1;
701                 while(*c && *c != '>') c++;
702                 if (*c != '>') {
703                         ast_log(LOG_WARNING, "No closing brace in '%s'\n", tmp);
704                 } else {
705                         *c = '\0';
706                 }
707                 return n+1;
708         }
709         return c;
710 }
711
712 static int sip_sendtext(struct ast_channel *ast, char *text)
713 {
714         struct sip_pvt *p = ast->pvt->pvt;
715         if (sip_debug_test_pvt(p))
716                 ast_verbose("Sending text %s on %s\n", text, ast->name);
717         if (!p)
718                 return -1;
719         if (!text || !strlen(text))
720                 return 0;
721         if (sip_debug_test_pvt(p))
722                 ast_verbose("Really sending text %s on %s\n", text, ast->name);
723         transmit_message_with_text(p, text);
724         return 0;       
725 }
726
727 #ifdef MYSQL_FRIENDS
728
729 static void mysql_update_peer(char *peer, struct sockaddr_in *sin, char *username, int expiry)
730 {
731         if (mysql && (strlen(peer) < 128)) {
732                 char query[512];
733                 char *name;
734                 char *uname;
735                 time_t nowtime;
736                 name = alloca(strlen(peer) * 2 + 1);
737                 uname = alloca(strlen(username) * 2 + 1);
738                 time(&nowtime);
739                 mysql_real_escape_string(mysql, name, peer, strlen(peer));
740                 mysql_real_escape_string(mysql, uname, username, strlen(username));
741                 snprintf(query, sizeof(query), "UPDATE sipfriends SET ipaddr=\"%s\", port=\"%d\", regseconds=\"%ld\", username=\"%s\" WHERE name=\"%s\"", 
742                         inet_ntoa(sin->sin_addr), ntohs(sin->sin_port), nowtime + expiry, uname, name);
743                 ast_mutex_lock(&mysqllock);
744                 if (mysql_real_query(mysql, query, strlen(query))) 
745                         ast_log(LOG_WARNING, "Unable to update database\n");
746                         
747                 ast_mutex_unlock(&mysqllock);
748         }
749 }
750
751 static struct sip_peer *mysql_peer(char *peer, struct sockaddr_in *sin)
752 {
753         struct sip_peer *p;
754         int success = 0;
755         
756         p = malloc(sizeof(struct sip_peer));
757         memset(p, 0, sizeof(struct sip_peer));
758         if (mysql && (!peer || (strlen(peer) < 128))) {
759                 char query[512];
760                 char *name = NULL;
761                 int numfields, x;
762                 int port;
763                 time_t regseconds, nowtime;
764                 MYSQL_RES *result;
765                 MYSQL_FIELD *fields;
766                 MYSQL_ROW rowval;
767                 if (peer) {
768                         name = alloca(strlen(peer) * 2 + 1);
769                         mysql_real_escape_string(mysql, name, peer, strlen(peer));
770                 }
771                 if (sin)
772                         snprintf(query, sizeof(query), "SELECT name, secret, context, username, ipaddr, port, regseconds FROM sipfriends WHERE ipaddr=\"%s\" AND port=\"%d\"", inet_ntoa(sin->sin_addr), ntohs(sin->sin_port));
773                 else
774                         snprintf(query, sizeof(query), "SELECT name, secret, context, username, ipaddr, port, regseconds FROM sipfriends WHERE name=\"%s\"", name);
775                 ast_mutex_lock(&mysqllock);
776                 mysql_query(mysql, query);
777                 if ((result = mysql_store_result(mysql))) {
778                         if ((rowval = mysql_fetch_row(result))) {
779                                 numfields = mysql_num_fields(result);
780                                 fields = mysql_fetch_fields(result);
781                                 success = 1;
782                                 for (x=0;x<numfields;x++) {
783                                         if (rowval[x]) {
784                                                 if (!strcasecmp(fields[x].name, "secret")) {
785                                                         strncpy(p->secret, rowval[x], sizeof(p->secret));
786                                                 } else if (!strcasecmp(fields[x].name, "name")) {
787                                                         strncpy(p->name, rowval[x], sizeof(p->name) - 1);
788                                                 } else if (!strcasecmp(fields[x].name, "context")) {
789                                                         strncpy(p->context, rowval[x], sizeof(p->context) - 1);
790                                                 } else if (!strcasecmp(fields[x].name, "username")) {
791                                                         strncpy(p->username, rowval[x], sizeof(p->username) - 1);
792                                                 } else if (!strcasecmp(fields[x].name, "ipaddr")) {
793                                                         inet_aton(rowval[x], &p->addr.sin_addr);
794                                                 } else if (!strcasecmp(fields[x].name, "port")) {
795                                                         if (sscanf(rowval[x], "%i", &port) != 1)
796                                                                 port = 0;
797                                                         p->addr.sin_port = htons(port);
798                                                 } else if (!strcasecmp(fields[x].name, "regseconds")) {
799                                                         if (sscanf(rowval[x], "%li", &regseconds) != 1)
800                                                                 regseconds = 0;
801                                                 }
802                                         }
803                                 }
804                                 time(&nowtime);
805                                 if (nowtime > regseconds) 
806                                         memset(&p->addr, 0, sizeof(p->addr));
807                         }
808                         mysql_free_result(result);
809                         result = NULL;
810                 }
811                 ast_mutex_unlock(&mysqllock);
812         }
813         if (!success) {
814                 free(p);
815                 p = NULL;
816         } else {
817                 p->dynamic = 1;
818                 p->capability = capability;
819                 p->nat = globalnat;
820                 p->dtmfmode = globaldtmfmode;
821                 p->insecure = 1;
822                 p->expire = -1;
823                 p->temponly = 1;
824                 
825         }
826         return p;
827 }
828 #endif /* MYSQL_FRIENDS */
829
830 static void update_peer(struct sip_peer *p, int expiry)
831 {
832 #ifdef MYSQL_FRIENDS
833         if (p->temponly)
834                 mysql_update_peer(p->name, &p->addr, p->username, expiry);
835 #endif
836         return;
837 }
838
839 static struct sip_peer *find_peer(char *peer, struct sockaddr_in *sin)
840 {
841         struct sip_peer *p = NULL;
842
843         p = peerl.peers;
844         if (peer) {
845                 /* Find by peer name */
846                 while(p) {
847                         if (!strcasecmp(p->name, peer)) {
848                                 break;
849                         }
850                         p = p->next;
851                 }       
852         }
853         else {
854                 /* Find by sin */
855                 while(p) {
856                         if (!inaddrcmp(&p->addr, sin) || 
857                                         (p->insecure &&
858                                         (p->addr.sin_addr.s_addr == sin->sin_addr.s_addr))) {
859                                 break;
860                         }
861                         p = p->next;
862                 }
863         }
864
865 #ifdef MYSQL_FRIENDS
866         if (!p) {
867                 p = mysql_peer(peer, sin);
868         }
869 #endif
870
871         return(p);
872 }
873
874 static struct sip_user *find_user(char *name)
875 {
876         struct sip_user *u = NULL;
877
878         u = userl.users;
879         while(u) {
880                 if (!strcasecmp(u->name, name)) {
881                         break;
882                 }
883                 u = u->next;
884         }
885
886         return(u);
887 }
888
889 static int sip_debug_test_addr(struct sockaddr_in *addr) {
890         /* See if we pass debug IP filter */
891         if (sipdebug == 0) return 0;
892         if (debugaddr.sin_addr.s_addr) {
893                 if (((ntohs(debugaddr.sin_port) != 0) &&
894                      (debugaddr.sin_port != addr->sin_port)) ||
895                     (debugaddr.sin_addr.s_addr != addr->sin_addr.s_addr))
896                         return 0;
897         }
898         return 1;
899 }
900
901 static int sip_debug_test_pvt(struct sip_pvt *p) {
902         return (sipdebug && sip_debug_test_addr((p->nat ? &p->recv : &p->sa)));
903 }
904
905 static int create_addr(struct sip_pvt *r, char *peer)
906 {
907         struct hostent *hp;
908         struct ast_hostent ahp;
909         struct sip_peer *p;
910         int found=0;
911         char *port;
912         int portno;
913         char host[256], *hostn;
914
915         r->sa.sin_family = AF_INET;
916         ast_mutex_lock(&peerl.lock);
917         p = find_peer(peer, NULL);
918
919         if (p) {
920                         found++;
921                         r->capability = p->capability;
922                         r->nat = p->nat;
923                         if (r->rtp) {
924                                 ast_log(LOG_DEBUG, "Setting NAT on RTP to %d\n", r->nat);
925                                 ast_rtp_setnat(r->rtp, r->nat);
926                         }
927                         if (r->vrtp) {
928                                 ast_log(LOG_DEBUG, "Setting NAT on VRTP to %d\n", r->nat);
929                                 ast_rtp_setnat(r->vrtp, r->nat);
930                         }
931                         strncpy(r->peername, p->username, sizeof(r->peername)-1);
932                         strncpy(r->authname, p->username, sizeof(r->authname)-1);
933                         strncpy(r->peersecret, p->secret, sizeof(r->peersecret)-1);
934                         strncpy(r->peermd5secret, p->md5secret, sizeof(r->peermd5secret)-1);
935                         strncpy(r->username, p->username, sizeof(r->username)-1);
936                         strncpy(r->tohost, p->tohost, sizeof(r->tohost)-1);
937                         if (!strlen(r->tohost)) {
938                                 if (p->addr.sin_addr.s_addr)
939                                         snprintf(r->tohost, sizeof(r->tohost), inet_ntoa(p->addr.sin_addr));
940                                 else
941                                         snprintf(r->tohost, sizeof(r->tohost), inet_ntoa(p->defaddr.sin_addr));
942                         }
943                         if (strlen(p->fromdomain))
944                                 strncpy(r->fromdomain, p->fromdomain, sizeof(r->fromdomain)-1);
945                         if (strlen(p->fromuser))
946                                 strncpy(r->fromuser, p->fromuser, sizeof(r->fromuser)-1);
947                         r->insecure = p->insecure;
948                         r->canreinvite = p->canreinvite;
949                         r->maxtime = p->maxms;
950                         r->callgroup = p->callgroup;
951                         r->pickupgroup = p->pickupgroup;
952                         if (p->dtmfmode) {
953                                 r->dtmfmode = p->dtmfmode;
954                                 if (r->dtmfmode & SIP_DTMF_RFC2833)
955                                         r->noncodeccapability |= AST_RTP_DTMF;
956                                 else
957                                         r->noncodeccapability &= ~AST_RTP_DTMF;
958                         }
959                         strncpy(r->context, p->context,sizeof(r->context)-1);
960                         if ((p->addr.sin_addr.s_addr || p->defaddr.sin_addr.s_addr) &&
961                                 (!p->maxms || ((p->lastms > 0)  && (p->lastms <= p->maxms)))) {
962                                 if (p->addr.sin_addr.s_addr) {
963                                         r->sa.sin_addr = p->addr.sin_addr;
964                                         r->sa.sin_port = p->addr.sin_port;
965                                 } else {
966                                         r->sa.sin_addr = p->defaddr.sin_addr;
967                                         r->sa.sin_port = p->defaddr.sin_port;
968                                 }
969                                 memcpy(&r->recv, &r->sa, sizeof(r->recv));
970                         } else {
971                                 if (p->temponly) {
972                                         if (p->ha) {
973                                                 ast_free_ha(p->ha);
974                                         }
975                                         free(p);
976                                 }
977                                 p = NULL;
978                         }
979         }
980         ast_mutex_unlock(&peerl.lock);
981         if (!p && !found) {
982                 if ((port=strchr(peer, ':'))) {
983                         *port='\0';
984                         port++;
985                 }
986                 hostn = peer;
987                 if (port)
988                         portno = atoi(port);
989                 else
990                         portno = DEFAULT_SIP_PORT;
991                 if (srvlookup) {
992                         char service[256];
993                         int tportno;
994                         int ret;
995                         snprintf(service, sizeof(service), "_sip._udp.%s", peer);
996                         ret = ast_get_srv(NULL, host, sizeof(host), &tportno, service);
997                         if (ret > 0) {
998                                 hostn = host;
999                                 portno = tportno;
1000                         }
1001                 }
1002                 hp = ast_gethostbyname(hostn, &ahp);
1003                 if (hp) {
1004                         strncpy(r->tohost, peer, sizeof(r->tohost) - 1);
1005                         memcpy(&r->sa.sin_addr, hp->h_addr, sizeof(r->sa.sin_addr));
1006                         r->sa.sin_port = htons(portno);
1007                         memcpy(&r->recv, &r->sa, sizeof(r->recv));
1008                         return 0;
1009                 } else {
1010                         ast_log(LOG_WARNING, "No such host: %s\n", peer);
1011                         return -1;
1012                 }
1013         } else if (!p)
1014                 return -1;
1015         else {
1016                 if (p->temponly) {
1017                         if (p->ha) {
1018                                 ast_free_ha(p->ha);
1019                         }
1020                         free(p);
1021                 }
1022                 return 0;
1023         }
1024 }
1025
1026 static int auto_congest(void *nothing)
1027 {
1028         struct sip_pvt *p = nothing;
1029         ast_mutex_lock(&p->lock);
1030         p->initid = -1;
1031         if (p->owner) {
1032                 if (!ast_mutex_trylock(&p->owner->lock)) {
1033                         ast_log(LOG_NOTICE, "Auto-congesting %s\n", p->owner->name);
1034                         ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
1035                         ast_mutex_unlock(&p->owner->lock);
1036                 }
1037         }
1038         ast_mutex_unlock(&p->lock);
1039         return 0;
1040 }
1041
1042 static void sip_prefs_free(void)
1043 {
1044         struct sip_codec_pref *cur, *next;
1045         cur = prefs;
1046         while(cur) {
1047                 next = cur->next;
1048                 free(cur);
1049                 cur = next;
1050         }
1051         prefs = NULL;
1052 }
1053
1054 static void sip_pref_remove(int format)
1055 {
1056         struct sip_codec_pref *cur, *prev=NULL;
1057         cur = prefs;
1058         while(cur) {
1059                 if (cur->codec == format) {
1060                         if (prev)
1061                                 prev->next = cur->next;
1062                         else
1063                                 prefs = cur->next;
1064                         free(cur);
1065                         return;
1066                 }
1067                 prev = cur;
1068                 cur = cur->next;
1069         }
1070 }
1071
1072 static int sip_pref_append(int format)
1073 {
1074         struct sip_codec_pref *cur, *tmp;
1075         sip_pref_remove(format);
1076         tmp = (struct sip_codec_pref *)malloc(sizeof(struct sip_codec_pref));
1077         if (!tmp)
1078                 return -1;
1079         memset(tmp, 0, sizeof(struct sip_codec_pref));
1080         tmp->codec = format;
1081         if (prefs) {
1082                 cur = prefs;
1083                 while(cur->next)
1084                         cur = cur->next;
1085                 cur->next = tmp;
1086         } else
1087                 prefs = tmp;
1088         return 0;
1089 }
1090
1091 static int sip_codec_choose(int formats)
1092 {
1093         struct sip_codec_pref *cur;
1094         formats &= ((AST_FORMAT_MAX_AUDIO << 1) - 1);
1095         cur = prefs;
1096         while(cur) {
1097                 if (formats & cur->codec)
1098                         return cur->codec;
1099                 cur = cur->next;
1100         }
1101         return ast_best_codec(formats);
1102 }
1103
1104 static int sip_call(struct ast_channel *ast, char *dest, int timeout)
1105 {
1106         int res;
1107         struct sip_pvt *p;
1108         char *vxml_url = NULL;
1109         char *distinctive_ring = NULL;
1110         struct varshead *headp;
1111         struct ast_var_t *current;
1112         
1113         p = ast->pvt->pvt;
1114         if ((ast->_state != AST_STATE_DOWN) && (ast->_state != AST_STATE_RESERVED)) {
1115                 ast_log(LOG_WARNING, "sip_call called on %s, neither down nor reserved\n", ast->name);
1116                 return -1;
1117         }
1118         /* Check whether there is vxml_url, distinctive ring variables */
1119
1120         headp=&ast->varshead;
1121         AST_LIST_TRAVERSE(headp,current,entries) {
1122                 /* Check whether there is a VXML_URL variable */
1123                 if (strcasecmp(ast_var_name(current),"VXML_URL")==0)
1124                 {
1125                         vxml_url = ast_var_value(current);
1126                         break;
1127                 }
1128                 /* Check whether there is a ALERT_INFO variable */
1129                 if (strcasecmp(ast_var_name(current),"ALERT_INFO")==0)
1130                 {
1131                         distinctive_ring = ast_var_value(current);
1132                         break;
1133                 }
1134         }
1135         
1136         res = 0;
1137         p->outgoing = 1;
1138         ast_log(LOG_DEBUG, "Outgoing Call for %s\n", p->username);
1139         res = update_user_counter(p,INC_OUT_USE);
1140         if ( res != -1 ) {
1141                 p->restrictcid = ast->restrictcid;
1142                 p->jointcapability = p->capability;
1143                 transmit_invite(p, "INVITE", 1, NULL, NULL, vxml_url,distinctive_ring, 1);
1144                 if (p->maxtime) {
1145                         /* Initialize auto-congest time */
1146                         p->initid = ast_sched_add(sched, p->maxtime * 4, auto_congest, p);
1147                 }
1148         }
1149         return res;
1150 }
1151
1152 static void __sip_destroy(struct sip_pvt *p, int lockowner)
1153 {
1154         struct sip_pvt *cur, *prev = NULL;
1155         struct sip_pkt *cp;
1156         if (sip_debug_test_pvt(p))
1157                 ast_verbose("Destroying call '%s'\n", p->callid);
1158         if (p->stateid > -1)
1159                 ast_extension_state_del(p->stateid, NULL);
1160         if (p->initid > -1)
1161                 ast_sched_del(sched, p->initid);
1162         if (p->autokillid > -1)
1163                 ast_sched_del(sched, p->autokillid);
1164
1165         if (p->rtp) {
1166                 ast_rtp_destroy(p->rtp);
1167         }
1168         if (p->vrtp) {
1169                 ast_rtp_destroy(p->vrtp);
1170         }
1171         if (p->route) {
1172                 free_old_route(p->route);
1173                 p->route = NULL;
1174         }
1175         if (p->registry) {
1176                 /* Carefully unlink from registry */
1177                 struct sip_registry *reg;
1178                 ast_mutex_lock(&regl.lock);
1179                 reg = regl.registrations;
1180                 while(reg) {
1181                         if ((reg == p->registry) && (p->registry->call == p))
1182                                 p->registry->call=NULL;
1183                         reg = reg->next;
1184                 }
1185                 ast_mutex_unlock(&regl.lock);
1186         }
1187         /* Unlink us from the owner if we have one */
1188         if (p->owner) {
1189                 if (lockowner)
1190                         ast_mutex_lock(&p->owner->lock);
1191                 ast_log(LOG_DEBUG, "Detaching from %s\n", p->owner->name);
1192                 p->owner->pvt->pvt = NULL;
1193                 if (lockowner)
1194                         ast_mutex_unlock(&p->owner->lock);
1195         }
1196         cur = iflist;
1197         while(cur) {
1198                 if (cur == p) {
1199                         if (prev)
1200                                 prev->next = cur->next;
1201                         else
1202                                 iflist = cur->next;
1203                         break;
1204                 }
1205                 prev = cur;
1206                 cur = cur->next;
1207         }
1208         if (!cur) {
1209                 ast_log(LOG_WARNING, "%p is not in list?!?! \n", cur);
1210         } else {
1211                 if (p->initid > -1)
1212                         ast_sched_del(sched, p->initid);
1213                 while((cp = p->packets)) {
1214                         p->packets = p->packets->next;
1215                         if (cp->retransid > -1)
1216                                 ast_sched_del(sched, cp->retransid);
1217                         free(cp);
1218                 }
1219                 free(p);
1220         }
1221 }
1222
1223 static int update_user_counter(struct sip_pvt *fup, int event)
1224 {
1225         char name[256] = "";
1226         struct sip_user *u;
1227         strncpy(name, fup->username, sizeof(name) - 1);
1228         ast_mutex_lock(&userl.lock);
1229         u = find_user(name);
1230         if (!u) {
1231                 ast_log(LOG_DEBUG, "%s is not a local user\n", name);
1232                 ast_mutex_unlock(&userl.lock);
1233                 return 0;
1234         }
1235         switch(event) {
1236                 /* incoming and outgoing affects the inUse counter */
1237                 case DEC_OUT_USE:
1238                 case DEC_IN_USE:
1239                         if ( u->inUse > 0 ) {
1240                                 u->inUse--;
1241                         } else {
1242                                 u->inUse = 0;
1243                         }
1244                         break;
1245                 case INC_IN_USE:
1246                 case INC_OUT_USE:
1247                         if (u->incominglimit > 0 ) {
1248                                 if (u->inUse >= u->incominglimit) {
1249                                         ast_log(LOG_ERROR, "Call from user '%s' rejected due to usage limit of %d\n", u->name, u->incominglimit);
1250                                         /* inc inUse as well */
1251                                         if ( event == INC_OUT_USE ) {
1252                                                 u->inUse++;
1253                                         }
1254                                         ast_mutex_unlock(&userl.lock);
1255                                         return -1; 
1256                                 }
1257                         }
1258                         u->inUse++;
1259                         ast_log(LOG_DEBUG, "Call from user '%s' is %d out of %d\n", u->name, u->inUse, u->incominglimit);
1260                         break;
1261                 /* we don't use these anymore
1262                 case DEC_OUT_USE:
1263                         if ( u->outUse > 0 ) {
1264                                 u->outUse--;
1265                         } else {
1266                                 u->outUse = 0;
1267                         }
1268                         break;
1269                 case INC_OUT_USE:
1270                         if ( u->outgoinglimit > 0 ) {
1271                                 if ( u->outUse >= u->outgoinglimit ) {
1272                                         ast_log(LOG_ERROR, "Outgoing call from user '%s' rejected due to usage limit of %d\n", u->name, u->outgoinglimit);
1273                                         ast_mutex_unlock(&userl.lock);
1274                                         return -1;
1275                                 }
1276                         }
1277                         u->outUse++;
1278                         break;
1279                 */
1280                 default:
1281                         ast_log(LOG_ERROR, "update_user_counter(%s,%d) called with no event!\n",u->name,event);
1282         }
1283         ast_mutex_unlock(&userl.lock);
1284         return 0;
1285 }
1286
1287 static void sip_destroy(struct sip_pvt *p)
1288 {
1289         ast_mutex_lock(&iflock);
1290         __sip_destroy(p, 1);
1291         ast_mutex_unlock(&iflock);
1292 }
1293
1294 static int transmit_response_reliable(struct sip_pvt *p, char *msg, struct sip_request *req, int fatal);
1295
1296 static int hangup_sip2cause(int cause)
1297 {
1298         switch(cause)
1299         {
1300                 case 486:
1301                         return AST_CAUSE_BUSY;
1302                 default:
1303                         return AST_CAUSE_NORMAL;
1304         }
1305         /* Never reached */
1306         return 0;
1307 }
1308
1309 static char *hangup_cause2sip(int cause)
1310 {
1311         switch(cause)
1312         {
1313                 case AST_CAUSE_BUSY:
1314                         return "486 Busy";
1315                 default:
1316                         return NULL;
1317         }
1318         /* Never reached */
1319         return 0;
1320 }
1321
1322 static int sip_hangup(struct ast_channel *ast)
1323 {
1324         struct sip_pvt *p = ast->pvt->pvt;
1325         int needcancel = 0;
1326         int needdestroy = 0;
1327         if (option_debug)
1328                 ast_log(LOG_DEBUG, "sip_hangup(%s)\n", ast->name);
1329         if (!ast->pvt->pvt) {
1330                 ast_log(LOG_DEBUG, "Asked to hangup channel not connected\n");
1331                 return 0;
1332         }
1333         ast_mutex_lock(&p->lock);
1334         if ( p->outgoing ) {
1335                 ast_log(LOG_DEBUG, "update_user_counter(%s) - decrement outUse counter\n", p->username);
1336                 update_user_counter(p, DEC_OUT_USE);
1337         } else {
1338                 ast_log(LOG_DEBUG, "update_user_counter(%s) - decrement inUse counter\n", p->username);
1339                 update_user_counter(p, DEC_IN_USE);
1340         }
1341         /* Determine how to disconnect */
1342         if (p->owner != ast) {
1343                 ast_log(LOG_WARNING, "Huh?  We aren't the owner?\n");
1344                 ast_mutex_unlock(&p->lock);
1345                 return 0;
1346         }
1347         if (!ast || (ast->_state != AST_STATE_UP))
1348                 needcancel = 1;
1349         /* Disconnect */
1350         p = ast->pvt->pvt;
1351         if (p->vad) {
1352             ast_dsp_free(p->vad);
1353         }
1354         p->owner = NULL;
1355         ast->pvt->pvt = NULL;
1356
1357         ast_mutex_lock(&usecnt_lock);
1358         usecnt--;
1359         ast_mutex_unlock(&usecnt_lock);
1360         ast_update_use_count();
1361
1362         needdestroy = 1;
1363         /* Start the process if it's not already started */
1364         if (!p->alreadygone && strlen(p->initreq.data)) {
1365                 if (needcancel) {
1366                         if (p->outgoing) {
1367                                 transmit_request_with_auth(p, "CANCEL", p->ocseq, 1, 0);
1368                                 /* Actually don't destroy us yet, wait for the 487 on our original 
1369                                    INVITE, but do set an autodestruct just in case. */
1370                                 needdestroy = 0;
1371                                 sip_scheddestroy(p, 15000);
1372                                 if ( p->initid != -1 ) {
1373                                         /* channel still up - reverse dec of inUse counter
1374                                            only if the channel is not auto-congested */
1375                                         if ( p->outgoing ) {
1376                                                 update_user_counter(p, INC_OUT_USE);
1377                                         }
1378                                         else {
1379                                                 update_user_counter(p, INC_IN_USE);
1380                                         }
1381                                 }
1382                         } else {
1383                                 char *res;
1384                                 if (ast->hangupcause && ((res = hangup_cause2sip(ast->hangupcause)))) {
1385                                         transmit_response_reliable(p, res, &p->initreq, 1);
1386                                 } else 
1387                                         transmit_response_reliable(p, "403 Forbidden", &p->initreq, 1);
1388                         }
1389                 } else {
1390                         if (!p->pendinginvite) {
1391                                 /* Send a hangup */
1392                                 transmit_request_with_auth(p, "BYE", 0, 1, 1);
1393                         } else {
1394                                 /* Note we will need a BYE when this all settles out
1395                                    but we can't send one while we have "INVITE" outstanding. */
1396                                 p->pendingbye = 1;
1397                         }
1398                 }
1399         }
1400         p->needdestroy = needdestroy;
1401         ast_mutex_unlock(&p->lock);
1402         return 0;
1403 }
1404
1405 static int sip_answer(struct ast_channel *ast)
1406 {
1407         int res = 0,fmt;
1408         char *codec;
1409         struct sip_pvt *p = ast->pvt->pvt;
1410
1411         
1412         if (ast->_state != AST_STATE_UP) {
1413         
1414         
1415         
1416                 codec=pbx_builtin_getvar_helper(p->owner,"SIP_CODEC");
1417                 if (codec) {
1418                         fmt=ast_getformatbyname(codec);
1419                         if (fmt) {
1420                                 ast_log(LOG_NOTICE, "Changing codec to '%s' for this call because of ${SIP_CODEC) variable\n",codec);
1421                                 p->jointcapability=fmt;
1422                         } else ast_log(LOG_NOTICE, "Ignoring ${SIP_CODEC} variable because of unrecognized/not configured codec (check allow/disallow in sip.conf): %s\n",codec);
1423                 }
1424
1425                 ast_setstate(ast, AST_STATE_UP);
1426                 if (option_debug)
1427                         ast_log(LOG_DEBUG, "sip_answer(%s)\n", ast->name);
1428                 res = transmit_response_with_sdp(p, "200 OK", &p->initreq, 1);
1429         }
1430         return res;
1431 }
1432
1433 static int sip_write(struct ast_channel *ast, struct ast_frame *frame)
1434 {
1435         struct sip_pvt *p = ast->pvt->pvt;
1436         int res = 0;
1437         if (frame->frametype == AST_FRAME_VOICE) {
1438                 if (!(frame->subclass & ast->nativeformats)) {
1439                         ast_log(LOG_WARNING, "Asked to transmit frame type %d, while native formats is %d (read/write = %d/%d)\n",
1440                                 frame->subclass, ast->nativeformats, ast->readformat, ast->writeformat);
1441                         return -1;
1442                 }
1443                 if (p) {
1444                         ast_mutex_lock(&p->lock);
1445                         if (p->rtp) {
1446                                 if ((ast->_state != AST_STATE_UP) && !p->progress && !p->outgoing) {
1447                                         transmit_response_with_sdp(p, "183 Session Progress", &p->initreq, 0);
1448                                         p->progress = 1;
1449                                 }
1450                                 res =  ast_rtp_write(p->rtp, frame);
1451                         }
1452                         ast_mutex_unlock(&p->lock);
1453                 }
1454         } else if (frame->frametype == AST_FRAME_VIDEO) {
1455                 if (p) {
1456                         ast_mutex_lock(&p->lock);
1457                         if (p->vrtp) {
1458                                 if ((ast->_state != AST_STATE_UP) && !p->progress && !p->outgoing) {
1459                                         transmit_response_with_sdp(p, "183 Session Progress", &p->initreq, 0);
1460                                         p->progress = 1;
1461                                 }
1462                                 res =  ast_rtp_write(p->vrtp, frame);
1463                         }
1464                         ast_mutex_unlock(&p->lock);
1465                 }
1466         } else if (frame->frametype == AST_FRAME_IMAGE) {
1467                 return 0;
1468         } else {
1469                 ast_log(LOG_WARNING, "Can't send %d type frames with SIP write\n", frame->frametype);
1470                 return 0;
1471         }
1472
1473         return res;
1474 }
1475
1476 static int sip_fixup(struct ast_channel *oldchan, struct ast_channel *newchan)
1477 {
1478         struct sip_pvt *p = newchan->pvt->pvt;
1479         ast_mutex_lock(&p->lock);
1480         if (p->owner != oldchan) {
1481                 ast_log(LOG_WARNING, "old channel wasn't %p but was %p\n", oldchan, p->owner);
1482                 ast_mutex_unlock(&p->lock);
1483                 return -1;
1484         }
1485         p->owner = newchan;
1486         ast_mutex_unlock(&p->lock);
1487         return 0;
1488 }
1489
1490 static int sip_senddigit(struct ast_channel *ast, char digit)
1491 {
1492         struct sip_pvt *p = ast->pvt->pvt;
1493         if (p && (p->dtmfmode & SIP_DTMF_INFO)) {
1494                 transmit_info_with_digit(p, digit);
1495         }
1496         if (p && p->rtp && (p->dtmfmode & SIP_DTMF_RFC2833)) {
1497                 ast_rtp_senddigit(p->rtp, digit);
1498         }
1499         /* If in-band DTMF is desired, send that */
1500         if (p->dtmfmode & SIP_DTMF_INBAND)
1501                 return -1;
1502         return 0;
1503 }
1504
1505 static int sip_transfer(struct ast_channel *ast, char *dest)
1506 {
1507         struct sip_pvt *p = ast->pvt->pvt;
1508         int res;
1509         res = transmit_refer(p, dest);
1510         return res;
1511 }
1512
1513 static int sip_indicate(struct ast_channel *ast, int condition)
1514 {
1515         struct sip_pvt *p = ast->pvt->pvt;
1516         switch(condition) {
1517         case AST_CONTROL_RINGING:
1518                 if (ast->_state == AST_STATE_RING) {
1519                         if (!p->progress) {
1520                                 transmit_response(p, "180 Ringing", &p->initreq);
1521                                 p->ringing = 1;
1522                                 break;
1523                         } else {
1524                                 /* Oops, we've sent progress tones.  Let Asterisk do it instead */
1525                         }
1526                 }
1527                 return -1;
1528         case AST_CONTROL_BUSY:
1529                 if (ast->_state != AST_STATE_UP) {
1530                         transmit_response(p, "486 Busy Here", &p->initreq);
1531                         p->alreadygone = 1;
1532                         ast_softhangup_nolock(ast, AST_SOFTHANGUP_DEV);
1533                         break;
1534                 }
1535                 return -1;
1536         case AST_CONTROL_CONGESTION:
1537                 if (ast->_state != AST_STATE_UP) {
1538                         transmit_response(p, "503 Service Unavailable", &p->initreq);
1539                         p->alreadygone = 1;
1540                         ast_softhangup_nolock(ast, AST_SOFTHANGUP_DEV);
1541                         break;
1542                 }
1543                 return -1;
1544         case AST_CONTROL_PROGRESS:
1545                 if ((ast->_state != AST_STATE_UP) && !p->progress && !p->outgoing) {
1546                         transmit_response_with_sdp(p, "183 Session Progress", &p->initreq, 0);
1547                         p->progress = 1;
1548                         break;
1549                 }
1550                 return -1;
1551         case -1:
1552                 return -1;
1553         default:
1554                 ast_log(LOG_WARNING, "Don't know how to indicate condition %d\n", condition);
1555                 return -1;
1556         }
1557         return 0;
1558 }
1559
1560
1561
1562 static struct ast_channel *sip_new(struct sip_pvt *i, int state, char *title)
1563 {
1564         struct ast_channel *tmp;
1565         int fmt;
1566         tmp = ast_channel_alloc(1);
1567         if (tmp) {
1568                 /* Select our native format based on codec preference until we receive
1569                    something from another device to the contrary. */
1570                 if (i->jointcapability)
1571                         tmp->nativeformats = sip_codec_choose(i->jointcapability);
1572                 else if (i->capability)
1573                         tmp->nativeformats = sip_codec_choose(i->capability);
1574                 else
1575                         tmp->nativeformats = sip_codec_choose(capability);
1576                 fmt = ast_best_codec(tmp->nativeformats);
1577                 if (title)
1578                         snprintf(tmp->name, sizeof(tmp->name), "SIP/%s-%04x", title, rand() & 0xffff);
1579                 else
1580                         if (strchr(i->fromdomain,':'))
1581                         {
1582                                 snprintf(tmp->name, sizeof(tmp->name), "SIP/%s-%08x", strchr(i->fromdomain,':')+1, (int)(i));
1583                         }
1584                         else
1585                         {
1586                                 snprintf(tmp->name, sizeof(tmp->name), "SIP/%s-%08x", i->fromdomain, (int)(i));
1587                         }
1588                 tmp->type = type;
1589                 if (i->dtmfmode & SIP_DTMF_INBAND) {
1590                     i->vad = ast_dsp_new();
1591                     ast_dsp_set_features(i->vad, DSP_FEATURE_DTMF_DETECT);
1592                     if (relaxdtmf)
1593                         ast_dsp_digitmode(i->vad, DSP_DIGITMODE_DTMF | DSP_DIGITMODE_RELAXDTMF);
1594                 }
1595                 tmp->fds[0] = ast_rtp_fd(i->rtp);
1596                 tmp->fds[1] = ast_rtcp_fd(i->rtp);
1597                 if (i->vrtp) {
1598                         tmp->fds[2] = ast_rtp_fd(i->vrtp);
1599                         tmp->fds[3] = ast_rtcp_fd(i->vrtp);
1600                 }
1601                 if (state == AST_STATE_RING)
1602                         tmp->rings = 1;
1603                 tmp->adsicpe = AST_ADSI_UNAVAILABLE;
1604                 tmp->writeformat = fmt;
1605                 tmp->pvt->rawwriteformat = fmt;
1606                 tmp->readformat = fmt;
1607                 tmp->pvt->rawreadformat = fmt;
1608                 tmp->pvt->pvt = i;
1609                 tmp->pvt->send_text = sip_sendtext;
1610                 tmp->pvt->call = sip_call;
1611                 tmp->pvt->hangup = sip_hangup;
1612                 tmp->pvt->answer = sip_answer;
1613                 tmp->pvt->read = sip_read;
1614                 tmp->pvt->write = sip_write;
1615                 tmp->pvt->write_video = sip_write;
1616                 tmp->pvt->indicate = sip_indicate;
1617                 tmp->pvt->transfer = sip_transfer;
1618                 tmp->pvt->fixup = sip_fixup;
1619                 tmp->pvt->send_digit = sip_senddigit;
1620
1621                 tmp->pvt->bridge = ast_rtp_bridge;
1622
1623                 tmp->callgroup = i->callgroup;
1624                 tmp->pickupgroup = i->pickupgroup;
1625                 tmp->restrictcid = i->restrictcid;
1626                 if (strlen(i->accountcode))
1627                         strncpy(tmp->accountcode, i->accountcode, sizeof(tmp->accountcode)-1);
1628                 if (i->amaflags)
1629                         tmp->amaflags = i->amaflags;
1630                 if (strlen(i->language))
1631                         strncpy(tmp->language, i->language, sizeof(tmp->language)-1);
1632                 i->owner = tmp;
1633                 ast_mutex_lock(&usecnt_lock);
1634                 usecnt++;
1635                 ast_mutex_unlock(&usecnt_lock);
1636                 strncpy(tmp->context, i->context, sizeof(tmp->context)-1);
1637                 strncpy(tmp->exten, i->exten, sizeof(tmp->exten)-1);
1638                 if (strlen(i->callerid))
1639                         tmp->callerid = strdup(i->callerid);
1640                 if (strlen(i->rdnis))
1641                         tmp->rdnis = strdup(i->rdnis);
1642                 if (strlen(i->exten) && strcmp(i->exten, "s"))
1643                         tmp->dnid = strdup(i->exten);
1644                 tmp->priority = 1;
1645                 if (strlen(i->domain)) {
1646                         pbx_builtin_setvar_helper(tmp, "SIPDOMAIN", i->domain);
1647                 }
1648                 ast_setstate(tmp, state);
1649                 if (state != AST_STATE_DOWN) {
1650                         if (ast_pbx_start(tmp)) {
1651                                 ast_log(LOG_WARNING, "Unable to start PBX on %s\n", tmp->name);
1652                                 ast_hangup(tmp);
1653                                 tmp = NULL;
1654                         }
1655                 }
1656         } else
1657                 ast_log(LOG_WARNING, "Unable to allocate channel structure\n");
1658         return tmp;
1659 }
1660
1661 static struct cfalias {
1662         char *fullname;
1663         char *shortname;
1664 } aliases[] = {
1665         { "Content-Type", "c" },
1666         { "Content-Encoding", "e" },
1667         { "From", "f" },
1668         { "Call-ID", "i" },
1669         { "Contact", "m" },
1670         { "Content-Length", "l" },
1671         { "Subject", "s" },
1672         { "To", "t" },
1673         { "Via", "v" },
1674 };
1675
1676 static char* get_sdp_by_line(char* line, char *name, int nameLen) {
1677   if (strncasecmp(line, name, nameLen) == 0 && line[nameLen] == '=') {
1678     char* r = line + nameLen + 1;
1679     while (*r && (*r < 33)) ++r;
1680     return r;
1681   }
1682
1683   return "";
1684 }
1685
1686 static char *get_sdp(struct sip_request *req, char *name) {
1687   int x;
1688   int len = strlen(name);
1689   char *r;
1690
1691   for (x=0; x<req->lines; x++) {
1692     r = get_sdp_by_line(req->line[x], name, len);
1693     if (r[0] != '\0') return r;
1694   }
1695   return "";
1696 }
1697
1698 static void sdpLineNum_iterator_init(int* iterator) {
1699   *iterator = 0;
1700 }
1701
1702 static char* get_sdp_iterate(int* iterator,
1703                              struct sip_request *req, char *name) {
1704   int len = strlen(name);
1705   char *r;
1706   while (*iterator < req->lines) {
1707     r = get_sdp_by_line(req->line[(*iterator)++], name, len);
1708     if (r[0] != '\0') return r;
1709   }
1710   return "";
1711 }
1712
1713 static char *__get_header(struct sip_request *req, char *name, int *start)
1714 {
1715         int x;
1716         int len = strlen(name);
1717         char *r;
1718         for (x=*start;x<req->headers;x++) {
1719                 if (!strncasecmp(req->header[x], name, len) && 
1720                                 (req->header[x][len] == ':')) {
1721                                         r = req->header[x] + len + 1;
1722                                         while(*r && (*r < 33))
1723                                                         r++;
1724                                         *start = x+1;
1725                                         return r;
1726                 }
1727         }
1728         /* Try aliases */
1729         for (x=0;x<sizeof(aliases) / sizeof(aliases[0]); x++) 
1730                 if (!strcasecmp(aliases[x].fullname, name))
1731                         return __get_header(req, aliases[x].shortname, start);
1732
1733         /* Don't return NULL, so get_header is always a valid pointer */
1734         return "";
1735 }
1736
1737 static char *get_header(struct sip_request *req, char *name)
1738 {
1739         int start = 0;
1740         return __get_header(req, name, &start);
1741 }
1742
1743 static struct ast_frame *sip_rtp_read(struct ast_channel *ast, struct sip_pvt *p)
1744 {
1745         /* Retrieve audio/etc from channel.  Assumes p->lock is already held. */
1746         struct ast_frame *f;
1747         static struct ast_frame null_frame = { AST_FRAME_NULL, };
1748         switch(ast->fdno) {
1749         case 0:
1750                 f = ast_rtp_read(p->rtp);
1751                 break;
1752         case 1:
1753                 f = ast_rtcp_read(p->rtp);
1754                 break;
1755         case 2:
1756                 f = ast_rtp_read(p->vrtp);
1757                 break;
1758         case 3:
1759                 f = ast_rtcp_read(p->vrtp);
1760                 break;
1761         default:
1762                 f = &null_frame;
1763         }
1764         /* Don't send RFC2833 if we're not supposed to */
1765         if (f && (f->frametype == AST_FRAME_DTMF) && !(p->dtmfmode & SIP_DTMF_RFC2833))
1766                 return &null_frame;
1767         if (p->owner) {
1768                 /* We already hold the channel lock */
1769                 if (f->frametype == AST_FRAME_VOICE) {
1770                         if (f->subclass != p->owner->nativeformats) {
1771                                 ast_log(LOG_DEBUG, "Oooh, format changed to %d\n", f->subclass);
1772                                 p->owner->nativeformats = f->subclass;
1773                                 ast_set_read_format(p->owner, p->owner->readformat);
1774                                 ast_set_write_format(p->owner, p->owner->writeformat);
1775                         }
1776             if ((p->dtmfmode & SIP_DTMF_INBAND) && p->vad) {
1777                    f = ast_dsp_process(p->owner,p->vad,f);
1778                    if (f && (f->frametype == AST_FRAME_DTMF)) 
1779                         ast_log(LOG_DEBUG, "Detected DTMF '%c'\n", f->subclass);
1780             }
1781                 }
1782         }
1783         return f;
1784 }
1785
1786 static struct ast_frame *sip_read(struct ast_channel *ast)
1787 {
1788         struct ast_frame *fr;
1789         struct sip_pvt *p = ast->pvt->pvt;
1790         ast_mutex_lock(&p->lock);
1791         fr = sip_rtp_read(ast, p);
1792         ast_mutex_unlock(&p->lock);
1793         return fr;
1794 }
1795
1796 static void build_callid(char *callid, int len, struct in_addr ourip)
1797 {
1798         int res;
1799         int val;
1800         int x;
1801         for (x=0;x<4;x++) {
1802                 val = rand();
1803                 res = snprintf(callid, len, "%08x", val);
1804                 len -= res;
1805                 callid += res;
1806         }
1807         /* It's not important that we really use our right IP here... */
1808         snprintf(callid, len, "@%s", inet_ntoa(ourip));
1809 }
1810
1811 static struct sip_pvt *sip_alloc(char *callid, struct sockaddr_in *sin, int useglobalnat)
1812 {
1813         struct sip_pvt *p;
1814
1815         p = malloc(sizeof(struct sip_pvt));
1816         if (!p)
1817                 return NULL;
1818         /* Keep track of stuff */
1819         memset(p, 0, sizeof(struct sip_pvt));
1820         p->initid = -1;
1821         p->autokillid = -1;
1822         p->stateid = -1;
1823         p->rtp = ast_rtp_new(sched, io, 1, 0);
1824         if (videosupport)
1825                 p->vrtp = ast_rtp_new(sched, io, 1, 0);
1826         p->branch = rand();     
1827         p->tag = rand();
1828         
1829         /* Start with 101 instead of 1 */
1830         p->ocseq = 101;
1831         if (!p->rtp) {
1832                 ast_log(LOG_WARNING, "Unable to create RTP session: %s\n", strerror(errno));
1833                 free(p);
1834                 return NULL;
1835         }
1836         ast_rtp_settos(p->rtp, tos);
1837         if (p->vrtp)
1838                 ast_rtp_settos(p->vrtp, tos);
1839         if (useglobalnat && sin) {
1840                 /* Setup NAT structure according to global settings if we have an address */
1841                 p->nat = globalnat;
1842                 memcpy(&p->recv, sin, sizeof(p->recv));
1843                 ast_rtp_setnat(p->rtp, p->nat);
1844                 if (p->vrtp)
1845                         ast_rtp_setnat(p->vrtp, p->nat);
1846         }
1847         ast_mutex_init(&p->lock);
1848
1849         if (sin) {
1850                 memcpy(&p->sa, sin, sizeof(p->sa));
1851                 if (ast_sip_ouraddrfor(&p->sa.sin_addr,&p->ourip))
1852                         memcpy(&p->ourip, &__ourip, sizeof(p->ourip));
1853         } else {
1854                 memcpy(&p->ourip, &__ourip, sizeof(p->ourip));
1855         }
1856         /* z9hG4bK is a magic cookie.  See RFC 3261 section 8.1.1.7 */
1857         snprintf(p->via, sizeof(p->via), "SIP/2.0/UDP %s:%d;branch=z9hG4bK%08x", inet_ntoa(p->ourip), ourport, p->branch);
1858         if (!callid)
1859                 build_callid(p->callid, sizeof(p->callid), p->ourip);
1860         else
1861                 strncpy(p->callid, callid, sizeof(p->callid) - 1);
1862         /* Assume reinvite OK and via INVITE */
1863         p->canreinvite = globalcanreinvite;
1864         p->dtmfmode = globaldtmfmode;
1865         p->capability = capability;
1866         if (p->dtmfmode & SIP_DTMF_RFC2833)
1867                 p->noncodeccapability |= AST_RTP_DTMF;
1868         strncpy(p->context, context, sizeof(p->context) - 1);
1869         strncpy(p->fromdomain, fromdomain, sizeof(p->fromdomain) - 1);
1870         /* Add to list */
1871         ast_mutex_lock(&iflock);
1872         p->next = iflist;
1873         iflist = p;
1874         ast_mutex_unlock(&iflock);
1875         if (option_debug)
1876                 ast_log(LOG_DEBUG, "Allocating new SIP call for %s\n", callid);
1877         return p;
1878 }
1879
1880 static struct sip_pvt *find_call(struct sip_request *req, struct sockaddr_in *sin)
1881 {
1882         struct sip_pvt *p;
1883         char *callid;
1884         char tmp[256] = "";
1885         char *cmd;
1886         char *tag = "", *c;
1887         int themisfrom;
1888         callid = get_header(req, "Call-ID");
1889
1890         if (pedanticsipchecking) {
1891                 /* In principle Call-ID's uniquely identify a call, however some vendors
1892                    (i.e. Pingtel) send multiple calls with the same Call-ID and different
1893                    tags in order to simplify billing.  The RFC does state that we have to
1894                    compare tags in addition to the call-id, but this generate substantially
1895                    more overhead which is totally unnecessary for the vast majority of sane
1896                    SIP implementations, and thus Asterisk does not enable this behavior
1897                    by default. Short version: You'll need this option to support conferencing
1898                    on the pingtel */
1899                 strncpy(tmp, req->header[0], sizeof(tmp) - 1);
1900                 cmd = tmp;
1901                 c = strchr(tmp, ' ');
1902                 if (c)
1903                         *c = '\0';
1904                 if (!strcasecmp(cmd, "SIP/2.0")) {
1905                         themisfrom = 0;
1906                 } else {
1907                         themisfrom = 1;
1908                 }
1909                 if (themisfrom)
1910                         strncpy(tmp, get_header(req, "From"), sizeof(tmp) - 1);
1911                 else
1912                         strncpy(tmp, get_header(req, "To"), sizeof(tmp) - 1);
1913                 tag = strstr(tmp, "tag=");
1914                 if (tag) {
1915                         tag += 4;
1916                         c = strchr(tag, ';');
1917                         if (c)
1918                                 *c = '\0';
1919                 }
1920                         
1921         }
1922                 
1923         if (!strlen(callid)) {
1924                 ast_log(LOG_WARNING, "Call missing call ID from '%s'\n", inet_ntoa(sin->sin_addr));
1925                 return NULL;
1926         }
1927         ast_mutex_lock(&iflock);
1928         p = iflist;
1929         while(p) {
1930                 if (!strcmp(p->callid, callid) && 
1931                         (!pedanticsipchecking || !tag || !strlen(p->theirtag) || !strcmp(p->theirtag, tag))) {
1932                         /* Found the call */
1933                         ast_mutex_lock(&p->lock);
1934                         ast_mutex_unlock(&iflock);
1935                         return p;
1936                 }
1937                 p = p->next;
1938         }
1939         ast_mutex_unlock(&iflock);
1940         p = sip_alloc(callid, sin, 1);
1941         if (p)
1942                 ast_mutex_lock(&p->lock);
1943         return p;
1944 }
1945
1946 static int sip_register(char *value, int lineno)
1947 {
1948         struct sip_registry *reg;
1949         char copy[256] = "";
1950         char *username=NULL, *hostname=NULL, *secret=NULL, *authuser=NULL;
1951         char *porta=NULL;
1952         char *contact=NULL;
1953         char *stringp=NULL;
1954         
1955         struct hostent *hp;
1956         struct ast_hostent ahp;
1957         if (!value)
1958                 return -1;
1959         strncpy(copy, value, sizeof(copy)-1);
1960         stringp=copy;
1961         username = stringp;
1962         hostname = strrchr(stringp, '@');
1963         if (hostname) {
1964                 *hostname = '\0';
1965                 hostname++;
1966         }
1967         if (!username || !strlen(username) || !hostname || !strlen(hostname)) {
1968                 ast_log(LOG_WARNING, "Format for registration is user[:secret[:authuser]]@host[:port][/contact] at line %d", lineno);
1969                 return -1;
1970         }
1971         stringp=username;
1972         username = strsep(&stringp, ":");
1973         if (username) {
1974                 secret = strsep(&stringp, ":");
1975                 if (secret) 
1976                         authuser = strsep(&stringp, ":");
1977         }
1978         stringp = hostname;
1979         hostname = strsep(&stringp, "/");
1980         if (hostname) 
1981                 contact = strsep(&stringp, "/");
1982         if (!contact || !strlen(contact))
1983                 contact = "s";
1984         stringp=hostname;
1985         hostname = strsep(&stringp, ":");
1986         porta = strsep(&stringp, ":");
1987         
1988         if (porta && !atoi(porta)) {
1989                 ast_log(LOG_WARNING, "%s is not a valid port number at line %d\n", porta, lineno);
1990                 return -1;
1991         }
1992         hp = ast_gethostbyname(hostname, &ahp);
1993         if (!hp) {
1994                 ast_log(LOG_WARNING, "Host '%s' not found at line %d\n", hostname, lineno);
1995                 return -1;
1996         }
1997         reg = malloc(sizeof(struct sip_registry));
1998         if (reg) {
1999                 memset(reg, 0, sizeof(struct sip_registry));
2000                 strncpy(reg->contact, contact, sizeof(reg->contact) - 1);
2001                 if (username)
2002                         strncpy(reg->username, username, sizeof(reg->username)-1);
2003                 if (hostname)
2004                         strncpy(reg->hostname, hostname, sizeof(reg->hostname)-1);
2005                 if (authuser)
2006                         strncpy(reg->authuser, authuser, sizeof(reg->authuser)-1);
2007                 if (secret)
2008                         strncpy(reg->secret, secret, sizeof(reg->secret)-1);
2009                 reg->expire = -1;
2010                 reg->timeout =  -1;
2011                 reg->refresh = default_expiry;
2012                 reg->addr.sin_family = AF_INET;
2013                 memcpy(&reg->addr.sin_addr, hp->h_addr, sizeof(&reg->addr.sin_addr));
2014                 reg->addr.sin_port = porta ? htons(atoi(porta)) : htons(DEFAULT_SIP_PORT);
2015                 reg->callid_valid = 0;
2016                 reg->ocseq = 101;
2017                 ast_mutex_lock(&regl.lock);
2018                 reg->next = regl.registrations;
2019                 regl.registrations = reg;
2020                 ast_mutex_unlock(&regl.lock);
2021         } else {
2022                 ast_log(LOG_ERROR, "Out of memory\n");
2023                 return -1;
2024         }
2025         return 0;
2026 }
2027
2028 static int lws2sws(char *msgbuf, int len) 
2029
2030         int h = 0, t = 0; 
2031         int lws = 0; 
2032
2033         for (; h < len;) { 
2034                 /* Eliminate all CRs */ 
2035                 if (msgbuf[h] == '\r') { 
2036                         h++; 
2037                         continue; 
2038                 } 
2039                 /* Check for end-of-line */ 
2040                 if (msgbuf[h] == '\n') { 
2041                 /* Check for end-of-message */ 
2042                         if (h + 1 == len) 
2043                         break; 
2044                 /* Check for a continuation line */ 
2045                 if (msgbuf[h + 1] == ' ') { 
2046                 /* Merge continuation line */ 
2047                         h++; 
2048                         continue; 
2049                 } 
2050                 /* Propagate LF and start new line */ 
2051                 msgbuf[t++] = msgbuf[h++]; 
2052                 lws = 0;
2053                 continue; 
2054         } 
2055
2056         if (msgbuf[h] == ' ' || msgbuf[h] == '\t') { 
2057                 if (lws) { 
2058                         h++; 
2059                         continue; 
2060                 } 
2061                 msgbuf[t++] = msgbuf[h++]; 
2062                 lws = 1; 
2063                 continue; 
2064         } 
2065         msgbuf[t++] = msgbuf[h++]; 
2066         if (lws) 
2067                 lws = 0; 
2068         } 
2069         msgbuf[t] = '\0'; 
2070         return t; 
2071 }
2072
2073 static void parse(struct sip_request *req)
2074 {
2075         /* Divide fields by NULL's */
2076         char *c;
2077         int f = 0;
2078         c = req->data;
2079
2080         /* First header starts immediately */
2081         req->header[f] = c;
2082         while(*c) {
2083                 if (*c == '\n') {
2084                         /* We've got a new header */
2085                         *c = 0;
2086
2087 #if 0
2088                         printf("Header: %s (%d)\n", req->header[f], strlen(req->header[f]));
2089 #endif                  
2090                         if (!strlen(req->header[f])) {
2091                                 /* Line by itself means we're now in content */
2092                                 c++;
2093                                 break;
2094                         }
2095                         if (f >= SIP_MAX_HEADERS - 1) {
2096                                 ast_log(LOG_WARNING, "Too many SIP headers...\n");
2097                         } else
2098                                 f++;
2099                         req->header[f] = c + 1;
2100                 } else if (*c == '\r') {
2101                         /* Ignore but eliminate \r's */
2102                         *c = 0;
2103                 }
2104                 c++;
2105         }
2106         /* Check for last header */
2107         if (strlen(req->header[f])) 
2108                 f++;
2109         req->headers = f;
2110         /* Now we process any mime content */
2111         f = 0;
2112         req->line[f] = c;
2113         while(*c) {
2114                 if (*c == '\n') {
2115                         /* We've got a new line */
2116                         *c = 0;
2117 #if 0
2118                         printf("Line: %s (%d)\n", req->line[f], strlen(req->line[f]));
2119 #endif                  
2120                         if (f >= SIP_MAX_LINES - 1) {
2121                                 ast_log(LOG_WARNING, "Too many SDP lines...\n");
2122                         } else
2123                                 f++;
2124                         req->line[f] = c + 1;
2125                 } else if (*c == '\r') {
2126                         /* Ignore and eliminate \r's */
2127                         *c = 0;
2128                 }
2129                 c++;
2130         }
2131         /* Check for last line */
2132         if (strlen(req->line[f])) 
2133                 f++;
2134         req->lines = f;
2135         if (*c) 
2136                 ast_log(LOG_WARNING, "Odd content, extra stuff left over ('%s')\n", c);
2137 }
2138
2139 static int process_sdp(struct sip_pvt *p, struct sip_request *req)
2140 {
2141         char *m;
2142         char *c;
2143         char *a;
2144         char host[258];
2145         int len = -1;
2146         int portno=0;
2147         int vportno=0;
2148         int peercapability, peernoncodeccapability;
2149         int vpeercapability=0, vpeernoncodeccapability=0;
2150         struct sockaddr_in sin;
2151         char *codecs;
2152         struct hostent *hp;
2153         struct ast_hostent ahp;
2154         int codec;
2155         int iterator;
2156         int sendonly = 0;
2157         int x;
2158
2159         /* Get codec and RTP info from SDP */
2160         if (strcasecmp(get_header(req, "Content-Type"), "application/sdp")) {
2161                 ast_log(LOG_NOTICE, "Content is '%s', not 'application/sdp'\n", get_header(req, "Content-Type"));
2162                 return -1;
2163         }
2164         m = get_sdp(req, "m");
2165         c = get_sdp(req, "c");
2166         if (!strlen(m) || !strlen(c)) {
2167                 ast_log(LOG_WARNING, "Insufficient information for SDP (m = '%s', c = '%s')\n", m, c);
2168                 return -1;
2169         }
2170         if (sscanf(c, "IN IP4 %256s", host) != 1) {
2171                 ast_log(LOG_WARNING, "Invalid host in c= line, '%s'\n", c);
2172                 return -1;
2173         }
2174         /* XXX This could block for a long time, and block the main thread! XXX */
2175         hp = ast_gethostbyname(host, &ahp);
2176         if (!hp) {
2177                 ast_log(LOG_WARNING, "Unable to lookup host in c= line, '%s'\n", c);
2178                 return -1;
2179         }
2180         sdpLineNum_iterator_init(&iterator);
2181         while ((m = get_sdp_iterate(&iterator, req, "m"))[0] != '\0') {
2182                 if ((sscanf(m, "audio %d RTP/AVP %n", &x, &len) == 1)) {
2183                         portno = x;
2184                         /* Scan through the RTP payload types specified in a "m=" line: */
2185                         ast_rtp_pt_clear(p->rtp);
2186                         codecs = m + len;
2187                         while(strlen(codecs)) {
2188                                 if (sscanf(codecs, "%d%n", &codec, &len) != 1) {
2189                                         ast_log(LOG_WARNING, "Error in codec string '%s'\n", codecs);
2190                                         return -1;
2191                                 }
2192                                 if (sip_debug_test_pvt(p))
2193                                         ast_verbose("Found RTP audio format %d\n", codec);
2194                                 ast_rtp_set_m_type(p->rtp, codec);
2195                                 codecs += len;
2196                                 /* Skip over any whitespace */
2197                                 while(*codecs && (*codecs < 33)) codecs++;
2198                         }
2199                 }
2200                 if (p->vrtp)
2201                         ast_rtp_pt_clear(p->vrtp);  /* Must be cleared in case no m=video line exists */
2202
2203                 if (p->vrtp && (sscanf(m, "video %d RTP/AVP %n", &x, &len) == 1)) {
2204                         vportno = x;
2205                         /* Scan through the RTP payload types specified in a "m=" line: */
2206                         codecs = m + len;
2207                         while(strlen(codecs)) {
2208                                 if (sscanf(codecs, "%d%n", &codec, &len) != 1) {
2209                                         ast_log(LOG_WARNING, "Error in codec string '%s'\n", codecs);
2210                                         return -1;
2211                                 }
2212                                 if (sip_debug_test_pvt(p))
2213                                         ast_verbose("Found video format %s\n", ast_getformatname(codec));
2214                                 ast_rtp_set_m_type(p->vrtp, codec);
2215                                 codecs += len;
2216                                 /* Skip over any whitespace */
2217                                 while(*codecs && (*codecs < 33)) codecs++;
2218                         }
2219                 }
2220         }
2221         sin.sin_family = AF_INET;
2222         memcpy(&sin.sin_addr, hp->h_addr, sizeof(sin.sin_addr));
2223         /* Setup audio port number */
2224         sin.sin_port = htons(portno);
2225         if (p->rtp && sin.sin_port)
2226                 ast_rtp_set_peer(p->rtp, &sin);
2227         /* Setup video port number */
2228         sin.sin_port = htons(vportno);
2229         if (p->vrtp && sin.sin_port)
2230                 ast_rtp_set_peer(p->vrtp, &sin);
2231 #if 0
2232         printf("Peer RTP is at port %s:%d\n", inet_ntoa(sin.sin_addr), ntohs(sin.sin_port));
2233 #endif  
2234         /* Next, scan through each "a=rtpmap:" line, noting each
2235          * specified RTP payload type (with corresponding MIME subtype):
2236          */
2237         sdpLineNum_iterator_init(&iterator);
2238         while ((a = get_sdp_iterate(&iterator, req, "a"))[0] != '\0') {
2239       char* mimeSubtype = ast_strdupa(a); /* ensures we have enough space */
2240           if (!strcasecmp(a, "sendonly")) {
2241                 sendonly=1;
2242                 continue;
2243           }
2244           if (!strcasecmp(a, "sendrecv")) {
2245                 sendonly=0;
2246           }
2247           if (sscanf(a, "rtpmap: %u %[^/]/", &codec, mimeSubtype) != 2) continue;
2248           if (sip_debug_test_pvt(p))
2249                 ast_verbose("Found description format %s\n", mimeSubtype);
2250           /* Note: should really look at the 'freq' and '#chans' params too */
2251           ast_rtp_set_rtpmap_type(p->rtp, codec, "audio", mimeSubtype);
2252           if (p->vrtp)
2253                   ast_rtp_set_rtpmap_type(p->vrtp, codec, "video", mimeSubtype);
2254         }
2255
2256         /* Now gather all of the codecs that were asked for: */
2257         ast_rtp_get_current_formats(p->rtp,
2258                                 &peercapability, &peernoncodeccapability);
2259         if (p->vrtp)
2260                 ast_rtp_get_current_formats(p->vrtp,
2261                                 &vpeercapability, &vpeernoncodeccapability);
2262         p->jointcapability = p->capability & (peercapability | vpeercapability);
2263         p->noncodeccapability = noncodeccapability & (peernoncodeccapability | vpeernoncodeccapability);
2264         
2265         if (sip_debug_test_pvt(p)) {
2266                 ast_verbose("Capabilities: us - %d, them - %d/%d, combined - %d\n",
2267                             p->capability, peercapability, vpeercapability, p->jointcapability);
2268                 ast_verbose("Non-codec capabilities: us - %d, them - %d, combined - %d\n",
2269                             noncodeccapability, peernoncodeccapability,
2270                             p->noncodeccapability);
2271         }
2272         if (!p->jointcapability) {
2273                 ast_log(LOG_WARNING, "No compatible codecs!\n");
2274                 return -1;
2275         }
2276         if (p->owner) {
2277                 if (!(p->owner->nativeformats & p->jointcapability)) {
2278                         ast_log(LOG_DEBUG, "Oooh, we need to change our formats since our peer supports only %d and not %d\n", p->jointcapability, p->owner->nativeformats);
2279                         p->owner->nativeformats = sip_codec_choose(p->jointcapability);
2280                         ast_set_read_format(p->owner, p->owner->readformat);
2281                         ast_set_write_format(p->owner, p->owner->writeformat);
2282                 }
2283                 if (p->owner->bridge) {
2284                         /* Turn on/off music on hold if we are holding/unholding */
2285                         if (sin.sin_addr.s_addr && !sendonly) {
2286                                 ast_moh_stop(p->owner->bridge);
2287                         } else {
2288                                 ast_moh_start(p->owner->bridge, NULL);
2289                         }
2290                 }
2291         }
2292         return 0;
2293         
2294 }
2295
2296 static int add_header(struct sip_request *req, char *var, char *value)
2297 {
2298         if (req->len >= sizeof(req->data) - 4) {
2299                 ast_log(LOG_WARNING, "Out of space, can't add anymore (%s:%s)\n", var, value);
2300                 return -1;
2301         }
2302         if (req->lines) {
2303                 ast_log(LOG_WARNING, "Can't add more headers when lines have been added\n");
2304                 return -1;
2305         }
2306         req->header[req->headers] = req->data + req->len;
2307         snprintf(req->header[req->headers], sizeof(req->data) - req->len - 4, "%s: %s\r\n", var, value);
2308         req->len += strlen(req->header[req->headers]);
2309         if (req->headers < SIP_MAX_HEADERS)
2310                 req->headers++;
2311         else {
2312                 ast_log(LOG_WARNING, "Out of header space\n");
2313                 return -1;
2314         }
2315         return 0;       
2316 }
2317
2318 static int add_blank_header(struct sip_request *req)
2319 {
2320         if (req->len >= sizeof(req->data) - 4) {
2321                 ast_log(LOG_WARNING, "Out of space, can't add anymore\n");
2322                 return -1;
2323         }
2324         if (req->lines) {
2325                 ast_log(LOG_WARNING, "Can't add more headers when lines have been added\n");
2326                 return -1;
2327         }
2328         req->header[req->headers] = req->data + req->len;
2329         snprintf(req->header[req->headers], sizeof(req->data) - req->len, "\r\n");
2330         req->len += strlen(req->header[req->headers]);
2331         if (req->headers < SIP_MAX_HEADERS)
2332                 req->headers++;
2333         else {
2334                 ast_log(LOG_WARNING, "Out of header space\n");
2335                 return -1;
2336         }
2337         return 0;       
2338 }
2339
2340 static int add_line(struct sip_request *req, char *line)
2341 {
2342         if (req->len >= sizeof(req->data) - 4) {
2343                 ast_log(LOG_WARNING, "Out of space, can't add anymore\n");
2344                 return -1;
2345         }
2346         if (!req->lines) {
2347                 /* Add extra empty return */
2348                 snprintf(req->data + req->len, sizeof(req->data) - req->len, "\r\n");
2349                 req->len += strlen(req->data + req->len);
2350         }
2351         req->line[req->lines] = req->data + req->len;
2352         snprintf(req->line[req->lines], sizeof(req->data) - req->len, "%s", line);
2353         req->len += strlen(req->line[req->lines]);
2354         if (req->lines < SIP_MAX_LINES)
2355                 req->lines++;
2356         else {
2357                 ast_log(LOG_WARNING, "Out of line space\n");
2358                 return -1;
2359         }
2360         return 0;       
2361 }
2362
2363 static int copy_header(struct sip_request *req, struct sip_request *orig, char *field)
2364 {
2365         char *tmp;
2366         tmp = get_header(orig, field);
2367         if (strlen(tmp)) {
2368                 /* Add what we're responding to */
2369                 return add_header(req, field, tmp);
2370         }
2371         ast_log(LOG_NOTICE, "No field '%s' present to copy\n", field);
2372         return -1;
2373 }
2374
2375 static int copy_all_header(struct sip_request *req, struct sip_request *orig, char *field)
2376 {
2377         char *tmp;
2378         int start = 0;
2379         int copied = 0;
2380         for (;;) {
2381                 tmp = __get_header(orig, field, &start);
2382                 if (strlen(tmp)) {
2383                         /* Add what we're responding to */
2384                         add_header(req, field, tmp);
2385                         copied++;
2386                 } else
2387                         break;
2388         }
2389         return copied ? 0 : -1;
2390 }
2391
2392 static int copy_via_headers(struct sip_pvt *p, struct sip_request *req, struct sip_request *orig, char *field)
2393 {
2394         char *tmp;
2395         int start = 0;
2396         int copied = 0;
2397         char new[256];
2398         for (;;) {
2399                 tmp = __get_header(orig, field, &start);
2400                 if (strlen(tmp)) {
2401                         if (!copied && p->nat) {
2402 #ifdef THE_SIP_AUTHORS_CAN_SUCK_MY_GONADS
2403                                 /* SLD: FIXME: Nice try, but the received= should not have a port */
2404                                 /* SLD: FIXME: See RFC2543 BNF in Section 6.40.5 */
2405                                 /* MAS: Yup, RFC says you can't do it.  No way to indicate PAT...
2406                                    good job fellas. */
2407                                 if (ntohs(p->recv.sin_port) != DEFAULT_SIP_PORT)
2408                                         snprintf(new, sizeof(new), "%s;received=%s:%d", tmp, inet_ntoa(p->recv.sin_addr), ntohs(p->recv.sin_port));
2409                                 else
2410 #endif                          
2411                                         snprintf(new, sizeof(new), "%s;received=%s", tmp, inet_ntoa(p->recv.sin_addr));
2412                                 add_header(req, field, new);
2413                         } else {
2414                                 /* Add what we're responding to */
2415                                 add_header(req, field, tmp);
2416                         }
2417                         copied++;
2418                 } else
2419                         break;
2420         }
2421         if (!copied) {
2422                 ast_log(LOG_NOTICE, "No field '%s' present to copy\n", field);
2423                 return -1;
2424         }
2425         return 0;
2426 }
2427
2428 /* Add Route: header into request per learned route */
2429 static void add_route(struct sip_request *req, struct sip_route *route)
2430 {
2431         char r[256], *p;
2432         int n, rem = 255; /* sizeof(r)-1: Room for terminating 0 */
2433
2434         if (!route) return;
2435
2436         p = r;
2437         while (route) {
2438                 n = strlen(route->hop);
2439                 if ((n+3)>rem) break;
2440                 if (p != r) {
2441                         *p++ = ',';
2442                         --rem;
2443                 }
2444                 *p++ = '<';
2445                 strcpy(p, route->hop);  p += n;
2446                 *p++ = '>';
2447                 rem -= (n+2);
2448                 route = route->next;
2449         }
2450         *p = '\0';
2451         add_header(req, "Route", r);
2452 }
2453
2454 static void set_destination(struct sip_pvt *p, char *uri)
2455 {
2456         char *h, *maddr, hostname[256];
2457         int port, hn;
2458         struct hostent *hp;
2459         struct ast_hostent ahp;
2460
2461         /* Parse uri to h (host) and port - uri is already just the part inside the <> */
2462         /* general form we are expecting is sip[s]:username[:password]@host[:port][;...] */
2463
2464         if (sip_debug_test_pvt(p))
2465                 ast_verbose("set_destination: Parsing <%s> for address/port to send to\n", uri);
2466
2467         /* Find and parse hostname */
2468         h = strchr(uri, '@');
2469         if (h)
2470                 ++h;
2471         else {
2472                 h = uri;
2473                 if (strncmp(h, "sip:", 4) == 0)
2474                         h += 4;
2475                 else if (strncmp(h, "sips:", 5) == 0)
2476                         h += 5;
2477         }
2478         hn = strcspn(h, ":;>");
2479         if (hn>255) hn=255;
2480         strncpy(hostname, h, hn);  hostname[hn] = '\0';
2481         h+=hn;
2482
2483         /* Is "port" present? if not default to 5060 */
2484         if (*h == ':') {
2485                 /* Parse port */
2486                 ++h;
2487                 port = strtol(h, &h, 10);
2488         }
2489         else
2490                 port = 5060;
2491
2492         /* Got the hostname:port - but maybe there's a "maddr=" to override address? */
2493         maddr = strstr(h, "maddr=");
2494         if (maddr) {
2495                 maddr += 6;
2496                 hn = strspn(maddr, "0123456789.");
2497                 if (hn>255) hn=255;
2498                 strncpy(hostname, maddr, hn);  hostname[hn] = '\0';
2499         }
2500         
2501         hp = ast_gethostbyname(hostname, &ahp);
2502         if (hp == NULL)  {
2503                 ast_log(LOG_WARNING, "Can't find address for host '%s'\n", hostname);
2504                 return;
2505         }
2506         p->sa.sin_family = AF_INET;
2507         memcpy(&p->sa.sin_addr, hp->h_addr, sizeof(p->sa.sin_addr));
2508         p->sa.sin_port = htons(port);
2509         if (sip_debug_test_pvt(p))
2510                 ast_verbose("set_destination: set destination to %s, port %d\n", inet_ntoa(p->sa.sin_addr), port);
2511 }
2512
2513 static int init_resp(struct sip_request *req, char *resp, struct sip_request *orig)
2514 {
2515         /* Initialize a response */
2516         if (req->headers || req->len) {
2517                 ast_log(LOG_WARNING, "Request already initialized?!?\n");
2518                 return -1;
2519         }
2520         req->header[req->headers] = req->data + req->len;
2521         snprintf(req->header[req->headers], sizeof(req->data) - req->len, "SIP/2.0 %s\r\n", resp);
2522         req->len += strlen(req->header[req->headers]);
2523         if (req->headers < SIP_MAX_HEADERS)
2524                 req->headers++;
2525         else
2526                 ast_log(LOG_WARNING, "Out of header space\n");
2527         return 0;
2528 }
2529
2530 static int init_req(struct sip_request *req, char *resp, char *recip)
2531 {
2532         /* Initialize a response */
2533         if (req->headers || req->len) {
2534                 ast_log(LOG_WARNING, "Request already initialized?!?\n");
2535                 return -1;
2536         }
2537         req->header[req->headers] = req->data + req->len;
2538         snprintf(req->header[req->headers], sizeof(req->data) - req->len, "%s %s SIP/2.0\r\n", resp, recip);
2539         req->len += strlen(req->header[req->headers]);
2540         if (req->headers < SIP_MAX_HEADERS)
2541                 req->headers++;
2542         else
2543                 ast_log(LOG_WARNING, "Out of header space\n");
2544         return 0;
2545 }
2546
2547 static int respprep(struct sip_request *resp, struct sip_pvt *p, char *msg, struct sip_request *req)
2548 {
2549         char newto[256] = "", *ot;
2550         memset(resp, 0, sizeof(*resp));
2551         init_resp(resp, msg, req);
2552         copy_via_headers(p, resp, req, "Via");
2553         if (msg[0] == '2') copy_all_header(resp, req, "Record-Route");
2554         copy_header(resp, req, "From");
2555         ot = get_header(req, "To");
2556         if (!strstr(ot, "tag=")) {
2557                 /* Add the proper tag if we don't have it already.  If they have specified
2558                    their tag, use it.  Otherwise, use our own tag */
2559                 if (strlen(p->theirtag) && p->outgoing)
2560                         snprintf(newto, sizeof(newto), "%s;tag=%s", ot, p->theirtag);
2561                 else if (p->tag && !p->outgoing)
2562                         snprintf(newto, sizeof(newto), "%s;tag=as%08x", ot, p->tag);
2563                 else
2564                         strncpy(newto, ot, sizeof(newto) - 1);
2565                 ot = newto;
2566         }
2567         add_header(resp, "To", ot);
2568         copy_header(resp, req, "Call-ID");
2569         copy_header(resp, req, "CSeq");
2570         add_header(resp, "User-Agent", "Asterisk PBX");
2571         add_header(resp, "Allow", ALLOWED_METHODS);
2572         if (p->expiry) {
2573                 /* For registration responses, we also need expiry and
2574                    contact info */
2575                 char contact[256];
2576                 char tmp[256];
2577                 snprintf(contact, sizeof(contact), "%s;expires=%d", p->our_contact, p->expiry);
2578                 snprintf(tmp, sizeof(tmp), "%d", p->expiry);
2579                 add_header(resp, "Expires", tmp);
2580                 add_header(resp, "Contact", contact);
2581         } else {
2582                 add_header(resp, "Contact", p->our_contact);
2583         }
2584         return 0;
2585 }
2586
2587 static int reqprep(struct sip_request *req, struct sip_pvt *p, char *msg, int seqno, int newbranch)
2588 {
2589         struct sip_request *orig = &p->initreq;
2590         char stripped[80] ="";
2591         char tmp[80];
2592         char newto[256];
2593         char *c, *n;
2594         char *ot, *of;
2595
2596         memset(req, 0, sizeof(struct sip_request));
2597         
2598         snprintf(p->lastmsg, sizeof(p->lastmsg), "Tx: %s", msg);
2599         
2600         if (!seqno) {
2601                 p->ocseq++;
2602                 seqno = p->ocseq;
2603         }
2604         
2605         if (newbranch) {
2606                 p->branch ^= rand();
2607                 snprintf(p->via, sizeof(p->via), "SIP/2.0/UDP %s:%d;branch=z9hG4bK%08x", inet_ntoa(p->ourip), ourport, p->branch);
2608         }
2609
2610         if (strlen(p->uri)) {
2611                 c = p->uri;
2612         } else {
2613                 if (p->outgoing)
2614                         strncpy(stripped, get_header(orig, "To"), sizeof(stripped) - 1);
2615                 else
2616                         strncpy(stripped, get_header(orig, "From"), sizeof(stripped) - 1);
2617                 
2618                 c = strchr(stripped, '<');
2619                 if (c) 
2620                         c++;
2621                 else
2622                         c = stripped;
2623                 n = strchr(c, '>');
2624                 if (n)
2625                         *n = '\0';
2626                 n = strchr(c, ';');
2627                 if (n)
2628                         *n = '\0';
2629         }       
2630         init_req(req, msg, c);
2631
2632         snprintf(tmp, sizeof(tmp), "%d %s", seqno, msg);
2633
2634         add_header(req, "Via", p->via);
2635         if (p->route) {
2636                 set_destination(p, p->route->hop);
2637                 add_route(req, p->route->next);
2638         }
2639
2640         ot = get_header(orig, "To");
2641         of = get_header(orig, "From");
2642
2643         /* Add tag *unless* this is a CANCEL, in which case we need to send it exactly
2644            as our original request, including tag (or presumably lack thereof) */
2645         if (!strstr(ot, "tag=") && strcasecmp(msg, "CANCEL")) {
2646                 /* Add the proper tag if we don't have it already.  If they have specified
2647                    their tag, use it.  Otherwise, use our own tag */
2648                 if (p->outgoing && strlen(p->theirtag))
2649                         snprintf(newto, sizeof(newto), "%s;tag=%s", ot, p->theirtag);
2650                 else if (!p->outgoing)
2651                         snprintf(newto, sizeof(newto), "%s;tag=as%08x", ot, p->tag);
2652                 else
2653                         snprintf(newto, sizeof(newto), "%s", ot);
2654                 ot = newto;
2655         }
2656
2657         if (p->outgoing) {
2658                 add_header(req, "From", of);
2659                 add_header(req, "To", ot);
2660         } else {
2661                 add_header(req, "From", ot);
2662                 add_header(req, "To", of);
2663         }
2664         add_header(req, "Contact", p->our_contact);
2665         copy_header(req, orig, "Call-ID");
2666         add_header(req, "CSeq", tmp);
2667
2668         add_header(req, "User-Agent", "Asterisk PBX");
2669         return 0;
2670 }
2671
2672 static int __transmit_response(struct sip_pvt *p, char *msg, struct sip_request *req, int reliable)
2673 {
2674         struct sip_request resp;
2675         int seqno = 0;
2676         if (reliable && (sscanf(get_header(req, "CSeq"), "%i ", &seqno) != 1)) {
2677                 ast_log(LOG_WARNING, "Unable to determine sequence number from '%s'\n", get_header(req, "CSeq"));
2678                 return -1;
2679         }
2680         respprep(&resp, p, msg, req);
2681         add_header(&resp, "Content-Length", "0");
2682         add_blank_header(&resp);
2683         return send_response(p, &resp, reliable, seqno);
2684 }
2685
2686 static int transmit_response(struct sip_pvt *p, char *msg, struct sip_request *req) 
2687 {
2688         return __transmit_response(p, msg, req, 0);
2689 }
2690 static int transmit_response_reliable(struct sip_pvt *p, char *msg, struct sip_request *req, int fatal)
2691 {
2692         return __transmit_response(p, msg, req, fatal ? 2 : 1);
2693 }
2694
2695 static void append_date(struct sip_request *req)
2696 {
2697         char tmpdat[256];
2698         struct tm tm;
2699         time_t t;
2700         time(&t);
2701         gmtime_r(&t, &tm);
2702         strftime(tmpdat, sizeof(tmpdat), "%a, %d %b %Y %T GMT", &tm);
2703         add_header(req, "Date", tmpdat);
2704 }
2705
2706 static int transmit_response_with_date(struct sip_pvt *p, char *msg, struct sip_request *req)
2707 {
2708         struct sip_request resp;
2709         respprep(&resp, p, msg, req);
2710         append_date(&resp);
2711         add_header(&resp, "Content-Length", "0");
2712         add_blank_header(&resp);
2713         return send_response(p, &resp, 0, 0);
2714 }
2715
2716 static int transmit_response_with_allow(struct sip_pvt *p, char *msg, struct sip_request *req)
2717 {
2718         struct sip_request resp;
2719         respprep(&resp, p, msg, req);
2720         add_header(&resp, "Accept", "application/sdp");
2721         add_header(&resp, "Content-Length", "0");
2722         add_blank_header(&resp);
2723         return send_response(p, &resp, 0, 0);
2724 }
2725
2726 static int transmit_response_with_auth(struct sip_pvt *p, char *msg, struct sip_request *req, char *randdata, int reliable)
2727 {
2728         struct sip_request resp;
2729         char tmp[256];
2730         int seqno = 0;
2731         if (reliable && (sscanf(get_header(req, "CSeq"), "%i ", &seqno) != 1)) {
2732                 ast_log(LOG_WARNING, "Unable to determine sequence number from '%s'\n", get_header(req, "CSeq"));
2733                 return -1;
2734         }
2735         snprintf(tmp, sizeof(tmp), "Digest realm=\"asterisk\", nonce=\"%s\"", randdata);
2736         respprep(&resp, p, msg, req);
2737         add_header(&resp, "Proxy-Authenticate", tmp);
2738         add_header(&resp, "Content-Length", "0");
2739         add_blank_header(&resp);
2740         return send_response(p, &resp, reliable, seqno);
2741 }
2742
2743 static int add_text(struct sip_request *req, char *text)
2744 {
2745         /* XXX Convert \n's to \r\n's XXX */
2746         int len = strlen(text);
2747         char clen[256];
2748         snprintf(clen, sizeof(clen), "%d", len);
2749         add_header(req, "Content-Type", "text/plain");
2750         add_header(req, "Content-Length", clen);
2751         add_line(req, text);
2752         return 0;
2753 }
2754
2755 static int add_digit(struct sip_request *req, char digit)
2756 {
2757         char tmp[256];
2758         int len;
2759         char clen[256];
2760         snprintf(tmp, sizeof(tmp), "Signal=%c\r\nDuration=250\r\n", digit);
2761         len = strlen(tmp);
2762         snprintf(clen, sizeof(clen), "%d", len);
2763         add_header(req, "Content-Type", "application/dtmf-relay");
2764         add_header(req, "Content-Length", clen);
2765         add_line(req, tmp);
2766         return 0;
2767 }
2768
2769 static int add_sdp(struct sip_request *resp, struct sip_pvt *p, struct ast_rtp *rtp, struct ast_rtp *vrtp)
2770 {
2771         int len;
2772         int codec;
2773         int alreadysent = 0;
2774         char costr[80];
2775         struct sockaddr_in sin;
2776         struct sockaddr_in vsin;
2777         struct sip_codec_pref *cur;
2778         char v[256];
2779         char s[256];
2780         char o[256];
2781         char c[256];
2782         char t[256];
2783         char m[256];
2784         char m2[256];
2785         char a[1024] = "";
2786         char a2[1024] = "";
2787         int x;
2788         struct sockaddr_in dest;
2789         struct sockaddr_in vdest = { 0, };
2790         /* XXX We break with the "recommendation" and send our IP, in order that our
2791                peer doesn't have to ast_gethostbyname() us XXX */
2792         len = 0;
2793         if (!p->rtp) {
2794                 ast_log(LOG_WARNING, "No way to add SDP without an RTP structure\n");
2795                 return -1;
2796         }
2797         if (!p->sessionid) {
2798                 p->sessionid = getpid();
2799                 p->sessionversion = p->sessionid;
2800         } else
2801                 p->sessionversion++;
2802         ast_rtp_get_us(p->rtp, &sin);
2803         if (p->vrtp)
2804                 ast_rtp_get_us(p->vrtp, &vsin);
2805
2806         if (p->redirip.sin_addr.s_addr) {
2807                 dest.sin_port = p->redirip.sin_port;
2808                 dest.sin_addr = p->redirip.sin_addr;
2809         } else if (rtp) {
2810                 ast_rtp_get_peer(rtp, &dest);
2811         } else {
2812                 dest.sin_addr = p->ourip;
2813                 dest.sin_port = sin.sin_port;
2814         }
2815
2816         /* Determine video destination */
2817         if (p->vrtp) {
2818                 if (p->vredirip.sin_addr.s_addr) {
2819                         vdest.sin_port = p->vredirip.sin_port;
2820                         vdest.sin_addr = p->vredirip.sin_addr;
2821                 } else if (vrtp) {
2822                         ast_rtp_get_peer(vrtp, &vdest);
2823                 } else {
2824                         vdest.sin_addr = p->ourip;
2825                         vdest.sin_port = vsin.sin_port;
2826                 }
2827         }
2828         if (sip_debug_test_pvt(p))
2829                 ast_verbose("We're at %s port %d\n", inet_ntoa(p->ourip), ntohs(sin.sin_port)); 
2830         if (sip_debug_test_pvt(p) && p->vrtp)
2831                 ast_verbose("Video is at %s port %d\n", inet_ntoa(p->ourip), ntohs(vsin.sin_port));     
2832         snprintf(v, sizeof(v), "v=0\r\n");
2833         snprintf(o, sizeof(o), "o=root %d %d IN IP4 %s\r\n", p->sessionid, p->sessionversion, inet_ntoa(dest.sin_addr));
2834         snprintf(s, sizeof(s), "s=session\r\n");
2835         snprintf(c, sizeof(c), "c=IN IP4 %s\r\n", inet_ntoa(dest.sin_addr));
2836         snprintf(t, sizeof(t), "t=0 0\r\n");
2837         snprintf(m, sizeof(m), "m=audio %d RTP/AVP", ntohs(dest.sin_port));
2838         snprintf(m2, sizeof(m2), "m=video %d RTP/AVP", ntohs(vdest.sin_port));
2839         if (p->jointcapability & p->prefcodec) {
2840                 if (sip_debug_test_pvt(p))
2841                         ast_verbose("Answering/Requesting with root capability %d\n", p->prefcodec);
2842                 codec = ast_rtp_lookup_code(p->rtp, 1, p->prefcodec);
2843                 if (codec > -1) {
2844                         snprintf(costr, sizeof(costr), " %d", codec);
2845                         if (p->prefcodec <= AST_FORMAT_MAX_AUDIO) {
2846                                 strncat(m, costr, sizeof(m) - strlen(m));
2847                                 snprintf(costr, sizeof(costr), "a=rtpmap:%d %s/8000\r\n", codec, ast_rtp_lookup_mime_subtype(1, p->prefcodec));
2848                                 strncat(a, costr, sizeof(a));
2849                         } else {
2850                                 strncat(m2, costr, sizeof(m2) - strlen(m2));
2851                                 snprintf(costr, sizeof(costr), "a=rtpmap:%d %s/90000\r\n", codec, ast_rtp_lookup_mime_subtype(1, p->prefcodec));
2852                                 strncat(a2, costr, sizeof(a2));
2853                         }
2854                 }
2855                 alreadysent |= p->prefcodec;
2856         }
2857         /* Start by sending our preferred codecs */
2858         cur = prefs;
2859         while(cur) {
2860                 if (p->jointcapability & cur->codec) {
2861                         if (sip_debug_test_pvt(p))
2862                                 ast_verbose("Answering/Requesting with preferred capability %d\n", cur->codec);
2863                         codec = ast_rtp_lookup_code(p->rtp, 1, cur->codec);
2864                         if (codec > -1) {
2865                                 snprintf(costr, sizeof(costr), " %d", codec);
2866                                 if (cur->codec <= AST_FORMAT_MAX_AUDIO) {
2867                                         strncat(m, costr, sizeof(m) - strlen(m));
2868                                         snprintf(costr, sizeof(costr), "a=rtpmap:%d %s/8000\r\n", codec, ast_rtp_lookup_mime_subtype(1, cur->codec));
2869                                         strncat(a, costr, sizeof(a));
2870                                 } else {
2871                                         strncat(m2, costr, sizeof(m2) - strlen(m2));
2872                                         snprintf(costr, sizeof(costr), "a=rtpmap:%d %s/90000\r\n", codec, ast_rtp_lookup_mime_subtype(1, cur->codec));
2873                                         strncat(a2, costr, sizeof(a2));
2874                                 }
2875                         }
2876                 }
2877                 alreadysent |= cur->codec;
2878                 cur = cur->next;
2879         }
2880         /* Now send any other common codecs, and non-codec formats: */
2881         for (x = 1; x <= (videosupport ? AST_FORMAT_MAX_VIDEO : AST_FORMAT_MAX_AUDIO); x <<= 1) {
2882                 if ((p->jointcapability & x) && !(alreadysent & x)) {
2883                         if (sip_debug_test_pvt(p))
2884                                 ast_verbose("Answering with capability %d\n", x);       
2885                         codec = ast_rtp_lookup_code(p->rtp, 1, x);
2886                         if (codec > -1) {
2887                                 snprintf(costr, sizeof(costr), " %d", codec);
2888                                 if (x <= AST_FORMAT_MAX_AUDIO) {
2889                                         strncat(m, costr, sizeof(m) - strlen(m));
2890                                         snprintf(costr, sizeof(costr), "a=rtpmap:%d %s/8000\r\n", codec, ast_rtp_lookup_mime_subtype(1, x));
2891                                         strncat(a, costr, sizeof(a) - strlen(a));
2892                                 } else {
2893                                         strncat(m2, costr, sizeof(m2) - strlen(m2));
2894                                         snprintf(costr, sizeof(costr), "a=rtpmap:%d %s/90000\r\n", codec, ast_rtp_lookup_mime_subtype(1, x));
2895                                         strncat(a2, costr, sizeof(a2) - strlen(a2));
2896                                 }
2897                         }
2898                 }
2899         }
2900         for (x = 1; x <= AST_RTP_MAX; x <<= 1) {
2901                 if (p->noncodeccapability & x) {
2902                         if (sip_debug_test_pvt(p))
2903                                 ast_verbose("Answering with non-codec capability %d\n", x);
2904                         codec = ast_rtp_lookup_code(p->rtp, 0, x);
2905                         if (codec > -1) {
2906                                 snprintf(costr, sizeof(costr), " %d", codec);
2907                                 strncat(m, costr, sizeof(m) - strlen(m));
2908                                 snprintf(costr, sizeof(costr), "a=rtpmap:%d %s/8000\r\n", codec, ast_rtp_lookup_mime_subtype(0, x));
2909                                 strncat(a, costr, sizeof(a) - strlen(a));
2910                                 if (x == AST_RTP_DTMF) {
2911                                   /* Indicate we support DTMF...  Not sure about 16, but MSN supports it so dang it, we will too... */
2912                                   snprintf(costr, sizeof costr, "a=fmtp:%d 0-16\r\n",
2913                                            codec);
2914                                   strncat(a, costr, sizeof(a) - strlen(a));
2915                                 }
2916                         }
2917                 }
2918         }
2919         strncat(a, "a=silenceSupp:off - - - -\r\n", sizeof(a) - strlen(a));
2920         if (strlen(m) < sizeof(m) - 2)
2921                 strcat(m, "\r\n");
2922         if (strlen(m2) < sizeof(m2) - 2)
2923                 strcat(m2, "\r\n");
2924         if ((sizeof(m) <= strlen(m) - 2) || (sizeof(m2) <= strlen(m2) - 2) || (sizeof(a) == strlen(a)) || (sizeof(a2) == strlen(a2)))
2925                 ast_log(LOG_WARNING, "SIP SDP may be truncated due to undersized buffer!!\n");
2926         len = strlen(v) + strlen(s) + strlen(o) + strlen(c) + strlen(t) + strlen(m) + strlen(a);
2927         if ((p->vrtp) && (p->jointcapability & VIDEO_CODEC_MASK)) /* only if video response is appropriate */
2928                 len += strlen(m2) + strlen(a2);
2929         snprintf(costr, sizeof(costr), "%d", len);
2930         add_header(resp, "Content-Type", "application/sdp");
2931         add_header(resp, "Content-Length", costr);
2932         add_line(resp, v);
2933         add_line(resp, o);
2934         add_line(resp, s);
2935         add_line(resp, c);
2936         add_line(resp, t);
2937         add_line(resp, m);
2938         add_line(resp, a);
2939         if ((p->vrtp) && (p->jointcapability & VIDEO_CODEC_MASK)) { /* only if video response is appropriate */
2940                 add_line(resp, m2);
2941                 add_line(resp, a2);
2942         }
2943         return 0;
2944 }
2945
2946 static void copy_request(struct sip_request *dst,struct sip_request *src)
2947 {
2948         long offset;
2949         int x;
2950         offset = ((void *)dst) - ((void *)src);
2951         /* First copy stuff */
2952         memcpy(dst, src, sizeof(*dst));
2953         /* Now fix pointer arithmetic */
2954         for (x=0;x<src->headers;x++)
2955                 dst->header[x] += offset;
2956         for (x=0;x<src->lines;x++)
2957                 dst->line[x] += offset;
2958 }
2959
2960 static int transmit_response_with_sdp(struct sip_pvt *p, char *msg, struct sip_request *req, int retrans)
2961 {
2962         struct sip_request resp;
2963         int seqno;
2964         if (sscanf(get_header(req, "CSeq"), "%i ", &seqno) != 1) {
2965                 ast_log(LOG_WARNING, "Unable to get seqno from '%s'\n", get_header(req, "CSeq"));
2966                 return -1;
2967         }
2968         respprep(&resp, p, msg, req);
2969         add_sdp(&resp, p, NULL, NULL);
2970         return send_response(p, &resp, retrans, seqno);
2971 }
2972
2973 static int determine_firstline_parts( struct sip_request *req ) {
2974
2975   char *e, *cmd;
2976   int len;
2977   
2978   cmd= req->header[0];
2979   while(*cmd && (*cmd < 33)) {
2980     cmd++;
2981   }
2982   if (!*cmd) {
2983     return -1;
2984   }
2985   e= cmd;
2986   while(*e && (*e > 32)) {
2987     e++;
2988   }
2989   /* Get the command */
2990   if (*e) {
2991     *e = '\0';
2992     e++;
2993   }
2994   req->rlPart1= cmd;
2995   while( *e && ( *e < 33 ) ) {
2996     e++; 
2997   }
2998   if( !*e ) {
2999     return -1;
3000   }
3001     
3002   if ( !strcasecmp(cmd, "SIP/2.0") ) {
3003     /* We have a response */
3004     req->rlPart2= e;
3005     len= strlen( req->rlPart2 );
3006     if( len < 2 ) { return -1; }
3007     e+= len - 1;
3008     while( *e && *e<33 ) {
3009       e--; 
3010     }
3011     *(++e)= '\0';
3012   } else {
3013     /* We have a request */
3014     if( *e == '<' ) { 
3015       e++;
3016       if( !*e ) { return -1; }  
3017     }
3018     req->rlPart2= e;
3019     if( ( e= strrchr( req->rlPart2, 'S' ) ) == NULL ) {
3020       return -1;
3021     }
3022     while( isspace( *(--e) ) ) {}
3023     if( *e == '>' ) {
3024       *e= '\0';
3025     } else {
3026       *(++e)= '\0';
3027     }
3028   }
3029   return 1;
3030 }
3031
3032 static int transmit_reinvite_with_sdp(struct sip_pvt *p, struct ast_rtp *rtp, struct ast_rtp *vrtp)
3033 {
3034         struct sip_request req;
3035         if (p->canreinvite == REINVITE_UPDATE)
3036                 reqprep(&req, p, "UPDATE", 0, 1);
3037         else 
3038                 reqprep(&req, p, "INVITE", 0, 1);
3039         
3040         add_header(&req, "Allow", ALLOWED_METHODS);
3041         add_sdp(&req, p, rtp, vrtp);
3042         /* Use this as the basis */
3043         copy_request(&p->initreq, &req);
3044         parse(&p->initreq);
3045         if (sip_debug_test_pvt(p))
3046                 ast_verbose("%d headers, %d lines\n", p->initreq.headers, p->initreq.lines);
3047         determine_firstline_parts(&p->initreq);
3048         p->lastinvite = p->ocseq;
3049         p->outgoing = 1;
3050         return send_request(p, &req, 1, p->ocseq);
3051 }
3052
3053 static void extract_uri(struct sip_pvt *p, struct sip_request *req)
3054 {
3055         char stripped[256]="";
3056         char *c, *n;
3057         strncpy(stripped, get_header(req, "Contact"), sizeof(stripped) - 1);
3058         c = strchr(stripped, '<');
3059         if (c) 
3060                 c++;
3061         else
3062                 c = stripped;
3063         n = strchr(c, '>');
3064         if (n)
3065                 *n = '\0';
3066         n = strchr(c, ';');
3067         if (n)
3068                 *n = '\0';
3069         if (c && strlen(c))
3070                 strncpy(p->uri, c, sizeof(p->uri) - 1);
3071 }
3072
3073 static void build_contact(struct sip_pvt *p)
3074 {
3075         /* Construct Contact: header */
3076         if (ourport != 5060)
3077                 snprintf(p->our_contact, sizeof(p->our_contact), "<sip:%s@%s:%d>", p->exten, inet_ntoa(p->ourip), ourport);
3078         else
3079                 snprintf(p->our_contact, sizeof(p->our_contact), "<sip:%s@%s>", p->exten, inet_ntoa(p->ourip));
3080 }
3081
3082 static void initreqprep(struct sip_request *req, struct sip_pvt *p, char *cmd, char *vxml_url)
3083 {
3084         char invite[256];
3085         char from[256];
3086         char to[256];
3087         char tmp[80];
3088         char cid[256];
3089         char *l = callerid, *n=NULL;
3090
3091         snprintf(p->lastmsg, sizeof(p->lastmsg), "Init: %s", cmd);
3092
3093         if (p->owner && p->owner->callerid) {
3094                 strcpy(cid, p->owner->callerid);
3095                 ast_callerid_parse(cid, &n, &l);
3096                 if (l) 
3097                         ast_shrink_phone_number(l);
3098                 if (!l || !ast_isphonenumber(l))
3099                                 l = callerid;
3100         }
3101         /* if user want's his callerid restricted */
3102         if (p->restrictcid) {
3103                 l = CALLERID_UNKNOWN;
3104                 n = l;
3105         }
3106         if (!n || !strlen(n))
3107                 n = l;
3108         /* Allow user to be overridden */
3109         if (strlen(p->fromuser))
3110                 l = p->fromuser;
3111
3112         if ((ourport != 5060) && !strlen(p->fromdomain))
3113                 snprintf(from, sizeof(from), "\"%s\" <sip:%s@%s:%d>;tag=as%08x", n, l, strlen(p->fromdomain) ? p->fromdomain : inet_ntoa(p->ourip), ourport, p->tag);
3114         else
3115                 snprintf(from, sizeof(from), "\"%s\" <sip:%s@%s>;tag=as%08x", n, l, strlen(p->fromdomain) ? p->fromdomain : inet_ntoa(p->ourip), p->tag);
3116
3117         if (strlen(p->username)) {
3118                 if (ntohs(p->sa.sin_port) != DEFAULT_SIP_PORT) {
3119                         snprintf(invite, sizeof(invite), "sip:%s@%s:%d",p->username, p->tohost, ntohs(p->sa.sin_port));
3120                 } else {
3121                         snprintf(invite, sizeof(invite), "sip:%s@%s",p->username, p->tohost);
3122                 }
3123         } else if (ntohs(p->sa.sin_port) != DEFAULT_SIP_PORT) {
3124                 snprintf(invite, sizeof(invite), "sip:%s:%d", p->tohost, ntohs(p->sa.sin_port));
3125         } else {
3126                 snprintf(invite, sizeof(invite), "sip:%s", p->tohost);
3127         }
3128         strncpy(p->uri, invite, sizeof(p->uri) - 1);
3129         /* If there is a VXML URL append it to the SIP URL */
3130         if (vxml_url)
3131         {
3132                 snprintf(to, sizeof(to), "<%s>;%s", invite, vxml_url);
3133         }
3134         else
3135         {
3136                 snprintf(to, sizeof(to), "<%s>", invite );
3137         }
3138         memset(req, 0, sizeof(struct sip_request));
3139         init_req(req, cmd, invite);
3140         snprintf(tmp, sizeof(tmp), "%d %s", ++p->ocseq, cmd);
3141
3142         add_header(req, "Via", p->via);
3143         /* SLD: FIXME?: do Route: here too?  I think not cos this is the first request.
3144          * OTOH, then we won't have anything in p->route anyway */
3145         add_header(req, "From", from);
3146         strncpy(p->exten, l, sizeof(p->exten) - 1);
3147         build_contact(p);
3148         add_header(req, "To", to);
3149         add_header(req, "Contact", p->our_contact);
3150         add_header(req, "Call-ID", p->callid);
3151         add_header(req, "CSeq", tmp);
3152         add_header(req, "User-Agent", "Asterisk PBX");
3153 }
3154
3155 static int transmit_invite(struct sip_pvt *p, char *cmd, int sdp, char *auth, char *authheader, char *vxml_url, char *distinctive_ring, int init)
3156 {
3157         struct sip_request req;
3158         
3159         if (init) {
3160                 /* Bump branch even on initial requests */
3161                 p->branch ^= rand();
3162                 snprintf(p->via, sizeof(p->via), "SIP/2.0/UDP %s:%d;branch=z9hG4bK%08x", inet_ntoa(p->ourip), ourport, p->branch);
3163                 initreqprep(&req, p, cmd, vxml_url);
3164         } else
3165                 reqprep(&req, p, cmd, 0, 1);
3166                 
3167         if (auth)
3168                 add_header(&req, authheader, auth);
3169         append_date(&req);
3170         if (!strcasecmp(cmd, "REFER")) {
3171                 if (strlen(p->refer_to))
3172                         add_header(&req, "Refer-To", p->refer_to);
3173                 if (strlen(p->referred_by))
3174                         add_header(&req, "Referred-By", p->referred_by);
3175         }
3176         
3177         if (distinctive_ring)
3178         {
3179                 add_header(&req, "Alert-info",distinctive_ring);
3180         }
3181         add_header(&req, "Allow", ALLOWED_METHODS);
3182         if (sdp) {
3183                 add_sdp(&req, p, NULL, NULL);
3184         } else {
3185                 add_header(&req, "Content-Length", "0");
3186                 add_blank_header(&req);
3187         }
3188
3189         if (!p->initreq.headers) {
3190                 /* Use this as the basis */
3191                 copy_request(&p->initreq, &req);
3192                 parse(&p->initreq);
3193                 if (sip_debug_test_pvt(p))
3194                         ast_verbose("%d headers, %d lines\n", p->initreq.headers, p->initreq.lines);
3195                 determine_firstline_parts(&p->initreq);
3196         }
3197         p->lastinvite = p->ocseq;
3198         return send_request(p, &req, init ? 2 : 1, p->ocseq);
3199 }
3200
3201 static int transmit_state_notify(struct sip_pvt *p, int state, int full)
3202 {
3203         char tmp[2000];
3204         char from[256], to[256];
3205         char *t, *c, *a;
3206         char *mfrom, *mto;
3207         struct sip_request req;
3208         char clen[20];
3209         
3210         strncpy(from, get_header(&p->initreq, "From"), sizeof(from)-1);
3211
3212         c = ditch_braces(from);
3213         if (strncmp(c, "sip:", 4)) {
3214                 ast_log(LOG_WARNING, "Huh?  Not a SIP header (%s)?\n", c);
3215                 return -1;
3216         }
3217         if ((a = strchr(c, ';'))) {
3218                 *a = '\0';
3219         }
3220         mfrom = c;
3221                 
3222         reqprep(&req, p, "NOTIFY", 0, 1);
3223
3224         if (p->subscribed == 1) {
3225             strncpy(to, get_header(&p->initreq, "To"), sizeof(to)-1);
3226
3227             c = ditch_braces(to);
3228             if (strncmp(c, "sip:", 4)) {
3229                 ast_log(LOG_WARNING, "Huh?  Not a SIP header (%s)?\n", c);
3230                 return -1;
3231             }
3232             if ((a = strchr(c, ';'))) {
3233                 *a = '\0';
3234             }
3235             mto = c;
3236
3237             add_header(&req, "Content-Type", "application/xpidf+xml");
3238
3239             if ((state==AST_EXTENSION_UNAVAILABLE) || (state==AST_EXTENSION_BUSY))
3240                 state = 2;
3241             else if (state==AST_EXTENSION_INUSE)
3242                 state = 1;
3243             else
3244                 state = 0;
3245             
3246             t = tmp;            
3247             sprintf(t, "<?xml version=\"1.0\"?>\n");
3248             t = tmp + strlen(tmp);
3249             sprintf(t, "<!DOCTYPE presence PUBLIC \"-//IETF//DTD RFCxxxx XPIDF 1.0//EN\" \"xpidf.dtd\">\n");
3250             t = tmp + strlen(tmp);
3251             sprintf(t, "<presence>\n");
3252             t = tmp + strlen(tmp);
3253             sprintf(t, "<presentity uri=\"%s;method=SUBSCRIBE\" />\n", mfrom);
3254             t = tmp + strlen(tmp);
3255             sprintf(t, "<atom id=\"%s\">\n", p->exten);
3256             t = tmp + strlen(tmp);
3257             sprintf(t, "<address uri=\"%s;user=ip\" priority=\"0,800000\">\n", mto);
3258             t = tmp + strlen(tmp);
3259             sprintf(t, "<status status=\"%s\" />\n", !state ? "open" : (state==1) ? "inuse" : "closed");
3260             t = tmp + strlen(tmp);
3261             sprintf(t, "<msnsubstatus substatus=\"%s\" />\n", !state ? "online" : (state==1) ? "onthephone" : "offline");
3262             t = tmp + strlen(tmp);
3263             sprintf(t, "</address>\n</atom>\n</presence>\n");           
3264         } else {
3265             add_header(&req, "Event", "dialog");
3266             add_header(&req, "Content-Type", "application/dialog-info+xml");
3267         
3268             t = tmp;            
3269             sprintf(t, "<?xml version=\"1.0\"?>\n");
3270             t = tmp + strlen(tmp);
3271             sprintf(t, "<dialog-info xmlns=\"urn:ietf:params:xml:ns:dialog-info\" version=\"%d\" state=\"%s\" entity=\"%s\">\n", p->dialogver++, full ? "full":"partial", mfrom);
3272             t = tmp + strlen(tmp);
3273             sprintf(t, "<dialog id=\"%s\">\n", p->exten);
3274             t = tmp + strlen(tmp);
3275             sprintf(t, "<state>%s</state>\n", state ? "confirmed" : "terminated");
3276             t = tmp + strlen(tmp);
3277             sprintf(t, "</dialog>\n</dialog-info>\n");  
3278         }
3279         if (t > tmp + sizeof(tmp))
3280                 ast_log(LOG_WARNING, "Buffer overflow detected!!  (Please file a bug report)\n");
3281
3282         snprintf(clen, sizeof(clen), "%d", strlen(tmp));
3283         add_header(&req, "Content-Length", clen);
3284         add_line(&req, tmp);
3285
3286         return send_request(p, &req, 1, p->ocseq);
3287 }
3288
3289 static int transmit_notify(struct sip_pvt *p, int newmsgs, int oldmsgs)
3290 {
3291         struct sip_request req;
3292         char tmp[256];
3293         char tmp2[256];
3294         char clen[20];
3295         initreqprep(&req, p, "NOTIFY", NULL);
3296         add_header(&req, "Event", "message-summary");
3297         add_header(&req, "Content-Type", notifymime);
3298
3299         snprintf(tmp, sizeof(tmp), "Messages-Waiting: %s\n", newmsgs ? "yes" : "no");
3300         snprintf(tmp2, sizeof(tmp2), "Voicemail: %d/%d\n", newmsgs, oldmsgs);
3301         snprintf(clen, sizeof(clen), "%d", strlen(tmp) + strlen(tmp2));
3302         add_header(&req, "Content-Length", clen);
3303         add_line(&req, tmp);
3304         add_line(&req, tmp2);
3305
3306         if (!p->initreq.headers) {
3307                 /* Use this as the basis */
3308                 copy_request(&p->initreq, &req);
3309                 parse(&p->initreq);
3310                 if (sip_debug_test_pvt(p))
3311                         ast_verbose("%d headers, %d lines\n", p->initreq.headers, p->initreq.lines);
3312                 determine_firstline_parts(&p->initreq);
3313         }
3314
3315         return send_request(p, &req, 1, p->ocseq);
3316 }
3317
3318 static int transmit_register(struct sip_registry *r, char *cmd, char *auth, char *authheader);
3319
3320 static int sip_reregister(void *data) 
3321 {
3322         /* if we are here, we know that we need to reregister. */
3323         struct sip_registry *r=(struct sip_registry *)data;
3324         ast_mutex_lock(&regl.lock);
3325         r->expire = -1;
3326         __sip_do_register(r);
3327         ast_mutex_unlock(&regl.lock);
3328         return 0;
3329 }
3330
3331
3332 static int __sip_do_register(struct sip_registry *r)
3333 {
3334         int res;
3335         res=transmit_register(r, "REGISTER", NULL, NULL);
3336         return res;
3337 }
3338
3339 static int sip_reg_timeout(void *data)
3340 {
3341         /* if we are here, our registration timed out, so we'll just do it over */
3342         struct sip_registry *r=data;
3343         struct sip_pvt *p;
3344         int res;
3345         ast_mutex_lock(&regl.lock);
3346         ast_log(LOG_NOTICE, "Registration for '%s@%s' timed out, trying again\n", r->username, inet_ntoa(r->addr.sin_addr)); 
3347         if (r->call) {
3348                 /* Unlink us, destroy old call.  Locking is not relevent here because all this happens
3349                    in the single SIP manager thread. */
3350                 p = r->call;
3351                 p->registry = NULL;
3352                 r->call = NULL;
3353                 p->needdestroy = 1;
3354         }
3355         r->regstate=REG_STATE_UNREGISTERED;
3356         r->timeout = -1;
3357         res=transmit_register(r, "REGISTER", NULL, NULL);
3358         ast_mutex_unlock(&regl.lock);
3359         return 0;
3360 }
3361
3362 static int transmit_register(struct sip_registry *r, char *cmd, char *auth, char *authheader)
3363 {
3364         struct sip_request req;
3365         char from[256];
3366         char to[256];
3367         char tmp[80];
3368         char via[80];
3369         char addr[80];
3370         struct sip_pvt *p;
3371         struct ast_hostent ahp;
3372         struct hostent *hp;
3373
3374         /* exit if we are already in process with this registrar ?*/
3375         if ( r == NULL || ((auth==NULL) && (r->regstate==REG_STATE_REGSENT || r->regstate==REG_STATE_AUTHSENT))) {
3376                 ast_log(LOG_NOTICE, "Strange, trying to register when registration already pending\n");
3377                 return 0;
3378         }
3379
3380         if (r->call) {
3381                 if (!auth) {
3382                         ast_log(LOG_WARNING, "Already have a call??\n");
3383                         return 0;
3384                 } else
3385                         p = r->call;
3386         } else {
3387                 if (!r->callid_valid) {
3388                         build_callid(r->callid, sizeof(r->callid), __ourip);
3389                         r->callid_valid = 1;
3390                 }
3391                 p=sip_alloc( r->callid, &r->addr, 0);
3392                 if (!p) {
3393                         ast_log(LOG_WARNING, "Unable to allocate registration call\n");
3394                         return 0;
3395                 }
3396                 p->outgoing = 1;
3397                 r->call=p;
3398                 p->registry=r;
3399                 strncpy(p->peersecret, r->secret, sizeof(p->peersecret)-1);
3400                 strncpy(p->peermd5secret, r->md5secret, sizeof(p->peermd5secret)-1);
3401                 if (strlen(r->authuser)) {
3402                         strncpy(p->peername, r->authuser, sizeof(p->peername)-1);
3403                         strncpy(p->authname, r->authuser, sizeof(p->authname)-1);
3404                 } else {
3405                         strncpy(p->peername, r->username, sizeof(p->peername)-1);
3406                         strncpy(p->authname, r->username, sizeof(p->authname)-1);
3407                 }
3408                 strncpy(p->username, r->username, sizeof(p->username)-1);
3409                 strncpy(p->exten, r->contact, sizeof(p->exten) - 1);
3410
3411                 /*
3412                   check which address we should use in our contact header 
3413                   based on whether the remote host is on the external or
3414                   internal network so we can register through nat
3415                  */
3416                 if ((hp = ast_gethostbyname(r->hostname, &ahp))) {
3417                         if (ast_sip_ouraddrfor((struct in_addr *)hp->h_addr, &p->ourip))
3418                                 memcpy(&p->ourip, &bindaddr.sin_addr, sizeof(p->ourip));
3419                 }
3420                 build_contact(p);
3421         }
3422
3423         /* set up a timeout */
3424         if (auth==NULL)  {
3425                 if (r->timeout > -1) {
3426                         ast_log(LOG_WARNING, "Still have a timeout, %d\n", r->timeout);
3427                         ast_sched_del(sched, r->timeout);
3428                 }
3429                 r->timeout = ast_sched_add(sched, 20*1000, sip_reg_timeout, r);
3430                 ast_log(LOG_DEBUG, "Scheduled a timeout # %d\n", r->timeout);
3431         }
3432
3433         if (strchr(r->username, '@')) {
3434                 snprintf(from, sizeof(from), "<sip:%s>;tag=as%08x", r->username, p->tag);
3435                 snprintf(to, sizeof(to),     "<sip:%s>", r->username);
3436         } else {
3437                 snprintf(from, sizeof(from), "<sip:%s@%s>;tag=as%08x", r->username, r->hostname, p->tag);
3438                 snprintf(to, sizeof(to),     "<sip:%s@%s>", r->username, r->hostname);
3439         }
3440         
3441         snprintf(addr, sizeof(addr), "sip:%s", r->hostname);
3442         strncpy(p->uri, addr, sizeof(p->uri) - 1);
3443
3444         p->branch ^= rand();
3445
3446         memset(&req, 0, sizeof(req));
3447         init_req(&req, cmd, addr);
3448
3449         snprintf(tmp, sizeof(tmp), "%u %s", ++r->ocseq, cmd);
3450         p->ocseq = r->ocseq;
3451
3452         /* z9hG4bK is a magic cookie.  See RFC 3261 section 8.1.1.7 */
3453         snprintf(via, sizeof(via), "SIP/2.0/UDP %s:%d;branch=z9hG4bK%08x", inet_ntoa(p->ourip), ourport, p->branch);
3454         add_header(&req, "Via", via);
3455         add_header(&req, "From", from);
3456         add_header(&req, "To", to);
3457         add_header(&req, "Call-ID", p->callid);
3458         add_header(&req, "CSeq", tmp);
3459         add_header(&req, "User-Agent", "Asterisk PBX");
3460         if (auth) 
3461                 add_header(&req, authheader, auth);
3462
3463         snprintf(tmp, sizeof(tmp), "%d", default_expiry);
3464         add_header(&req, "Expires", tmp);
3465         add_header(&req, "Contact", p->our_contact);
3466         add_header(&req, "Event", "registration");
3467         add_header(&req, "Content-Length", "0");
3468         add_blank_header(&req);
3469         copy_request(&p->initreq, &req);
3470         parse(&p->initreq);
3471         if (sip_debug_test_pvt(p))
3472                 ast_verbose("%d headers, %d lines\n", p->initreq.headers, p->initreq.lines);
3473         determine_firstline_parts(&p->initreq);
3474         r->regstate=auth?REG_STATE_AUTHSENT:REG_STATE_REGSENT;
3475         return send_request(p, &req, 2, p->ocseq);
3476 }
3477
3478 static int transmit_message_with_text(struct sip_pvt *p, char *text)
3479 {
3480         struct sip_request req;
3481         reqprep(&req, p, "MESSAGE", 0, 1);
3482         add_text(&req, text);
3483         return send_request(p, &req, 1, p->ocseq);
3484 }
3485
3486 static int transmit_refer(struct sip_pvt *p, char *dest)
3487 {
3488         struct sip_request req;
3489         char from[256];
3490         char *of, *c;
3491         char referto[256];
3492         if (p->outgoing) 
3493                 of = get_header(&p->initreq, "To");
3494         else
3495                 of = get_header(&p->initreq, "From");
3496         strncpy(from, of, sizeof(from) - 1);
3497         of = ditch_braces(from);
3498         strncpy(p->from,of,sizeof(p->from) - 1);
3499         if (strncmp(of, "sip:", 4)) {
3500                 ast_log(LOG_NOTICE, "From address missing 'sip:', using it anyway\n");
3501         } else
3502                 of += 4;
3503         /* Get just the username part */
3504         if ((c = strchr(of, '@'))) {
3505                 *c = '\0';
3506                 c++;
3507         }
3508         if (c) {
3509                 snprintf(referto, sizeof(referto), "<sip:%s@%s>", dest, c);
3510         } else {
3511                 snprintf(referto, sizeof(referto), "<sip:%s>", dest);
3512         }
3513
3514         /* save in case we get 407 challenge */
3515         strncpy(p->refer_to, referto, sizeof(p->refer_to) - 1); 
3516         strncpy(p->referred_by, p->our_contact, sizeof(p->referred_by) - 1); 
3517
3518         reqprep(&req, p, "REFER", 0, 1);
3519         add_header(&req, "Refer-To", referto);
3520         if (strlen(p->our_contact))
3521                 add_header(&req, "Referred-By", p->our_contact);
3522         add_blank_header(&req);
3523         return send_request(p, &req, 1, p->ocseq);
3524 }
3525
3526 static int transmit_info_with_digit(struct sip_pvt *p, char digit)
3527 {
3528         struct sip_request req;