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