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