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