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