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