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