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