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