mer feb 12 14:56:57 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)
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                 snprintf(tmp->name, sizeof(tmp->name), "SIP/%s:%d", inet_ntoa(i->sa.sin_addr), ntohs(i->sa.sin_port));
811                 tmp->type = type;
812                 tmp->fds[0] = ast_rtp_fd(i->rtp);
813                 ast_setstate(tmp, state);
814                 if (state == AST_STATE_RING)
815                         tmp->rings = 1;
816                 tmp->writeformat = fmt;
817                 tmp->pvt->rawwriteformat = fmt;
818                 tmp->readformat = fmt;
819                 tmp->pvt->rawreadformat = fmt;
820                 tmp->pvt->pvt = i;
821                 tmp->pvt->send_text = sip_sendtext;
822                 tmp->pvt->call = sip_call;
823                 tmp->pvt->hangup = sip_hangup;
824                 tmp->pvt->answer = sip_answer;
825                 tmp->pvt->read = sip_read;
826                 tmp->pvt->write = sip_write;
827                 tmp->pvt->indicate = sip_indicate;
828                 tmp->pvt->fixup = sip_fixup;
829                 tmp->pvt->send_digit = sip_senddigit;
830                 tmp->pvt->bridge = sip_bridge;
831                 if (strlen(i->language))
832                         strncpy(tmp->language, i->language, sizeof(tmp->language)-1);
833                 i->owner = tmp;
834                 ast_pthread_mutex_lock(&usecnt_lock);
835                 usecnt++;
836                 ast_pthread_mutex_unlock(&usecnt_lock);
837                 ast_update_use_count();
838                 strncpy(tmp->context, i->context, sizeof(tmp->context)-1);
839                 strncpy(tmp->exten, i->exten, sizeof(tmp->exten)-1);
840                 if (strlen(i->callerid))
841                         tmp->callerid = strdup(i->callerid);
842                 tmp->priority = 1;
843                 if (state != AST_STATE_DOWN) {
844                         if (ast_pbx_start(tmp)) {
845                                 ast_log(LOG_WARNING, "Unable to start PBX on %s\n", tmp->name);
846                                 ast_hangup(tmp);
847                                 tmp = NULL;
848                         }
849                 }
850         } else
851                 ast_log(LOG_WARNING, "Unable to allocate channel structure\n");
852         return tmp;
853 }
854
855 static struct cfalias {
856         char *fullname;
857         char *shortname;
858 } aliases[] = {
859         { "Content-Type", "c" },
860         { "Content-Encoding", "e" },
861         { "From", "f" },
862         { "Call-ID", "i" },
863         { "Contact", "m" },
864         { "Content-Length", "l" },
865         { "Subject", "s" },
866         { "To", "t" },
867         { "Via", "v" },
868 };
869
870 static char *get_sdp(struct sip_request *req, char *name)
871 {
872         int x;
873         int len = strlen(name);
874         char *r;
875         for (x=0;x<req->lines;x++) {
876                 if (!strncasecmp(req->line[x], name, len) && 
877                                 (req->line[x][len] == '=')) {
878                                         r = req->line[x] + len + 1;
879                                         while(*r && (*r < 33))
880                                                         r++;
881                                         return r;
882                 }
883         }
884         return "";
885 }
886
887 static char *__get_header(struct sip_request *req, char *name, int *start)
888 {
889         int x;
890         int len = strlen(name);
891         char *r;
892         for (x=*start;x<req->headers;x++) {
893                 if (!strncasecmp(req->header[x], name, len) && 
894                                 (req->header[x][len] == ':')) {
895                                         r = req->header[x] + len + 1;
896                                         while(*r && (*r < 33))
897                                                         r++;
898                                         *start = x+1;
899                                         return r;
900                 }
901         }
902         /* Try aliases */
903         for (x=0;x<sizeof(aliases) / sizeof(aliases[0]); x++) 
904                 if (!strcasecmp(aliases[x].fullname, name))
905                         return __get_header(req, aliases[x].shortname, start);
906
907         /* Don't return NULL, so get_header is always a valid pointer */
908         return "";
909 }
910
911 static char *get_header(struct sip_request *req, char *name)
912 {
913         int start = 0;
914         return __get_header(req, name, &start);
915 }
916
917 static struct ast_frame *sip_rtp_read(struct sip_pvt *p)
918 {
919         /* Retrieve audio/etc from channel.  Assumes p->lock is already held. */
920         struct ast_frame *f;
921         f = ast_rtp_read(p->rtp);
922         if (p->owner) {
923                 /* We already hold the channel lock */
924                 if (f->frametype == AST_FRAME_VOICE) {
925                         if (f->subclass != p->owner->nativeformats) {
926                                 ast_log(LOG_DEBUG, "Oooh, format changed to %d\n", f->subclass);
927                                 p->owner->nativeformats = f->subclass;
928                                 ast_set_read_format(p->owner, p->owner->readformat);
929                                 ast_set_write_format(p->owner, p->owner->writeformat);
930                         }
931                 }
932         }
933         return f;
934 }
935
936 static struct ast_frame *sip_read(struct ast_channel *ast)
937 {
938         struct ast_frame *fr;
939         struct sip_pvt *p = ast->pvt->pvt;
940         ast_pthread_mutex_lock(&p->lock);
941         fr = sip_rtp_read(p);
942         ast_pthread_mutex_unlock(&p->lock);
943         return fr;
944 }
945
946 static void build_callid(char *callid, int len, struct in_addr ourip)
947 {
948         int res;
949         int val;
950         int x;
951         for (x=0;x<4;x++) {
952                 val = rand();
953                 res = snprintf(callid, len, "%08x", val);
954                 len -= res;
955                 callid += res;
956         }
957         /* It's not important that we really use our right IP here... */
958         snprintf(callid, len, "@%s", inet_ntoa(ourip));
959 }
960
961 static struct sip_pvt *sip_alloc(char *callid, struct sockaddr_in *sin)
962 {
963         struct sip_pvt *p;
964
965         p = malloc(sizeof(struct sip_pvt));
966         if (!p)
967                 return NULL;
968         /* Keep track of stuff */
969         memset(p, 0, sizeof(struct sip_pvt));
970         p->initid = -1;
971         p->rtp = ast_rtp_new(NULL, NULL);
972         p->branch = rand();     
973         p->tag = rand();
974         /* Start with 101 instead of 1 */
975         p->ocseq = 101;
976         if (!p->rtp) {
977                 ast_log(LOG_WARNING, "Unable to create RTP session: %s\n", strerror(errno));
978                 free(p);
979                 return NULL;
980         }
981         ast_rtp_settos(p->rtp, tos);
982         ast_pthread_mutex_init(&p->lock);
983 #if 0
984         ast_rtp_set_data(p->rtp, p);
985         ast_rtp_set_callback(p->rtp, rtpready);
986 #endif  
987         if (sin) {
988                 memcpy(&p->sa, sin, sizeof(p->sa));
989                 memcpy(&p->ourip, myaddrfor(&p->sa.sin_addr), sizeof(p->ourip));
990         } else {
991                 memcpy(&p->ourip, &__ourip, sizeof(p->ourip));
992         }
993         snprintf(p->via, sizeof(p->via), "SIP/2.0/UDP %s:%d;branch=%08x", inet_ntoa(p->ourip), ourport, p->branch);
994         if (!callid)
995                 build_callid(p->callid, sizeof(p->callid), p->ourip);
996         else
997                 strncpy(p->callid, callid, sizeof(p->callid) - 1);
998         /* Assume reinvite OK */
999         p->canreinvite = 1;
1000         /* Add to list */
1001         ast_pthread_mutex_lock(&iflock);
1002         p->next = iflist;
1003         iflist = p;
1004         ast_pthread_mutex_unlock(&iflock);
1005         if (option_debug)
1006                 ast_log(LOG_DEBUG, "Allocating new SIP call for %s\n", callid);
1007         return p;
1008 }
1009
1010 static struct sip_pvt *find_call(struct sip_request *req, struct sockaddr_in *sin)
1011 {
1012         struct sip_pvt *p;
1013         char *callid;
1014         callid = get_header(req, "Call-ID");
1015         if (!strlen(callid)) {
1016                 ast_log(LOG_WARNING, "Call missing call ID from '%s'\n", inet_ntoa(sin->sin_addr));
1017                 return NULL;
1018         }
1019         ast_pthread_mutex_lock(&iflock);
1020         p = iflist;
1021         while(p) {
1022                 if (!strcmp(p->callid, callid)) {
1023                         /* Found the call */
1024 #if 0
1025                         if (!p->insecure && ((p->sa.sin_addr.s_addr != sin->sin_addr.s_addr) ||
1026                             (p->sa.sin_port != sin->sin_port))) {
1027                                         char orig[80];
1028                                         char new[80];
1029                                         snprintf(orig, sizeof(orig), "%s:%d", inet_ntoa(p->sa.sin_addr), ntohs(p->sa.sin_port));
1030                                         snprintf(new, sizeof(new), "%s:%d", inet_ntoa(sin->sin_addr), ntohs(sin->sin_port));
1031                                         ast_log(LOG_WARNING, "Looks like %s is trying to steal call '%s' from %s?\n", new, p->callid, orig);
1032                                         ast_pthread_mutex_unlock(&iflock);
1033                                         return NULL;
1034                         }
1035 #endif
1036                         ast_pthread_mutex_unlock(&iflock);
1037                         return p;
1038                 }
1039                 p = p->next;
1040         }
1041         ast_pthread_mutex_unlock(&iflock);
1042         return sip_alloc(callid, sin);
1043 }
1044
1045 static int sip_register(char *value, int lineno)
1046 {
1047         struct sip_registry *reg;
1048         char copy[256] = "";
1049         char *username, *hostname, *secret;
1050         char *porta;
1051         char *stringp=NULL;
1052         
1053         struct hostent *hp;
1054         if (!value)
1055                 return -1;
1056         strncpy(copy, value, sizeof(copy)-1);
1057         stringp=copy;
1058         username = strsep(&stringp, "@");
1059         hostname = strsep(&stringp, "@");
1060         if (!hostname) {
1061                 ast_log(LOG_WARNING, "Format for registration is user[:secret]@host[:port] at line %d", lineno);
1062                 return -1;
1063         }
1064         stringp=username;
1065         username = strsep(&stringp, ":");
1066         secret = strsep(&stringp, ":");
1067         stringp=hostname;
1068         hostname = strsep(&stringp, ":");
1069         porta = strsep(&stringp, ";");
1070         
1071         if (porta && !atoi(porta)) {
1072                 ast_log(LOG_WARNING, "%s is not a valid port number at line %d\n", porta, lineno);
1073                 return -1;
1074         }
1075         hp = gethostbyname(hostname);
1076         if (!hp) {
1077                 ast_log(LOG_WARNING, "Host '%s' not found at line %d\n", hostname, lineno);
1078                 return -1;
1079         }
1080         reg = malloc(sizeof(struct sip_registry));
1081         if (reg) {
1082                 memset(reg, 0, sizeof(struct sip_registry));
1083                 strncpy(reg->username, username, sizeof(reg->username)-1);
1084                 if (secret)
1085                         strncpy(reg->secret, secret, sizeof(reg->secret)-1);
1086                 reg->expire = -1;
1087                 reg->refresh = DEFAULT_EXPIREY;
1088                 reg->addr.sin_family = AF_INET;
1089                 memcpy(&reg->addr.sin_addr, hp->h_addr, sizeof(&reg->addr.sin_addr));
1090                 reg->addr.sin_port = porta ? htons(atoi(porta)) : htons(DEFAULT_SIP_PORT);
1091                 reg->next = registrations;
1092                 reg->callid_valid = 0;
1093                 registrations = reg;
1094         } else {
1095                 ast_log(LOG_ERROR, "Out of memory\n");
1096                 return -1;
1097         }
1098         return 0;
1099 }
1100
1101 static void parse(struct sip_request *req)
1102 {
1103         /* Divide fields by NULL's */
1104         char *c;
1105         int f = 0;
1106         c = req->data;
1107
1108         /* First header starts immediately */
1109         req->header[f] = c;
1110         while(*c) {
1111                 if (*c == '\n') {
1112                         /* We've got a new header */
1113                         *c = 0;
1114
1115 #if 0
1116                         printf("Header: %s (%d)\n", req->header[f], strlen(req->header[f]));
1117 #endif                  
1118                         if (!strlen(req->header[f])) {
1119                                 /* Line by itself means we're now in content */
1120                                 c++;
1121                                 break;
1122                         }
1123                         if (f >= SIP_MAX_HEADERS - 1) {
1124                                 ast_log(LOG_WARNING, "Too many SIP headers...\n");
1125                         } else
1126                                 f++;
1127                         req->header[f] = c + 1;
1128                 } else if (*c == '\r') {
1129                         /* Ignore but eliminate \r's */
1130                         *c = 0;
1131                 }
1132                 c++;
1133         }
1134         /* Check for last header */
1135         if (strlen(req->header[f])) 
1136                 f++;
1137         req->headers = f;
1138         /* Now we process any mime content */
1139         f = 0;
1140         req->line[f] = c;
1141         while(*c) {
1142                 if (*c == '\n') {
1143                         /* We've got a new line */
1144                         *c = 0;
1145 #if 0
1146                         printf("Line: %s (%d)\n", req->line[f], strlen(req->line[f]));
1147 #endif                  
1148                         if (f >= SIP_MAX_LINES - 1) {
1149                                 ast_log(LOG_WARNING, "Too many SDP lines...\n");
1150                         } else
1151                                 f++;
1152                         req->line[f] = c + 1;
1153                 } else if (*c == '\r') {
1154                         /* Ignore and eliminate \r's */
1155                         *c = 0;
1156                 }
1157                 c++;
1158         }
1159         /* Check for last line */
1160         if (strlen(req->line[f])) 
1161                 f++;
1162         req->lines = f;
1163         if (sipdebug)
1164                 ast_verbose("%d headers, %d lines\n", req->headers, req->lines);
1165         if (*c) 
1166                 ast_log(LOG_WARNING, "Odd content, extra stuff left over ('%s')\n", c);
1167 }
1168
1169 static int process_sdp(struct sip_pvt *p, struct sip_request *req)
1170 {
1171         char *m;
1172         char *c;
1173         char host[258];
1174         int len = -1;
1175         int portno;
1176         int peercapability;
1177         struct sockaddr_in sin;
1178         char *codecs;
1179         struct hostent *hp;
1180         int codec;
1181         /* Get codec and RTP info from SDP */
1182         if (strcasecmp(get_header(req, "Content-Type"), "application/sdp")) {
1183                 ast_log(LOG_NOTICE, "Content is '%s', not 'application/sdp'\n", get_header(req, "Content-Type"));
1184                 return -1;
1185         }
1186         m = get_sdp(req, "m");
1187         c = get_sdp(req, "c");
1188         if (!strlen(m) || !strlen(c)) {
1189                 ast_log(LOG_WARNING, "Insufficient information for SDP (m = '%s', c = '%s')\n", m, c);
1190                 return -1;
1191         }
1192         if (sscanf(c, "IN IP4 %256s", host) != 1) {
1193                 ast_log(LOG_WARNING, "Invalid host in c= line, '%s'\n", c);
1194                 return -1;
1195         }
1196         /* XXX This could block for a long time, and block the main thread! XXX */
1197         hp = gethostbyname(host);
1198         if (!hp) {
1199                 ast_log(LOG_WARNING, "Unable to lookup host in c= line, '%s'\n", c);
1200                 return -1;
1201         }
1202         if ((sscanf(m, "audio %d RTP/AVP %n", &portno, &len) != 1) || (len < 0)) {
1203                 ast_log(LOG_WARNING, "Unable to determine port number for RTP in '%s'\n", m); 
1204                 return -1;
1205         }
1206         sin.sin_family = AF_INET;
1207         memcpy(&sin.sin_addr, hp->h_addr, sizeof(sin.sin_addr));
1208         sin.sin_port = htons(portno);
1209         if (p->rtp)
1210                 ast_rtp_set_peer(p->rtp, &sin);
1211 #if 0
1212         printf("Peer RTP is at port %s:%d\n", inet_ntoa(sin.sin_addr), ntohs(sin.sin_port));
1213 #endif  
1214         peercapability = 0;
1215         codecs = m + len;
1216         while(strlen(codecs)) {
1217                 if (sscanf(codecs, "%d %n", &codec, &len) != 1) {
1218                         ast_log(LOG_WARNING, "Error in codec string '%s'\n", codecs);
1219                         return -1;
1220                 }
1221 #if 0
1222                 printf("Codec: %d\n", codec);
1223 #endif          
1224                 codec = rtp2ast(codec);
1225                 if (codec  > -1)
1226                         peercapability |= codec;
1227                 codecs += len;
1228         }
1229         p->capability = capability & peercapability;
1230         if (sipdebug)
1231                 ast_verbose("Capabilities: us - %d, them - %d, combined - %d\n",
1232                 capability, peercapability, p->capability);
1233         if (!p->capability) {
1234                 ast_log(LOG_WARNING, "No compatible codecs!\n");
1235                 return -1;
1236         }
1237         if (p->owner && !(p->owner->nativeformats & p->capability)) {
1238                 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);
1239                 p->owner->nativeformats = p->capability;
1240                 ast_set_read_format(p->owner, p->owner->readformat);
1241                 ast_set_write_format(p->owner, p->owner->writeformat);
1242         }
1243         return 0;
1244         
1245 }
1246
1247 static int add_header(struct sip_request *req, char *var, char *value)
1248 {
1249         if (req->len >= sizeof(req->data) - 4) {
1250                 ast_log(LOG_WARNING, "Out of space, can't add anymore\n");
1251                 return -1;
1252         }
1253         if (req->lines) {
1254                 ast_log(LOG_WARNING, "Can't add more headers when lines have been added\n");
1255                 return -1;
1256         }
1257         req->header[req->headers] = req->data + req->len;
1258         snprintf(req->header[req->headers], sizeof(req->data) - req->len - 4, "%s: %s\r\n", var, value);
1259         req->len += strlen(req->header[req->headers]);
1260         if (req->headers < SIP_MAX_HEADERS)
1261                 req->headers++;
1262         else {
1263                 ast_log(LOG_WARNING, "Out of header space\n");
1264                 return -1;
1265         }
1266         return 0;       
1267 }
1268
1269 static int add_blank_header(struct sip_request *req)
1270 {
1271         if (req->len >= sizeof(req->data) - 4) {
1272                 ast_log(LOG_WARNING, "Out of space, can't add anymore\n");
1273                 return -1;
1274         }
1275         if (req->lines) {
1276                 ast_log(LOG_WARNING, "Can't add more headers when lines have been added\n");
1277                 return -1;
1278         }
1279         req->header[req->headers] = req->data + req->len;
1280         snprintf(req->header[req->headers], sizeof(req->data) - req->len, "\r\n");
1281         req->len += strlen(req->header[req->headers]);
1282         if (req->headers < SIP_MAX_HEADERS)
1283                 req->headers++;
1284         else {
1285                 ast_log(LOG_WARNING, "Out of header space\n");
1286                 return -1;
1287         }
1288         return 0;       
1289 }
1290
1291 static int add_line(struct sip_request *req, char *line)
1292 {
1293         if (req->len >= sizeof(req->data) - 4) {
1294                 ast_log(LOG_WARNING, "Out of space, can't add anymore\n");
1295                 return -1;
1296         }
1297         if (!req->lines) {
1298                 /* Add extra empty return */
1299                 snprintf(req->data + req->len, sizeof(req->data) - req->len, "\r\n");
1300                 req->len += strlen(req->data + req->len);
1301         }
1302         req->line[req->lines] = req->data + req->len;
1303         snprintf(req->line[req->lines], sizeof(req->data) - req->len, "%s", line);
1304         req->len += strlen(req->line[req->lines]);
1305         if (req->lines < SIP_MAX_LINES)
1306                 req->lines++;
1307         else {
1308                 ast_log(LOG_WARNING, "Out of line space\n");
1309                 return -1;
1310         }
1311         return 0;       
1312 }
1313
1314 static int copy_header(struct sip_request *req, struct sip_request *orig, char *field)
1315 {
1316         char *tmp;
1317         tmp = get_header(orig, field);
1318         if (strlen(tmp)) {
1319                 /* Add what we're responding to */
1320                 return add_header(req, field, tmp);
1321         }
1322         ast_log(LOG_NOTICE, "No field '%s' present to copy\n", field);
1323         return -1;
1324 }
1325
1326 static int copy_all_header(struct sip_request *req, struct sip_request *orig, char *field)
1327 {
1328         char *tmp;
1329         int start = 0;
1330         int copied = 0;
1331         for (;;) {
1332                 tmp = __get_header(orig, field, &start);
1333                 if (strlen(tmp)) {
1334                         /* Add what we're responding to */
1335                         add_header(req, field, tmp);
1336                         copied++;
1337                 } else
1338                         break;
1339         }
1340         if (!copied) {
1341                 ast_log(LOG_NOTICE, "No field '%s' present to copy\n", field);
1342                 return -1;
1343         }
1344         return 0;
1345 }
1346
1347 static int init_resp(struct sip_request *req, char *resp, struct sip_request *orig)
1348 {
1349         /* Initialize a response */
1350         if (req->headers || req->len) {
1351                 ast_log(LOG_WARNING, "Request already initialized?!?\n");
1352                 return -1;
1353         }
1354         req->header[req->headers] = req->data + req->len;
1355         snprintf(req->header[req->headers], sizeof(req->data) - req->len, "SIP/2.0 %s\r\n", resp);
1356         req->len += strlen(req->header[req->headers]);
1357         if (req->headers < SIP_MAX_HEADERS)
1358                 req->headers++;
1359         else
1360                 ast_log(LOG_WARNING, "Out of header space\n");
1361         return 0;
1362 }
1363
1364 static int init_req(struct sip_request *req, char *resp, char *recip)
1365 {
1366         /* Initialize a response */
1367         if (req->headers || req->len) {
1368                 ast_log(LOG_WARNING, "Request already initialized?!?\n");
1369                 return -1;
1370         }
1371         req->header[req->headers] = req->data + req->len;
1372         snprintf(req->header[req->headers], sizeof(req->data) - req->len, "%s %s SIP/2.0\r\n", resp, recip);
1373         req->len += strlen(req->header[req->headers]);
1374         if (req->headers < SIP_MAX_HEADERS)
1375                 req->headers++;
1376         else
1377                 ast_log(LOG_WARNING, "Out of header space\n");
1378         return 0;
1379 }
1380
1381 static int respprep(struct sip_request *resp, struct sip_pvt *p, char *msg, struct sip_request *req)
1382 {
1383         char newto[256] = "", *ot;
1384         memset(resp, 0, sizeof(*resp));
1385         init_resp(resp, msg, req);
1386         copy_all_header(resp, req, "Via");
1387         copy_header(resp, req, "From");
1388         ot = get_header(req, "To");
1389         if (!strstr(ot, "tag=")) {
1390                 /* Add the proper tag if we don't have it already.  If they have specified
1391                    their tag, use it.  Otherwise, use our own tag */
1392                 if (strlen(p->theirtag))
1393                         snprintf(newto, sizeof(newto), "%s;tag=%s", ot, p->theirtag);
1394                 else if (p->tag)
1395                         snprintf(newto, sizeof(newto), "%s;tag=%08x", ot, p->tag);
1396                 else
1397                         strncpy(newto, ot, sizeof(newto) - 1);
1398                 ot = newto;
1399         }
1400         add_header(resp, "To", ot);
1401         copy_header(resp, req, "Call-ID");
1402         copy_header(resp, req, "CSeq");
1403         add_header(resp, "User-Agent", "Asterisk PBX");
1404         if (p->expirey) {
1405                 /* For registration responses, we also need expirey and
1406                    contact info */
1407                 char tmp[80];
1408                 char contact2[256] = "", *c, contact[256];
1409                 snprintf(tmp, sizeof(tmp), "%d", p->expirey);
1410                 strncpy(contact2, get_header(req, "Contact"), sizeof(contact2)-1);
1411                 c = ditch_braces(contact2);
1412                 snprintf(contact, sizeof(contact), "<%s>", c);
1413                 add_header(resp, "Expires", tmp);
1414                 add_header(resp, "Contact", contact);
1415         } else {
1416                 char contact2[256] = "", *c, contact[256];
1417                 /* XXX This isn't exactly right and it's implemented
1418                        very stupidly *sigh* XXX */
1419                 strncpy(contact2, get_header(req, "To"), sizeof(contact2)-1);
1420                 c = ditch_braces(contact2);
1421                 snprintf(contact, sizeof(contact), "<%s>", c);
1422                 add_header(resp, "Contact", contact);
1423         }
1424         return 0;
1425 }
1426
1427 static int reqprep(struct sip_request *req, struct sip_pvt *p, char *msg, int inc)
1428 {
1429         struct sip_request *orig = &p->initreq;
1430         char stripped[80] ="";
1431         char tmp[80];
1432         char newto[256];
1433         char *c, *n;
1434         char *ot, *of;
1435
1436         memset(req, 0, sizeof(struct sip_request));
1437         
1438         if (inc)
1439                 p->ocseq++;
1440
1441         if (p->outgoing)
1442                 strncpy(stripped, get_header(orig, "To"), sizeof(stripped) - 1);
1443         else
1444                 strncpy(stripped, get_header(orig, "From"), sizeof(stripped) - 1);
1445         
1446         c = strchr(stripped, '<');
1447         if (c) 
1448                 c++;
1449         else
1450                 c = stripped;
1451         n = strchr(c, '>');
1452         if (n)
1453                 *n = '\0';
1454         
1455         init_req(req, msg, c);
1456
1457         snprintf(tmp, sizeof(tmp), "%d %s", p->ocseq, msg);
1458
1459         add_header(req, "Via", p->via);
1460
1461         ot = get_header(orig, "To");
1462         of = get_header(orig, "From");
1463
1464         if (!strstr(ot, "tag=")) {
1465                 /* Add the proper tag if we don't have it already.  If they have specified
1466                    their tag, use it.  Otherwise, use our own tag */
1467                 if (strlen(p->theirtag))
1468                         snprintf(newto, sizeof(newto), "%s;tag=%s", ot, p->theirtag);
1469                 else
1470                         snprintf(newto, sizeof(newto), "%s;tag=%08x", ot, p->tag);
1471                 ot = newto;
1472         }
1473
1474         if (p->outgoing) {
1475                 add_header(req, "From", of);
1476                 add_header(req, "To", ot);
1477         } else {
1478                 add_header(req, "From", ot);
1479                 add_header(req, "To", of);
1480         }
1481         copy_header(req, orig, "Call-ID");
1482         add_header(req, "CSeq", tmp);
1483
1484         add_header(req, "User-Agent", "Asterisk PBX");
1485         return 0;
1486 }
1487
1488 static int transmit_response(struct sip_pvt *p, char *msg, struct sip_request *req)
1489 {
1490         struct sip_request resp;
1491         respprep(&resp, p, msg, req);
1492         add_header(&resp, "Content-Length", "0");
1493         add_blank_header(&resp);
1494         return send_response(p, &resp);
1495 }
1496
1497 static int transmit_response_with_allow(struct sip_pvt *p, char *msg, struct sip_request *req)
1498 {
1499         struct sip_request resp;
1500         respprep(&resp, p, msg, req);
1501         add_header(&resp, "Allow", "INVITE, ACK, CANCEL, OPTIONS, BYE, REFER");
1502         add_header(&resp, "Accept", "application/sdp");
1503         add_header(&resp, "Content-Length", "0");
1504         add_blank_header(&resp);
1505         return send_response(p, &resp);
1506 }
1507
1508 static int transmit_response_with_auth(struct sip_pvt *p, char *msg, struct sip_request *req, char *randdata)
1509 {
1510         struct sip_request resp;
1511         char tmp[256];
1512         snprintf(tmp, sizeof(tmp), "DIGEST realm=\"asterisk\", nonce=\"%s\"", randdata);
1513         respprep(&resp, p, msg, req);
1514         add_header(&resp, "Proxy-Authenticate", tmp);
1515         add_header(&resp, "Content-Length", "0");
1516         add_blank_header(&resp);
1517         return send_response(p, &resp);
1518 }
1519
1520 static int add_text(struct sip_request *req, char *text)
1521 {
1522         /* XXX Convert \n's to \r\n's XXX */
1523         int len = strlen(text);
1524         char clen[256];
1525         snprintf(clen, sizeof(clen), "%d", len);
1526         add_header(req, "Content-Type", "text/plain");
1527         add_header(req, "Content-Length", clen);
1528         add_line(req, text);
1529         return 0;
1530 }
1531
1532 static int add_sdp(struct sip_request *resp, struct sip_pvt *p, struct ast_rtp *rtp)
1533 {
1534         int len;
1535         int codec;
1536         char costr[80];
1537         struct sockaddr_in sin;
1538         char v[256];
1539         char s[256];
1540         char o[256];
1541         char c[256];
1542         char t[256];
1543         char m[256];
1544         char a[1024] = "";
1545         int x;
1546         struct sockaddr_in dest;
1547         /* XXX We break with the "recommendation" and send our IP, in order that our
1548                peer doesn't have to gethostbyname() us XXX */
1549         len = 0;
1550         if (!p->rtp) {
1551                 ast_log(LOG_WARNING, "No way to add SDP without an RTP structure\n");
1552                 return -1;
1553         }
1554         ast_rtp_get_us(p->rtp, &sin);
1555         if (rtp) {
1556                 ast_rtp_get_peer(rtp, &dest);
1557         } else {
1558                 dest.sin_addr = p->ourip;
1559                 dest.sin_port = sin.sin_port;
1560         }
1561         if (sipdebug)
1562                 ast_verbose("We're at %s port %d\n", inet_ntoa(p->ourip), ntohs(sin.sin_port)); 
1563         snprintf(v, sizeof(v), "v=0\r\n");
1564         snprintf(o, sizeof(o), "o=root %d %d IN IP4 %s\r\n", getpid(), getpid(), inet_ntoa(dest.sin_addr));
1565         snprintf(s, sizeof(s), "s=session\r\n");
1566         snprintf(c, sizeof(c), "c=IN IP4 %s\r\n", inet_ntoa(dest.sin_addr));
1567         snprintf(t, sizeof(t), "t=0 0\r\n");
1568         snprintf(m, sizeof(m), "m=audio %d RTP/AVP", ntohs(dest.sin_port));
1569         for (x=1;x<= AST_FORMAT_MAX_AUDIO; x <<= 1) {
1570                 if (p->capability & x) {
1571                         if (sipdebug)
1572                                 ast_verbose("Answering with capability %d\n", x);
1573                         if ((codec = ast2rtp(x)) > -1) {
1574                                 snprintf(costr, sizeof(costr), " %d", codec);
1575                                 strcat(m, costr);
1576                                 snprintf(costr, sizeof(costr), "a=rtpmap:%d %s/8000\r\n", codec, ast2rtpn(x));
1577                                 strcat(a, costr);
1578                         }
1579                 }
1580         }
1581         strcat(m, " 101\r\n");
1582         strcat(a, "a=rtpmap:101 telephone-event/8000\r\n");
1583         /* Indicate we support DTMF only...  Not sure about 16, but MSN supports it so dang it, we will too... */
1584         strcat(a, "a=fmtp:101 0-16\r\n");
1585         len = strlen(v) + strlen(s) + strlen(o) + strlen(c) + strlen(t) + strlen(m) + strlen(a);
1586         snprintf(costr, sizeof(costr), "%d", len);
1587         add_header(resp, "Content-Type", "application/sdp");
1588         add_header(resp, "Content-Length", costr);
1589         add_line(resp, v);
1590         add_line(resp, o);
1591         add_line(resp, s);
1592         add_line(resp, c);
1593         add_line(resp, t);
1594         add_line(resp, m);
1595         add_line(resp, a);
1596         return 0;
1597 }
1598
1599 static void copy_request(struct sip_request *dst,struct sip_request *src)
1600 {
1601         long offset;
1602         int x;
1603         offset = ((void *)dst) - ((void *)src);
1604         /* First copy stuff */
1605         memcpy(dst, src, sizeof(*dst));
1606         /* Now fix pointer arithmetic */
1607         for (x=0;x<src->headers;x++)
1608                 dst->header[x] += offset;
1609         for (x=0;x<src->lines;x++)
1610                 dst->line[x] += offset;
1611 }
1612
1613 static int transmit_response_with_sdp(struct sip_pvt *p, char *msg, struct sip_request *req)
1614 {
1615         struct sip_request resp;
1616         respprep(&resp, p, msg, req);
1617         add_sdp(&resp, p, NULL);
1618         return send_response(p, &resp);
1619 }
1620
1621 static int transmit_reinvite_with_sdp(struct sip_pvt *p, struct ast_rtp *rtp)
1622 {
1623         struct sip_request resp;
1624         reqprep(&resp, p, "INVITE", 1);
1625         add_sdp(&resp, p, rtp);
1626         return send_response(p, &resp);
1627 }
1628
1629 static void initreqprep(struct sip_request *req, struct sip_pvt *p, char *cmd, char *vxml_url)
1630 {
1631         char invite[256];
1632         char from[256];
1633         char to[256];
1634         char tmp[80];
1635         char cid[256];
1636         char *l = "asterisk", *n=NULL;
1637         if (p->owner && p->owner->callerid) {
1638                 strcpy(cid, p->owner->callerid);
1639                 ast_callerid_parse(cid, &n, &l);
1640                 if (l) 
1641                         ast_shrink_phone_number(l);
1642                 if (!l || !ast_isphonenumber(l))
1643                                 l = "asterisk";
1644         }
1645         if (!n)
1646                 n = "asterisk";
1647         snprintf(from, sizeof(from), "\"%s\" <sip:%s@%s>;tag=%08x", n, l, inet_ntoa(p->ourip), p->tag);
1648         if (strlen(p->username)) {
1649                 if (ntohs(p->sa.sin_port) != DEFAULT_SIP_PORT) {
1650                         snprintf(invite, sizeof(invite), "sip:%s@%s:%d",p->username, inet_ntoa(p->sa.sin_addr), ntohs(p->sa.sin_port));
1651                 } else {
1652                         snprintf(invite, sizeof(invite), "sip:%s@%s",p->username, inet_ntoa(p->sa.sin_addr));
1653                 }
1654         } else if (ntohs(p->sa.sin_port) != DEFAULT_SIP_PORT) {
1655                 snprintf(invite, sizeof(invite), "sip:%s:%d", inet_ntoa(p->sa.sin_addr), ntohs(p->sa.sin_port));
1656         } else {
1657                 snprintf(invite, sizeof(invite), "sip:%s", inet_ntoa(p->sa.sin_addr));
1658         }
1659         /* If there is a VXML URL append it to the SIP URL */
1660         if (vxml_url)
1661         {
1662                 snprintf(to, sizeof(to), "<%s>;%s", invite, vxml_url);
1663         }
1664         else
1665         {
1666                 snprintf(to, sizeof(to), "<%s>", invite );
1667         }
1668         memset(req, 0, sizeof(struct sip_request));
1669         init_req(req, cmd, invite);
1670         snprintf(tmp, sizeof(tmp), "%d %s", ++p->ocseq, cmd);
1671
1672         add_header(req, "Via", p->via);
1673         add_header(req, "From", from);
1674         {
1675                 char contact2[256] ="", *c, contact[256];
1676                 /* XXX This isn't exactly right and it's implemented
1677                        very stupidly *sigh* XXX */
1678                 strncpy(contact2, from, sizeof(contact2)-1);
1679                 c = ditch_braces(contact2);
1680                 snprintf(contact, sizeof(contact), "<%s>", c);
1681                 add_header(req, "Contact", contact);
1682         }
1683         add_header(req, "To", to);
1684         add_header(req, "Call-ID", p->callid);
1685         add_header(req, "CSeq", tmp);
1686         add_header(req, "User-Agent", "Asterisk PBX");
1687 }
1688
1689 static int transmit_invite(struct sip_pvt *p, char *cmd, int sdp, char *auth, char *vxml_url)
1690 {
1691         struct sip_request req;
1692         initreqprep(&req, p, cmd, vxml_url);
1693         if (auth)
1694                 add_header(&req, "Proxy-Authorization", auth);
1695         if (sdp) {
1696                 add_sdp(&req, p, NULL);
1697         } else {
1698                 add_header(&req, "Content-Length", "0");
1699                 add_blank_header(&req);
1700         }
1701         if (!p->initreq.headers) {
1702                 /* Use this as the basis */
1703                 copy_request(&p->initreq, &req);
1704                 parse(&p->initreq);
1705         }
1706         p->lastinvite = p->ocseq;
1707         return send_request(p, &req);
1708 }
1709
1710 static int transmit_notify(struct sip_pvt *p, int hasmsgs)
1711 {
1712         struct sip_request req;
1713         char tmp[256];
1714         char clen[20];
1715         initreqprep(&req, p, "NOTIFY", NULL);
1716         add_header(&req, "Event", "message-summary");
1717         add_header(&req, "Content-Type", "text/plain");
1718
1719         snprintf(tmp, sizeof(tmp), "Message-Waiting: %s\n", hasmsgs ? "yes" : "no");
1720         snprintf(clen, sizeof(clen), "%d", strlen(tmp));
1721         add_header(&req, "Content-Length", clen);
1722         add_line(&req, tmp);
1723
1724         if (!p->initreq.headers) {
1725                 /* Use this as the basis */
1726                 copy_request(&p->initreq, &req);
1727                 parse(&p->initreq);
1728         }
1729
1730         p->lastinvite = p->ocseq;
1731         return send_request(p, &req);
1732 }
1733
1734 static int transmit_register(struct sip_registry *r, char *cmd, char *auth);
1735
1736 static int sip_reregister(void *data) 
1737 {
1738         /* if we are here, we know that we need to reregister. */
1739         struct sip_registry *r=(struct sip_registry *)data;
1740         return sip_do_register(r);
1741         
1742 }
1743
1744
1745 static int sip_do_register(struct sip_registry *r)
1746 {
1747         int res;
1748         ast_pthread_mutex_lock(&r->lock);
1749         res=transmit_register(r, "REGISTER", NULL);
1750         ast_pthread_mutex_unlock(&r->lock);
1751         return res;
1752 }
1753
1754 static int sip_reg_timeout(void *data)
1755 {
1756         /* if we are here, our registration timed out, so we'll just do it over */
1757         struct sip_registry *r=data;
1758         int res;
1759         ast_pthread_mutex_lock(&r->lock);
1760         ast_log(LOG_NOTICE, "Registration timed out, trying again\n"); 
1761         r->regstate=REG_STATE_UNREGISTERED;
1762         /* cancel ourselves first!!! */
1763         /* ast_sched_del(sched,r->timeout); */
1764         res=transmit_register(r, "REGISTER", NULL);
1765         ast_pthread_mutex_unlock(&r->lock);
1766         return res;
1767 }
1768
1769 static int transmit_register(struct sip_registry *r, char *cmd, char *auth)
1770 {
1771         struct sip_request req;
1772         char from[256];
1773         char to[256];
1774         char tmp[80];
1775         char via[80];
1776         char addr[80];
1777         struct sip_pvt *p;
1778         /* exit if we are already in process with this registrar ?*/
1779         if ( (auth==NULL && r->regstate==REG_STATE_REGSENT) || r->regstate==REG_STATE_AUTHSENT) {
1780                 ast_log(LOG_NOTICE, "Strange, trying to register when registration already pending\n");
1781                 return 0;
1782         }
1783
1784
1785         if (!(p=r->call)) {
1786                 if (!r->callid_valid) {
1787                   build_callid(r->callid, sizeof(r->callid), __ourip);
1788                   r->callid_valid=1;
1789                 }
1790                 p=sip_alloc( r->callid, &r->addr );
1791                 p->outgoing = 1;
1792                 r->call=p;
1793                 p->registry=r;
1794                 strncpy(p->peersecret, r->secret, sizeof(p->peersecret)-1);
1795                 strncpy(p->peername, r->username, sizeof(p->peername)-1);
1796                 strncpy(p->username, r->username, sizeof(p->username)-1);
1797         }
1798
1799         /* set up a timeout */
1800         if (auth==NULL && !r->timeout)  {
1801                 r->timeout = ast_sched_add(sched, 10*1000, sip_reg_timeout, r);
1802                 ast_log(LOG_NOTICE, "Scheduled a timeout # %d\n", r->timeout);
1803         }
1804
1805         snprintf(from, sizeof(from), "<sip:%s@%s>;tag=%08x", r->username, inet_ntoa(r->addr.sin_addr), p->tag);
1806         snprintf(to, sizeof(to),     "<sip:%s@%s>;tag=%08x", r->username, inet_ntoa(r->addr.sin_addr), p->tag);
1807         
1808         snprintf(addr, sizeof(addr), "sip:%s", inet_ntoa(r->addr.sin_addr));
1809
1810         memset(&req, 0, sizeof(req));
1811         init_req(&req, cmd, addr);
1812
1813         snprintf(tmp, sizeof(tmp), "%d %s", ++p->ocseq, cmd);
1814
1815         snprintf(via, sizeof(via), "SIP/2.0/UDP %s:%d;branch=%08x", inet_ntoa(p->ourip), ourport, p->branch);
1816         add_header(&req, "Via", via);
1817         add_header(&req, "From", from);
1818         add_header(&req, "To", to);
1819         {
1820                 char contact[256];
1821                 snprintf(contact, sizeof(contact), "<sip:s@%s:%d;transport=udp>", inet_ntoa(p->ourip), ourport);
1822                 add_header(&req, "Contact", contact);
1823         }
1824         add_header(&req, "Call-ID", p->callid);
1825         add_header(&req, "CSeq", tmp);
1826         add_header(&req, "User-Agent", "Asterisk PBX");
1827         if (auth) 
1828                 add_header(&req, "Authorization", auth);
1829
1830         snprintf(tmp, sizeof(tmp), "%d", DEFAULT_EXPIREY);
1831         add_header(&req, "Expires", tmp);
1832         add_header(&req, "Event", "registration");
1833         copy_request(&p->initreq, &req);
1834         r->regstate=auth?REG_STATE_AUTHSENT:REG_STATE_REGSENT;
1835         return send_request(p, &req);
1836 }
1837
1838 static int transmit_message_with_text(struct sip_pvt *p, char *text)
1839 {
1840         struct sip_request req;
1841         reqprep(&req, p, "MESSAGE", 1);
1842         add_text(&req, text);
1843         return send_request(p, &req);
1844 }
1845
1846 static int transmit_request(struct sip_pvt *p, char *msg, int inc)
1847 {
1848         struct sip_request resp;
1849         reqprep(&resp, p, msg, inc);
1850         add_header(&resp, "Content-Length", "0");
1851         add_blank_header(&resp);
1852         return send_request(p, &resp);
1853 }
1854
1855 static int expire_register(void *data)
1856 {
1857         struct sip_peer *p = data;
1858         memset(&p->addr, 0, sizeof(p->addr));
1859         p->expire = -1;
1860         return 0;
1861 }
1862
1863 static int sip_poke_peer(struct sip_peer *peer);
1864
1865 static int parse_contact(struct sip_pvt *pvt, struct sip_peer *p, struct sip_request *req)
1866 {
1867         char contact[80]= ""; 
1868         char *expires = get_header(req, "Expires");
1869         int expirey = atoi(expires);
1870         char *c, *n, *pt;
1871         int port;
1872         struct hostent *hp;
1873         struct sockaddr_in oldsin;
1874         if (!strlen(expires)) {
1875                 expires = strstr(get_header(req, "Contact"), "expires=");
1876                 if (expires) 
1877                         if (sscanf(expires + 8, "%d;", &expirey) != 1)
1878                                 expirey = 0;
1879         }
1880         /* Look for brackets */
1881         strncpy(contact, get_header(req, "Contact"), sizeof(contact) - 1);
1882         c = contact;
1883         
1884         if ((n=strchr(c, '<'))) {
1885                 c = n + 1;
1886                 n = strchr(c, '>');
1887                 /* Lose the part after the > */
1888                 if (n) 
1889                         *n = '\0';
1890         }
1891         /* Make sure it's a SIP URL */
1892         if (strncasecmp(c, "sip:", 4)) {
1893                 ast_log(LOG_NOTICE, "'%s' is not a valid SIP contcact\n", c);
1894                 return -1;
1895         }
1896         c += 4;
1897         /* Ditch q */
1898         n = strchr(c, ';');
1899         if (n) 
1900                 *n = '\0';
1901         /* Grab host */
1902         n = strchr(c, '@');
1903         if (!n) {
1904                 n = c;
1905                 c = NULL;
1906         } else {
1907                 *n = '\0';
1908                 n++;
1909         }
1910         pt = strchr(n, ':');
1911         if (pt) {
1912                 *pt = '\0';
1913                 pt++;
1914                 port = atoi(pt);
1915         } else
1916                 port = DEFAULT_SIP_PORT;
1917         /* XXX This could block for a long time XXX */
1918         hp = gethostbyname(n);
1919         if (!hp)  {
1920                 ast_log(LOG_WARNING, "Invalid host '%s'\n", n);
1921                 return -1;
1922         }
1923         memcpy(&oldsin, &p->addr, sizeof(oldsin));
1924         p->addr.sin_family = AF_INET;
1925         memcpy(&p->addr.sin_addr, hp->h_addr, sizeof(p->addr.sin_addr));
1926         p->addr.sin_port = htons(port);
1927         if (c)
1928                 strncpy(p->username, c, sizeof(p->username) - 1);
1929         else
1930                 strcpy(p->username, "");
1931         if (p->expire > -1)
1932                 ast_sched_del(sched, p->expire);
1933         if ((expirey < 1) || (expirey > MAX_EXPIREY))
1934                 expirey = DEFAULT_EXPIREY;
1935         p->expire = ast_sched_add(sched, expirey * 1000, expire_register, p);
1936         pvt->expirey = expirey;
1937         if (memcmp(&p->addr, &oldsin, sizeof(oldsin))) {
1938                 sip_poke_peer(p);
1939                 if (option_verbose > 2)
1940                         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);
1941         }
1942         return 0;
1943 }
1944
1945 static void md5_hash(char *output, char *input)
1946 {
1947                 struct MD5Context md5;
1948                 unsigned char digest[16];
1949                 char *ptr;
1950                 int x;
1951                 MD5Init(&md5);
1952                 MD5Update(&md5, input, strlen(input));
1953                 MD5Final(digest, &md5);
1954                 ptr = output;
1955                 for (x=0;x<16;x++)
1956                         ptr += sprintf(ptr, "%2.2x", digest[x]);
1957 }
1958
1959 static int check_auth(struct sip_pvt *p, struct sip_request *req, char *randdata, int randlen, char *username, char *secret, char *method, char *uri)
1960 {
1961         int res = -1;
1962         /* Always OK if no secret */
1963         if (!strlen(secret))
1964                 return 0;
1965         if (!strlen(randdata)) {
1966                 snprintf(randdata, randlen, "%08x", rand());
1967                 transmit_response_with_auth(p, "407 Proxy Authentication Required", req, randdata);
1968                 res = 1;
1969         } else {
1970                 /* Whoever came up with the authentication section of SIP can suck my %&#$&* for not putting
1971                    an example in the spec of just what it is you're doing a hash on. */
1972                 char a1[256];
1973                 char a2[256];
1974                 char a1_hash[256];
1975                 char a2_hash[256];
1976                 char resp[256];
1977                 char resp_hash[256];
1978                 char tmp[256] = "";
1979                 char *c;
1980                 char *response ="";
1981                 char *resp_uri ="";
1982
1983                 /* Find their response among the mess that we'r sent for comparison */
1984                 strncpy(tmp, get_header(req, "Proxy-Authorization"), sizeof(tmp) - 1);
1985                 c = tmp;
1986
1987                 while(c) {
1988                         while (*c && (*c < 33)) c++;
1989                         if (!*c)
1990                                 break;
1991                         if (!strncasecmp(c, "response=", strlen("response="))) {
1992                                 c+= strlen("response=");
1993                                 if ((*c == '\"')) {
1994                                         response=++c;
1995                                         if((c = strchr(c,'\"')))
1996                                                 *c = '\0';
1997
1998                                 } else {
1999                                         response=c;
2000                                         if((c = strchr(c,',')))
2001                                                 *c = '\0';
2002                                 }
2003
2004                         } else if (!strncasecmp(c, "uri=", strlen("uri="))) {
2005                                 c+= strlen("uri=");
2006                                 if ((*c == '\"')) {
2007                                         resp_uri=++c;
2008                                         if((c = strchr(c,'\"')))
2009                                                 *c = '\0';
2010                                 } else {
2011                                         resp_uri=c;
2012                                         if((c = strchr(c,',')))
2013                                                 *c = '\0';
2014                                 }
2015
2016                         } else
2017                                 c = strchr(c, ',');
2018                         if (c)
2019                                 c++;
2020                 }
2021                 snprintf(a1, sizeof(a1), "%s:%s:%s", username, "asterisk", secret);
2022                 if(strlen(resp_uri))
2023                         snprintf(a2, sizeof(a2), "%s:%s", method, resp_uri);
2024                 else
2025                         snprintf(a2, sizeof(a2), "%s:%s", method, uri);
2026                 md5_hash(a1_hash, a1);
2027                 md5_hash(a2_hash, a2);
2028                 snprintf(resp, sizeof(resp), "%s:%s:%s", a1_hash, randdata, a2_hash);
2029                 md5_hash(resp_hash, resp);
2030
2031                 /* resp_hash now has the expected response, compare the two */
2032
2033                 if (response && !strncasecmp(response, resp_hash, strlen(resp_hash))) {
2034                         /* Auth is OK */
2035                         res = 0;
2036                 }
2037                 /* Assume success ;-) */
2038                 /* Eliminate random data */
2039                 strcpy(randdata, "");
2040         }
2041         return res;
2042 }
2043
2044 static int register_verify(struct sip_pvt *p, struct sockaddr_in *sin, struct sip_request *req, char *uri)
2045 {
2046         int res = -1;
2047         struct sip_peer *peer;
2048         char tmp[256] = "";
2049         char *name, *c;
2050         char *t;
2051         /* Terminate URI */
2052         t = uri;
2053         while(*t && (*t > 32) && (*t != ';'))
2054                 t++;
2055         *t = '\0';
2056         
2057         strncpy(tmp, get_header(req, "To"), sizeof(tmp) - 1);
2058         c = ditch_braces(tmp);
2059         if (strncmp(c, "sip:", 4)) {
2060                 ast_log(LOG_NOTICE, "Invalid to address: '%s' from %s\n", tmp, inet_ntoa(sin->sin_addr));
2061                 return -1;
2062         }
2063         name = c + 4;
2064         c = strchr(name, '@');
2065         if (c) 
2066                 *c = '\0';
2067         ast_pthread_mutex_lock(&peerl.lock);
2068         peer = peerl.peers;
2069         while(peer) {
2070                 if (!strcasecmp(peer->name, name) && peer->dynamic) {
2071                         if (!(res = check_auth(p, req, p->randdata, sizeof(p->randdata), peer->name, peer->secret, "REGISTER", uri))) {
2072                                 if (parse_contact(p, peer, req)) {
2073                                         ast_log(LOG_WARNING, "Failed to parse contact info\n");
2074                                 } else {
2075                                         /* Say OK and ask subsystem to retransmit msg counter */
2076                                         transmit_response(p, "200 OK", req);
2077                                         peer->lastmsgssent = -1;
2078                                         res = 0;
2079                                 }
2080                         } 
2081                         break;
2082                 }       
2083                 peer = peer->next;
2084         }
2085         ast_pthread_mutex_unlock(&peerl.lock);
2086         if (res < 0)
2087                 transmit_response(p, "401 Unauthorized", &p->initreq);
2088         return res;
2089 }
2090
2091 static int get_destination(struct sip_pvt *p, struct sip_request *oreq)
2092 {
2093         char tmp[256] = "", *c, *a;
2094         struct sip_request *req;
2095         
2096         req = oreq;
2097         if (!req)
2098                 req = &p->initreq;
2099         strncpy(tmp, req->rlPart2, sizeof(tmp) - 1);
2100         c = ditch_braces(tmp);
2101         if (strncmp(c, "sip:", 4)) {
2102                 ast_log(LOG_WARNING, "Huh?  Not a SIP header (%s)?\n", c);
2103                 return -1;
2104         }
2105         c += 4;
2106         if ((a = strchr(c, '@')) || (a = strchr(c, ';'))) {
2107                 *a = '\0';
2108         }
2109         if (sipdebug)
2110                 ast_verbose("Looking for %s in %s\n", c, p->context);
2111         if (ast_exists_extension(NULL, p->context, c, 1, NULL)) {
2112                 if (!oreq)
2113                         strncpy(p->exten, c, sizeof(p->exten) - 1);
2114                 return 0;
2115         }
2116
2117         if (ast_canmatch_extension(NULL, p->context, c, 1, NULL)) {
2118                 return 1;
2119         }
2120         
2121         return -1;
2122 }
2123
2124 static int get_refer_info(struct sip_pvt *p, struct sip_request *oreq)
2125 {
2126         char tmp[256] = "", *c, *a;
2127         char tmp2[256] = "", *c2, *a2;
2128         char tmp3[256];
2129         char tmp4[256];
2130         struct sip_request *req;
2131         
2132         req = oreq;
2133         if (!req)
2134                 req = &p->initreq;
2135         strncpy(tmp, get_header(req, "Refer-To"), sizeof(tmp) - 1);
2136         strncpy(tmp2, get_header(req, "Referred-By"), sizeof(tmp2) - 1);
2137         strncpy(tmp3, get_header(req, "Contact"), sizeof(tmp3) - 1);
2138         strncpy(tmp4, get_header(req, "Remote-Party-ID"), sizeof(tmp4) - 1);
2139         
2140         c = ditch_braces(tmp);
2141         c2 = ditch_braces(tmp2);
2142         
2143                 
2144         if (strncmp(c, "sip:", 4) && strncmp(c2, "sip:", 4)) {
2145                 ast_log(LOG_WARNING, "Huh?  Not a SIP header (%s)?\n", c);
2146                 ast_log(LOG_WARNING, "Huh?  Not a SIP header (%s)?\n", c2);
2147                 return -1;
2148         }
2149         c += 4;
2150         c2 += 4;
2151         if ((a = strchr(c, '@')) || (a = strchr(c, ';'))) {
2152                 *a = '\0';
2153         }
2154         if ((a2 = strchr(c2, '@')) || (a2 = strchr(c2, ';'))) { 
2155                 *a2 = '\0';
2156         }
2157         
2158         if (sipdebug)
2159                 ast_verbose("Looking for %s in %s\n", c, p->context);
2160                 ast_verbose("Looking for %s in %s\n", c2, p->context);
2161         
2162         if (ast_exists_extension(NULL, p->context, c, 1, NULL) && ast_exists_extension(NULL, p->context, c2, 1, NULL)) {
2163                 if (!oreq)
2164                         ast_log(LOG_DEBUG,"Something is wrong with this line.\n");      //This line is ignored for some reason....
2165                         ast_log(LOG_DEBUG,"Assigning Extension %s to REFER-TO\n", c);
2166                         ast_log(LOG_DEBUG,"Assigning Extension %s to REFERRED-BY\n", c2);
2167                         ast_log(LOG_DEBUG,"Assigning Contact Info %s to REFER_CONTACT\n", tmp3);
2168                         ast_log(LOG_DEBUG,"Assigning Remote-Party-ID Info %s to REMOTE_PARTY_ID\n",tmp4);
2169                         strncpy(p->refer_to, c, sizeof(p->refer_to) - 1);
2170                         strncpy(p->referred_by, c2, sizeof(p->referred_by) - 1);
2171                         strncpy(p->refer_contact, tmp3, sizeof(p->refer_contact) - 1);
2172                         strncpy(p->remote_party_id, tmp4, sizeof(p->remote_party_id) - 1);
2173                         return 0;
2174         }
2175
2176         if (ast_canmatch_extension(NULL, p->context, c, 1, NULL)) {
2177                 return 1;
2178         }
2179
2180         return -1;
2181 }
2182
2183
2184 static int check_via(struct sip_pvt *p, struct sip_request *req)
2185 {
2186         char via[256] = "";
2187         char *c, *pt;
2188         struct hostent *hp;
2189
2190         memset(via, 0, sizeof(via));
2191         strncpy(via, get_header(req, "Via"), sizeof(via) - 1);
2192         c = strchr(via, ';');
2193         if (c) 
2194                 *c = '\0';
2195         c = strchr(via, ' ');
2196         if (c) {
2197                 *c = '\0';
2198                 c++;
2199                 while(*c && (*c < 33))
2200                         c++;
2201                 if (strcmp(via, "SIP/2.0/UDP")) {
2202                         ast_log(LOG_WARNING, "Don't know how to respond via '%s'\n", via);
2203                         return -1;
2204                 }
2205                 pt = strchr(c, ':');
2206                 if (pt) {
2207                         *pt = '\0';
2208                         pt++;
2209                 }
2210                 hp = gethostbyname(c);
2211                 if (!hp) {
2212                         ast_log(LOG_WARNING, "'%s' is not a valid host\n", c);
2213                         return -1;
2214                 }
2215                 memset(&p->sa, 0, sizeof(p->sa));
2216                 p->sa.sin_family = AF_INET;
2217                 p->sa.sin_port = htons(pt ? atoi(pt) : DEFAULT_SIP_PORT);
2218                 memcpy(&p->sa.sin_addr, hp->h_addr, sizeof(p->sa.sin_addr));
2219                 if (sipdebug)
2220                         ast_verbose("Sending to %s : %d\n", inet_ntoa(p->sa.sin_addr), ntohs(p->sa.sin_port));
2221         }
2222         return 0;
2223 }
2224
2225 static int check_user(struct sip_pvt *p, struct sip_request *req, char *cmd, char *uri)
2226 {
2227         struct sip_user *user;
2228         char *of, from[256] = "", *c;
2229         int res = 0;
2230         char *t;
2231         /* Terminate URI */
2232         t = uri;
2233         while(*t && (*t > 32) && (*t != ';'))
2234                 t++;
2235         *t = '\0';
2236         of = get_header(req, "From");
2237         strncpy(from, of, sizeof(from) - 1);
2238         of = ditch_braces(from);
2239         if (strncmp(of, "sip:", 4))
2240                 return 0;
2241         else
2242                 of += 4;
2243         /* Get just the username part */
2244         if ((c = strchr(of, '@')))
2245                 *c = '\0';
2246         if ((c = strchr(of, ':')))
2247                 *c = '\0';
2248         strncpy(p->callerid, of, sizeof(p->callerid) - 1);
2249         if (!strlen(of))
2250                         return 0;
2251         ast_pthread_mutex_lock(&userl.lock);
2252         user = userl.users;
2253         while(user) {
2254                 if (!strcasecmp(user->name, of)) {
2255                         if (!(res = check_auth(p, req, p->randdata, sizeof(p->randdata), user->name, user->secret, cmd, uri))) {
2256                                 strncpy(p->context, user->context, sizeof(p->context) - 1);
2257                                 if (strlen(user->callerid) && strlen(p->callerid)) 
2258                                         strncpy(p->callerid, user->callerid, sizeof(p->callerid) - 1);
2259                                 strncpy(p->accountcode, user->accountcode, sizeof(p->accountcode)  -1);
2260                                 p->canreinvite = user->canreinvite;
2261                                 p->amaflags = user->amaflags;
2262                         }
2263                         break;
2264                 }
2265                 user = user->next;
2266         }
2267         ast_pthread_mutex_unlock(&userl.lock);
2268         return res;
2269 }
2270
2271 static int get_msg_text(char *buf, int len, struct sip_request *req)
2272 {
2273         int x;
2274         strcpy(buf, "");
2275         for (x=0;x<req->lines;x++) {
2276                 strncat(buf, req->line[x], len - strlen(buf) - 5);
2277                 strcat(buf, "\n");
2278         }
2279         return 0;
2280 }
2281
2282 static void receive_message(struct sip_pvt *p, struct sip_request *req)
2283 {
2284         char buf[1024];
2285         struct ast_frame f;
2286         if (get_msg_text(buf, sizeof(buf), req)) {
2287                 ast_log(LOG_WARNING, "Unable to retrieve text from %s\n", p->callid);
2288                 return;
2289         }
2290         if (p->owner) {
2291                 if (sipdebug)
2292                         ast_verbose("Message received: '%s'\n", buf);
2293                 memset(&f, 0, sizeof(f));
2294                 f.frametype = AST_FRAME_TEXT;
2295                 f.subclass = 0;
2296                 f.offset = 0;
2297                 f.data = buf;
2298                 f.datalen = strlen(buf);
2299                 ast_queue_frame(p->owner, &f, 1);
2300         }
2301 }
2302
2303 static int sip_show_users(int fd, int argc, char *argv[])
2304 {
2305 #define FORMAT "%-15.15s  %-15.15s  %-15.15s  %-15.15s  %-5.5s\n"
2306         struct sip_user *user;
2307         if (argc != 3) 
2308                 return RESULT_SHOWUSAGE;
2309         ast_pthread_mutex_lock(&userl.lock);
2310         ast_cli(fd, FORMAT, "Username", "Secret", "Authen", "Def.Context", "A/C");
2311         for(user=userl.users;user;user=user->next) {
2312                 ast_cli(fd, FORMAT, user->name, user->secret, user->methods, 
2313                                 user->context,
2314                                 user->ha ? "Yes" : "No");
2315         }
2316         ast_pthread_mutex_unlock(&userl.lock);
2317         return RESULT_SUCCESS;
2318 #undef FORMAT
2319 }
2320
2321 static int sip_show_peers(int fd, int argc, char *argv[])
2322 {
2323 #define FORMAT2 "%-15.15s  %-15.15s %s  %-15.15s  %-8s %-10s\n"
2324 #define FORMAT "%-15.15s  %-15.15s %s  %-15.15s  %-8d %-10s\n"
2325         struct sip_peer *peer;
2326         char name[256] = "";
2327         if (argc != 3)
2328                 return RESULT_SHOWUSAGE;
2329         ast_pthread_mutex_lock(&peerl.lock);
2330         ast_cli(fd, FORMAT2, "Name/username", "Host", "   ", "Mask", "Port", "Status");
2331         for (peer = peerl.peers;peer;peer = peer->next) {
2332                 char nm[20] = "";
2333                 char status[20];
2334                 strncpy(nm, inet_ntoa(peer->mask), sizeof(nm)-1);
2335                 if (strlen(peer->username))
2336                         snprintf(name, sizeof(name), "%s/%s", peer->name, peer->username);
2337                 else
2338                         strncpy(name, peer->name, sizeof(name) - 1);
2339                 if (peer->maxms) {
2340                         if (peer->lastms < 0)
2341                                 strcpy(status, "UNREACHABLE");
2342                         else if (peer->lastms > peer->maxms) 
2343                                 snprintf(status, sizeof(status), "LAGGED (%d ms)", peer->lastms);
2344                         else if (peer->lastms) 
2345                                 snprintf(status, sizeof(status), "OK (%d ms)", peer->lastms);
2346                         else 
2347                                 strcpy(status, "UNKNOWN");
2348                 } else 
2349                         strcpy(status, "Unmonitored");
2350                 ast_cli(fd, FORMAT, name, 
2351                                         peer->addr.sin_addr.s_addr ? inet_ntoa(peer->addr.sin_addr) : "(Unspecified)",
2352                                         peer->dynamic ? "(D)" : "   ",
2353                                         nm,
2354                                         ntohs(peer->addr.sin_port), status);
2355         }
2356         ast_pthread_mutex_unlock(&peerl.lock);
2357         return RESULT_SUCCESS;
2358 #undef FORMAT
2359 #undef FORMAT2
2360 }
2361
2362 static char *regstate2str(int regstate)
2363 {
2364         switch(regstate) {
2365         case REG_STATE_UNREGISTERED:
2366                 return "Unregistered";
2367         case REG_STATE_REGSENT:
2368                 return "Request Sent";
2369         case REG_STATE_AUTHSENT:
2370                 return "Auth. Sent";
2371         case REG_STATE_REGISTERED:
2372                 return "Registered";
2373         case REG_STATE_REJECTED:
2374                 return "Rejected";
2375         case REG_STATE_TIMEOUT:
2376                 return "Timeout";
2377         case REG_STATE_NOAUTH:
2378                 return "No Authentication";
2379         default:
2380                 return "Unknown";
2381         }
2382 }
2383
2384 static int sip_show_registry(int fd, int argc, char *argv[])
2385 {
2386 #define FORMAT2 "%-20.20s  %-10.10s  %-20.20s %8.8s  %s\n"
2387 #define FORMAT "%-20.20s  %-10.10s  %-20.20s %8d  %s\n"
2388         struct sip_registry *reg;
2389         char host[80];
2390         char state[20];
2391         if (argc != 3)
2392                 return RESULT_SHOWUSAGE;
2393         ast_pthread_mutex_lock(&peerl.lock);
2394         ast_cli(fd, FORMAT2, "Host", "Username", "Refresh", "State");
2395         for (reg = registrations;reg;reg = reg->next) {
2396                 snprintf(host, sizeof(host), "%s:%d", inet_ntoa(reg->addr.sin_addr), ntohs(reg->addr.sin_port));
2397                 snprintf(state, sizeof(state), "%s", regstate2str(reg->regstate));
2398                 ast_cli(fd, FORMAT, host, 
2399                                         reg->username, state, reg->refresh, regstate2str(reg->regstate));
2400         }
2401         ast_pthread_mutex_unlock(&peerl.lock);
2402         return RESULT_SUCCESS;
2403 #undef FORMAT
2404 #undef FORMAT2
2405 }
2406
2407 static int sip_show_channels(int fd, int argc, char *argv[])
2408 {
2409 #define FORMAT2 "%-15.15s  %-10.10s  %-11.11s  %-11.11s  %-7.7s  %-6.6s  %s\n"
2410 #define FORMAT  "%-15.15s  %-10.10s  %-11.11s  %5.5d/%5.5d  %-5.5dms  %-4.4dms  %d\n"
2411         struct sip_pvt *cur;
2412         if (argc != 3)
2413                 return RESULT_SHOWUSAGE;
2414         ast_pthread_mutex_lock(&iflock);
2415         cur = iflist;
2416         ast_cli(fd, FORMAT2, "Peer", "Username", "Call ID", "Seq (Tx/Rx)", "Lag", "Jitter", "Format");
2417         while (cur) {
2418                         ast_cli(fd, FORMAT, inet_ntoa(cur->sa.sin_addr), 
2419                                                 strlen(cur->username) ? cur->username : "(None)", 
2420                                                 cur->callid, 
2421                                                 cur->ocseq, cur->icseq, 
2422                                                 0,
2423                                                 0,
2424                                                 cur->owner ? cur->owner->nativeformats : 0);
2425                 cur = cur->next;
2426         }
2427         ast_pthread_mutex_unlock(&iflock);
2428         return RESULT_SUCCESS;
2429 #undef FORMAT
2430 #undef FORMAT2
2431 }
2432
2433 static void receive_info(struct sip_pvt *p, struct sip_request *req)
2434 {
2435         char buf[1024] = "";
2436         struct ast_frame f;
2437         char *c;
2438         /* Try getting the "signal=" part */
2439         if ((c = get_sdp(req, "Signal"))) {
2440                 strncpy(buf, c, sizeof(buf) - 1);
2441         } else if (get_msg_text(buf, sizeof(buf), req)) {
2442                 /* Normal INFO method */
2443                 ast_log(LOG_WARNING, "Unable to retrieve text from %s\n", p->callid);
2444                 return;
2445         }
2446         
2447         if (p->owner) {
2448                 if (strlen(buf)) {
2449                         if (sipdebug)
2450                                 ast_verbose("DTMF received: '%c'\n", buf[0]);
2451                         memset(&f, 0, sizeof(f));
2452                         f.frametype = AST_FRAME_DTMF;
2453                         f.subclass = buf[0];
2454                         f.offset = 0;
2455                         f.data = NULL;
2456                         f.datalen = 0;
2457                         ast_queue_frame(p->owner, &f, 1);
2458                 }
2459         }
2460 }
2461
2462 static int sip_do_debug(int fd, int argc, char *argv[])
2463 {
2464         if (argc != 2)
2465                 return RESULT_SHOWUSAGE;
2466         sipdebug = 1;
2467         ast_cli(fd, "SIP Debugging Enabled\n");
2468         return RESULT_SUCCESS;
2469 }
2470
2471 static int sip_no_debug(int fd, int argc, char *argv[])
2472 {
2473         if (argc != 3)
2474                 return RESULT_SHOWUSAGE;
2475         sipdebug = 0;
2476         ast_cli(fd, "SIP Debugging Disabled\n");
2477         return RESULT_SUCCESS;
2478 }
2479
2480 static int reply_digest(struct sip_pvt *p, struct sip_request *req, char *header, char *orig_header, char *digest, int digest_len);
2481
2482 static int do_register_auth(struct sip_pvt *p, struct sip_request *req) {
2483         char digest[256];
2484         memset(digest,0,sizeof(digest));
2485         reply_digest(p,req, "WWW-Authenticate", "REGISTER", (char *)&digest, sizeof(digest) );
2486         return transmit_register(p->registry,"REGISTER",(char *)&digest); 
2487 }
2488
2489 static int do_proxy_auth(struct sip_pvt *p, struct sip_request *req) {
2490         char digest[256];
2491         memset(digest,0,sizeof(digest));
2492         reply_digest(p,req, "Proxy-Authenticate", "INVITE", (char *)&digest, sizeof(digest) );
2493         return transmit_invite(p,"INVITE",1,(char *)&digest, NULL); 
2494 }
2495
2496 static int reply_digest(struct sip_pvt *p, struct sip_request *req, char *header, char *orig_header, char *digest, int digest_len) {
2497
2498         char tmp[256] = "";
2499         char *realm = "";
2500         char *nonce = "";
2501         char *c;
2502         char a1[256];
2503         char a2[256];
2504         char a1_hash[256];
2505         char a2_hash[256];
2506         char resp[256];
2507         char resp_hash[256];
2508         char uri[256] = "";
2509
2510
2511         strncpy(tmp, get_header(req, header),sizeof(tmp) - 1);
2512         c = tmp;
2513         c+=strlen("DIGEST ");
2514         while (c) {
2515                 while (*c && (*c < 33)) c++;
2516                 if (!*c)
2517                         break;
2518                         if (!strncasecmp(c,"realm=", strlen("realm="))) {
2519                                 c+=strlen("realm=");
2520                                 if ((*c == '\"')) {
2521                                         realm=++c;
2522                                         if ((c = strchr(c,'\"')))
2523                                                 *c = '\0';
2524                                 } else {
2525                                         realm = c;
2526                                         if ((c = strchr(c,',')))
2527                                                 *c = '\0';
2528                                 }
2529
2530                         } else if (!strncasecmp(c, "nonce=", strlen("nonce="))) {
2531                                 c+=strlen("nonce=");
2532                                 if ((*c == '\"')) {
2533                                         nonce=++c;
2534                                         if ((c = strchr(c,'\"')))
2535                                                 *c = '\0';
2536                                 } else {
2537                                         nonce = c;
2538                                         if ((c = strchr(c,',')))
2539                                                 *c = '\0';
2540                                 }
2541                         } else
2542                                 c = strchr(c,',');
2543                         if (c)
2544                                 c++;
2545                         }
2546
2547         /* Okay.  We've got the realm and nonce from the server.  Now lets build the MD5 digest. */
2548         snprintf(uri, sizeof(uri), "sip:%s@%s",p->username, inet_ntoa(p->sa.sin_addr));
2549
2550         snprintf(a1,sizeof(a1),"%s:%s:%s",p->peername,realm,p->peersecret);
2551         snprintf(a2,sizeof(a2),"%s:%s",orig_header,uri);
2552         md5_hash(a1_hash,a1);
2553         md5_hash(a2_hash,a2);
2554         snprintf(resp,sizeof(resp),"%s:%s:%s",a1_hash,nonce,a2_hash);
2555         md5_hash(resp_hash,resp);
2556
2557         snprintf(digest,digest_len,"DIGEST username=\"%s\", realm=\"%s\", algorithm=\"MD5\", uri=\"%s\", nonce=\"%s\", response=\"%s\"",p->peername,realm,uri,nonce,resp_hash);
2558
2559         return 0;
2560 }
2561         
2562
2563         
2564         
2565
2566
2567 static char show_users_usage[] = 
2568 "Usage: sip show users\n"
2569 "       Lists all users known to the SIP (Session Initiation Protocol) subsystem.\n";
2570
2571 static char show_channels_usage[] = 
2572 "Usage: sip show channels\n"
2573 "       Lists all currently active SIP channels.\n";
2574
2575 static char show_peers_usage[] = 
2576 "Usage: sip show peers\n"
2577 "       Lists all known SIP peers.\n";
2578
2579 static char show_reg_usage[] =
2580 "Usage: sip show registry\n"
2581 "       Lists all registration requests and status.\n";
2582
2583 static char debug_usage[] = 
2584 "Usage: sip debug\n"
2585 "       Enables dumping of SIP packets for debugging purposes\n";
2586
2587 static char no_debug_usage[] = 
2588 "Usage: sip no debug\n"
2589 "       Disables dumping of SIP packets for debugging purposes\n";
2590
2591 static struct ast_cli_entry  cli_show_users = 
2592         { { "sip", "show", "users", NULL }, sip_show_users, "Show defined SIP users", show_users_usage };
2593 static struct ast_cli_entry  cli_show_channels =
2594         { { "sip", "show", "channels", NULL }, sip_show_channels, "Show active SIP channels", show_channels_usage };
2595 static struct ast_cli_entry  cli_show_peers =
2596         { { "sip", "show", "peers", NULL }, sip_show_peers, "Show defined SIP peers", show_peers_usage };
2597 static struct ast_cli_entry  cli_show_registry =
2598         { { "sip", "show", "registry", NULL }, sip_show_registry, "Show SIP registration status", show_reg_usage };
2599 static struct ast_cli_entry  cli_debug =
2600         { { "sip", "debug", NULL }, sip_do_debug, "Enable SIP debugging", debug_usage };
2601 static struct ast_cli_entry  cli_no_debug =
2602         { { "sip", "no", "debug", NULL }, sip_no_debug, "Disable SIP debugging", no_debug_usage };
2603
2604
2605 static int sip_poke_peer_s(void *data)
2606 {
2607         struct sip_peer *peer = data;
2608         peer->pokeexpire = -1;
2609         sip_poke_peer(peer);
2610         return 0;
2611 }
2612
2613 static void handle_response(struct sip_pvt *p, int resp, char *rest, struct sip_request *req)
2614 {
2615         char *to;
2616         char *msg, *c;
2617         struct ast_rtp *rtp;
2618         struct ast_channel *owner;
2619         struct sip_peer *peer;
2620         int pingtime;
2621         struct timeval tv;
2622         c = get_header(req, "Cseq");
2623         msg = strchr(c, ' ');
2624         if (!msg) msg = ""; else msg++;
2625 retrylock:
2626         ast_pthread_mutex_lock(&p->lock);
2627         /* Go ahead and lock the owner if it has one -- we may need it */
2628         if (p->owner && pthread_mutex_trylock(&p->owner->lock)) {
2629                 ast_log(LOG_DEBUG, "Failed to grab lock, trying again...\n");
2630                 ast_pthread_mutex_unlock(&p->lock);
2631                 /* Sleep infintismly short amount of time */
2632                 usleep(1);
2633                 goto retrylock;
2634         }
2635         owner = p->owner;
2636         if (p->peerpoke) {
2637                 /* We don't really care what the response is, just that it replied back. 
2638                    Well, as long as it's not a 100 response...  since we might
2639                    need to hang around for something more "difinitive" */
2640                 if (resp != 100) {
2641                         peer = p->peerpoke;
2642                         gettimeofday(&tv, NULL);
2643                         pingtime = (tv.tv_sec - peer->ps.tv_sec) * 1000 +
2644                                                 (tv.tv_usec - peer->ps.tv_usec) / 1000;
2645                         if (pingtime < 1)
2646                                 pingtime = 1;
2647                         if ((peer->lastms < 0)  || (peer->lastms > peer->maxms)) {
2648                                 if (pingtime <= peer->maxms)
2649                                 ast_log(LOG_NOTICE, "Peer '%s' is now REACHABLE!\n", peer->name);
2650                         } else if ((peer->lastms > 0) && (peer->lastms <= peer->maxms)) {
2651                                 if (pingtime > peer->maxms)
2652                                         ast_log(LOG_NOTICE, "Peer '%s' is now TOO LAGGED!\n", peer->name);
2653                         }
2654                         peer->lastms = pingtime;
2655                         peer->call = NULL;
2656                         if (peer->pokeexpire > -1)
2657                                 ast_sched_del(sched, peer->pokeexpire);
2658                         if (!strcasecmp(msg, "INVITE"))
2659                                 transmit_request(p, "ACK", 0);
2660                         sip_destroy(p);
2661                         p = NULL;
2662                         /* Try again eventually */
2663                         if ((peer->lastms < 0)  || (peer->lastms > peer->maxms))
2664                                 peer->pokeexpire = ast_sched_add(sched, DEFAULT_FREQ_NOTOK, sip_poke_peer_s, peer);
2665                         else
2666                                 peer->pokeexpire = ast_sched_add(sched, DEFAULT_FREQ_OK, sip_poke_peer_s, peer);
2667                 }
2668         } else if (p->outgoing) {
2669                 if (p->initid > -1) {
2670                         /* Don't auto congest anymore since we've gotten something useful back */
2671                         ast_sched_del(sched, p->initid);
2672                         p->initid = -1;
2673                 }
2674                 /* Get their tag if we haven't already */
2675                 if (!strlen(p->theirtag)) {
2676                         to = get_header(req, "To");
2677                         to = strstr(to, "tag=");
2678                         if (to) {
2679                                 to += 4;
2680                                 strncpy(p->theirtag, to, sizeof(p->theirtag) - 1);
2681                                 to = strchr(p->theirtag, ';');
2682                                 if (to)
2683                                         *to = '\0';
2684                         }
2685                 }
2686                 
2687                 switch(resp) {
2688                 case 100:
2689                         break;
2690                 case 183:       /* We don't really need this since we pass in-band audio anyway */
2691                         /* Not important */
2692                         if (strlen(get_header(req, "Content-Type")))
2693                                 process_sdp(p, req);
2694                         break;
2695                 case 180:
2696                         if (p->owner) {
2697                                 ast_queue_control(p->owner, AST_CONTROL_RINGING, 0);
2698                                 if (p->owner->_state != AST_STATE_UP)
2699                                         ast_setstate(p->owner, AST_STATE_RINGING);
2700                         }
2701                         break;
2702                 case 200:
2703                         if (strlen(get_header(req, "Content-Type")))
2704                                 process_sdp(p, req);
2705                         if (p->owner) {
2706                                 if (p->owner->_state != AST_STATE_UP) {
2707                                         ast_setstate(p->owner, AST_STATE_UP);
2708                                         ast_queue_control(p->owner, AST_CONTROL_ANSWER, 0);
2709                                 }
2710                         }
2711                         if (!strcasecmp(msg, "INVITE"))
2712                                 transmit_request(p, "ACK", 0);
2713                         else if (!strcasecmp(msg, "REGISTER"))
2714                         {
2715                                 /* char *exp; */
2716                                 int expires;
2717                                 struct sip_registry *r;
2718                                 transmit_request(p, "ACK", 0);
2719                                 r=p->registry;
2720                                 r->regstate=REG_STATE_REGISTERED;
2721                                 ast_log(LOG_NOTICE, "Registration successful\n");
2722                                 ast_log(LOG_NOTICE, "Cancelling timeout %d\n", r->timeout);
2723                                 if (r->timeout) 
2724                                         ast_sched_del(sched, r->timeout);
2725                                 r->timeout=0;
2726                                 /* set us up for re-registering */
2727                                 /* figure out how long we got registered for */
2728                                 if (r->expire != -1)
2729                                         ast_sched_del(sched, r->expire);
2730                                 expires=atoi(get_header(req, "expires"));
2731                                 if (!expires) expires=DEFAULT_EXPIREY;
2732                                         r->expire=ast_sched_add(sched, (expires-2)*1000, sip_reregister, r); 
2733
2734                         }
2735                         break;
2736                 case 401: /* Not authorized on REGISTER */
2737                         /* XXX: Do I need to ACK the 401? 
2738                         transmit_request(p, "ACK", 0);
2739                         */
2740                         do_register_auth(p, req);
2741                         break;
2742                 case 407:
2743                         /* First we ACK */
2744                         transmit_request(p, "ACK", 0);
2745                         /* Then we AUTH */
2746                         do_proxy_auth(p, req);
2747                         /* This is just a hack to kill the channel while testing */
2748                         /* 
2749                         p->alreadygone = 1;
2750                         if (p->rtp) {
2751                                 rtp = p->rtp;
2752                                 p->rtp = NULL;
2753                                 ast_rtp_destroy(rtp);
2754                         }
2755                         if (p->owner)
2756                                 ast_queue_hangup(p->owner,0);
2757                         transmit_request(p,"ACK",0);
2758                         sip_destroy(p);
2759                         p = NULL;
2760                         */
2761                         break;
2762                 default:
2763                         if ((resp >= 400) && (resp < 700)) {
2764                                 if (option_verbose > 2) 
2765                                         ast_verbose(VERBOSE_PREFIX_3 "Got SIP response %d \"%s\" back from %s\n", resp, rest, inet_ntoa(p->sa.sin_addr));
2766                                 p->alreadygone = 1;
2767                                 if (p->rtp) {
2768                                         rtp = p->rtp;
2769                                         p->rtp = NULL;
2770                                         /* Immediately stop RTP */
2771                                         ast_rtp_destroy(rtp);
2772                                 }
2773                                 /* XXX Locking issues?? XXX */
2774                                 switch(resp) {
2775                                 case 486: /* Busy here */
2776                                 case 600: /* Busy everywhere */
2777                                         if (p->owner)
2778                                                 ast_queue_control(p->owner, AST_CONTROL_BUSY, 0);
2779                                         break;
2780                                 case 480: /* Temporarily Unavailable */
2781                                 case 404: /* Not Found */
2782                                 case 410: /* Gone */
2783                                 case 500: /* Server error */
2784                                 case 501: /* Not Implemented */
2785                                         if (owner)
2786                                                 ast_queue_control(p->owner, AST_CONTROL_CONGESTION, 0);
2787                                         break;
2788                                 default:
2789                                         /* Send hangup */       
2790                                         if (owner)
2791                                                 ast_queue_hangup(p->owner, 0);
2792                                         break;
2793                                 }
2794                                 transmit_request(p, "ACK", 0);
2795                                 __sip_destroy(p, 0);
2796                                 p = NULL;
2797                         } else
2798                                 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));
2799                 }
2800         } else {
2801                 if (sipdebug)
2802                         ast_verbose("Message is %s\n", msg);
2803                 switch(resp) {
2804                 case 200:
2805                         if (!strcasecmp(msg, "INVITE") || !strcasecmp(msg, "REGISTER") )
2806                                 transmit_request(p, "ACK", 0);
2807                         break;
2808                 }
2809         }
2810         if (owner)
2811                 ast_pthread_mutex_unlock(&owner->lock);
2812         if (p)
2813                 ast_pthread_mutex_unlock(&p->lock);
2814 }
2815
2816 static int determine_firstline_parts( struct sip_request *req ) {
2817
2818   char *e, *cmd;
2819   int len;
2820   
2821   cmd= req->header[0];
2822   while(*cmd && (*cmd < 33)) {
2823     cmd++;
2824   }
2825   if (!*cmd) {
2826     return -1;
2827   }
2828   e= cmd;
2829   while(*e && (*e > 32)) {
2830     e++;
2831   }
2832   /* Get the command */
2833   if (*e) {
2834     *e = '\0';
2835     e++;
2836   }
2837   req->rlPart1= cmd;
2838   while( *e && ( *e < 33 ) ) {
2839     e++; 
2840   }
2841   if( !*e ) {
2842     return -1;
2843   }
2844     
2845   if ( !strcasecmp(cmd, "SIP/2.0") ) {
2846     /* We have a response */
2847     req->rlPart2= e;
2848     len= strlen( req->rlPart2 );
2849     if( len < 2 ) { return -1; }
2850     e+= len - 1;
2851     while( *e && *e<33 ) {
2852       e--; 
2853     }
2854     *(++e)= '\0';
2855   } else {
2856     /* We have a request */
2857     if( *e == '<' ) { 
2858       e++;
2859       if( !*e ) { return -1; }  
2860     }
2861     req->rlPart2= e;
2862     if( ( e= strrchr( req->rlPart2, 'S' ) ) == NULL ) {
2863       return -1;
2864     }
2865     while( isspace( *(--e) ) ) {}
2866     if( *e == '>' ) {
2867       *e= '\0';
2868     } else {
2869       *(++e)= '\0';
2870     }
2871   }
2872   return 1;
2873 }
2874
2875 static int handle_request(struct sip_pvt *p, struct sip_request *req, struct sockaddr_in *sin)
2876 {
2877         struct sip_request resp;
2878         char *cmd;
2879         char *cseq;
2880         char *e;
2881         struct ast_channel *c=NULL;
2882         int seqno;
2883         int len;
2884         int ignore=0;
2885         int respid;
2886         int res;
2887         /* Clear out potential response */
2888         memset(&resp, 0, sizeof(resp));
2889         /* Get Method and Cseq */
2890         cseq = get_header(req, "Cseq");
2891         cmd = req->header[0];
2892         /* Must have Cseq */
2893         if (!strlen(cmd) || !strlen(cseq))
2894                         return -1;
2895         if (sscanf(cseq, "%i%n", &seqno, &len) != 1) {
2896                 ast_log(LOG_DEBUG, "No seqno in '%s'\n", cmd);
2897                 return -1;
2898         }
2899         /* Get the command */
2900         cseq += len;
2901
2902   /* Determine the request URI for sip, sips or tel URIs */
2903         if( determine_firstline_parts( req ) < 0 ) {
2904           return -1; 
2905         }
2906         cmd= req->rlPart1;
2907         e= req->rlPart2;
2908         
2909         if (strcasecmp(cmd, "SIP/2.0")) {
2910                 /* Request coming in */                 
2911                 if (p->icseq && (p->icseq < seqno)) {
2912                         ast_log(LOG_DEBUG, "Ignoring out of order packet %d (expecting %d)\n", seqno, p->icseq);
2913                         return -1;
2914                 } else if (p->icseq && (p->icseq != seqno)) {
2915                         /* ignore means "don't do anything with it" but still have to 
2916                            respond appropriately  */
2917                         ignore=1;
2918                 }
2919         } else {
2920                 /* Response to our request -- Do some sanity checks */  
2921                 if (!p->initreq.headers) {
2922                         ast_log(LOG_DEBUG, "That's odd...  Got a response on a call we dont know about.\n");
2923                         sip_destroy(p);
2924                         return 0;
2925                 } else if (p->ocseq && (p->ocseq < seqno)) {
2926                         ast_log(LOG_DEBUG, "Ignoring out of order response %d (expecting %d)\n", seqno, p->ocseq);
2927                         return -1;
2928                 } else if (p->ocseq && (p->ocseq != seqno)) {
2929                         /* ignore means "don't do anything with it" but still have to 
2930                            respond appropriately  */
2931                         ignore=1;
2932                 }
2933         }
2934         
2935         if (strcmp(cmd, "SIP/2.0"))
2936                 /* Next should follow monotonically increasing */
2937                 p->icseq = seqno + 1;
2938
2939         /* Initialize the context if it hasn't been already */
2940         if (!strcasecmp(cmd, "OPTIONS")) {
2941                 if (!strlen(p->context))
2942                         strncpy(p->context, context, sizeof(p->context) - 1);
2943                 res = get_destination(p, req);
2944                 if (res < 0)
2945                         transmit_response_with_allow(p, "404 Not Found", req);
2946                 else if (res > 0)
2947                         transmit_response_with_allow(p, "484 Address Incomplete", req);
2948                 else 
2949                         transmit_response_with_allow(p, "200 OK", req);
2950         } else if (!strcasecmp(cmd, "INVITE")) {
2951                 /* Process the SDP portion */
2952                 if (!ignore) {
2953                         /* Use this as the basis */
2954                         if (sipdebug)
2955                                 ast_verbose("Using latest request as basis request\n");
2956                         copy_request(&p->initreq, req);
2957                         check_via(p, req);
2958                         if (strlen(get_header(req, "Content-Type"))) {
2959                                 if (process_sdp(p, req))
2960                                         return -1;
2961                         } else {
2962                                 p->capability = capability;
2963                                 ast_log(LOG_DEBUG, "Hm....  No sdp for the moemnt\n");
2964                         }
2965                 } else if (sipdebug)
2966                         ast_verbose("Ignoring this request\n");
2967                 if (!p->lastinvite) {
2968                         /* Handle authentication if this is our first invite */
2969                         res = check_user(p, req, cmd, e);
2970                         if (res) {
2971                                 if (res < 0) {
2972                                         ast_log(LOG_NOTICE, "Failed to authenticate user %s\n", get_header(req, "From"));
2973                                         sip_destroy(p);
2974                                 }
2975                                 return 0;
2976                         }
2977                         /* Initialize the context if it hasn't been already */
2978                         if (!strlen(p->context))
2979                                 strncpy(p->context, context, sizeof(p->context) - 1);
2980                         if ((res = get_destination(p, NULL))) {
2981                                 if (res < 0)
2982                                         transmit_response(p, "404 Not Found", req);
2983                                 else
2984                                         transmit_response(p, "484 Address Incomplete", req);
2985                                 sip_destroy(p);
2986                                 p = NULL;
2987                                 c = NULL;
2988                         } else {
2989                                 /* If no extension was specified, use the s one */
2990                                 if (!strlen(p->exten))
2991                                         strncpy(p->exten, "s", sizeof(p->exten) - 1);
2992                                 /* Initialize tag */    
2993                                 p->tag = rand();
2994                                 /* First invitation */
2995                                 c = sip_new(p, AST_STATE_DOWN);
2996                         }
2997                         
2998                 } else 
2999                         c = p->owner;
3000                 if (!ignore && p)
3001                         p->lastinvite = seqno;
3002                 if (c) {
3003                         switch(c->_state) {
3004                         case AST_STATE_DOWN:
3005                                 transmit_response(p, "100 Trying", req);
3006                                 ast_setstate(c, AST_STATE_RING);
3007                                 if (ast_pbx_start(c)) {
3008                                         ast_log(LOG_WARNING, "Failed to start PBX :(\n");
3009                                         ast_hangup(c);
3010                                         transmit_response(p, "503 Unavailable", req);
3011                                         sip_destroy(p);
3012                                 }
3013                                 break;
3014                         case AST_STATE_RING:
3015                                 transmit_response(p, "100 Trying", req);
3016                                 break;
3017                         case AST_STATE_RINGING:
3018                                 transmit_response(p, "180 Ringing", req);
3019                                 break;
3020                         case AST_STATE_UP:
3021                                 transmit_response_with_sdp(p, "200 OK", req);
3022                                 break;
3023                         default:
3024                                 ast_log(LOG_WARNING, "Don't know how to handle INVITE in state %d\n", c->_state);
3025                                 transmit_response(p, "100 Trying", req);
3026                         }
3027                 } else {
3028                         if (p) {
3029                                 ast_log(LOG_NOTICE, "Unable to create/find channel\n");
3030                                 transmit_response(p, "503 Unavailable", req);
3031                                 sip_destroy(p);
3032                         }
3033                 }
3034         } else if (!strcasecmp(cmd, "REFER")) {
3035                 struct ast_channel *transfer_to;
3036                 ast_log(LOG_DEBUG, "We found a REFER!\n");
3037                 if (!strlen(p->context))
3038                         strncpy(p->context, context, sizeof(p->context) - 1);
3039                 res = get_refer_info(p, req);
3040                 if (res < 0)
3041                         transmit_response_with_allow(p, "404 Not Found", req);
3042                 else if (res > 0)
3043                         transmit_response_with_allow(p, "484 Address Incomplete", req);
3044                 else
3045                         transmit_response(p, "202 Accepted", req);
3046                 ast_log(LOG_DEBUG,"202 Accepted\n");
3047                 transfer_to = c->bridge;
3048                 if (transfer_to)
3049                         ast_async_goto(transfer_to,"", p->refer_to,1, 1);
3050                         
3051         } else if (!strcasecmp(cmd, "CANCEL") || !strcasecmp(cmd, "BYE")) {
3052                 copy_request(&p->initreq, req);
3053                 p->alreadygone = 1;
3054                 if (p->rtp) {
3055                         /* Immediately stop RTP */
3056                         ast_rtp_destroy(p->rtp);
3057                         p->rtp = NULL;
3058                 }
3059                 if (p->owner)
3060                         ast_queue_hangup(p->owner, 1);
3061                 transmit_response(p, "200 OK", req);
3062         } else if (!strcasecmp(cmd, "MESSAGE")) {
3063                 if (sipdebug)
3064                         ast_verbose("Receiving message!\n");
3065                 receive_message(p, req);
3066                 transmit_response(p, "200 OK", req);
3067         } else if (!strcasecmp(cmd, "INFO")) {
3068                 if (sipdebug)
3069                         ast_verbose("Receiving DTMF!\n");
3070                 receive_info(p, req);
3071                 transmit_response(p, "200 OK", req);
3072         } else if (!strcasecmp(cmd, "REGISTER")) {
3073                 /* Use this as the basis */
3074                 if (sipdebug)
3075                         ast_verbose("Using latest request as basis request\n");