Thu Feb 13 07:00:00 CET 2003
[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 <sys/socket.h>
36 #include <sys/ioctl.h>
37 #include <net/if.h>
38 #include <errno.h>
39 #include <unistd.h>
40 #include <stdlib.h>
41 #include <fcntl.h>
42 #include <netdb.h>
43 #include <arpa/inet.h>
44 #include <sys/signal.h>
45 #include <netinet/ip.h>
46
47 /* #define VOCAL_DATA_HACK */
48
49 #define SIPDUMPER
50 #define DEFAULT_EXPIREY 120
51 #define MAX_EXPIREY     3600
52 #define DEFAULT_MAXMS           2000            /* Must be faster than 2 seconds by default */
53
54 #define DEFAULT_MAXMS           2000            /* Must be faster than 2 seconds by default */
55 #define DEFAULT_FREQ_OK         60 * 1000               /* How often to check for the host to be up */
56 #define DEFAULT_FREQ_NOTOK      10 * 1000               /* How often to check, if the host is down... */
57
58 static char *desc = "Session Initiation Protocol (SIP)";
59 static char *type = "sip";
60 static char *tdesc = "Session Initiation Protocol (SIP)";
61 static char *config = "sip.conf";
62
63 #define DEFAULT_SIP_PORT        5060    /* From RFC 2543 */
64 #define SIP_MAX_PACKET  1500            /* Also from RFC 2543, should sub headers tho */
65
66 static char context[AST_MAX_EXTENSION] = "default";
67
68 static char language[MAX_LANGUAGE] = "";
69
70 static int usecnt =0;
71 static pthread_mutex_t usecnt_lock = AST_MUTEX_INITIALIZER;
72
73 /* Protect the interface list (of sip_pvt's) */
74 static pthread_mutex_t iflock = AST_MUTEX_INITIALIZER;
75
76 /* Protect the monitoring thread, so only one process can kill or start it, and not
77    when it's doing something critical. */
78 static pthread_mutex_t netlock = AST_MUTEX_INITIALIZER;
79
80 static pthread_mutex_t monlock = AST_MUTEX_INITIALIZER;
81
82 /* This is the thread for the monitor which checks for input on the channels
83    which are not currently in use.  */
84 static pthread_t monitor_thread = 0;
85
86 static int restart_monitor(void);
87
88 /* Just about everybody seems to support ulaw, so make it a nice default */
89 static int capability = AST_FORMAT_ULAW | AST_FORMAT_ALAW | AST_FORMAT_GSM;
90
91 static char ourhost[256];
92 static struct in_addr __ourip;
93 static int ourport;
94
95 static int sipdebug = 0;
96
97 static int tos = 0;
98
99 /* Expire slowly */
100 static int expirey = 900;
101
102 static struct sched_context *sched;
103 static struct io_context *io;
104 /* The private structures of the  sip channels are linked for
105    selecting outgoing channels */
106    
107 #define SIP_MAX_HEADERS         64
108 #define SIP_MAX_LINES           64
109
110 struct sip_request {
111   char *rlPart1; /* SIP Method Name or "SIP/2.0" protocol version */
112   char *rlPart2; /* The Request URI or Response Status */
113         int len;
114         int headers;                                    /* SIP Headers */
115         char *header[SIP_MAX_HEADERS];
116         int lines;                                              /* SDP Content */
117         char *line[SIP_MAX_LINES];
118         char data[SIP_MAX_PACKET];
119 };
120
121 static struct sip_pvt {
122         pthread_mutex_t lock;                           /* Channel private lock */
123         char callid[80];                                        /* Global CallID */
124         char randdata[80];      /* Random data */
125         unsigned int ocseq;                                     /* Current outgoing seqno */
126         unsigned int icseq;                                     /* Current incoming seqno */
127         int lastinvite;                                         /* Last Cseq of invite */
128         int alreadygone;                                        /* Whether or not we've already been destroyed by or peer */
129         int needdestroy;                                        /* if we need to be destroyed */
130         int capability;                                         /* Special capability */
131         int outgoing;                                           /* Outgoing or incoming call? */
132         int insecure;                                           /* Don't check source port/ip */
133         int expirey;                                            /* How long we take to expire */
134         int branch;                                                     /* One random number */
135         int canreinvite;                                        /* Do we support reinvite */
136         int progress;                                           /* Have sent 183 message progress */
137         int tag;                                                        /* Another random number */
138         struct sockaddr_in sa;                          /* Our peer */
139         struct in_addr ourip;                           /* Our IP */
140         struct ast_channel *owner;                      /* Who owns us */
141         char exten[AST_MAX_EXTENSION];          /* Extention where to start */
142         char refer_to[AST_MAX_EXTENSION];       /* Place to store REFER-TO extension */
143         char referred_by[AST_MAX_EXTENSION];/* Place to store REFERRED-BY extension */
144         char refer_contact[AST_MAX_EXTENSION];/* Place to store Contact info from a REFER extension */
145         char record_route[256];
146         char record_route_info[256];
147         char remote_party_id[256];
148         char context[AST_MAX_EXTENSION];
149         char language[MAX_LANGUAGE];
150         char theirtag[256];                             /* Their tag */
151         char username[81];
152         char peername[81];
153         char peersecret[81];
154         char callerid[256];                                     /* Caller*ID */
155         char via[256];
156         char accountcode[256];                          /* Account code */
157         int amaflags;                                           /* AMA Flags */
158         struct sip_request initreq;                     /* Initial request */
159         
160         int maxtime;                                            /* Max time for first response */
161         int initid;                                                     /* Auto-congest ID if appropriate */
162         
163         struct sip_peer *peerpoke;                      /* If this calls is to poke a peer, which one */
164         struct sip_registry *registry;                  /* If this is a REGISTER call, to which registry */
165         struct ast_rtp *rtp;                            /* RTP Session */
166         struct sip_pvt *next;
167 } *iflist = NULL;
168
169 static struct sip_pkt {
170         int retrans;
171         struct sip_pvt *owner;
172         int packetlen;
173         char data[SIP_MAX_PACKET];
174         struct sip_pkt *next;
175 } *packets = NULL;      
176
177 struct sip_user {
178         /* Users who can access various contexts */
179         char name[80];
180         char secret[80];
181         char context[80];
182         char callerid[80];
183         char methods[80];
184         char accountcode[80];
185         int hascallerid;
186         int amaflags;
187         int insecure;
188         int canreinvite;
189         struct ast_ha *ha;
190         struct sip_user *next;
191 };
192
193 struct sip_peer {
194         char name[80];
195         char secret[80];
196         char context[80];               /* JK02: peers need context too to allow parking etc */
197         char methods[80];
198         char username[80];
199         char mailbox[AST_MAX_EXTENSION];
200         int lastmsgssent;
201         time_t  lastmsgcheck;
202         int dynamic;
203         int expire;
204         int expirey;
205         int capability;
206         int insecure;
207         int canreinvite;
208         struct sockaddr_in addr;
209         struct in_addr mask;
210
211         /* Qualification */
212         struct sip_pvt *call;           /* Call pointer */
213         int pokeexpire;                         /* When to expire poke */
214         int lastms;                                     /* How long last response took (in ms), or -1 for no response */
215         int maxms;                                      /* Max ms we will accept for the host to be up, 0 to not monitor */
216         struct timeval ps;                      /* Ping send time */
217         
218         struct sockaddr_in defaddr;
219         struct ast_ha *ha;
220         int delme;
221         int lastmsg;
222         struct sip_peer *next;
223 };
224
225 static struct ast_user_list {
226         struct sip_user *users;
227         pthread_mutex_t lock;
228 } userl = { NULL, AST_MUTEX_INITIALIZER };
229
230 static struct ast_peer_list {
231         struct sip_peer *peers;
232         pthread_mutex_t lock;
233 } peerl = { NULL, AST_MUTEX_INITIALIZER };
234
235
236 #define REG_STATE_UNREGISTERED 0
237 #define REG_STATE_REGSENT          1
238 #define REG_STATE_AUTHSENT         2
239 #define REG_STATE_REGISTERED   3
240 #define REG_STATE_REJECTED         4
241 #define REG_STATE_TIMEOUT          5
242 #define REG_STATE_NOAUTH           6
243
244 struct sip_registry {
245         pthread_mutex_t lock;                           /* Channel private lock */
246         struct sockaddr_in addr;                /* Who we connect to for registration purposes */
247         char username[80];
248         char secret[80];                        /* Password or key name in []'s */
249         char random[80];
250         int expire;                                     /* Sched ID of expiration */
251         int timeout;                                    /* sched id of sip_reg_timeout */
252         int refresh;                                    /* How often to refresh */
253         struct sip_pvt *call;                           /* create a sip_pvt structure for each outbound "registration call" in progress */
254         int regstate;
255         int callid_valid;               /* 0 means we haven't chosen callid for this registry yet. */
256         char callid[80];                /* Global CallID for this registry */
257         struct sockaddr_in us;                  /* Who the server thinks we are */
258         struct sip_registry *next;
259 };
260
261 static int sip_do_register(struct sip_registry *r);
262 struct sip_registry *registrations;
263
264 static int sipsock  = -1;
265
266 static struct sockaddr_in bindaddr;
267
268 static struct ast_frame  *sip_read(struct ast_channel *ast);
269 static int transmit_response(struct sip_pvt *p, char *msg, struct sip_request *req);
270 static int transmit_response_with_sdp(struct sip_pvt *p, char *msg, struct sip_request *req);
271 static int transmit_response_with_auth(struct sip_pvt *p, char *msg, struct sip_request *req, char *rand);
272 static int transmit_request(struct sip_pvt *p, char *msg, int inc);
273 static int transmit_invite(struct sip_pvt *p, char *msg, int sendsdp, char *auth, char *vxml_url);
274 static int transmit_reinvite_with_sdp(struct sip_pvt *p, struct ast_rtp *rtp);
275 static int transmit_message_with_text(struct sip_pvt *p, char *text);
276 static int do_proxy_auth(struct sip_pvt *p, struct sip_request *req);
277
278 static int __sip_xmit(struct sip_pvt *p, char *data, int len)
279 {
280         int res;
281     res=sendto(sipsock, data, len, 0, (struct sockaddr *)&p->sa, sizeof(struct sockaddr_in));
282         if (res != len) {
283                 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));
284         }
285         return res;
286 }
287
288 static int send_response(struct sip_pvt *p, struct sip_request *req)
289 {
290         int res;
291         if (sipdebug)
292                 ast_verbose("Transmitting:\n%s\n to %s:%d\n", req->data, inet_ntoa(p->sa.sin_addr), ntohs(p->sa.sin_port));
293         res = __sip_xmit(p, req->data, req->len);
294         if (res > 0)
295                 res = 0;
296         return res;
297 }
298
299 static int send_request(struct sip_pvt *p, struct sip_request *req)
300 {
301         int res;
302         if (sipdebug)
303                 ast_verbose("XXX Need to handle Retransmitting XXX:\n%s to %s:%d\n", req->data, inet_ntoa(p->sa.sin_addr), ntohs(p->sa.sin_port));
304         res = __sip_xmit(p, req->data, req->len);
305         return res;
306 }
307
308 static char *ditch_braces(char *tmp)
309 {
310         char *c = tmp;
311         char *n;
312         c = tmp;
313         if ((n = strchr(tmp, '<')) ) {
314                 c = n + 1;
315                 while(*c && *c != '>') c++;
316                 if (*c != '>') {
317                         ast_log(LOG_WARNING, "No closing brace in '%s'\n", tmp);
318                 } else {
319                         *c = '\0';
320                 }
321                 return n+1;
322         }
323         return c;
324 }
325
326 static int sip_sendtext(struct ast_channel *ast, char *text)
327 {
328         struct sip_pvt *p = ast->pvt->pvt;
329         if (sipdebug) 
330                 ast_verbose("Sending text %s on %s\n", text, ast->name);
331         if (!p)
332                 return -1;
333         if (!text || !strlen(text))
334                 return 0;
335         if (sipdebug)
336                 ast_verbose("Really sending text %s on %s\n", text, ast->name);
337         transmit_message_with_text(p, text);
338         return 0;       
339 }
340
341 static int create_addr(struct sip_pvt *r, char *peer)
342 {
343         struct hostent *hp;
344         struct sip_peer *p;
345         int found=0;
346         r->sa.sin_family = AF_INET;
347         ast_pthread_mutex_lock(&peerl.lock);
348         p = peerl.peers;
349         while(p) {
350                 if (!strcasecmp(p->name, peer)) {
351                         found++;
352                         r->capability = p->capability;
353                         strncpy(r->peername, p->username, sizeof(r->peername)-1);
354                         strncpy(r->peersecret, p->secret, sizeof(r->peersecret)-1);
355                         strncpy(r->username, p->username, sizeof(r->username)-1);
356                         r->insecure = p->insecure;
357                         r->canreinvite = p->canreinvite;
358                         r->maxtime = p->maxms;
359                         strncpy(r->context, p->context,sizeof(r->context)-1);
360                         if ((p->addr.sin_addr.s_addr || p->defaddr.sin_addr.s_addr) &&
361                                 (!p->maxms || ((p->lastms > 0)  && (p->lastms <= p->maxms)))) {
362                                 if (p->addr.sin_addr.s_addr) {
363                                         r->sa.sin_addr = p->addr.sin_addr;
364                                         r->sa.sin_port = p->addr.sin_port;
365                                 } else {
366                                         r->sa.sin_addr = p->defaddr.sin_addr;
367                                         r->sa.sin_port = p->defaddr.sin_port;
368                                 }
369                                 break;
370                         }
371                 }
372                 p = p->next;
373         }
374         ast_pthread_mutex_unlock(&peerl.lock);
375         if (!p && !found) {
376                 hp = gethostbyname(peer);
377                 if (hp) {
378                         memcpy(&r->sa.sin_addr, hp->h_addr, sizeof(r->sa.sin_addr));
379                         r->sa.sin_port = htons(DEFAULT_SIP_PORT);
380                         return 0;
381                 } else {
382                         ast_log(LOG_WARNING, "No such host: %s\n", peer);
383                         return -1;
384                 }
385         } else if (!p)
386                 return -1;
387         else
388                 return 0;
389 }
390
391 static int auto_congest(void *nothing)
392 {
393         struct sip_pvt *p = nothing;
394         ast_pthread_mutex_lock(&p->lock);
395         p->initid = -1;
396         if (p->owner) {
397                 if (!pthread_mutex_trylock(&p->owner->lock)) {
398                         ast_log(LOG_NOTICE, "Auto-congesting %s\n", p->owner->name);
399                         ast_queue_control(p->owner, AST_CONTROL_CONGESTION, 0);
400                         ast_pthread_mutex_unlock(&p->owner->lock);
401                 }
402         }
403         ast_pthread_mutex_unlock(&p->lock);
404         return 0;
405 }
406
407 static int sip_call(struct ast_channel *ast, char *dest, int timeout)
408 {
409         int res;
410         struct sip_pvt *p;
411         char *vxml_url = NULL;
412         struct varshead *headp;
413         struct ast_var_t *current;
414         
415         p = ast->pvt->pvt;
416         if ((ast->_state != AST_STATE_DOWN) && (ast->_state != AST_STATE_RESERVED)) {
417                 ast_log(LOG_WARNING, "sip_call called on %s, neither down nor reserved\n", ast->name);
418                 return -1;
419         }
420
421         /* Check whether there is a VXML_URL variable */
422         headp=&ast->varshead;
423         AST_LIST_TRAVERSE(headp,current,entries) {
424                 if (strcasecmp(ast_var_name(current),"VXML_URL")==0)
425                 {
426                         vxml_url = ast_var_value(current);
427                         break;
428                 }
429         }
430         
431         res = 0;
432         p->outgoing = 1;
433         transmit_invite(p, "INVITE", 1, NULL, vxml_url);
434         if (p->maxtime) {
435                 /* Initialize auto-congest time */
436                 p->initid = ast_sched_add(sched, p->maxtime * 2, auto_congest, p);
437         }
438         return res;
439 }
440
441 static void __sip_destroy(struct sip_pvt *p, int lockowner)
442 {
443         struct sip_pvt *cur, *prev = NULL;
444         if (p->rtp) {
445                 ast_rtp_destroy(p->rtp);
446         }
447         /* Unlink us from the owner if we have one */
448         if (p->owner) {
449                 if (lockowner)
450                         ast_pthread_mutex_lock(&p->owner->lock);
451                 ast_log(LOG_DEBUG, "Detaching from %s\n", p->owner->name);
452                 p->owner->pvt->pvt = NULL;
453                 if (lockowner)
454                         ast_pthread_mutex_unlock(&p->owner->lock);
455         }
456         cur = iflist;
457         while(cur) {
458                 if (cur == p) {
459                         if (prev)
460                                 prev->next = cur->next;
461                         else
462                                 iflist = cur->next;
463                         break;
464                 }
465                 prev = cur;
466                 cur = cur->next;
467         }
468         if (!cur) {
469                 ast_log(LOG_WARNING, "%p is not in list?!?! \n", cur);
470         } else {
471                 if (p->initid > -1)
472                         ast_sched_del(sched, p->initid);
473                 free(p);
474         }
475 }
476 static void sip_destroy(struct sip_pvt *p)
477 {
478         ast_pthread_mutex_lock(&iflock);
479         __sip_destroy(p, 1);
480         ast_pthread_mutex_unlock(&iflock);
481 }
482
483 /* Interface lookup code courtesy Tilghman of DrunkCoder.com.  Thanks! */
484
485 struct my_ifreq {
486     union
487       {
488         char ifrn_name[IFNAMSIZ];       /* Interface name, e.g. "en0".  */
489       } ifr_ifrn;
490
491     union
492       {
493         struct sockaddr_in ifru_addr;
494         char ifru_data[512];
495       } ifr_ifru;
496 };
497
498 struct in_addr *lookup_iface(char *iface) {
499         int mysock;
500         int res;
501         static struct  my_ifreq ifreq;
502         memset(&ifreq, 0, sizeof(ifreq));
503         strncpy(ifreq.ifr_ifrn.ifrn_name,iface,sizeof(ifreq.ifr_ifrn.ifrn_name) - 1);
504
505         mysock = socket(PF_INET,SOCK_DGRAM,IPPROTO_IP);
506         res = ioctl(mysock,SIOCGIFADDR,&ifreq);
507         
508         close(mysock);
509         if (res < 0) {
510                 ast_log(LOG_WARNING, "Unable to get IP of %s: %s\n", iface, strerror(errno));
511                 return &__ourip;
512         }
513         return( (struct in_addr *) &ifreq.ifr_ifru.ifru_addr.sin_addr );
514 }
515
516 static struct in_addr *myaddrfor(struct in_addr *them)
517 {
518         FILE *PROC;
519         struct in_addr *temp = NULL;
520         unsigned int remote_ip;
521         char line[256];
522         remote_ip = them->s_addr;
523         
524         PROC = fopen("/proc/net/route","r");
525         if (!PROC) {
526                 /* If /proc/net/route doesn't exist, fall back to the old method */
527                 return &__ourip;
528         }
529         /* First line contains headers */
530         fgets(line,sizeof(line),PROC);
531
532         while (!feof(PROC)) {
533                 char iface[8];
534                 unsigned int dest, gateway, mask;
535                 int i,aoffset;
536                 char *fields[40];
537
538                 fgets(line,sizeof(line),PROC);
539
540                 aoffset = 0;
541                 for (i=0;i<sizeof(line);i++) {
542                         char *boffset;
543
544                         fields[aoffset++] = line + i;
545                         boffset = strchr(line + i,'\t');
546                         if (boffset == NULL) {
547                                 /* Exit loop */
548                                 break;
549                         } else {
550                                 *boffset = '\0';
551                                 i = boffset - line;
552                         }
553                 }
554
555                 sscanf(fields[0],"%s",iface);
556                 sscanf(fields[1],"%x",&dest);
557                 sscanf(fields[2],"%x",&gateway);
558                 sscanf(fields[7],"%x",&mask);
559 #if 0
560                 printf("Addr: %s %08x Dest: %08x Mask: %08x\n", inet_ntoa(*them), remote_ip, dest, mask);
561 #endif          
562                 if (((remote_ip & mask) ^ dest) == 0) {
563                         if (sipdebug)
564                                 ast_verbose("Interface is %s\n",iface);
565                         temp = lookup_iface(iface);
566                         if (sipdebug)
567                                 ast_verbose("IP Address is %s\n",inet_ntoa(*temp));
568                         break;
569                 }
570         }
571         fclose(PROC);
572         if (!temp) {
573                 ast_log(LOG_WARNING, "Couldn't figure out how to get to %s.  Using default\n", inet_ntoa(*them));
574                 temp = &__ourip;
575         }
576         return temp;
577 }
578
579
580 static int sip_hangup(struct ast_channel *ast)
581 {
582         struct sip_pvt *p = ast->pvt->pvt;
583         int needcancel = 0;
584         if (option_debug)
585                 ast_log(LOG_DEBUG, "sip_hangup(%s)\n", ast->name);
586         if (!ast->pvt->pvt) {
587                 ast_log(LOG_DEBUG, "Asked to hangup channel not connected\n");
588                 return 0;
589         }
590         ast_pthread_mutex_lock(&p->lock);
591         /* Determine how to disconnect */
592         if (p->owner != ast) {
593                 ast_log(LOG_WARNING, "Huh?  We aren't the owner?\n");
594                 ast_pthread_mutex_unlock(&p->lock);
595                 return 0;
596         }
597         if (!ast || (ast->_state != AST_STATE_UP))
598                 needcancel = 1;
599         /* Disconnect */
600         p = ast->pvt->pvt;
601         p->owner = NULL;
602         ast->pvt->pvt = NULL;
603
604         p->needdestroy = 1;
605 #if 0
606         /* Invert sense of outgoing */
607         p->outgoing = 1 - p->outgoing;
608 #endif  
609         /* Start the process if it's not already started */
610         if (!p->alreadygone && strlen(p->initreq.data)) {
611                 if (needcancel) {
612                         transmit_request(p, "CANCEL", 0);
613                 } else {
614                         /* Send a hangup */
615                         transmit_request(p, "BYE", p->outgoing);
616                 }
617         }
618 #if 0
619         /* Restore sense of outgoing */
620         p->outgoing = 1 - p->outgoing;
621 #endif  
622         ast_pthread_mutex_unlock(&p->lock);
623         return 0;
624 }
625
626 static int sip_answer(struct ast_channel *ast)
627 {
628         int res = 0;
629         struct sip_pvt *p = ast->pvt->pvt;
630         if (ast->_state != AST_STATE_UP) {
631                 ast_setstate(ast, AST_STATE_UP);
632                 if (option_debug)
633                         ast_log(LOG_DEBUG, "sip_answer(%s)\n", ast->name);
634                 res = transmit_response_with_sdp(p, "200 OK", &p->initreq);
635         }
636         return res;
637 }
638
639 static int sip_write(struct ast_channel *ast, struct ast_frame *frame)
640 {
641         struct sip_pvt *p = ast->pvt->pvt;
642         int res = 0;
643         if (frame->frametype != AST_FRAME_VOICE) {
644                 if (frame->frametype == AST_FRAME_IMAGE)
645                         return 0;
646                 else {
647                         ast_log(LOG_WARNING, "Can't send %d type frames with SIP write\n", frame->frametype);
648                         return 0;
649                 }
650         } else {
651                 if (!(frame->subclass & ast->nativeformats)) {
652                         ast_log(LOG_WARNING, "Asked to transmit frame type %d, while native formats is %d (read/write = %d/%d)\n",
653                                 frame->subclass, ast->nativeformats, ast->readformat, ast->writeformat);
654                         return -1;
655                 }
656         }
657         if (p) {
658                 ast_pthread_mutex_lock(&p->lock);
659                 if (p->rtp) {
660                         if ((ast->_state != AST_STATE_UP) && !p->progress && !p->outgoing) {
661                                 transmit_response_with_sdp(p, "183 Session Progress", &p->initreq);
662                                 p->progress = 1;
663                         }
664                         res =  ast_rtp_write(p->rtp, frame);
665                 }
666                 ast_pthread_mutex_unlock(&p->lock);
667         }
668         return res;
669 }
670
671 static int sip_fixup(struct ast_channel *oldchan, struct ast_channel *newchan)
672 {
673         struct sip_pvt *p = newchan->pvt->pvt;
674         ast_pthread_mutex_lock(&p->lock);
675         if (p->owner != oldchan) {
676                 ast_log(LOG_WARNING, "old channel wasn't %p but was %p\n", oldchan, p->owner);
677                 ast_pthread_mutex_unlock(&p->lock);
678                 return -1;
679         }
680         p->owner = newchan;
681         ast_pthread_mutex_unlock(&p->lock);
682         return 0;
683 }
684
685 static int sip_senddigit(struct ast_channel *ast, char digit)
686 {
687         struct sip_pvt *p = ast->pvt->pvt;
688         if (p && p->rtp) {
689                 ast_rtp_senddigit(p->rtp, digit);
690                 return 0;
691         }
692         return -1;
693 }
694
695 static int sip_indicate(struct ast_channel *ast, int condition)
696 {
697         struct sip_pvt *p = ast->pvt->pvt;
698         switch(condition) {
699         case AST_CONTROL_RINGING:
700                 if (ast->_state == AST_STATE_RING) {
701                         transmit_response(p, "180 Ringing", &p->initreq);
702                         break;
703                 }
704                 return -1;
705         case AST_CONTROL_BUSY:
706                 if (ast->_state != AST_STATE_UP) {
707                         transmit_response(p, "600 Busy everywhere", &p->initreq);
708                         p->alreadygone = 1;
709                         ast_softhangup(ast, AST_SOFTHANGUP_DEV);
710                         break;
711                 }
712                 return -1;
713         case AST_CONTROL_CONGESTION:
714                 if (ast->_state != AST_STATE_UP) {
715                         transmit_response(p, "486 Busy here", &p->initreq);
716                         p->alreadygone = 1;
717                         ast_softhangup(ast, AST_SOFTHANGUP_DEV);
718                         break;
719                 }
720                 return -1;
721         case -1:
722                 return -1;
723         default:
724                 ast_log(LOG_WARNING, "Don't know how to indicate condition %d\n", condition);
725                 return -1;
726         }
727         return 0;
728 }
729
730
731 static int sip_bridge(struct ast_channel *c0, struct ast_channel *c1, int flags, struct ast_frame **fo, struct ast_channel **rc)
732 {
733         struct sip_pvt *p0, *p1;
734         struct ast_frame *f;
735         struct ast_channel *who, *cs[3];
736         int to;
737
738         /* if need DTMF, cant native bridge */
739         if (flags & (AST_BRIDGE_DTMF_CHANNEL_0 | AST_BRIDGE_DTMF_CHANNEL_1))
740                 return -2;
741         ast_pthread_mutex_lock(&c0->lock);
742         ast_pthread_mutex_lock(&c1->lock);
743         p0 = c0->pvt->pvt;
744         p1 = c1->pvt->pvt;
745         if (!p0->canreinvite || !p1->canreinvite) {
746                 /* Not gonna support reinvite */
747                 ast_pthread_mutex_unlock(&c0->lock);
748                 ast_pthread_mutex_unlock(&c1->lock);
749                 return -2;
750         }
751         transmit_reinvite_with_sdp(p0, p1->rtp);
752         transmit_reinvite_with_sdp(p1, p0->rtp);
753         ast_pthread_mutex_unlock(&c0->lock);
754         ast_pthread_mutex_unlock(&c1->lock);
755         cs[0] = c0;
756         cs[1] = c1;
757         cs[2] = NULL;
758         for (;;) {
759                 if ((c0->pvt->pvt != p0)  ||
760                         (c1->pvt->pvt != p1) ||
761                         (c0->masq || c0->masqr || c1->masq || c1->masqr)) {
762                                 ast_log(LOG_DEBUG, "Oooh, something is weird, backing out\n");
763                                 if (c0->pvt->pvt == p0)
764                                         transmit_reinvite_with_sdp(p0, NULL);
765                                 if (c1->pvt->pvt == p1)
766                                         transmit_reinvite_with_sdp(p1, NULL);
767                                 /* Tell it to try again later */
768                                 return -3;
769                 }
770                 to = -1;
771                 who = ast_waitfor_n(cs, 2, &to);
772                 if (!who) {
773                         ast_log(LOG_DEBUG, "Ooh, empty read...\n");
774                         continue;
775                 }
776                 f = ast_read(who);
777                 if (!f || ((f->frametype == AST_FRAME_DTMF) &&
778                                    (((who == c0) && (flags & AST_BRIDGE_DTMF_CHANNEL_0)) || 
779                                ((who == c1) && (flags & AST_BRIDGE_DTMF_CHANNEL_1))))) {
780                         *fo = f;
781                         *rc = who;
782                         ast_log(LOG_DEBUG, "Oooh, got a %s\n", f ? "digit" : "hangup");
783                         if (c0->pvt->pvt == p0 && !c0->_softhangup)
784                                 transmit_reinvite_with_sdp(p0, NULL);
785                         if (c1->pvt->pvt == p1 && !c1->_softhangup)
786                                 transmit_reinvite_with_sdp(p1, NULL);
787                         /* That's all we needed */
788                         return 0;
789                 } else 
790                         ast_frfree(f);
791                 /* Swap priority not that it's a big deal at this point */
792                 cs[2] = cs[0];
793                 cs[0] = cs[1];
794                 cs[1] = cs[2];
795                 
796         }
797         return -1;
798 }
799
800 static struct ast_channel *sip_new(struct sip_pvt *i, int state, char *title)
801 {
802         struct ast_channel *tmp;
803         int fmt;
804         tmp = ast_channel_alloc(1);
805         if (tmp) {
806                 tmp->nativeformats = i->capability;
807                 if (!tmp->nativeformats)
808                         tmp->nativeformats = capability;
809                 fmt = ast_best_codec(tmp->nativeformats);
810                 if (title)
811                         snprintf(tmp->name, sizeof(tmp->name), "SIP/%s", title);
812                 else
813                         snprintf(tmp->name, sizeof(tmp->name), "SIP/%s:%d", inet_ntoa(i->sa.sin_addr), ntohs(i->sa.sin_port));
814                 tmp->type = type;
815                 tmp->fds[0] = ast_rtp_fd(i->rtp);
816                 ast_setstate(tmp, state);
817                 if (state == AST_STATE_RING)
818                         tmp->rings = 1;
819                 tmp->writeformat = fmt;
820                 tmp->pvt->rawwriteformat = fmt;
821                 tmp->readformat = fmt;
822                 tmp->pvt->rawreadformat = fmt;
823                 tmp->pvt->pvt = i;
824                 tmp->pvt->send_text = sip_sendtext;
825                 tmp->pvt->call = sip_call;
826                 tmp->pvt->hangup = sip_hangup;
827                 tmp->pvt->answer = sip_answer;
828                 tmp->pvt->read = sip_read;
829                 tmp->pvt->write = sip_write;
830                 tmp->pvt->indicate = sip_indicate;
831                 tmp->pvt->fixup = sip_fixup;
832                 tmp->pvt->send_digit = sip_senddigit;
833                 tmp->pvt->bridge = sip_bridge;
834                 if (strlen(i->language))
835                         strncpy(tmp->language, i->language, sizeof(tmp->language)-1);
836                 i->owner = tmp;
837                 ast_pthread_mutex_lock(&usecnt_lock);
838                 usecnt++;
839                 ast_pthread_mutex_unlock(&usecnt_lock);
840                 ast_update_use_count();
841                 strncpy(tmp->context, i->context, sizeof(tmp->context)-1);
842                 strncpy(tmp->exten, i->exten, sizeof(tmp->exten)-1);
843                 if (strlen(i->callerid))
844                         tmp->callerid = strdup(i->callerid);
845                 tmp->priority = 1;
846                 if (state != AST_STATE_DOWN) {
847                         if (ast_pbx_start(tmp)) {
848                                 ast_log(LOG_WARNING, "Unable to start PBX on %s\n", tmp->name);
849                                 ast_hangup(tmp);
850                                 tmp = NULL;
851                         }
852                 }
853         } else
854                 ast_log(LOG_WARNING, "Unable to allocate channel structure\n");
855         return tmp;
856 }
857
858 static struct cfalias {
859         char *fullname;
860         char *shortname;
861 } aliases[] = {
862         { "Content-Type", "c" },
863         { "Content-Encoding", "e" },
864         { "From", "f" },
865         { "Call-ID", "i" },
866         { "Contact", "m" },
867         { "Content-Length", "l" },
868         { "Subject", "s" },
869         { "To", "t" },
870         { "Via", "v" },
871 };
872
873 static char *get_sdp(struct sip_request *req, char *name)
874 {
875         int x;
876         int len = strlen(name);
877         char *r;
878         for (x=0;x<req->lines;x++) {
879                 if (!strncasecmp(req->line[x], name, len) && 
880                                 (req->line[x][len] == '=')) {
881                                         r = req->line[x] + len + 1;
882                                         while(*r && (*r < 33))
883                                                         r++;
884                                         return r;
885                 }
886         }
887         return "";
888 }
889
890 static char *__get_header(struct sip_request *req, char *name, int *start)
891 {
892         int x;
893         int len = strlen(name);
894         char *r;
895         for (x=*start;x<req->headers;x++) {
896                 if (!strncasecmp(req->header[x], name, len) && 
897                                 (req->header[x][len] == ':')) {
898                                         r = req->header[x] + len + 1;
899                                         while(*r && (*r < 33))
900                                                         r++;
901                                         *start = x+1;
902                                         return r;
903                 }
904         }
905         /* Try aliases */
906         for (x=0;x<sizeof(aliases) / sizeof(aliases[0]); x++) 
907                 if (!strcasecmp(aliases[x].fullname, name))
908                         return __get_header(req, aliases[x].shortname, start);
909
910         /* Don't return NULL, so get_header is always a valid pointer */
911         return "";
912 }
913
914 static char *get_header(struct sip_request *req, char *name)
915 {
916         int start = 0;
917         return __get_header(req, name, &start);
918 }
919
920 static struct ast_frame *sip_rtp_read(struct sip_pvt *p)
921 {
922         /* Retrieve audio/etc from channel.  Assumes p->lock is already held. */
923         struct ast_frame *f;
924         f = ast_rtp_read(p->rtp);
925         if (p->owner) {
926                 /* We already hold the channel lock */
927                 if (f->frametype == AST_FRAME_VOICE) {
928                         if (f->subclass != p->owner->nativeformats) {
929                                 ast_log(LOG_DEBUG, "Oooh, format changed to %d\n", f->subclass);
930                                 p->owner->nativeformats = f->subclass;
931                                 ast_set_read_format(p->owner, p->owner->readformat);
932                                 ast_set_write_format(p->owner, p->owner->writeformat);
933                         }
934                 }
935         }
936         return f;
937 }
938
939 static struct ast_frame *sip_read(struct ast_channel *ast)
940 {
941         struct ast_frame *fr;
942         struct sip_pvt *p = ast->pvt->pvt;
943         ast_pthread_mutex_lock(&p->lock);
944         fr = sip_rtp_read(p);
945         ast_pthread_mutex_unlock(&p->lock);
946         return fr;
947 }
948
949 static void build_callid(char *callid, int len, struct in_addr ourip)
950 {
951         int res;
952         int val;
953         int x;
954         for (x=0;x<4;x++) {
955                 val = rand();
956                 res = snprintf(callid, len, "%08x", val);
957                 len -= res;
958                 callid += res;
959         }
960         /* It's not important that we really use our right IP here... */
961         snprintf(callid, len, "@%s", inet_ntoa(ourip));
962 }
963
964 static struct sip_pvt *sip_alloc(char *callid, struct sockaddr_in *sin)
965 {
966         struct sip_pvt *p;
967
968         p = malloc(sizeof(struct sip_pvt));
969         if (!p)
970                 return NULL;
971         /* Keep track of stuff */
972         memset(p, 0, sizeof(struct sip_pvt));
973         p->initid = -1;
974         p->rtp = ast_rtp_new(NULL, NULL);
975         p->branch = rand();     
976         p->tag = rand();
977         /* Start with 101 instead of 1 */
978         p->ocseq = 101;
979         if (!p->rtp) {
980                 ast_log(LOG_WARNING, "Unable to create RTP session: %s\n", strerror(errno));
981                 free(p);
982                 return NULL;
983         }
984         ast_rtp_settos(p->rtp, tos);
985         ast_pthread_mutex_init(&p->lock);
986 #if 0
987         ast_rtp_set_data(p->rtp, p);
988         ast_rtp_set_callback(p->rtp, rtpready);
989 #endif  
990         if (sin) {
991                 memcpy(&p->sa, sin, sizeof(p->sa));
992                 memcpy(&p->ourip, myaddrfor(&p->sa.sin_addr), sizeof(p->ourip));
993         } else {
994                 memcpy(&p->ourip, &__ourip, sizeof(p->ourip));
995         }
996         snprintf(p->via, sizeof(p->via), "SIP/2.0/UDP %s:%d;branch=%08x", inet_ntoa(p->ourip), ourport, p->branch);
997         if (!callid)
998                 build_callid(p->callid, sizeof(p->callid), p->ourip);
999         else
1000                 strncpy(p->callid, callid, sizeof(p->callid) - 1);
1001         /* Assume reinvite OK */
1002         p->canreinvite = 1;
1003         /* Add to list */
1004         ast_pthread_mutex_lock(&iflock);
1005         p->next = iflist;
1006         iflist = p;
1007         ast_pthread_mutex_unlock(&iflock);
1008         if (option_debug)
1009                 ast_log(LOG_DEBUG, "Allocating new SIP call for %s\n", callid);
1010         return p;
1011 }
1012
1013 static struct sip_pvt *find_call(struct sip_request *req, struct sockaddr_in *sin)
1014 {
1015         struct sip_pvt *p;
1016         char *callid;
1017         callid = get_header(req, "Call-ID");
1018         if (!strlen(callid)) {
1019                 ast_log(LOG_WARNING, "Call missing call ID from '%s'\n", inet_ntoa(sin->sin_addr));
1020                 return NULL;
1021         }
1022         ast_pthread_mutex_lock(&iflock);
1023         p = iflist;
1024         while(p) {
1025                 if (!strcmp(p->callid, callid)) {
1026                         /* Found the call */
1027 #if 0
1028                         if (!p->insecure && ((p->sa.sin_addr.s_addr != sin->sin_addr.s_addr) ||
1029                             (p->sa.sin_port != sin->sin_port))) {
1030                                         char orig[80];
1031                                         char new[80];
1032                                         snprintf(orig, sizeof(orig), "%s:%d", inet_ntoa(p->sa.sin_addr), ntohs(p->sa.sin_port));
1033                                         snprintf(new, sizeof(new), "%s:%d", inet_ntoa(sin->sin_addr), ntohs(sin->sin_port));
1034                                         ast_log(LOG_WARNING, "Looks like %s is trying to steal call '%s' from %s?\n", new, p->callid, orig);
1035                                         ast_pthread_mutex_unlock(&iflock);
1036                                         return NULL;
1037                         }
1038 #endif
1039                         ast_pthread_mutex_unlock(&iflock);
1040                         return p;
1041                 }
1042                 p = p->next;
1043         }
1044         ast_pthread_mutex_unlock(&iflock);
1045         return sip_alloc(callid, sin);
1046 }
1047
1048 static int sip_register(char *value, int lineno)
1049 {
1050         struct sip_registry *reg;
1051         char copy[256] = "";
1052         char *username, *hostname, *secret;
1053         char *porta;
1054         char *stringp=NULL;
1055         
1056         struct hostent *hp;
1057         if (!value)
1058                 return -1;
1059         strncpy(copy, value, sizeof(copy)-1);
1060         stringp=copy;
1061         username = strsep(&stringp, "@");
1062         hostname = strsep(&stringp, "@");
1063         if (!hostname) {
1064                 ast_log(LOG_WARNING, "Format for registration is user[:secret]@host[:port] at line %d", lineno);
1065                 return -1;
1066         }
1067         stringp=username;
1068         username = strsep(&stringp, ":");
1069         secret = strsep(&stringp, ":");
1070         stringp=hostname;
1071         hostname = strsep(&stringp, ":");
1072         porta = strsep(&stringp, ";");
1073         
1074         if (porta && !atoi(porta)) {
1075                 ast_log(LOG_WARNING, "%s is not a valid port number at line %d\n", porta, lineno);
1076                 return -1;
1077         }
1078         hp = gethostbyname(hostname);
1079         if (!hp) {
1080                 ast_log(LOG_WARNING, "Host '%s' not found at line %d\n", hostname, lineno);
1081                 return -1;
1082         }
1083         reg = malloc(sizeof(struct sip_registry));
1084         if (reg) {
1085                 memset(reg, 0, sizeof(struct sip_registry));
1086                 strncpy(reg->username, username, sizeof(reg->username)-1);
1087                 if (secret)
1088                         strncpy(reg->secret, secret, sizeof(reg->secret)-1);
1089                 reg->expire = -1;
1090                 reg->refresh = DEFAULT_EXPIREY;
1091                 reg->addr.sin_family = AF_INET;
1092                 memcpy(&reg->addr.sin_addr, hp->h_addr, sizeof(&reg->addr.sin_addr));
1093                 reg->addr.sin_port = porta ? htons(atoi(porta)) : htons(DEFAULT_SIP_PORT);
1094                 reg->next = registrations;
1095                 reg->callid_valid = 0;
1096                 registrations = reg;
1097         } else {
1098                 ast_log(LOG_ERROR, "Out of memory\n");
1099                 return -1;
1100         }
1101         return 0;
1102 }
1103
1104 static void parse(struct sip_request *req)
1105 {
1106         /* Divide fields by NULL's */
1107         char *c;
1108         int f = 0;
1109         c = req->data;
1110
1111         /* First header starts immediately */
1112         req->header[f] = c;
1113         while(*c) {
1114                 if (*c == '\n') {
1115                         /* We've got a new header */
1116                         *c = 0;
1117
1118 #if 0
1119                         printf("Header: %s (%d)\n", req->header[f], strlen(req->header[f]));
1120 #endif                  
1121                         if (!strlen(req->header[f])) {
1122                                 /* Line by itself means we're now in content */
1123                                 c++;
1124                                 break;
1125                         }
1126                         if (f >= SIP_MAX_HEADERS - 1) {
1127                                 ast_log(LOG_WARNING, "Too many SIP headers...\n");
1128                         } else
1129                                 f++;
1130                         req->header[f] = c + 1;
1131                 } else if (*c == '\r') {
1132                         /* Ignore but eliminate \r's */
1133                         *c = 0;
1134                 }
1135                 c++;
1136         }
1137         /* Check for last header */
1138         if (strlen(req->header[f])) 
1139                 f++;
1140         req->headers = f;
1141         /* Now we process any mime content */
1142         f = 0;
1143         req->line[f] = c;
1144         while(*c) {
1145                 if (*c == '\n') {
1146                         /* We've got a new line */
1147                         *c = 0;
1148 #if 0
1149                         printf("Line: %s (%d)\n", req->line[f], strlen(req->line[f]));
1150 #endif                  
1151                         if (f >= SIP_MAX_LINES - 1) {
1152                                 ast_log(LOG_WARNING, "Too many SDP lines...\n");
1153                         } else
1154                                 f++;
1155                         req->line[f] = c + 1;
1156                 } else if (*c == '\r') {
1157                         /* Ignore and eliminate \r's */
1158                         *c = 0;
1159                 }
1160                 c++;
1161         }
1162         /* Check for last line */
1163         if (strlen(req->line[f])) 
1164                 f++;
1165         req->lines = f;
1166         if (sipdebug)
1167                 ast_verbose("%d headers, %d lines\n", req->headers, req->lines);
1168         if (*c) 
1169                 ast_log(LOG_WARNING, "Odd content, extra stuff left over ('%s')\n", c);
1170 }
1171
1172 static int process_sdp(struct sip_pvt *p, struct sip_request *req)
1173 {
1174         char *m;
1175         char *c;
1176         char host[258];
1177         int len = -1;
1178         int portno;
1179         int peercapability;
1180         struct sockaddr_in sin;
1181         char *codecs;
1182         struct hostent *hp;
1183         int codec;
1184         /* Get codec and RTP info from SDP */
1185         if (strcasecmp(get_header(req, "Content-Type"), "application/sdp")) {
1186                 ast_log(LOG_NOTICE, "Content is '%s', not 'application/sdp'\n", get_header(req, "Content-Type"));
1187                 return -1;
1188         }
1189         m = get_sdp(req, "m");
1190         c = get_sdp(req, "c");
1191         if (!strlen(m) || !strlen(c)) {
1192                 ast_log(LOG_WARNING, "Insufficient information for SDP (m = '%s', c = '%s')\n", m, c);
1193                 return -1;
1194         }
1195         if (sscanf(c, "IN IP4 %256s", host) != 1) {
1196                 ast_log(LOG_WARNING, "Invalid host in c= line, '%s'\n", c);
1197                 return -1;
1198         }
1199         /* XXX This could block for a long time, and block the main thread! XXX */
1200         hp = gethostbyname(host);
1201         if (!hp) {
1202                 ast_log(LOG_WARNING, "Unable to lookup host in c= line, '%s'\n", c);
1203                 return -1;
1204         }
1205         if ((sscanf(m, "audio %d RTP/AVP %n", &portno, &len) != 1) || (len < 0)) {
1206                 ast_log(LOG_WARNING, "Unable to determine port number for RTP in '%s'\n", m); 
1207                 return -1;
1208         }
1209         sin.sin_family = AF_INET;
1210         memcpy(&sin.sin_addr, hp->h_addr, sizeof(sin.sin_addr));
1211         sin.sin_port = htons(portno);
1212         if (p->rtp)
1213                 ast_rtp_set_peer(p->rtp, &sin);
1214 #if 0
1215         printf("Peer RTP is at port %s:%d\n", inet_ntoa(sin.sin_addr), ntohs(sin.sin_port));
1216 #endif  
1217         peercapability = 0;
1218         codecs = m + len;
1219         while(strlen(codecs)) {
1220                 if (sscanf(codecs, "%d %n", &codec, &len) != 1) {
1221                         ast_log(LOG_WARNING, "Error in codec string '%s'\n", codecs);
1222                         return -1;
1223                 }
1224 #if 0
1225                 printf("Codec: %d\n", codec);
1226 #endif          
1227                 codec = rtp2ast(codec);
1228                 if (codec  > -1)
1229                         peercapability |= codec;
1230                 codecs += len;
1231         }
1232         p->capability = capability & peercapability;
1233         if (sipdebug)
1234                 ast_verbose("Capabilities: us - %d, them - %d, combined - %d\n",
1235                 capability, peercapability, p->capability);
1236         if (!p->capability) {
1237                 ast_log(LOG_WARNING, "No compatible codecs!\n");
1238                 return -1;
1239         }
1240         if (p->owner && !(p->owner->nativeformats & p->capability)) {
1241                 ast_log(LOG_DEBUG, "Oooh, we need to change our formats since our peer supports only %d and not %d\n", p->capability, p->owner->nativeformats);
1242                 p->owner->nativeformats = p->capability;
1243                 ast_set_read_format(p->owner, p->owner->readformat);
1244                 ast_set_write_format(p->owner, p->owner->writeformat);
1245         }
1246         return 0;
1247         
1248 }
1249
1250 static int add_header(struct sip_request *req, char *var, char *value)
1251 {
1252         if (req->len >= sizeof(req->data) - 4) {
1253                 ast_log(LOG_WARNING, "Out of space, can't add anymore\n");
1254                 return -1;
1255         }
1256         if (req->lines) {
1257                 ast_log(LOG_WARNING, "Can't add more headers when lines have been added\n");
1258                 return -1;
1259         }
1260         req->header[req->headers] = req->data + req->len;
1261         snprintf(req->header[req->headers], sizeof(req->data) - req->len - 4, "%s: %s\r\n", var, value);
1262         req->len += strlen(req->header[req->headers]);
1263         if (req->headers < SIP_MAX_HEADERS)
1264                 req->headers++;
1265         else {
1266                 ast_log(LOG_WARNING, "Out of header space\n");
1267                 return -1;
1268         }
1269         return 0;       
1270 }
1271
1272 static int add_blank_header(struct sip_request *req)
1273 {
1274         if (req->len >= sizeof(req->data) - 4) {
1275                 ast_log(LOG_WARNING, "Out of space, can't add anymore\n");
1276                 return -1;
1277         }
1278         if (req->lines) {
1279                 ast_log(LOG_WARNING, "Can't add more headers when lines have been added\n");
1280                 return -1;
1281         }
1282         req->header[req->headers] = req->data + req->len;
1283         snprintf(req->header[req->headers], sizeof(req->data) - req->len, "\r\n");
1284         req->len += strlen(req->header[req->headers]);
1285         if (req->headers < SIP_MAX_HEADERS)
1286                 req->headers++;
1287         else {
1288                 ast_log(LOG_WARNING, "Out of header space\n");
1289                 return -1;
1290         }
1291         return 0;       
1292 }
1293
1294 static int add_line(struct sip_request *req, char *line)
1295 {
1296         if (req->len >= sizeof(req->data) - 4) {
1297                 ast_log(LOG_WARNING, "Out of space, can't add anymore\n");
1298                 return -1;
1299         }
1300         if (!req->lines) {
1301                 /* Add extra empty return */
1302                 snprintf(req->data + req->len, sizeof(req->data) - req->len, "\r\n");
1303                 req->len += strlen(req->data + req->len);
1304         }
1305         req->line[req->lines] = req->data + req->len;
1306         snprintf(req->line[req->lines], sizeof(req->data) - req->len, "%s", line);
1307         req->len += strlen(req->line[req->lines]);
1308         if (req->lines < SIP_MAX_LINES)
1309                 req->lines++;
1310         else {
1311                 ast_log(LOG_WARNING, "Out of line space\n");
1312                 return -1;
1313         }
1314         return 0;       
1315 }
1316
1317 static int copy_header(struct sip_request *req, struct sip_request *orig, char *field)
1318 {
1319         char *tmp;
1320         tmp = get_header(orig, field);
1321         if (strlen(tmp)) {
1322                 /* Add what we're responding to */
1323                 return add_header(req, field, tmp);
1324         }
1325         ast_log(LOG_NOTICE, "No field '%s' present to copy\n", field);
1326         return -1;
1327 }
1328
1329 static int copy_all_header(struct sip_request *req, struct sip_request *orig, char *field)
1330 {
1331         char *tmp;
1332         int start = 0;
1333         int copied = 0;
1334         for (;;) {
1335                 tmp = __get_header(orig, field, &start);
1336                 if (strlen(tmp)) {
1337                         /* Add what we're responding to */
1338                         add_header(req, field, tmp);
1339                         copied++;
1340                 } else
1341                         break;
1342         }
1343         if (!copied) {
1344                 ast_log(LOG_NOTICE, "No field '%s' present to copy\n", field);
1345                 return -1;
1346         }
1347         return 0;
1348 }
1349
1350 static int init_resp(struct sip_request *req, char *resp, struct sip_request *orig)
1351 {
1352         /* Initialize a response */
1353         if (req->headers || req->len) {
1354                 ast_log(LOG_WARNING, "Request already initialized?!?\n");
1355                 return -1;
1356         }
1357         req->header[req->headers] = req->data + req->len;
1358         snprintf(req->header[req->headers], sizeof(req->data) - req->len, "SIP/2.0 %s\r\n", resp);
1359         req->len += strlen(req->header[req->headers]);
1360         if (req->headers < SIP_MAX_HEADERS)
1361                 req->headers++;
1362         else
1363                 ast_log(LOG_WARNING, "Out of header space\n");
1364         return 0;
1365 }
1366
1367 static int init_req(struct sip_request *req, char *resp, char *recip)
1368 {
1369         /* Initialize a response */
1370         if (req->headers || req->len) {
1371                 ast_log(LOG_WARNING, "Request already initialized?!?\n");
1372                 return -1;
1373         }
1374         req->header[req->headers] = req->data + req->len;
1375         snprintf(req->header[req->headers], sizeof(req->data) - req->len, "%s %s SIP/2.0\r\n", resp, recip);
1376         req->len += strlen(req->header[req->headers]);
1377         if (req->headers < SIP_MAX_HEADERS)
1378                 req->headers++;
1379         else
1380                 ast_log(LOG_WARNING, "Out of header space\n");
1381         return 0;
1382 }
1383
1384 static int respprep(struct sip_request *resp, struct sip_pvt *p, char *msg, struct sip_request *req)
1385 {
1386         char newto[256] = "", *ot;
1387         memset(resp, 0, sizeof(*resp));
1388         init_resp(resp, msg, req);
1389         copy_all_header(resp, req, "Via");
1390         copy_header(resp, req, "From");
1391         ot = get_header(req, "To");
1392         if (!strstr(ot, "tag=")) {
1393                 /* Add the proper tag if we don't have it already.  If they have specified
1394                    their tag, use it.  Otherwise, use our own tag */
1395                 if (strlen(p->theirtag))
1396                         snprintf(newto, sizeof(newto), "%s;tag=%s", ot, p->theirtag);
1397                 else if (p->tag)
1398                         snprintf(newto, sizeof(newto), "%s;tag=%08x", ot, p->tag);
1399                 else
1400                         strncpy(newto, ot, sizeof(newto) - 1);
1401                 ot = newto;
1402         }
1403         add_header(resp, "To", ot);
1404         copy_header(resp, req, "Call-ID");
1405         copy_header(resp, req, "CSeq");
1406         add_header(resp, "User-Agent", "Asterisk PBX");
1407         if (p->expirey) {
1408                 /* For registration responses, we also need expirey and
1409                    contact info */
1410                 char tmp[80];
1411                 char contact2[256] = "", *c, contact[256];
1412                 snprintf(tmp, sizeof(tmp), "%d", p->expirey);
1413                 strncpy(contact2, get_header(req, "Contact"), sizeof(contact2)-1);
1414                 c = ditch_braces(contact2);
1415                 snprintf(contact, sizeof(contact), "<%s>", c);
1416                 add_header(resp, "Expires", tmp);
1417                 add_header(resp, "Contact", contact);
1418         } else {
1419                 char contact2[256] = "", *c, contact[256];
1420                 /* XXX This isn't exactly right and it's implemented
1421                        very stupidly *sigh* XXX */
1422                 strncpy(contact2, get_header(req, "To"), sizeof(contact2)-1);
1423                 c = ditch_braces(contact2);
1424                 snprintf(contact, sizeof(contact), "<%s>", c);
1425                 add_header(resp, "Contact", contact);
1426         }
1427         return 0;
1428 }
1429
1430 static int reqprep(struct sip_request *req, struct sip_pvt *p, char *msg, int inc)
1431 {
1432         struct sip_request *orig = &p->initreq;
1433         char stripped[80] ="";
1434         char tmp[80];
1435         char newto[256];
1436         char *c, *n;
1437         char *ot, *of;
1438
1439         memset(req, 0, sizeof(struct sip_request));
1440         
1441         if (inc)
1442                 p->ocseq++;
1443
1444         if (p->outgoing)
1445                 strncpy(stripped, get_header(orig, "To"), sizeof(stripped) - 1);
1446         else
1447                 strncpy(stripped, get_header(orig, "From"), sizeof(stripped) - 1);
1448         
1449         c = strchr(stripped, '<');
1450         if (c) 
1451                 c++;
1452         else
1453                 c = stripped;
1454         n = strchr(c, '>');
1455         if (n)
1456                 *n = '\0';
1457         
1458         init_req(req, msg, c);
1459
1460         snprintf(tmp, sizeof(tmp), "%d %s", p->ocseq, msg);
1461
1462         add_header(req, "Via", p->via);
1463
1464         ot = get_header(orig, "To");
1465         of = get_header(orig, "From");
1466
1467         if (!strstr(ot, "tag=")) {
1468                 /* Add the proper tag if we don't have it already.  If they have specified
1469                    their tag, use it.  Otherwise, use our own tag */
1470                 if (strlen(p->theirtag))
1471                         snprintf(newto, sizeof(newto), "%s;tag=%s", ot, p->theirtag);
1472                 else
1473                         snprintf(newto, sizeof(newto), "%s;tag=%08x", ot, p->tag);
1474                 ot = newto;
1475         }
1476
1477         if (p->outgoing) {
1478                 add_header(req, "From", of);
1479                 add_header(req, "To", ot);
1480         } else {
1481                 add_header(req, "From", ot);
1482                 add_header(req, "To", of);
1483         }
1484         copy_header(req, orig, "Call-ID");
1485         add_header(req, "CSeq", tmp);
1486
1487         add_header(req, "User-Agent", "Asterisk PBX");
1488         return 0;
1489 }
1490
1491 static int transmit_response(struct sip_pvt *p, char *msg, struct sip_request *req)
1492 {
1493         struct sip_request resp;
1494         respprep(&resp, p, msg, req);
1495         add_header(&resp, "Content-Length", "0");
1496         add_blank_header(&resp);
1497         return send_response(p, &resp);
1498 }
1499
1500 static int transmit_response_with_allow(struct sip_pvt *p, char *msg, struct sip_request *req)
1501 {
1502         struct sip_request resp;
1503         respprep(&resp, p, msg, req);
1504         add_header(&resp, "Allow", "INVITE, ACK, CANCEL, OPTIONS, BYE, REFER");
1505         add_header(&resp, "Accept", "application/sdp");
1506         add_header(&resp, "Content-Length", "0");
1507         add_blank_header(&resp);
1508         return send_response(p, &resp);
1509 }
1510
1511 static int transmit_response_with_auth(struct sip_pvt *p, char *msg, struct sip_request *req, char *randdata)
1512 {
1513         struct sip_request resp;
1514         char tmp[256];
1515         snprintf(tmp, sizeof(tmp), "DIGEST realm=\"asterisk\", nonce=\"%s\"", randdata);
1516         respprep(&resp, p, msg, req);
1517         add_header(&resp, "Proxy-Authenticate", tmp);
1518         add_header(&resp, "Content-Length", "0");
1519         add_blank_header(&resp);
1520         return send_response(p, &resp);
1521 }
1522
1523 static int add_text(struct sip_request *req, char *text)
1524 {
1525         /* XXX Convert \n's to \r\n's XXX */
1526         int len = strlen(text);
1527         char clen[256];
1528         snprintf(clen, sizeof(clen), "%d", len);
1529         add_header(req, "Content-Type", "text/plain");
1530         add_header(req, "Content-Length", clen);
1531         add_line(req, text);
1532         return 0;
1533 }
1534
1535 static int add_sdp(struct sip_request *resp, struct sip_pvt *p, struct ast_rtp *rtp)
1536 {
1537         int len;
1538         int codec;
1539         char costr[80];
1540         struct sockaddr_in sin;
1541         char v[256];
1542         char s[256];
1543         char o[256];
1544         char c[256];
1545         char t[256];
1546         char m[256];
1547         char a[1024] = "";
1548         int x;
1549         struct sockaddr_in dest;
1550         /* XXX We break with the "recommendation" and send our IP, in order that our
1551                peer doesn't have to gethostbyname() us XXX */
1552         len = 0;
1553         if (!p->rtp) {
1554                 ast_log(LOG_WARNING, "No way to add SDP without an RTP structure\n");
1555                 return -1;
1556         }
1557         ast_rtp_get_us(p->rtp, &sin);
1558         if (rtp) {
1559                 ast_rtp_get_peer(rtp, &dest);
1560         } else {
1561                 dest.sin_addr = p->ourip;
1562                 dest.sin_port = sin.sin_port;
1563         }
1564         if (sipdebug)
1565                 ast_verbose("We're at %s port %d\n", inet_ntoa(p->ourip), ntohs(sin.sin_port)); 
1566         snprintf(v, sizeof(v), "v=0\r\n");
1567         snprintf(o, sizeof(o), "o=root %d %d IN IP4 %s\r\n", getpid(), getpid(), inet_ntoa(dest.sin_addr));
1568         snprintf(s, sizeof(s), "s=session\r\n");
1569         snprintf(c, sizeof(c), "c=IN IP4 %s\r\n", inet_ntoa(dest.sin_addr));
1570         snprintf(t, sizeof(t), "t=0 0\r\n");
1571         snprintf(m, sizeof(m), "m=audio %d RTP/AVP", ntohs(dest.sin_port));
1572         for (x=1;x<= AST_FORMAT_MAX_AUDIO; x <<= 1) {
1573                 if (p->capability & x) {
1574                         if (sipdebug)
1575                                 ast_verbose("Answering with capability %d\n", x);
1576                         if ((codec = ast2rtp(x)) > -1) {
1577                                 snprintf(costr, sizeof(costr), " %d", codec);
1578                                 strcat(m, costr);
1579                                 snprintf(costr, sizeof(costr), "a=rtpmap:%d %s/8000\r\n", codec, ast2rtpn(x));
1580                                 strcat(a, costr);
1581                         }
1582                 }
1583         }
1584         strcat(m, " 101\r\n");
1585         strcat(a, "a=rtpmap:101 telephone-event/8000\r\n");
1586         /* Indicate we support DTMF only...  Not sure about 16, but MSN supports it so dang it, we will too... */
1587         strcat(a, "a=fmtp:101 0-16\r\n");
1588         len = strlen(v) + strlen(s) + strlen(o) + strlen(c) + strlen(t) + strlen(m) + strlen(a);
1589         snprintf(costr, sizeof(costr), "%d", len);
1590         add_header(resp, "Content-Type", "application/sdp");
1591         add_header(resp, "Content-Length", costr);
1592         add_line(resp, v);
1593         add_line(resp, o);
1594         add_line(resp, s);
1595         add_line(resp, c);
1596         add_line(resp, t);
1597         add_line(resp, m);
1598         add_line(resp, a);
1599         return 0;
1600 }
1601
1602 static void copy_request(struct sip_request *dst,struct sip_request *src)
1603 {
1604         long offset;
1605         int x;
1606         offset = ((void *)dst) - ((void *)src);
1607         /* First copy stuff */
1608         memcpy(dst, src, sizeof(*dst));
1609         /* Now fix pointer arithmetic */
1610         for (x=0;x<src->headers;x++)
1611                 dst->header[x] += offset;
1612         for (x=0;x<src->lines;x++)
1613                 dst->line[x] += offset;
1614 }
1615
1616 static int transmit_response_with_sdp(struct sip_pvt *p, char *msg, struct sip_request *req)
1617 {
1618         struct sip_request resp;
1619         respprep(&resp, p, msg, req);
1620         add_sdp(&resp, p, NULL);
1621         return send_response(p, &resp);
1622 }
1623
1624 static int transmit_reinvite_with_sdp(struct sip_pvt *p, struct ast_rtp *rtp)
1625 {
1626         struct sip_request resp;
1627         reqprep(&resp, p, "INVITE", 1);
1628         add_sdp(&resp, p, rtp);
1629         return send_response(p, &resp);
1630 }
1631
1632 static void initreqprep(struct sip_request *req, struct sip_pvt *p, char *cmd, char *vxml_url)
1633 {
1634         char invite[256];
1635         char from[256];
1636         char to[256];
1637         char tmp[80];
1638         char cid[256];
1639         char *l = "asterisk", *n=NULL;
1640         if (p->owner && p->owner->callerid) {
1641                 strcpy(cid, p->owner->callerid);
1642                 ast_callerid_parse(cid, &n, &l);
1643                 if (l) 
1644                         ast_shrink_phone_number(l);
1645                 if (!l || !ast_isphonenumber(l))
1646                                 l = "asterisk";
1647         }
1648         if (!n)
1649                 n = "asterisk";
1650         snprintf(from, sizeof(from), "\"%s\" <sip:%s@%s>;tag=%08x", n, l, inet_ntoa(p->ourip), p->tag);
1651         if (strlen(p->username)) {
1652                 if (ntohs(p->sa.sin_port) != DEFAULT_SIP_PORT) {
1653                         snprintf(invite, sizeof(invite), "sip:%s@%s:%d",p->username, inet_ntoa(p->sa.sin_addr), ntohs(p->sa.sin_port));
1654                 } else {
1655                         snprintf(invite, sizeof(invite), "sip:%s@%s",p->username, inet_ntoa(p->sa.sin_addr));
1656                 }
1657         } else if (ntohs(p->sa.sin_port) != DEFAULT_SIP_PORT) {
1658                 snprintf(invite, sizeof(invite), "sip:%s:%d", inet_ntoa(p->sa.sin_addr), ntohs(p->sa.sin_port));
1659         } else {
1660                 snprintf(invite, sizeof(invite), "sip:%s", inet_ntoa(p->sa.sin_addr));
1661         }
1662         /* If there is a VXML URL append it to the SIP URL */
1663         if (vxml_url)
1664         {
1665                 snprintf(to, sizeof(to), "<%s>;%s", invite, vxml_url);
1666         }
1667         else
1668         {
1669                 snprintf(to, sizeof(to), "<%s>", invite );
1670         }
1671         memset(req, 0, sizeof(struct sip_request));
1672         init_req(req, cmd, invite);
1673         snprintf(tmp, sizeof(tmp), "%d %s", ++p->ocseq, cmd);
1674
1675         add_header(req, "Via", p->via);
1676         add_header(req, "From", from);
1677         {
1678                 char contact2[256] ="", *c, contact[256];
1679                 /* XXX This isn't exactly right and it's implemented
1680                        very stupidly *sigh* XXX */
1681                 strncpy(contact2, from, sizeof(contact2)-1);
1682                 c = ditch_braces(contact2);
1683                 snprintf(contact, sizeof(contact), "<%s>", c);
1684                 add_header(req, "Contact", contact);
1685         }
1686         add_header(req, "To", to);
1687         add_header(req, "Call-ID", p->callid);
1688         add_header(req, "CSeq", tmp);
1689         add_header(req, "User-Agent", "Asterisk PBX");
1690 }
1691
1692 static int transmit_invite(struct sip_pvt *p, char *cmd, int sdp, char *auth, char *vxml_url)
1693 {
1694         struct sip_request req;
1695         initreqprep(&req, p, cmd, vxml_url);
1696         if (auth)
1697                 add_header(&req, "Proxy-Authorization", auth);
1698         if (sdp) {
1699                 add_sdp(&req, p, NULL);
1700         } else {
1701                 add_header(&req, "Content-Length", "0");
1702                 add_blank_header(&req);
1703         }
1704         if (!p->initreq.headers) {
1705                 /* Use this as the basis */
1706                 copy_request(&p->initreq, &req);
1707                 parse(&p->initreq);
1708         }
1709         p->lastinvite = p->ocseq;
1710         return send_request(p, &req);
1711 }
1712
1713 static int transmit_notify(struct sip_pvt *p, int hasmsgs)
1714 {
1715         struct sip_request req;
1716         char tmp[256];
1717         char clen[20];
1718         initreqprep(&req, p, "NOTIFY", NULL);
1719         add_header(&req, "Event", "message-summary");
1720         add_header(&req, "Content-Type", "text/plain");
1721
1722         snprintf(tmp, sizeof(tmp), "Message-Waiting: %s\n", hasmsgs ? "yes" : "no");
1723         snprintf(clen, sizeof(clen), "%d", strlen(tmp));
1724         add_header(&req, "Content-Length", clen);
1725         add_line(&req, tmp);
1726
1727         if (!p->initreq.headers) {
1728                 /* Use this as the basis */
1729                 copy_request(&p->initreq, &req);
1730                 parse(&p->initreq);
1731         }
1732
1733         p->lastinvite = p->ocseq;
1734         return send_request(p, &req);
1735 }
1736
1737 static int transmit_register(struct sip_registry *r, char *cmd, char *auth);
1738
1739 static int sip_reregister(void *data) 
1740 {
1741         /* if we are here, we know that we need to reregister. */
1742         struct sip_registry *r=(struct sip_registry *)data;
1743         return sip_do_register(r);
1744         
1745 }
1746
1747
1748 static int sip_do_register(struct sip_registry *r)
1749 {
1750         int res;
1751         ast_pthread_mutex_lock(&r->lock);
1752         res=transmit_register(r, "REGISTER", NULL);
1753         ast_pthread_mutex_unlock(&r->lock);
1754         return res;
1755 }
1756
1757 static int sip_reg_timeout(void *data)
1758 {
1759         /* if we are here, our registration timed out, so we'll just do it over */
1760         struct sip_registry *r=data;
1761         int res;
1762         ast_pthread_mutex_lock(&r->lock);
1763         ast_log(LOG_NOTICE, "Registration timed out, trying again\n"); 
1764         r->regstate=REG_STATE_UNREGISTERED;
1765         /* cancel ourselves first!!! */
1766         /* ast_sched_del(sched,r->timeout); */
1767         res=transmit_register(r, "REGISTER", NULL);
1768         ast_pthread_mutex_unlock(&r->lock);
1769         return res;
1770 }
1771
1772 static int transmit_register(struct sip_registry *r, char *cmd, char *auth)
1773 {
1774         struct sip_request req;
1775         char from[256];
1776         char to[256];
1777         char tmp[80];
1778         char via[80];
1779         char addr[80];
1780         struct sip_pvt *p;
1781         /* exit if we are already in process with this registrar ?*/
1782         if ( (auth==NULL && r->regstate==REG_STATE_REGSENT) || r->regstate==REG_STATE_AUTHSENT) {
1783                 ast_log(LOG_NOTICE, "Strange, trying to register when registration already pending\n");
1784                 return 0;
1785         }
1786
1787
1788         if (!(p=r->call)) {
1789                 if (!r->callid_valid) {
1790                   build_callid(r->callid, sizeof(r->callid), __ourip);
1791                   r->callid_valid=1;
1792                 }
1793                 p=sip_alloc( r->callid, &r->addr );
1794                 p->outgoing = 1;
1795                 r->call=p;
1796                 p->registry=r;
1797                 strncpy(p->peersecret, r->secret, sizeof(p->peersecret)-1);
1798                 strncpy(p->peername, r->username, sizeof(p->peername)-1);
1799                 strncpy(p->username, r->username, sizeof(p->username)-1);
1800         }
1801
1802         /* set up a timeout */
1803         if (auth==NULL && !r->timeout)  {
1804                 r->timeout = ast_sched_add(sched, 10*1000, sip_reg_timeout, r);
1805                 ast_log(LOG_NOTICE, "Scheduled a timeout # %d\n", r->timeout);
1806         }
1807
1808         snprintf(from, sizeof(from), "<sip:%s@%s>;tag=%08x", r->username, inet_ntoa(r->addr.sin_addr), p->tag);
1809         snprintf(to, sizeof(to),     "<sip:%s@%s>;tag=%08x", r->username, inet_ntoa(r->addr.sin_addr), p->tag);
1810         
1811         snprintf(addr, sizeof(addr), "sip:%s", inet_ntoa(r->addr.sin_addr));
1812
1813         memset(&req, 0, sizeof(req));
1814         init_req(&req, cmd, addr);
1815
1816         snprintf(tmp, sizeof(tmp), "%d %s", ++p->ocseq, cmd);
1817
1818         snprintf(via, sizeof(via), "SIP/2.0/UDP %s:%d;branch=%08x", inet_ntoa(p->ourip), ourport, p->branch);
1819         add_header(&req, "Via", via);
1820         add_header(&req, "From", from);
1821         add_header(&req, "To", to);
1822         {
1823                 char contact[256];
1824                 snprintf(contact, sizeof(contact), "<sip:s@%s:%d;transport=udp>", inet_ntoa(p->ourip), ourport);
1825                 add_header(&req, "Contact", contact);
1826         }
1827         add_header(&req, "Call-ID", p->callid);
1828         add_header(&req, "CSeq", tmp);
1829         add_header(&req, "User-Agent", "Asterisk PBX");
1830         if (auth) 
1831                 add_header(&req, "Authorization", auth);
1832
1833         snprintf(tmp, sizeof(tmp), "%d", DEFAULT_EXPIREY);
1834         add_header(&req, "Expires", tmp);
1835         add_header(&req, "Event", "registration");
1836         copy_request(&p->initreq, &req);
1837         r->regstate=auth?REG_STATE_AUTHSENT:REG_STATE_REGSENT;
1838         return send_request(p, &req);
1839 }
1840
1841 static int transmit_message_with_text(struct sip_pvt *p, char *text)
1842 {
1843         struct sip_request req;
1844         reqprep(&req, p, "MESSAGE", 1);
1845         add_text(&req, text);
1846         return send_request(p, &req);
1847 }
1848
1849 static int transmit_request(struct sip_pvt *p, char *msg, int inc)
1850 {
1851         struct sip_request resp;
1852         reqprep(&resp, p, msg, inc);
1853         add_header(&resp, "Content-Length", "0");
1854         add_blank_header(&resp);
1855         return send_request(p, &resp);
1856 }
1857
1858 static int expire_register(void *data)
1859 {
1860         struct sip_peer *p = data;
1861         memset(&p->addr, 0, sizeof(p->addr));
1862         p->expire = -1;
1863         return 0;
1864 }
1865
1866 static int sip_poke_peer(struct sip_peer *peer);
1867
1868 static int parse_contact(struct sip_pvt *pvt, struct sip_peer *p, struct sip_request *req)
1869 {
1870         char contact[80]= ""; 
1871         char *expires = get_header(req, "Expires");
1872         int expirey = atoi(expires);
1873         char *c, *n, *pt;
1874         int port;
1875         struct hostent *hp;
1876         struct sockaddr_in oldsin;
1877         if (!strlen(expires)) {
1878                 expires = strstr(get_header(req, "Contact"), "expires=");
1879                 if (expires) 
1880                         if (sscanf(expires + 8, "%d;", &expirey) != 1)
1881                                 expirey = 0;
1882         }
1883         /* Look for brackets */
1884         strncpy(contact, get_header(req, "Contact"), sizeof(contact) - 1);
1885         c = contact;
1886         
1887         if ((n=strchr(c, '<'))) {
1888                 c = n + 1;
1889                 n = strchr(c, '>');
1890                 /* Lose the part after the > */
1891                 if (n) 
1892                         *n = '\0';
1893         }
1894         /* Make sure it's a SIP URL */
1895         if (strncasecmp(c, "sip:", 4)) {
1896                 ast_log(LOG_NOTICE, "'%s' is not a valid SIP contcact\n", c);
1897                 return -1;
1898         }
1899         c += 4;
1900         /* Ditch q */
1901         n = strchr(c, ';');
1902         if (n) 
1903                 *n = '\0';
1904         /* Grab host */
1905         n = strchr(c, '@');
1906         if (!n) {
1907                 n = c;
1908                 c = NULL;
1909         } else {
1910                 *n = '\0';
1911                 n++;
1912         }
1913         pt = strchr(n, ':');
1914         if (pt) {
1915                 *pt = '\0';
1916                 pt++;
1917                 port = atoi(pt);
1918         } else
1919                 port = DEFAULT_SIP_PORT;
1920         /* XXX This could block for a long time XXX */
1921         hp = gethostbyname(n);
1922         if (!hp)  {
1923                 ast_log(LOG_WARNING, "Invalid host '%s'\n", n);
1924                 return -1;
1925         }
1926         memcpy(&oldsin, &p->addr, sizeof(oldsin));
1927         p->addr.sin_family = AF_INET;
1928         memcpy(&p->addr.sin_addr, hp->h_addr, sizeof(p->addr.sin_addr));
1929         p->addr.sin_port = htons(port);
1930         if (c)
1931                 strncpy(p->username, c, sizeof(p->username) - 1);
1932         else
1933                 strcpy(p->username, "");
1934         if (p->expire > -1)
1935                 ast_sched_del(sched, p->expire);
1936         if ((expirey < 1) || (expirey > MAX_EXPIREY))
1937                 expirey = DEFAULT_EXPIREY;
1938         p->expire = ast_sched_add(sched, expirey * 1000, expire_register, p);
1939         pvt->expirey = expirey;
1940         if (memcmp(&p->addr, &oldsin, sizeof(oldsin))) {
1941                 sip_poke_peer(p);
1942                 if (option_verbose > 2)
1943                         ast_verbose(VERBOSE_PREFIX_3 "Registered SIP '%s' at %s port %d expires %d\n", p->username, inet_ntoa(p->addr.sin_addr), ntohs(p->addr.sin_port), expirey);
1944         }
1945         return 0;
1946 }
1947
1948 static void md5_hash(char *output, char *input)
1949 {
1950                 struct MD5Context md5;
1951                 unsigned char digest[16];
1952                 char *ptr;
1953                 int x;
1954                 MD5Init(&md5);
1955                 MD5Update(&md5, input, strlen(input));
1956                 MD5Final(digest, &md5);
1957                 ptr = output;
1958                 for (x=0;x<16;x++)
1959                         ptr += sprintf(ptr, "%2.2x", digest[x]);
1960 }
1961
1962 static int check_auth(struct sip_pvt *p, struct sip_request *req, char *randdata, int randlen, char *username, char *secret, char *method, char *uri)
1963 {
1964         int res = -1;
1965         /* Always OK if no secret */
1966         if (!strlen(secret))
1967                 return 0;
1968         if (!strlen(randdata)) {
1969                 snprintf(randdata, randlen, "%08x", rand());
1970                 transmit_response_with_auth(p, "407 Proxy Authentication Required", req, randdata);
1971                 res = 1;
1972         } else {
1973                 /* Whoever came up with the authentication section of SIP can suck my %&#$&* for not putting
1974                    an example in the spec of just what it is you're doing a hash on. */
1975                 char a1[256];
1976                 char a2[256];
1977                 char a1_hash[256];
1978                 char a2_hash[256];
1979                 char resp[256];
1980                 char resp_hash[256];
1981                 char tmp[256] = "";
1982                 char *c;
1983                 char *response ="";
1984                 char *resp_uri ="";
1985
1986                 /* Find their response among the mess that we'r sent for comparison */
1987                 strncpy(tmp, get_header(req, "Proxy-Authorization"), sizeof(tmp) - 1);
1988                 c = tmp;
1989
1990                 while(c) {
1991                         while (*c && (*c < 33)) c++;
1992                         if (!*c)
1993                                 break;
1994                         if (!strncasecmp(c, "response=", strlen("response="))) {
1995                                 c+= strlen("response=");
1996                                 if ((*c == '\"')) {
1997                                         response=++c;
1998                                         if((c = strchr(c,'\"')))
1999                                                 *c = '\0';
2000
2001                                 } else {
2002                                         response=c;
2003                                         if((c = strchr(c,',')))
2004                                                 *c = '\0';
2005                                 }
2006
2007                         } else if (!strncasecmp(c, "uri=", strlen("uri="))) {
2008                                 c+= strlen("uri=");
2009                                 if ((*c == '\"')) {
2010                                         resp_uri=++c;
2011                                         if((c = strchr(c,'\"')))
2012                                                 *c = '\0';
2013                                 } else {
2014                                         resp_uri=c;
2015                                         if((c = strchr(c,',')))
2016                                                 *c = '\0';
2017                                 }
2018
2019                         } else
2020                                 c = strchr(c, ',');
2021                         if (c)
2022                                 c++;
2023                 }
2024                 snprintf(a1, sizeof(a1), "%s:%s:%s", username, "asterisk", secret);
2025                 if(strlen(resp_uri))
2026                         snprintf(a2, sizeof(a2), "%s:%s", method, resp_uri);
2027                 else
2028                         snprintf(a2, sizeof(a2), "%s:%s", method, uri);
2029                 md5_hash(a1_hash, a1);
2030                 md5_hash(a2_hash, a2);
2031                 snprintf(resp, sizeof(resp), "%s:%s:%s", a1_hash, randdata, a2_hash);
2032                 md5_hash(resp_hash, resp);
2033
2034                 /* resp_hash now has the expected response, compare the two */
2035
2036                 if (response && !strncasecmp(response, resp_hash, strlen(resp_hash))) {
2037                         /* Auth is OK */
2038                         res = 0;
2039                 }
2040                 /* Assume success ;-) */
2041                 /* Eliminate random data */
2042                 strcpy(randdata, "");
2043         }
2044         return res;
2045 }
2046
2047 static int register_verify(struct sip_pvt *p, struct sockaddr_in *sin, struct sip_request *req, char *uri)
2048 {
2049         int res = -1;
2050         struct sip_peer *peer;
2051         char tmp[256] = "";
2052         char *name, *c;
2053         char *t;
2054         /* Terminate URI */
2055         t = uri;
2056         while(*t && (*t > 32) && (*t != ';'))
2057                 t++;
2058         *t = '\0';
2059         
2060         strncpy(tmp, get_header(req, "To"), sizeof(tmp) - 1);
2061         c = ditch_braces(tmp);
2062         if (strncmp(c, "sip:", 4)) {
2063                 ast_log(LOG_NOTICE, "Invalid to address: '%s' from %s\n", tmp, inet_ntoa(sin->sin_addr));
2064                 return -1;
2065         }
2066         name = c + 4;
2067         c = strchr(name, '@');
2068         if (c) 
2069                 *c = '\0';
2070         ast_pthread_mutex_lock(&peerl.lock);
2071         peer = peerl.peers;
2072         while(peer) {
2073                 if (!strcasecmp(peer->name, name) && peer->dynamic) {
2074                         if (!(res = check_auth(p, req, p->randdata, sizeof(p->randdata), peer->name, peer->secret, "REGISTER", uri))) {
2075                                 if (parse_contact(p, peer, req)) {
2076                                         ast_log(LOG_WARNING, "Failed to parse contact info\n");
2077                                 } else {
2078                                         /* Say OK and ask subsystem to retransmit msg counter */
2079                                         transmit_response(p, "200 OK", req);
2080                                         peer->lastmsgssent = -1;
2081                                         res = 0;
2082                                 }
2083                         } 
2084                         break;
2085                 }       
2086                 peer = peer->next;
2087         }
2088         ast_pthread_mutex_unlock(&peerl.lock);
2089         if (res < 0)
2090                 transmit_response(p, "401 Unauthorized", &p->initreq);
2091         return res;
2092 }
2093
2094 static int get_destination(struct sip_pvt *p, struct sip_request *oreq)
2095 {
2096         char tmp[256] = "", *c, *a;
2097         struct sip_request *req;
2098         
2099         req = oreq;
2100         if (!req)
2101                 req = &p->initreq;
2102         strncpy(tmp, req->rlPart2, sizeof(tmp) - 1);
2103         c = ditch_braces(tmp);
2104         if (strncmp(c, "sip:", 4)) {
2105                 ast_log(LOG_WARNING, "Huh?  Not a SIP header (%s)?\n", c);
2106                 return -1;
2107         }
2108         c += 4;
2109         if ((a = strchr(c, '@')) || (a = strchr(c, ';'))) {
2110                 *a = '\0';
2111         }
2112         if (sipdebug)
2113                 ast_verbose("Looking for %s in %s\n", c, p->context);
2114         if (ast_exists_extension(NULL, p->context, c, 1, NULL)) {
2115                 if (!oreq)
2116                         strncpy(p->exten, c, sizeof(p->exten) - 1);
2117                 return 0;
2118         }
2119
2120         if (ast_canmatch_extension(NULL, p->context, c, 1, NULL)) {
2121                 return 1;
2122         }
2123         
2124         return -1;
2125 }
2126
2127 static int get_refer_info(struct sip_pvt *p, struct sip_request *oreq)
2128 {
2129         char tmp[256] = "", *c, *a;
2130         char tmp2[256] = "", *c2, *a2;
2131         char tmp3[256];
2132         char tmp4[256];
2133         struct sip_request *req;
2134         
2135         req = oreq;
2136         if (!req)
2137                 req = &p->initreq;
2138         strncpy(tmp, get_header(req, "Refer-To"), sizeof(tmp) - 1);
2139         strncpy(tmp2, get_header(req, "Referred-By"), sizeof(tmp2) - 1);
2140         strncpy(tmp3, get_header(req, "Contact"), sizeof(tmp3) - 1);
2141         strncpy(tmp4, get_header(req, "Remote-Party-ID"), sizeof(tmp4) - 1);
2142         
2143         c = ditch_braces(tmp);
2144         c2 = ditch_braces(tmp2);
2145         
2146                 
2147         if (strncmp(c, "sip:", 4) && strncmp(c2, "sip:", 4)) {
2148                 ast_log(LOG_WARNING, "Huh?  Not a SIP header (%s)?\n", c);
2149                 ast_log(LOG_WARNING, "Huh?  Not a SIP header (%s)?\n", c2);
2150                 return -1;
2151         }
2152         c += 4;
2153         c2 += 4;
2154         if ((a = strchr(c, '@')) || (a = strchr(c, ';'))) {
2155                 *a = '\0';
2156         }
2157         if ((a2 = strchr(c2, '@')) || (a2 = strchr(c2, ';'))) { 
2158                 *a2 = '\0';
2159         }
2160         
2161         if (sipdebug)
2162                 ast_verbose("Looking for %s in %s\n", c, p->context);
2163                 ast_verbose("Looking for %s in %s\n", c2, p->context);
2164         
2165         if (ast_exists_extension(NULL, p->context, c, 1, NULL) && ast_exists_extension(NULL, p->context, c2, 1, NULL)) {
2166                 if (!oreq)
2167                         ast_log(LOG_DEBUG,"Something is wrong with this line.\n");      //This line is ignored for some reason....
2168                         ast_log(LOG_DEBUG,"Assigning Extension %s to REFER-TO\n", c);
2169                         ast_log(LOG_DEBUG,"Assigning Extension %s to REFERRED-BY\n", c2);
2170                         ast_log(LOG_DEBUG,"Assigning Contact Info %s to REFER_CONTACT\n", tmp3);
2171                         ast_log(LOG_DEBUG,"Assigning Remote-Party-ID Info %s to REMOTE_PARTY_ID\n",tmp4);
2172                         strncpy(p->refer_to, c, sizeof(p->refer_to) - 1);
2173                         strncpy(p->referred_by, c2, sizeof(p->referred_by) - 1);
2174                         strncpy(p->refer_contact, tmp3, sizeof(p->refer_contact) - 1);
2175                         strncpy(p->remote_party_id, tmp4, sizeof(p->remote_party_id) - 1);
2176                         return 0;
2177         }
2178
2179         if (ast_canmatch_extension(NULL, p->context, c, 1, NULL)) {
2180                 return 1;
2181         }
2182
2183         return -1;
2184 }
2185
2186
2187 static int check_via(struct sip_pvt *p, struct sip_request *req)
2188 {
2189         char via[256] = "";
2190         char *c, *pt;
2191         struct hostent *hp;
2192
2193         memset(via, 0, sizeof(via));
2194         strncpy(via, get_header(req, "Via"), sizeof(via) - 1);
2195         c = strchr(via, ';');
2196         if (c) 
2197                 *c = '\0';
2198         c = strchr(via, ' ');
2199         if (c) {
2200                 *c = '\0';
2201                 c++;
2202                 while(*c && (*c < 33))
2203                         c++;
2204                 if (strcmp(via, "SIP/2.0/UDP")) {
2205                         ast_log(LOG_WARNING, "Don't know how to respond via '%s'\n", via);
2206                         return -1;
2207                 }
2208                 pt = strchr(c, ':');
2209                 if (pt) {
2210                         *pt = '\0';
2211                         pt++;
2212                 }
2213                 hp = gethostbyname(c);
2214                 if (!hp) {
2215                         ast_log(LOG_WARNING, "'%s' is not a valid host\n", c);
2216                         return -1;
2217                 }
2218                 memset(&p->sa, 0, sizeof(p->sa));
2219                 p->sa.sin_family = AF_INET;
2220                 p->sa.sin_port = htons(pt ? atoi(pt) : DEFAULT_SIP_PORT);
2221                 memcpy(&p->sa.sin_addr, hp->h_addr, sizeof(p->sa.sin_addr));
2222                 if (sipdebug)
2223                         ast_verbose("Sending to %s : %d\n", inet_ntoa(p->sa.sin_addr), ntohs(p->sa.sin_port));
2224         }
2225         return 0;
2226 }
2227
2228 static int check_user(struct sip_pvt *p, struct sip_request *req, char *cmd, char *uri)
2229 {
2230         struct sip_user *user;
2231         char *of, from[256] = "", *c;
2232         int res = 0;
2233         char *t;
2234         /* Terminate URI */
2235         t = uri;
2236         while(*t && (*t > 32) && (*t != ';'))
2237                 t++;
2238         *t = '\0';
2239         of = get_header(req, "From");
2240         strncpy(from, of, sizeof(from) - 1);
2241         of = ditch_braces(from);
2242         if (strncmp(of, "sip:", 4))
2243                 return 0;
2244         else
2245                 of += 4;
2246         /* Get just the username part */
2247         if ((c = strchr(of, '@')))
2248                 *c = '\0';
2249         if ((c = strchr(of, ':')))
2250                 *c = '\0';
2251         strncpy(p->callerid, of, sizeof(p->callerid) - 1);
2252         if (!strlen(of))
2253                         return 0;
2254         ast_pthread_mutex_lock(&userl.lock);
2255         user = userl.users;
2256         while(user) {
2257                 if (!strcasecmp(user->name, of)) {
2258                         if (!(res = check_auth(p, req, p->randdata, sizeof(p->randdata), user->name, user->secret, cmd, uri))) {
2259                                 strncpy(p->context, user->context, sizeof(p->context) - 1);
2260                                 if (strlen(user->callerid) && strlen(p->callerid)) 
2261                                         strncpy(p->callerid, user->callerid, sizeof(p->callerid) - 1);
2262                                 strncpy(p->username, user->name, sizeof(p->username) - 1);
2263                                 strncpy(p->accountcode, user->accountcode, sizeof(p->accountcode)  -1);
2264                                 p->canreinvite = user->canreinvite;
2265                                 p->amaflags = user->amaflags;
2266                         }
2267                         break;
2268                 }
2269                 user = user->next;
2270         }
2271         ast_pthread_mutex_unlock(&userl.lock);
2272         return res;
2273 }
2274
2275 static int get_msg_text(char *buf, int len, struct sip_request *req)
2276 {
2277         int x;
2278         strcpy(buf, "");
2279         for (x=0;x<req->lines;x++) {
2280                 strncat(buf, req->line[x], len - strlen(buf) - 5);
2281                 strcat(buf, "\n");
2282         }
2283         return 0;
2284 }
2285
2286 static void receive_message(struct sip_pvt *p, struct sip_request *req)
2287 {
2288         char buf[1024];
2289         struct ast_frame f;
2290         if (get_msg_text(buf, sizeof(buf), req)) {
2291                 ast_log(LOG_WARNING, "Unable to retrieve text from %s\n", p->callid);
2292                 return;
2293         }
2294         if (p->owner) {
2295                 if (sipdebug)
2296                         ast_verbose("Message received: '%s'\n", buf);
2297                 memset(&f, 0, sizeof(f));
2298                 f.frametype = AST_FRAME_TEXT;
2299                 f.subclass = 0;
2300                 f.offset = 0;
2301                 f.data = buf;
2302                 f.datalen = strlen(buf);
2303                 ast_queue_frame(p->owner, &f, 1);
2304         }
2305 }
2306
2307 static int sip_show_users(int fd, int argc, char *argv[])
2308 {
2309 #define FORMAT "%-15.15s  %-15.15s  %-15.15s  %-15.15s  %-5.5s\n"
2310         struct sip_user *user;
2311         if (argc != 3) 
2312                 return RESULT_SHOWUSAGE;
2313         ast_pthread_mutex_lock(&userl.lock);
2314         ast_cli(fd, FORMAT, "Username", "Secret", "Authen", "Def.Context", "A/C");
2315         for(user=userl.users;user;user=user->next) {
2316                 ast_cli(fd, FORMAT, user->name, user->secret, user->methods, 
2317                                 user->context,
2318                                 user->ha ? "Yes" : "No");
2319         }
2320         ast_pthread_mutex_unlock(&userl.lock);
2321         return RESULT_SUCCESS;
2322 #undef FORMAT
2323 }
2324
2325 static int sip_show_peers(int fd, int argc, char *argv[])
2326 {
2327 #define FORMAT2 "%-15.15s  %-15.15s %s  %-15.15s  %-8s %-10s\n"
2328 #define FORMAT "%-15.15s  %-15.15s %s  %-15.15s  %-8d %-10s\n"
2329         struct sip_peer *peer;
2330         char name[256] = "";
2331         if (argc != 3)
2332                 return RESULT_SHOWUSAGE;
2333         ast_pthread_mutex_lock(&peerl.lock);
2334         ast_cli(fd, FORMAT2, "Name/username", "Host", "   ", "Mask", "Port", "Status");
2335         for (peer = peerl.peers;peer;peer = peer->next) {
2336                 char nm[20] = "";
2337                 char status[20];
2338                 strncpy(nm, inet_ntoa(peer->mask), sizeof(nm)-1);
2339                 if (strlen(peer->username))
2340                         snprintf(name, sizeof(name), "%s/%s", peer->name, peer->username);
2341                 else
2342                         strncpy(name, peer->name, sizeof(name) - 1);
2343                 if (peer->maxms) {
2344                         if (peer->lastms < 0)
2345                                 strcpy(status, "UNREACHABLE");
2346                         else if (peer->lastms > peer->maxms) 
2347                                 snprintf(status, sizeof(status), "LAGGED (%d ms)", peer->lastms);
2348                         else if (peer->lastms) 
2349                                 snprintf(status, sizeof(status), "OK (%d ms)", peer->lastms);
2350                         else 
2351                                 strcpy(status, "UNKNOWN");
2352                 } else 
2353                         strcpy(status, "Unmonitored");
2354                 ast_cli(fd, FORMAT, name, 
2355                                         peer->addr.sin_addr.s_addr ? inet_ntoa(peer->addr.sin_addr) : "(Unspecified)",
2356                                         peer->dynamic ? "(D)" : "   ",
2357                                         nm,
2358                                         ntohs(peer->addr.sin_port), status);
2359         }
2360         ast_pthread_mutex_unlock(&peerl.lock);
2361         return RESULT_SUCCESS;
2362 #undef FORMAT
2363 #undef FORMAT2
2364 }
2365
2366 static char *regstate2str(int regstate)
2367 {
2368         switch(regstate) {
2369         case REG_STATE_UNREGISTERED:
2370                 return "Unregistered";
2371         case REG_STATE_REGSENT:
2372                 return "Request Sent";
2373         case REG_STATE_AUTHSENT:
2374                 return "Auth. Sent";
2375         case REG_STATE_REGISTERED:
2376                 return "Registered";
2377         case REG_STATE_REJECTED:
2378                 return "Rejected";
2379         case REG_STATE_TIMEOUT:
2380                 return "Timeout";
2381         case REG_STATE_NOAUTH:
2382                 return "No Authentication";
2383         default:
2384                 return "Unknown";
2385         }
2386 }
2387
2388 static int sip_show_registry(int fd, int argc, char *argv[])
2389 {
2390 #define FORMAT2 "%-20.20s  %-10.10s  %-20.20s %8.8s  %s\n"
2391 #define FORMAT "%-20.20s  %-10.10s  %-20.20s %8d  %s\n"
2392         struct sip_registry *reg;
2393         char host[80];
2394         char state[20];
2395         if (argc != 3)
2396                 return RESULT_SHOWUSAGE;
2397         ast_pthread_mutex_lock(&peerl.lock);
2398         ast_cli(fd, FORMAT2, "Host", "Username", "Refresh", "State");
2399         for (reg = registrations;reg;reg = reg->next) {
2400                 snprintf(host, sizeof(host), "%s:%d", inet_ntoa(reg->addr.sin_addr), ntohs(reg->addr.sin_port));
2401                 snprintf(state, sizeof(state), "%s", regstate2str(reg->regstate));
2402                 ast_cli(fd, FORMAT, host, 
2403                                         reg->username, state, reg->refresh, regstate2str(reg->regstate));
2404         }
2405         ast_pthread_mutex_unlock(&peerl.lock);
2406         return RESULT_SUCCESS;
2407 #undef FORMAT
2408 #undef FORMAT2
2409 }
2410
2411 static int sip_show_channels(int fd, int argc, char *argv[])
2412 {
2413 #define FORMAT2 "%-15.15s  %-10.10s  %-11.11s  %-11.11s  %-7.7s  %-6.6s  %s\n"
2414 #define FORMAT  "%-15.15s  %-10.10s  %-11.11s  %5.5d/%5.5d  %-5.5dms  %-4.4dms  %d\n"
2415         struct sip_pvt *cur;
2416         if (argc != 3)
2417                 return RESULT_SHOWUSAGE;
2418         ast_pthread_mutex_lock(&iflock);
2419         cur = iflist;
2420         ast_cli(fd, FORMAT2, "Peer", "Username", "Call ID", "Seq (Tx/Rx)", "Lag", "Jitter", "Format");
2421         while (cur) {
2422                         ast_cli(fd, FORMAT, inet_ntoa(cur->sa.sin_addr), 
2423                                                 strlen(cur->username) ? cur->username : "(None)", 
2424                                                 cur->callid, 
2425                                                 cur->ocseq, cur->icseq, 
2426                                                 0,
2427                                                 0,
2428                                                 cur->owner ? cur->owner->nativeformats : 0);
2429                 cur = cur->next;
2430         }
2431         ast_pthread_mutex_unlock(&iflock);
2432         return RESULT_SUCCESS;
2433 #undef FORMAT
2434 #undef FORMAT2
2435 }
2436
2437 static void receive_info(struct sip_pvt *p, struct sip_request *req)
2438 {
2439         char buf[1024] = "";
2440         struct ast_frame f;
2441         char *c;
2442         /* Try getting the "signal=" part */
2443         if ((c = get_sdp(req, "Signal"))) {
2444                 strncpy(buf, c, sizeof(buf) - 1);
2445         } else if (get_msg_text(buf, sizeof(buf), req)) {
2446                 /* Normal INFO method */
2447                 ast_log(LOG_WARNING, "Unable to retrieve text from %s\n", p->callid);
2448                 return;
2449         }
2450         
2451         if (p->owner) {
2452                 if (strlen(buf)) {
2453                         if (sipdebug)
2454                                 ast_verbose("DTMF received: '%c'\n", buf[0]);
2455                         memset(&f, 0, sizeof(f));
2456                         f.frametype = AST_FRAME_DTMF;
2457                         f.subclass = buf[0];
2458                         f.offset = 0;
2459                         f.data = NULL;
2460                         f.datalen = 0;
2461                         ast_queue_frame(p->owner, &f, 1);
2462                 }
2463         }
2464 }
2465
2466 static int sip_do_debug(int fd, int argc, char *argv[])
2467 {
2468         if (argc != 2)
2469                 return RESULT_SHOWUSAGE;
2470         sipdebug = 1;
2471         ast_cli(fd, "SIP Debugging Enabled\n");
2472         return RESULT_SUCCESS;
2473 }
2474
2475 static int sip_no_debug(int fd, int argc, char *argv[])
2476 {
2477         if (argc != 3)
2478                 return RESULT_SHOWUSAGE;
2479         sipdebug = 0;
2480         ast_cli(fd, "SIP Debugging Disabled\n");
2481         return RESULT_SUCCESS;
2482 }
2483
2484 static int reply_digest(struct sip_pvt *p, struct sip_request *req, char *header, char *orig_header, char *digest, int digest_len);
2485
2486 static int do_register_auth(struct sip_pvt *p, struct sip_request *req) {
2487         char digest[256];
2488         memset(digest,0,sizeof(digest));
2489         reply_digest(p,req, "WWW-Authenticate", "REGISTER", (char *)&digest, sizeof(digest) );
2490         return transmit_register(p->registry,"REGISTER",(char *)&digest); 
2491 }
2492
2493 static int do_proxy_auth(struct sip_pvt *p, struct sip_request *req) {
2494         char digest[256];
2495         memset(digest,0,sizeof(digest));
2496         reply_digest(p,req, "Proxy-Authenticate", "INVITE", (char *)&digest, sizeof(digest) );
2497         return transmit_invite(p,"INVITE",1,(char *)&digest, NULL); 
2498 }
2499
2500 static int reply_digest(struct sip_pvt *p, struct sip_request *req, char *header, char *orig_header, char *digest, int digest_len) {
2501
2502         char tmp[256] = "";
2503         char *realm = "";
2504         char *nonce = "";
2505         char *c;
2506         char a1[256];
2507         char a2[256];
2508         char a1_hash[256];
2509         char a2_hash[256];
2510         char resp[256];
2511         char resp_hash[256];
2512         char uri[256] = "";
2513
2514
2515         strncpy(tmp, get_header(req, header),sizeof(tmp) - 1);
2516         c = tmp;
2517         c+=strlen("DIGEST ");
2518         while (c) {
2519                 while (*c && (*c < 33)) c++;
2520                 if (!*c)
2521                         break;
2522                         if (!strncasecmp(c,"realm=", strlen("realm="))) {
2523                                 c+=strlen("realm=");
2524                                 if ((*c == '\"')) {
2525                                         realm=++c;
2526                                         if ((c = strchr(c,'\"')))
2527                                                 *c = '\0';
2528                                 } else {
2529                                         realm = c;
2530                                         if ((c = strchr(c,',')))
2531                                                 *c = '\0';
2532                                 }
2533
2534                         } else if (!strncasecmp(c, "nonce=", strlen("nonce="))) {
2535                                 c+=strlen("nonce=");
2536                                 if ((*c == '\"')) {
2537                                         nonce=++c;
2538                                         if ((c = strchr(c,'\"')))
2539                                                 *c = '\0';
2540                                 } else {
2541                                         nonce = c;
2542                                         if ((c = strchr(c,',')))
2543                                                 *c = '\0';
2544                                 }
2545                         } else
2546                                 c = strchr(c,',');
2547                         if (c)
2548                                 c++;
2549                         }
2550
2551         /* Okay.  We've got the realm and nonce from the server.  Now lets build the MD5 digest. */
2552         snprintf(uri, sizeof(uri), "sip:%s@%s",p->username, inet_ntoa(p->sa.sin_addr));
2553
2554         snprintf(a1,sizeof(a1),"%s:%s:%s",p->peername,realm,p->peersecret);
2555         snprintf(a2,sizeof(a2),"%s:%s",orig_header,uri);
2556         md5_hash(a1_hash,a1);
2557         md5_hash(a2_hash,a2);
2558         snprintf(resp,sizeof(resp),"%s:%s:%s",a1_hash,nonce,a2_hash);
2559         md5_hash(resp_hash,resp);
2560
2561         snprintf(digest,digest_len,"DIGEST username=\"%s\", realm=\"%s\", algorithm=\"MD5\", uri=\"%s\", nonce=\"%s\", response=\"%s\"",p->peername,realm,uri,nonce,resp_hash);
2562
2563         return 0;
2564 }
2565         
2566
2567         
2568         
2569
2570
2571 static char show_users_usage[] = 
2572 "Usage: sip show users\n"
2573 "       Lists all users known to the SIP (Session Initiation Protocol) subsystem.\n";
2574
2575 static char show_channels_usage[] = 
2576 "Usage: sip show channels\n"
2577 "       Lists all currently active SIP channels.\n";
2578
2579 static char show_peers_usage[] = 
2580 "Usage: sip show peers\n"
2581 "       Lists all known SIP peers.\n";
2582
2583 static char show_reg_usage[] =
2584 "Usage: sip show registry\n"
2585 "       Lists all registration requests and status.\n";
2586
2587 static char debug_usage[] = 
2588 "Usage: sip debug\n"
2589 "       Enables dumping of SIP packets for debugging purposes\n";
2590
2591 static char no_debug_usage[] = 
2592 "Usage: sip no debug\n"
2593 "       Disables dumping of SIP packets for debugging purposes\n";
2594
2595 static struct ast_cli_entry  cli_show_users = 
2596         { { "sip", "show", "users", NULL }, sip_show_users, "Show defined SIP users", show_users_usage };
2597 static struct ast_cli_entry  cli_show_channels =
2598         { { "sip", "show", "channels", NULL }, sip_show_channels, "Show active SIP channels", show_channels_usage };
2599 static struct ast_cli_entry  cli_show_peers =
2600         { { "sip", "show", "peers", NULL }, sip_show_peers, "Show defined SIP peers", show_peers_usage };
2601 static struct ast_cli_entry  cli_show_registry =
2602         { { "sip", "show", "registry", NULL }, sip_show_registry, "Show SIP registration status", show_reg_usage };
2603 static struct ast_cli_entry  cli_debug =
2604         { { "sip", "debug", NULL }, sip_do_debug, "Enable SIP debugging", debug_usage };
2605 static struct ast_cli_entry  cli_no_debug =
2606         { { "sip", "no", "debug", NULL }, sip_no_debug, "Disable SIP debugging", no_debug_usage };
2607
2608
2609 static int sip_poke_peer_s(void *data)
2610 {
2611         struct sip_peer *peer = data;
2612         peer->pokeexpire = -1;
2613         sip_poke_peer(peer);
2614         return 0;
2615 }
2616
2617 static void handle_response(struct sip_pvt *p, int resp, char *rest, struct sip_request *req)
2618 {
2619         char *to;
2620         char *msg, *c;
2621         struct ast_rtp *rtp;
2622         struct ast_channel *owner;
2623         struct sip_peer *peer;
2624         int pingtime;
2625         struct timeval tv;
2626         c = get_header(req, "Cseq");
2627         msg = strchr(c, ' ');
2628         if (!msg) msg = ""; else msg++;
2629 retrylock:
2630         ast_pthread_mutex_lock(&p->lock);
2631         /* Go ahead and lock the owner if it has one -- we may need it */
2632         if (p->owner && pthread_mutex_trylock(&p->owner->lock)) {
2633                 ast_log(LOG_DEBUG, "Failed to grab lock, trying again...\n");
2634                 ast_pthread_mutex_unlock(&p->lock);
2635                 /* Sleep infintismly short amount of time */
2636                 usleep(1);
2637                 goto retrylock;
2638         }
2639         owner = p->owner;
2640         if (p->peerpoke) {
2641                 /* We don't really care what the response is, just that it replied back. 
2642                    Well, as long as it's not a 100 response...  since we might
2643                    need to hang around for something more "difinitive" */
2644                 if (resp != 100) {
2645                         peer = p->peerpoke;
2646                         gettimeofday(&tv, NULL);
2647                         pingtime = (tv.tv_sec - peer->ps.tv_sec) * 1000 +
2648                                                 (tv.tv_usec - peer->ps.tv_usec) / 1000;
2649                         if (pingtime < 1)
2650                                 pingtime = 1;
2651                         if ((peer->lastms < 0)  || (peer->lastms > peer->maxms)) {
2652                                 if (pingtime <= peer->maxms)
2653                                 ast_log(LOG_NOTICE, "Peer '%s' is now REACHABLE!\n", peer->name);
2654                         } else if ((peer->lastms > 0) && (peer->lastms <= peer->maxms)) {
2655                                 if (pingtime > peer->maxms)
2656                                         ast_log(LOG_NOTICE, "Peer '%s' is now TOO LAGGED!\n", peer->name);
2657                         }
2658                         peer->lastms = pingtime;
2659                         peer->call = NULL;
2660                         if (peer->pokeexpire > -1)
2661                                 ast_sched_del(sched, peer->pokeexpire);
2662                         if (!strcasecmp(msg, "INVITE"))
2663                                 transmit_request(p, "ACK", 0);
2664                         sip_destroy(p);
2665                         p = NULL;
2666                         /* Try again eventually */
2667                         if ((peer->lastms < 0)  || (peer->lastms > peer->maxms))
2668                                 peer->pokeexpire = ast_sched_add(sched, DEFAULT_FREQ_NOTOK, sip_poke_peer_s, peer);
2669                         else
2670                                 peer->pokeexpire = ast_sched_add(sched, DEFAULT_FREQ_OK, sip_poke_peer_s, peer);
2671                 }
2672         } else if (p->outgoing) {
2673                 if (p->initid > -1) {
2674                         /* Don't auto congest anymore since we've gotten something useful back */
2675                         ast_sched_del(sched, p->initid);
2676                         p->initid = -1;
2677                 }
2678                 /* Get their tag if we haven't already */
2679                 if (!strlen(p->theirtag)) {
2680                         to = get_header(req, "To");
2681                         to = strstr(to, "tag=");
2682                         if (to) {
2683                                 to += 4;
2684                                 strncpy(p->theirtag, to, sizeof(p->theirtag) - 1);
2685                                 to = strchr(p->theirtag, ';');
2686                                 if (to)
2687                                         *to = '\0';
2688                         }
2689                 }
2690                 
2691                 switch(resp) {
2692                 case 100:
2693                         break;
2694                 case 183:       /* We don't really need this since we pass in-band audio anyway */
2695                         /* Not important */
2696                         if (strlen(get_header(req, "Content-Type")))
2697                                 process_sdp(p, req);
2698                         break;
2699                 case 180:
2700                         if (p->owner) {
2701                                 ast_queue_control(p->owner, AST_CONTROL_RINGING, 0);
2702                                 if (p->owner->_state != AST_STATE_UP)
2703                                         ast_setstate(p->owner, AST_STATE_RINGING);
2704                         }
2705                         break;
2706                 case 200:
2707                         if (strlen(get_header(req, "Content-Type")))
2708                                 process_sdp(p, req);
2709                         if (p->owner) {
2710                                 if (p->owner->_state != AST_STATE_UP) {
2711                                         ast_setstate(p->owner, AST_STATE_UP);
2712                                         ast_queue_control(p->owner, AST_CONTROL_ANSWER, 0);
2713                                 }
2714                         }
2715                         if (!strcasecmp(msg, "INVITE"))
2716                                 transmit_request(p, "ACK", 0);
2717                         else if (!strcasecmp(msg, "REGISTER"))
2718                         {
2719                                 /* char *exp; */
2720                                 int expires;
2721                                 struct sip_registry *r;
2722                                 transmit_request(p, "ACK", 0);
2723                                 r=p->registry;
2724                                 r->regstate=REG_STATE_REGISTERED;
2725                                 ast_log(LOG_NOTICE, "Registration successful\n");
2726                                 ast_log(LOG_NOTICE, "Cancelling timeout %d\n", r->timeout);
2727                                 if (r->timeout) 
2728                                         ast_sched_del(sched, r->timeout);
2729                                 r->timeout=0;
2730                                 /* set us up for re-registering */
2731                                 /* figure out how long we got registered for */
2732                                 if (r->expire != -1)
2733                                         ast_sched_del(sched, r->expire);
2734                                 expires=atoi(get_header(req, "expires"));
2735                                 if (!expires) expires=DEFAULT_EXPIREY;
2736                                         r->expire=ast_sched_add(sched, (expires-2)*1000, sip_reregister, r); 
2737
2738                         }
2739                         break;
2740                 case 401: /* Not authorized on REGISTER */
2741                         /* XXX: Do I need to ACK the 401? 
2742                         transmit_request(p, "ACK", 0);
2743                         */
2744                         do_register_auth(p, req);
2745                         break;
2746                 case 407:
2747                         /* First we ACK */
2748                         transmit_request(p, "ACK", 0);
2749                         /* Then we AUTH */
2750                         do_proxy_auth(p, req);
2751                         /* This is just a hack to kill the channel while testing */
2752                         /* 
2753                         p->alreadygone = 1;
2754                         if (p->rtp) {
2755                                 rtp = p->rtp;
2756                                 p->rtp = NULL;
2757                                 ast_rtp_destroy(rtp);
2758                         }
2759                         if (p->owner)
2760                                 ast_queue_hangup(p->owner,0);
2761                         transmit_request(p,"ACK",0);
2762                         sip_destroy(p);
2763                         p = NULL;
2764                         */
2765                         break;
2766                 default:
2767                         if ((resp >= 400) && (resp < 700)) {
2768                                 if (option_verbose > 2) 
2769                                         ast_verbose(VERBOSE_PREFIX_3 "Got SIP response %d \"%s\" back from %s\n", resp, rest, inet_ntoa(p->sa.sin_addr));
2770                                 p->alreadygone = 1;
2771                                 if (p->rtp) {
2772                                         rtp = p->rtp;
2773                                         p->rtp = NULL;
2774                                         /* Immediately stop RTP */
2775                                         ast_rtp_destroy(rtp);
2776                                 }
2777                                 /* XXX Locking issues?? XXX */
2778                                 switch(resp) {
2779                                 case 486: /* Busy here */
2780                                 case 600: /* Busy everywhere */
2781                                         if (p->owner)
2782                                                 ast_queue_control(p->owner, AST_CONTROL_BUSY, 0);
2783                                         break;
2784                                 case 480: /* Temporarily Unavailable */
2785                                 case 404: /* Not Found */
2786                                 case 410: /* Gone */
2787                                 case 500: /* Server error */
2788                                 case 501: /* Not Implemented */
2789                                         if (owner)
2790                                                 ast_queue_control(p->owner, AST_CONTROL_CONGESTION, 0);
2791                                         break;
2792                                 default:
2793                                         /* Send hangup */       
2794                                         if (owner)
2795                                                 ast_queue_hangup(p->owner, 0);
2796                                         break;
2797                                 }
2798                                 transmit_request(p, "ACK", 0);
2799                                 __sip_destroy(p, 0);
2800                                 p = NULL;
2801                         } else
2802                                 ast_log(LOG_NOTICE, "Dunno anything about a %d %s response from %s\n", resp, rest, p->owner ? p->owner->name : inet_ntoa(p->sa.sin_addr));
2803                 }
2804         } else {
2805                 if (sipdebug)
2806                         ast_verbose("Message is %s\n", msg);
2807                 switch(resp) {
2808                 case 200:
2809                         if (!strcasecmp(msg, "INVITE") || !strcasecmp(msg, "REGISTER") )
2810                                 transmit_request(p, "ACK", 0);
2811                         break;
2812                 }
2813         }
2814         if (owner)
2815                 ast_pthread_mutex_unlock(&owner->lock);
2816         if (p)
2817                 ast_pthread_mutex_unlock(&p->lock);
2818 }
2819
2820 static int determine_firstline_parts( struct sip_request *req ) {
2821
2822   char *e, *cmd;
2823   int len;
2824   
2825   cmd= req->header[0];
2826   while(*cmd && (*cmd < 33)) {
2827     cmd++;
2828   }
2829   if (!*cmd) {
2830     return -1;
2831   }
2832   e= cmd;
2833   while(*e && (*e > 32)) {
2834     e++;
2835   }
2836   /* Get the command */
2837   if (*e) {
2838     *e = '\0';
2839     e++;
2840   }
2841   req->rlPart1= cmd;
2842   while( *e && ( *e < 33 ) ) {
2843     e++; 
2844   }
2845   if( !*e ) {
2846     return -1;
2847   }
2848     
2849   if ( !strcasecmp(cmd, "SIP/2.0") ) {
2850     /* We have a response */
2851     req->rlPart2= e;
2852     len= strlen( req->rlPart2 );
2853     if( len < 2 ) { return -1; }
2854     e+= len - 1;
2855     while( *e && *e<33 ) {
2856       e--; 
2857     }
2858     *(++e)= '\0';
2859   } else {
2860     /* We have a request */
2861     if( *e == '<' ) { 
2862       e++;
2863       if( !*e ) { return -1; }  
2864     }
2865     req->rlPart2= e;
2866     if( ( e= strrchr( req->rlPart2, 'S' ) ) == NULL ) {
2867       return -1;
2868     }
2869     while( isspace( *(--e) ) ) {}
2870     if( *e == '>' ) {
2871       *e= '\0';
2872     } else {
2873       *(++e)= '\0';
2874     }
2875   }
2876   return 1;
2877 }
2878
2879 static int handle_request(struct sip_pvt *p, struct sip_request *req, struct sockaddr_in *sin)
2880 {
2881         struct sip_request resp;
2882         char *cmd;
2883         char *cseq;
2884         char *e;
2885         struct ast_channel *c=NULL;
2886         int seqno;
2887         int len;
2888         int ignore=0;
2889         int respid;
2890         int res;
2891         /* Clear out potential response */
2892         memset(&resp, 0, sizeof(resp));
2893         /* Get Method and Cseq */
2894         cseq = get_header(req, "Cseq");
2895         cmd = req->header[0];
2896         /* Must have Cseq */
2897         if (!strlen(cmd) || !strlen(cseq))
2898                         return -1;
2899         if (sscanf(cseq, "%i%n", &seqno, &len) != 1) {
2900                 ast_log(LOG_DEBUG, "No seqno in '%s'\n", cmd);
2901                 return -1;
2902         }
2903         /* Get the command */
2904         cseq += len;
2905
2906   /* Determine the request URI for sip, sips or tel URIs */
2907         if( determine_firstline_parts( req ) < 0 ) {
2908           return -1; 
2909         }
2910         cmd= req->rlPart1;
2911         e= req->rlPart2;
2912         
2913         if (strcasecmp(cmd, "SIP/2.0")) {
2914                 /* Request coming in */                 
2915                 if (p->icseq && (p->icseq < seqno)) {
2916                         ast_log(LOG_DEBUG, "Ignoring out of order packet %d (expecting %d)\n", seqno, p->icseq);
2917                         return -1;
2918                 } else if (p->icseq && (p->icseq != seqno)) {
2919                         /* ignore means "don't do anything with it" but still have to 
2920                            respond appropriately  */
2921                         ignore=1;
2922                 }
2923         } else {
2924                 /* Response to our request -- Do some sanity checks */  
2925                 if (!p->initreq.headers) {
2926                         ast_log(LOG_DEBUG, "That's odd...  Got a response on a call we dont know about.\n");
2927                         sip_destroy(p);
2928                         return 0;
2929                 } else if (p->ocseq && (p->ocseq < seqno)) {
2930                         ast_log(LOG_DEBUG, "Ignoring out of order response %d (expecting %d)\n", seqno, p->ocseq);
2931                         return -1;
2932                 } else if (p->ocseq && (p->ocseq != seqno)) {
2933                         /* ignore means "don't do anything with it" but still have to 
2934                            respond appropriately  */
2935                         ignore=1;
2936                 }
2937         }
2938         
2939         if (strcmp(cmd, "SIP/2.0"))
2940                 /* Next should follow monotonically increasing */
2941                 p->icseq = seqno + 1;
2942
2943         /* Initialize the context if it hasn't been already */
2944         if (!strcasecmp(cmd, "OPTIONS")) {
2945                 if (!strlen(p->context))
2946                         strncpy(p->context, context, sizeof(p->context) - 1);
2947                 res = get_destination(p, req);
2948                 if (res < 0)
2949                         transmit_response_with_allow(p, "404 Not Found", req);
2950                 else if (res > 0)
2951                         transmit_response_with_allow(p, "484 Address Incomplete", req);
2952                 else 
2953                         transmit_response_with_allow(p, "200 OK", req);
2954         } else if (!strcasecmp(cmd, "INVITE")) {
2955                 /* Process the SDP portion */
2956                 if (!ignore) {
2957                         /* Use this as the basis */
2958                         if (sipdebug)
2959                                 ast_verbose("Using latest request as basis request\n");
2960                         copy_request(&p->initreq, req);
2961                         check_via(p, req);
2962                         if (strlen(get_header(req, "Content-Type"))) {
2963                                 if (process_sdp(p, req))
2964                                         return -1;
2965                         } else {
2966                                 p->capability = capability;
2967                                 ast_log(LOG_DEBUG, "Hm....  No sdp for the moemnt\n");
2968                         }
2969                 } else if (sipdebug)
2970                         ast_verbose("Ignoring this request\n");
2971                 if (!p->lastinvite) {
2972                         /* Handle authentication if this is our first invite */
2973                         res = check_user(p, req, cmd, e);
2974                         if (res) {
2975                                 if (res < 0) {
2976                                         ast_log(LOG_NOTICE, "Failed to authenticate user %s\n", get_header(req, "From"));
2977                                         sip_destroy(p);
2978                                 }
2979                                 return 0;
2980                         }
2981                         /* Initialize the context if it hasn't been already */
2982                         if (!strlen(p->context))
2983                                 strncpy(p->context, context, sizeof(p->context) - 1);
2984                         if ((res = get_destination(p, NULL))) {
2985                                 if (res < 0)
2986                                         transmit_response(p, "404 Not Found", req);
2987                                 else
2988                                         transmit_response(p, "484 Address Incomplete", req);
2989                                 sip_destroy(p);
2990                                 p = NULL;
2991                                 c = NULL;
2992                         } else {
2993                                 /* If no extension was specified, use the s one */
2994                                 if (!strlen(p->exten))
2995                                         strncpy(p->exten, "s", sizeof(p->exten) - 1);
2996                                 /* Initialize tag */    
2997                                 p->tag = rand();
2998                                 /* First invitation */
2999                                 c = sip_new(p, AST_STATE_DOWN, strlen(p->username) ? p->username : NULL);
3000                         }
3001                         
3002                 } else 
3003                         c = p->owner;
3004                 if (!ignore && p)
3005                         p->lastinvite = seqno;
3006                 if (c) {
3007                         switch(c->_state) {
3008                         case AST_STATE_DOWN:
3009                                 transmit_response(p, "100 Trying", req);
3010                                 ast_setstate(c, AST_STATE_RING);
3011                                 if (ast_pbx_start(c)) {
3012                                         ast_log(LOG_WARNING, "Failed to start PBX :(\n");
3013                                         ast_hangup(c);
3014                                         transmit_response(p, "503 Unavailable", req);
3015                                         sip_destroy(p);
3016                                 }
3017                                 break;
3018                         case AST_STATE_RING:
3019                                 transmit_response(p, "100 Trying", req);
3020                                 break;
3021                         case AST_STATE_RINGING:
3022                                 transmit_response(p, "180 Ringing", req);
3023                                 break;
3024                         case AST_STATE_UP:
3025                                 transmit_response_with_sdp(p, "200 OK", req);
3026                                 break;
3027                         default:
3028                                 ast_log(LOG_WARNING, "Don't know how to handle INVITE in state %d\n", c->_state);
3029                                 transmit_response(p, "100 Trying", req);
3030                         }
3031                 } else {
3032                         if (p) {
3033                                 ast_log(LOG_NOTICE, "Unable to create/find channel\n");
3034                                 transmit_response(p, "503 Unavailable", req);
3035                                 sip_destroy(p);
3036                         }
3037                 }
3038         } else if (!strcasecmp(cmd, "REFER")) {
3039                 struct ast_channel *transfer_to;
3040                 ast_log(LOG_DEBUG, "We found a REFER!\n");
3041                 if (!strlen(p->context))
3042                         strncpy(p->context, context, sizeof(p->context) - 1);
3043                 res = get_refer_info(p, req);
3044                 if (res < 0)
3045                         transmit_response_with_allow(p, "404 Not Found", req);
3046                 else if (res > 0)
3047                         transmit_response_with_allow(p, "484 Address Incomplete", req);
3048                 else
3049                         transmit_response(p, "202 Accepted", req);
3050                 ast_log(LOG_DEBUG,"202 Accepted\n");
3051                 transfer_to = c->bridge;
3052                 if (transfer_to)
3053                         ast_async_goto(transfer_to,"", p->refer_to,1, 1);
3054                         
3055         } else if (!strcasecmp(cmd, "CANCEL") || !strcasecmp(cmd, "BYE")) {
3056                 copy_request(&p->initreq, req);
3057                 p->alreadygone = 1;
3058                 if (p->rtp) {
3059                         /* Immediately stop RTP */
3060                         ast_rtp_destroy(p->rtp);
3061                         p->rtp = NULL;
3062                 }
3063                 if (p->owner)
3064                         ast_queue_hangup(p->owner, 1);
3065                 transmit_response(p, "200 OK", req);
3066         } else if (!strcasecmp(cmd, "MESSAGE")) {
3067                 if (sipdebug)
3068                         ast_verbose("Receiving message!\n");
3069                 receive_message(p, req);
3070                 transmit_response(p, "200 OK", req);
3071         } else if (!strcasecmp(cmd, "INFO")) {
3072                 if (sipdebug)
3073                         ast_verbose("Receiving DTMF!\n");
3074                 receive_info(p, req);