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