Version 0.2.0 from FTP
[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 <pthread.h>
16 #include <string.h>
17 #include <asterisk/lock.h>
18 #include <asterisk/channel.h>
19 #include <asterisk/channel_pvt.h>
20 #include <asterisk/config.h>
21 #include <asterisk/logger.h>
22 #include <asterisk/module.h>
23 #include <asterisk/pbx.h>
24 #include <asterisk/options.h>
25 #include <asterisk/lock.h>
26 #include <asterisk/sched.h>
27 #include <asterisk/io.h>
28 #include <asterisk/rtp.h>
29 #include <asterisk/acl.h>
30 #include <asterisk/callerid.h>
31 #include <sys/socket.h>
32 #include <errno.h>
33 #include <unistd.h>
34 #include <stdlib.h>
35 #include <fcntl.h>
36 #include <netdb.h>
37 #include <arpa/inet.h>
38 #include <sys/signal.h>
39
40 #define SIPDUMPER
41 #define DEFAULT_EXPIREY 120
42 #define MAX_EXPIREY     3600
43
44 static char *desc = "Session Initiation Protocol (SIP)";
45 static char *type = "sip";
46 static char *tdesc = "Session Initiation Protocol (SIP)";
47 static char *config = "sip.conf";
48
49 #define DEFAULT_SIP_PORT        5060    /* From RFC 2543 */
50 #define SIP_MAX_PACKET  1500            /* Also from RFC 2543, should sub headers tho */
51
52 static char context[AST_MAX_EXTENSION] = "default";
53
54 static char language[MAX_LANGUAGE] = "";
55
56 static int usecnt =0;
57 static pthread_mutex_t usecnt_lock = AST_MUTEX_INITIALIZER;
58
59 /* Protect the interface list (of sip_pvt's) */
60 static pthread_mutex_t iflock = AST_MUTEX_INITIALIZER;
61
62 /* Protect the monitoring thread, so only one process can kill or start it, and not
63    when it's doing something critical. */
64 static pthread_mutex_t netlock = AST_MUTEX_INITIALIZER;
65
66 static pthread_mutex_t monlock = AST_MUTEX_INITIALIZER;
67
68 /* This is the thread for the monitor which checks for input on the channels
69    which are not currently in use.  */
70 static pthread_t monitor_thread = 0;
71
72 static int restart_monitor(void);
73
74 /* Just about everybody seems to support ulaw, so make it a nice default */
75 static int capability = AST_FORMAT_ULAW;
76
77 static char ourhost[256];
78 static struct in_addr ourip;
79 static int ourport;
80
81 /* Expire slowly */
82 static int expirey = 900;
83
84 static struct sched_context *sched;
85 static struct io_context *io;
86 /* The private structures of the  sip channels are linked for
87    selecting outgoing channels */
88    
89 #define SIP_MAX_HEADERS         64
90 #define SIP_MAX_LINES           64
91
92 struct sip_request {
93         int len;
94         int headers;                                    /* SIP Headers */
95         char *header[SIP_MAX_HEADERS];
96         int lines;                                              /* SDP Content */
97         char *line[SIP_MAX_LINES];
98         char data[SIP_MAX_PACKET];
99 };
100
101 static struct sip_pvt {
102         char callid[80];                                        /* Global CallID */
103         unsigned int cseq;                                                      /* Current seqno */
104         int lastinvite;                                         /* Last Cseq of invite */
105         int alreadygone;                                        /* Whether or not we've already been destroyed by or peer */
106         int needdestroy;                                        /* if we need to be destroyed */
107         int capability;                                         /* Special capability */
108         int outgoing;                                           /* Outgoing or incoming call? */
109         int insecure;                                           /* Don't check source port/ip */
110         int expirey;                                            /* How long we take to expire */
111         struct sockaddr_in sa;                          /* Our peer */
112         struct ast_channel *owner;                      /* Who owns us */
113         char exten[AST_MAX_EXTENSION];          /* Extention where to start */
114         char context[AST_MAX_EXTENSION];
115         char language[MAX_LANGUAGE];
116         struct sip_request initreq;                     /* Initial request */
117         struct ast_rtp *rtp;                            /* RTP Session */
118         struct sip_pvt *next;
119 } *iflist = NULL;
120
121 static struct sip_pkt {
122         int retrans;
123         struct sip_pvt *owner;
124         int packetlen;
125         char data[SIP_MAX_PACKET];
126         struct sip_pkt *next;
127 } *packets = NULL;      
128
129 struct sip_user {
130         /* Users who can access various contexts */
131         char name[80];
132         char secret[80];
133         char context[80];
134         char callerid[80];
135         char methods[80];
136         char accountcode[80];
137         int hascallerid;
138         int amaflags;
139         int insecure;
140         struct ast_ha *ha;
141         struct sip_user *next;
142 };
143
144 struct sip_peer {
145         char name[80];
146         char secret[80];
147         char methods[80];
148         char username[80];
149         int dynamic;
150         int expire;
151         int expirey;
152         int capability;
153         int insecure;
154         struct sockaddr_in addr;
155         struct in_addr mask;
156         
157         struct sockaddr_in defaddr;
158         struct ast_ha *ha;
159         int delme;
160         struct sip_peer *next;
161 };
162
163 static struct ast_user_list {
164         struct sip_user *users;
165         pthread_mutex_t lock;
166 } userl = { NULL, AST_MUTEX_INITIALIZER };
167
168 static struct ast_peer_list {
169         struct sip_peer *peers;
170         pthread_mutex_t lock;
171 } peerl = { NULL, AST_MUTEX_INITIALIZER };
172
173
174 static int sipsock  = -1;
175
176 static struct sockaddr_in bindaddr;
177
178 #ifdef SIPDUMPER
179
180 static void sip_dump_packet(char *data, int len)
181 {
182         printf("SIP Packet Dump\n");
183         printf("================\n");
184         printf("Data: \n%s\n", data);
185         fflush(stdout);
186 }
187
188 #endif
189
190 static struct ast_frame  *sip_read(struct ast_channel *ast);
191 static int transmit_response(struct sip_pvt *p, char *msg);
192 static int transmit_response_with_sdp(struct sip_pvt *p, char *msg);
193 static int transmit_request(struct sip_pvt *p, char *msg, int inc);
194 static int transmit_invite_with_sdp(struct sip_pvt *p, char *msg);
195
196 static int __sip_xmit(struct sip_pvt *p, char *data, int len)
197 {
198         int res;
199     res=sendto(sipsock, data, len, 0, (struct sockaddr *)&p->sa, sizeof(struct sockaddr_in));
200         if (res != len) {
201                 ast_log(LOG_WARNING, "sip_xmit returned %d\n", res);
202         }
203         return res;
204 }
205
206 static int send_response(struct sip_pvt *p, struct sip_request *req)
207 {
208         int res;
209         printf("Transmitting:\n%s\n", req->data);
210         res = __sip_xmit(p, req->data, req->len);
211         if (res > 0)
212                 res = 0;
213         return res;
214 }
215
216 static int send_request(struct sip_pvt *p, struct sip_request *req)
217 {
218         int res;
219         printf("XXX Need to handle Retransmitting XXX:\n%s\n", req->data);
220         res = __sip_xmit(p, req->data, req->len);
221         return res;
222 }
223
224 static char *ditch_braces(char *tmp)
225 {
226         char *c = tmp;
227         char *n;
228         c = tmp;
229         if ((n = strchr(tmp, '<')) ) {
230                 c = n + 1;
231                 while(*c && *c != '>') c++;
232                 if (*c != '>') {
233                         ast_log(LOG_WARNING, "No closing brace in '%s'\n", tmp);
234                 } else {
235                         *c = '\0';
236                 }
237                 return n+1;
238         }
239         return c;
240 }
241
242 static int sip_digit(struct ast_channel *ast, char digit)
243 {
244         printf("SIP digit! (%c)\n", digit);
245         return 0;
246 }
247
248 static int create_addr(struct sockaddr_in *sin, int *capability, char *peer, char *username, int *insecure)
249 {
250         struct hostent *hp;
251         struct sip_peer *p;
252         int found=0;
253         sin->sin_family = AF_INET;
254         ast_pthread_mutex_lock(&peerl.lock);
255         p = peerl.peers;
256         while(p) {
257                 if (!strcasecmp(p->name, peer)) {
258                         found++;
259                         if (capability)
260                                 *capability = p->capability;
261                         if (username)
262                                 strncpy(username, p->username, 80);
263                         if (insecure)
264                                 *insecure = p->insecure;
265                         if (p->addr.sin_addr.s_addr || p->defaddr.sin_addr.s_addr) {
266                                 if (p->addr.sin_addr.s_addr) {
267                                         sin->sin_addr = p->addr.sin_addr;
268                                         sin->sin_port = p->addr.sin_port;
269                                 } else {
270                                         sin->sin_addr = p->defaddr.sin_addr;
271                                         sin->sin_port = p->defaddr.sin_port;
272                                 }
273                                 break;
274                         }
275                 }
276                 p = p->next;
277         }
278         ast_pthread_mutex_unlock(&peerl.lock);
279         if (!p && !found) {
280                 hp = gethostbyname(peer);
281                 if (hp) {
282                         memcpy(&sin->sin_addr, hp->h_addr, sizeof(sin->sin_addr));
283                         sin->sin_port = htons(DEFAULT_SIP_PORT);
284                         return 0;
285                 } else {
286                         ast_log(LOG_WARNING, "No such host: %s\n", peer);
287                         return -1;
288                 }
289         } else if (!p)
290                 return -1;
291         else
292                 return 0;
293 }
294
295 static int sip_call(struct ast_channel *ast, char *dest, int timeout)
296 {
297         int res;
298         struct sip_pvt *p;
299         char *ext, *host;
300         char tmp[256];
301         char username[81];
302         strncpy(tmp, dest, sizeof(tmp) - 1);
303         
304         p = ast->pvt->pvt;
305         if ((ast->state != AST_STATE_DOWN) && (ast->state != AST_STATE_RESERVED)) {
306                 ast_log(LOG_WARNING, "sip_call called on %s, neither down nor reserved\n", ast->name);
307                 return -1;
308         }
309         host = strchr(tmp, '@');
310         if (host) {
311                 *host = '\0';
312                 host++;
313                 ext = tmp;
314         } else {
315                 host = tmp;
316                 ext = NULL;
317         }
318         if (create_addr(&p->sa, &p->capability, host, username, &p->insecure)) {
319                 return -1;
320         }
321         if (!ext && strlen(username))
322                 ext = username;
323         res = 0;
324         p->outgoing = 1;
325         transmit_invite_with_sdp(p, username);
326         printf("Calling extension '%s' at '%s'\n", ext ? ext : "<none>", host);
327         return res;
328 }
329
330 static void __sip_destroy(struct sip_pvt *p)
331 {
332         struct sip_pvt *cur, *prev = NULL;
333         if (p->rtp) {
334                 ast_rtp_destroy(p->rtp);
335         }
336         cur = iflist;
337         while(cur) {
338                 if (cur == p) {
339                         if (prev)
340                                 prev->next = cur->next;
341                         else
342                                 iflist = cur->next;
343                         break;
344                 }
345                 prev = cur;
346                 cur = cur->next;
347         }
348         if (!cur) {
349                 ast_log(LOG_WARNING, "%p is not in list?!?! \n", cur);
350         } else
351                 free(p);
352 }
353 static void sip_destroy(struct sip_pvt *p)
354 {
355         ast_pthread_mutex_lock(&iflock);
356         __sip_destroy(p);
357         ast_pthread_mutex_unlock(&iflock);
358 }
359
360
361 static int sip_hangup(struct ast_channel *ast)
362 {
363         struct sip_pvt *p;
364         if (option_debug)
365                 ast_log(LOG_DEBUG, "sip_hangup(%s)\n", ast->name);
366         if (!ast->pvt->pvt) {
367                 ast_log(LOG_WARNING, "Asked to hangup channel not connected\n");
368                 return 0;
369         }
370         p = ast->pvt->pvt;
371         if (!p->alreadygone && strlen(p->initreq.data)) {
372                 if (!p->owner || p->owner->state != AST_STATE_UP)
373                         transmit_request(p, "CANCEL", 0);
374                 else
375                         /* Send a hangup */
376                         transmit_request(p, "BYE", 1);
377         }
378         p->needdestroy = 1;
379         p->owner = NULL;
380         p->outgoing = 0;
381         ast->pvt->pvt = NULL;
382         printf("SIP Hangup!\n");
383         return 0;
384 }
385
386 static int sip_answer(struct ast_channel *ast)
387 {
388         int res = 0;
389         struct sip_pvt *p = ast->pvt->pvt;
390         if (ast->state != AST_STATE_UP) {
391                 ast->state = AST_STATE_UP;
392                 if (option_debug)
393                         ast_log(LOG_DEBUG, "sip_answer(%s)\n", ast->name);
394                 res = transmit_response_with_sdp(p, "200 OK");
395         }
396         return res;
397 }
398
399 static struct ast_frame  *sip_read(struct ast_channel *ast)
400 {
401         ast_log(LOG_WARNING, "I should never get called but am on %s!\n", ast->name);
402         return NULL;
403 }
404
405 static int sip_write(struct ast_channel *ast, struct ast_frame *frame)
406 {
407         struct sip_pvt *p = ast->pvt->pvt;
408         if (p->rtp) {
409                 return ast_rtp_write(p->rtp, frame);
410         }
411         return 0;
412 }
413
414 static int sip_fixup(struct ast_channel *oldchan, struct ast_channel *newchan)
415 {
416         struct sip_pvt *p = newchan->pvt->pvt;
417         if (p->owner != oldchan) {
418                 ast_log(LOG_WARNING, "old channel wasn't %p but was %p\n", oldchan, p->owner);
419                 return -1;
420         }
421         p->owner = newchan;
422         return 0;
423 }
424
425 static int sip_indicate(struct ast_channel *ast, int condition)
426 {
427         struct sip_pvt *p = ast->pvt->pvt;
428         switch(condition) {
429         case AST_CONTROL_RINGING:
430                 if (ast->state == AST_STATE_RING) {
431                         transmit_response(p, "180 Ringing");
432                 } else {
433                         ast_log(LOG_WARNING, "XXX Need to send in-band ringtone XXX\n");
434                 }
435                 break;
436         case AST_CONTROL_BUSY:
437                 if (ast->state != AST_STATE_UP) {
438                         transmit_response(p, "600 Busy everywhere");
439                 } else {
440                         ast_log(LOG_WARNING, "XXX Need to send in-band busy tone XXX\n");
441                 }
442                 break;
443         case AST_CONTROL_CONGESTION:
444                 if (ast->state != AST_STATE_UP) {
445                         transmit_response(p, "486 Busy here");
446                 } else {
447                         ast_log(LOG_WARNING, "XXX Need to send in-band congestion tone XXX\n");
448                 }
449                 break;
450         default:
451                 printf("Don't know how to indicate condition %d\n", condition);
452         }
453         return 0;
454 }
455
456 static struct ast_channel *sip_new(struct sip_pvt *i, int state)
457 {
458         struct ast_channel *tmp;
459         int fmt;
460         tmp = ast_channel_alloc(1);
461         if (tmp) {
462                 tmp->nativeformats = i->capability;
463                 if (!tmp->nativeformats)
464                         tmp->nativeformats = capability;
465                 fmt = ast_best_codec(tmp->nativeformats);
466                 snprintf(tmp->name, sizeof(tmp->name), "SIP/%s:%d", inet_ntoa(i->sa.sin_addr), ntohs(i->sa.sin_port));
467                 tmp->type = type;
468                 tmp->state = state;
469                 if (state == AST_STATE_RING)
470                         tmp->rings = 1;
471                 tmp->writeformat = fmt;
472                 tmp->pvt->rawwriteformat = fmt;
473                 tmp->readformat = fmt;
474                 tmp->pvt->rawreadformat = fmt;
475                 tmp->pvt->pvt = i;
476                 tmp->pvt->send_digit = sip_digit;
477                 tmp->pvt->call = sip_call;
478                 tmp->pvt->hangup = sip_hangup;
479                 tmp->pvt->answer = sip_answer;
480                 tmp->pvt->read = sip_read;
481                 tmp->pvt->write = sip_write;
482                 tmp->pvt->indicate = sip_indicate;
483                 tmp->pvt->fixup = sip_fixup;
484                 if (strlen(i->language))
485                         strncpy(tmp->language, i->language, sizeof(tmp->language)-1);
486                 i->owner = tmp;
487                 ast_pthread_mutex_lock(&usecnt_lock);
488                 usecnt++;
489                 ast_pthread_mutex_unlock(&usecnt_lock);
490                 ast_update_use_count();
491                 strncpy(tmp->context, i->context, sizeof(tmp->context)-1);
492                 strncpy(tmp->exten, i->exten, sizeof(tmp->exten)-1);
493                 tmp->priority = 1;
494                 if (state != AST_STATE_DOWN) {
495                         if (ast_pbx_start(tmp)) {
496                                 ast_log(LOG_WARNING, "Unable to start PBX on %s\n", tmp->name);
497                                 ast_hangup(tmp);
498                                 tmp = NULL;
499                         }
500                 }
501         } else
502                 ast_log(LOG_WARNING, "Unable to allocate channel structure\n");
503         return tmp;
504 }
505
506 static struct cfalias {
507         char *fullname;
508         char *shortname;
509 } aliases[] = {
510         { "Content-Type", "c" },
511         { "Content-Encoding", "e" },
512         { "From", "f" },
513         { "Call-ID", "i" },
514         { "Contact", "m" },
515         { "Content-Length", "l" },
516         { "Subject", "s" },
517         { "To", "t" },
518         { "Via", "v" },
519 };
520
521 static char *get_sdp(struct sip_request *req, char *name)
522 {
523         int x;
524         int len = strlen(name);
525         char *r;
526         for (x=0;x<req->lines;x++) {
527                 if (!strncasecmp(req->line[x], name, len) && 
528                                 (req->line[x][len] == '=')) {
529                                         r = req->line[x] + len + 1;
530                                         while(*r && (*r < 33))
531                                                         r++;
532                                         return r;
533                 }
534         }
535         return "";
536 }
537
538 static char *get_header(struct sip_request *req, char *name)
539 {
540         int x;
541         int len = strlen(name);
542         char *r;
543         for (x=0;x<req->headers;x++) {
544                 if (!strncasecmp(req->header[x], name, len) && 
545                                 (req->header[x][len] == ':')) {
546                                         r = req->header[x] + len + 1;
547                                         while(*r && (*r < 33))
548                                                         r++;
549                                         return r;
550                 }
551         }
552         /* Try aliases */
553         for (x=0;x<sizeof(aliases) / sizeof(aliases[0]); x++) 
554                 if (!strcasecmp(aliases[x].fullname, name)) 
555                         return get_header(req, aliases[x].shortname);
556
557         /* Don't return NULL, so get_header is always a valid pointer */
558         return "";
559 }
560
561 static int rtpready(struct ast_rtp *rtp, struct ast_frame *f, void *data)
562 {
563         /* Just deliver the audio directly */
564         struct sip_pvt *p = data;
565         if (p->owner)
566                 ast_queue_frame(p->owner, f, 1);
567         return 0;
568 }
569
570 static void build_callid(char *callid, int len)
571 {
572         int res;
573         int val;
574         int x;
575         for (x=0;x<4;x++) {
576                 val = rand();
577                 res = snprintf(callid, len, "%08x", val);
578                 len -= res;
579                 callid += res;
580         }
581         snprintf(callid, len, "@%s", inet_ntoa(ourip));
582 }
583
584 static struct sip_pvt *sip_alloc(char *callid, struct sockaddr_in *sin)
585 {
586         struct sip_pvt *p;
587         p = malloc(sizeof(struct sip_pvt));
588         if (!p)
589                 return NULL;
590         /* Keep track of stuff */
591         memset(p, 0, sizeof(struct sip_pvt));
592         if (!callid)
593                 build_callid(p->callid, sizeof(p->callid));
594         else
595                 strncpy(p->callid, callid, sizeof(p->callid) - 1);
596         if (sin)
597                 memcpy(&p->sa, sin, sizeof(p->sa));
598         p->rtp = ast_rtp_new(sched, io);
599         ast_rtp_set_data(p->rtp, p);
600         ast_rtp_set_callback(p->rtp, rtpready);
601         if (!p->rtp) {
602                 ast_log(LOG_WARNING, "Unable to create RTP session: %s\n", strerror(errno));
603                 free(p);
604                 return NULL;
605         }
606         
607         /* Add to list */
608         ast_pthread_mutex_lock(&iflock);
609         p->next = iflist;
610         iflist = p;
611         ast_pthread_mutex_unlock(&iflock);
612         return p;
613 }
614
615 static struct sip_pvt *find_call(struct sip_request *req, struct sockaddr_in *sin)
616 {
617         struct sip_pvt *p;
618         char *callid;
619         callid = get_header(req, "Call-ID");
620         if (!strlen(callid)) {
621                 ast_log(LOG_WARNING, "Call missing call ID from '%s'\n", inet_ntoa(sin->sin_addr));
622                 return NULL;
623         }
624         ast_pthread_mutex_lock(&iflock);
625         p = iflist;
626         while(p) {
627                 if (!strcmp(p->callid, callid)) {
628                         /* Found the call */
629 #if 0
630                         if (!p->insecure && ((p->sa.sin_addr.s_addr != sin->sin_addr.s_addr) ||
631                             (p->sa.sin_port != sin->sin_port))) {
632                                         char orig[80];
633                                         char new[80];
634                                         snprintf(orig, sizeof(orig), "%s:%d", inet_ntoa(p->sa.sin_addr), ntohs(p->sa.sin_port));
635                                         snprintf(new, sizeof(new), "%s:%d", inet_ntoa(sin->sin_addr), ntohs(sin->sin_port));
636                                         ast_log(LOG_WARNING, "Looks like %s is trying to steal call '%s' from %s?\n", new, p->callid, orig);
637                                         ast_pthread_mutex_unlock(&iflock);
638                                         return NULL;
639                         }
640 #endif
641                         ast_pthread_mutex_unlock(&iflock);
642                         return p;
643                 }
644                 p = p->next;
645         }
646         ast_pthread_mutex_unlock(&iflock);
647         return sip_alloc(callid, sin);
648 }
649
650 static void parse(struct sip_request *req)
651 {
652         /* Divide fields by NULL's */
653         char *c;
654         int f = 0;
655         c = req->data;
656
657         /* First header starts immediately */
658         req->header[f] = c;
659         while(*c) {
660                 if (*c == '\n') {
661                         /* We've got a new header */
662                         *c = 0;
663
664 #if 0
665                         printf("Header: %s (%d)\n", req->header[f], strlen(req->header[f]));
666 #endif                  
667                         if (!strlen(req->header[f])) {
668                                 /* Line by itself means we're now in content */
669                                 c++;
670                                 break;
671                         }
672                         if (f >= SIP_MAX_HEADERS - 1) {
673                                 ast_log(LOG_WARNING, "Too many SIP headers...\n");
674                         } else
675                                 f++;
676                         req->header[f] = c + 1;
677                 } else if (*c == '\r') {
678                         /* Ignore but eliminate \r's */
679                         *c = 0;
680                 }
681                 c++;
682         }
683         /* Check for last header */
684         if (strlen(req->header[f])) 
685                 f++;
686         req->headers = f;
687         /* Now we process any mime content */
688         f = 0;
689         req->line[f] = c;
690         while(*c) {
691                 if (*c == '\n') {
692                         /* We've got a new line */
693                         *c = 0;
694 #if 0
695                         printf("Line: %s (%d)\n", req->line[f], strlen(req->line[f]));
696 #endif                  
697                         if (f >= SIP_MAX_LINES - 1) {
698                                 ast_log(LOG_WARNING, "Too many SDP lines...\n");
699                         } else
700                                 f++;
701                         req->line[f] = c + 1;
702                 } else if (*c == '\r') {
703                         /* Ignore and eliminate \r's */
704                         *c = 0;
705                 }
706                 c++;
707         }
708         /* Check for last line */
709         if (strlen(req->line[f])) 
710                 f++;
711         req->lines = f;
712         printf("%d headers, %d lines\n", req->headers, req->lines);
713         if (*c) 
714                 ast_log(LOG_WARNING, "Odd content, extra stuff left over ('%s')\n", c);
715 }
716
717 static int process_sdp(struct sip_pvt *p, struct sip_request *req)
718 {
719         char *m;
720         char *c;
721         char host[258];
722         int len;
723         int portno;
724         int peercapability;
725         struct sockaddr_in sin;
726         char *codecs;
727         struct hostent *hp;
728         int codec;
729         /* Get codec and RTP info from SDP */
730         if (strcasecmp(get_header(req, "Content-Type"), "application/sdp")) {
731                 ast_log(LOG_NOTICE, "Content is '%s', not 'application/sdp'\n", get_header(req, "Content-Type"));
732                 return -1;
733         }
734         m = get_sdp(req, "m");
735         c = get_sdp(req, "c");
736         if (!strlen(m) || !strlen(c)) {
737                 ast_log(LOG_WARNING, "Insufficient information for SDP (m = '%s', c = '%s')\n", m, c);
738                 return -1;
739         }
740         if (sscanf(c, "IN IP4 %256s", host) != 1) {
741                 ast_log(LOG_WARNING, "Invalid host in c= line, '%s'\n", c);
742                 return -1;
743         }
744         /* XXX This could block for a long time, and block the main thread! XXX */
745         hp = gethostbyname(host);
746         if (!hp) {
747                 ast_log(LOG_WARNING, "Unable to lookup host in c= line, '%s'\n", c);
748                 return -1;
749         }
750         if (sscanf(m, "audio %d RTP/AVP %n", &portno, &len) != 1) {
751                 ast_log(LOG_WARNING, "Unable to determine port number for RTP in '%s'\n", m); 
752                 return -1;
753         }
754         sin.sin_family = AF_INET;
755         memcpy(&sin.sin_addr, hp->h_addr, sizeof(sin.sin_addr));
756         sin.sin_port = htons(portno);
757         ast_rtp_set_peer(p->rtp, &sin);
758 #if 0
759         printf("Peer RTP is at port %s:%d\n", inet_ntoa(sin.sin_addr), ntohs(sin.sin_port));
760 #endif  
761         peercapability = 0;
762         codecs = m + len;
763         while(strlen(codecs)) {
764                 if (sscanf(codecs, "%d %n", &codec, &len) != 1) {
765                         ast_log(LOG_WARNING, "Error in codec string '%s'\n", codecs);
766                         return -1;
767                 }
768 #if 0
769                 printf("Codec: %d\n", codec);
770 #endif          
771                 codec = rtp2ast(codec);
772                 if (codec  > -1)
773                         peercapability |= codec;
774                 codecs += len;
775         }
776         p->capability = capability & peercapability;
777         printf("Capabilities: us - %d, them - %d, combined - %d\n",
778                 capability, peercapability, p->capability);
779         if (!p->capability) {
780                 ast_log(LOG_WARNING, "No compatible codecs!\n");
781                 return -1;
782         }
783         return 0;
784         
785 }
786
787 static int add_header(struct sip_request *req, char *var, char *value)
788 {
789         if (req->lines) {
790                 ast_log(LOG_WARNING, "Can't add more headers when lines have been added\n");
791                 return -1;
792         }
793         req->header[req->headers] = req->data + req->len;
794         req->len += snprintf(req->header[req->headers], sizeof(req->data) - req->len, "%s: %s\r\n", var, value);
795         if (req->headers < SIP_MAX_HEADERS)
796                 req->headers++;
797         else {
798                 ast_log(LOG_WARNING, "Out of header space\n");
799                 return -1;
800         }
801         return 0;       
802 }
803
804 static int add_blank_header(struct sip_request *req)
805 {
806         if (req->lines) {
807                 ast_log(LOG_WARNING, "Can't add more headers when lines have been added\n");
808                 return -1;
809         }
810         req->header[req->headers] = req->data + req->len;
811         req->len += snprintf(req->header[req->headers], sizeof(req->data) - req->len, "\r\n");
812         if (req->headers < SIP_MAX_HEADERS)
813                 req->headers++;
814         else {
815                 ast_log(LOG_WARNING, "Out of header space\n");
816                 return -1;
817         }
818         return 0;       
819 }
820
821 static int add_line(struct sip_request *req, char *line)
822 {
823         if (!req->lines) {
824                 /* Add extra empty return */
825                 req->len += snprintf(req->data + req->len, sizeof(req->data) - req->len, "\r\n");
826         }
827         req->line[req->lines] = req->data + req->len;
828         req->len += snprintf(req->line[req->lines], sizeof(req->data) - req->len, "%s", line);
829         if (req->lines < SIP_MAX_LINES)
830                 req->lines++;
831         else {
832                 ast_log(LOG_WARNING, "Out of line space\n");
833                 return -1;
834         }
835         return 0;       
836 }
837
838 static int copy_header(struct sip_request *req, struct sip_request *orig, char *field)
839 {
840         char *tmp;
841         tmp = get_header(orig, field);
842         if (strlen(tmp)) {
843                 /* Add what we're responding to */
844                 return add_header(req, field, tmp);
845         }
846         ast_log(LOG_NOTICE, "No field '%s' present to copy\n", field);
847         return -1;
848 }
849
850 static int init_resp(struct sip_request *req, char *resp, struct sip_request *orig)
851 {
852         /* Initialize a response */
853         if (req->headers || req->len) {
854                 ast_log(LOG_WARNING, "Request already initialized?!?\n");
855                 return -1;
856         }
857         req->header[req->headers] = req->data + req->len;
858         req->len += snprintf(req->header[req->headers], sizeof(req->data) - req->len, "SIP/2.0 %s\r\n", resp);
859         if (req->headers < SIP_MAX_HEADERS)
860                 req->headers++;
861         else
862                 ast_log(LOG_WARNING, "Out of header space\n");
863         return 0;
864 }
865
866 static int init_req(struct sip_request *req, char *resp, char *recip)
867 {
868         /* Initialize a response */
869         if (req->headers || req->len) {
870                 ast_log(LOG_WARNING, "Request already initialized?!?\n");
871                 return -1;
872         }
873         req->header[req->headers] = req->data + req->len;
874         req->len += snprintf(req->header[req->headers], sizeof(req->data) - req->len, "%s %s SIP/2.0\r\n", resp, recip);
875         if (req->headers < SIP_MAX_HEADERS)
876                 req->headers++;
877         else
878                 ast_log(LOG_WARNING, "Out of header space\n");
879         return 0;
880 }
881
882 static int respprep(struct sip_request *resp, struct sip_pvt *p, char *msg)
883 {
884         struct sip_request *req = &p->initreq;
885         memset(resp, 0, sizeof(*resp));
886         init_resp(resp, msg, req);
887         copy_header(resp, req, "Via");
888         copy_header(resp, req, "From");
889         copy_header(resp, req, "To");
890         copy_header(resp, req, "Call-ID");
891         copy_header(resp, req, "CSeq");
892         add_header(resp, "User-Agent", "Asterisk PBX");
893         if (p->expirey) {
894                 /* For registration responses, we also need expirey and
895                    contact info */
896                 char tmp[80];
897                 char contact2[256], *c, contact[256];
898                 snprintf(tmp, sizeof(tmp), "%d", p->expirey);
899 #if 1
900                 /* XXX This isn't exactly right and it's implemented
901                        very stupidly *sigh* XXX */
902                 strncpy(contact2, get_header(req, "Contact"), sizeof(contact2)-1);
903                 c = ditch_braces(contact2);
904                 snprintf(contact, sizeof(contact), "<%s>", c);
905 #endif
906                 add_header(resp, "Expires", tmp);
907                 add_header(resp, "Contact", contact);
908         }
909         return 0;
910 }
911
912 static int reqprep(struct sip_request *req, struct sip_pvt *p, char *msg, int inc)
913 {
914         struct sip_request *orig = &p->initreq;
915         char stripped[80];
916         char tmp[80];
917         char *c, *n;
918         char *ot, *of;
919
920         memset(req, 0, sizeof(struct sip_request));
921         if (inc)
922                 p->cseq++;
923
924         
925         if (p->outgoing)
926                 strncpy(stripped, get_header(orig, "To"), sizeof(stripped) - 1);
927         else
928                 strncpy(stripped, get_header(orig, "From"), sizeof(stripped) - 1);
929         
930         c = strchr(stripped, '<');
931         if (c) 
932                 c++;
933         else
934                 c = stripped;
935         n = strchr(c, '>');
936         if (n)
937                 *n = '\0';
938         
939         init_req(req, msg, c);
940
941         snprintf(tmp, sizeof(tmp), "%d %s", p->cseq, msg);
942         add_header(req, "CSeq", tmp);
943
944         copy_header(req, orig, "Via");
945
946         ot = get_header(orig, "To");
947         of = get_header(orig, "From");
948         if (p->outgoing) {
949                 add_header(req, "From", of);
950                 add_header(req, "To", ot);
951         } else {
952                 add_header(req, "From", ot);
953                 add_header(req, "To", of);
954         }
955
956         copy_header(req, orig, "Call-ID");
957         add_header(req, "User-Agent", "Asterisk PBX");
958         return 0;
959 }
960
961 static int transmit_response(struct sip_pvt *p, char *msg)
962 {
963         struct sip_request resp;
964         respprep(&resp, p, msg);
965         add_header(&resp, "Content-Length", "0");
966         add_blank_header(&resp);
967         return send_response(p, &resp);
968 }
969
970 static int add_sdp(struct sip_request *resp, struct sip_pvt *p)
971 {
972         int len;
973         int codec;
974         char costr[80];
975         struct sockaddr_in sin;
976         char v[256];
977         char s[256];
978         char o[256];
979         char c[256];
980         char t[256];
981         char m[256];
982         int x;
983         /* XXX We break with the "recommendation" and send our IP, in order that our
984                peer doesn't have to gethostbyname() us XXX */
985         len = 0;
986         ast_rtp_get_us(p->rtp, &sin);
987         printf("We're at %s port %d\n", inet_ntoa(ourip), ntohs(sin.sin_port)); 
988         snprintf(v, sizeof(v), "v=0\r\n");
989         snprintf(s, sizeof(s), "s=Asterisk Call from %s\r\n", ourhost);
990         snprintf(o, sizeof(o), "o=root %d %d IN IP4 %s\r\n", getpid(), getpid(), inet_ntoa(ourip));
991         snprintf(c, sizeof(c), "c=IN IP4 %s\r\n", inet_ntoa(ourip));
992         snprintf(t, sizeof(t), "t=0 0\r\n");
993         snprintf(m, sizeof(m), "m=audio %d RTP/AVP 101", ntohs(sin.sin_port));
994         for (x=1;x<= AST_FORMAT_MAX_AUDIO; x <<= 1) {
995                 if (p->capability & x) {
996                         printf("Answering with capability %d\n", x);
997                         if ((codec = ast2rtp(x)) > -1) {
998                                 snprintf(costr, sizeof(costr), " %d", codec);
999                                 strcat(m, costr);
1000                         }
1001                 }
1002         }
1003         strcat(m, "\r\n");
1004         len = strlen(v) + strlen(s) + strlen(o) + strlen(c) + strlen(t) + strlen(m);
1005         snprintf(costr, sizeof(costr), "%d", len);
1006         add_header(resp, "Content-Type", "application/sdp");
1007         add_header(resp, "Content-Length", costr);
1008         add_line(resp, v);
1009         add_line(resp, s);
1010         add_line(resp, o);
1011         add_line(resp, c);
1012         add_line(resp, t);
1013         add_line(resp, m);
1014         return 0;
1015 }
1016
1017 static void copy_request(struct sip_request *dst,struct sip_request *src)
1018 {
1019         long offset;
1020         int x;
1021         offset = ((void *)dst) - ((void *)src);
1022         /* First copy stuff */
1023         memcpy(dst, src, sizeof(*dst));
1024         /* Now fix pointer arithmetic */
1025         for (x=0;x<src->headers;x++)
1026                 dst->header[x] += offset;
1027         for (x=0;x<src->lines;x++)
1028                 dst->line[x] += offset;
1029 }
1030
1031 static int transmit_response_with_sdp(struct sip_pvt *p, char *msg)
1032 {
1033         struct sip_request resp;
1034         respprep(&resp, p, msg);
1035         add_sdp(&resp, p);
1036         return send_response(p, &resp);
1037 }
1038
1039 static int transmit_invite_with_sdp(struct sip_pvt *p, char *username)
1040 {
1041         struct sip_request req;
1042         char from[256];
1043         char to[256];
1044         char tmp[80];
1045         char via[256];
1046         char cid[256];
1047         char *l, *n=NULL;
1048         if (p->owner && p->owner->callerid) {
1049                 strcpy(cid, p->owner->callerid);
1050                 ast_callerid_parse(cid, &n, &l);
1051                 if (!n)
1052                         n = l;
1053         }
1054         if (!n)
1055                 n = "";
1056         snprintf(from, sizeof(from), "\"%s\" <sip:sip@%s>;tag=%08x", n, inet_ntoa(ourip), rand());
1057         if (strlen(username))
1058                 snprintf(to, sizeof(to), " sip:%s@%s",username, inet_ntoa(p->sa.sin_addr));
1059         else
1060                 snprintf(to, sizeof(to), " sip:%s", inet_ntoa(p->sa.sin_addr));
1061         snprintf(via, sizeof(via), "SIP/2.0/UDP %s:%d", inet_ntoa(ourip), ourport);
1062         memset(&req, 0, sizeof(req));
1063
1064         init_req(&req, "INVITE", to);
1065         snprintf(tmp, sizeof(tmp), "%d %s", ++p->cseq, "INVITE");
1066         add_header(&req, "CSeq", tmp);
1067
1068         add_header(&req, "To", to);
1069         add_header(&req, "From", from);
1070         add_header(&req, "Call-ID", p->callid);
1071         add_header(&req, "Via", via);
1072         add_header(&req, "User-Agent", "Asterisk PBX");
1073         add_sdp(&req, p);
1074         /* Use this as the basis */
1075         copy_request(&p->initreq, &req);
1076         parse(&p->initreq);
1077         return send_request(p, &req);
1078 }
1079
1080 static int transmit_request(struct sip_pvt *p, char *msg, int inc)
1081 {
1082         struct sip_request resp;
1083         reqprep(&resp, p, msg, inc);
1084         add_header(&resp, "Content-Length", "0");
1085         add_blank_header(&resp);
1086         return send_request(p, &resp);
1087 }
1088
1089 static int expire_register(void *data)
1090 {
1091         struct sip_peer *p = data;
1092         memset(&p->addr, 0, sizeof(p->addr));
1093         p->expire = -1;
1094         return 0;
1095 }
1096
1097 static int parse_contact(struct sip_pvt *pvt, struct sip_peer *p, struct sip_request *req)
1098 {
1099         char contact[80]; 
1100         char *expires = get_header(req, "Expires");
1101         int expirey = atoi(expires);
1102         char *c, *n, *pt;
1103         int port;
1104         struct hostent *hp;
1105         struct sockaddr_in oldsin;
1106         if (!strlen(expires)) {
1107                 expires = strstr(get_header(req, "Contact"), "expires=");
1108                 if (expires) 
1109                         if (sscanf(expires + 8, "%d;", &expirey) != 1)
1110                                 expirey = 0;
1111         }
1112         /* Look for brackets */
1113         strncpy(contact, get_header(req, "Contact"), sizeof(contact) - 1);
1114         c = contact;
1115         
1116         if ((n=strchr(c, '<'))) {
1117                 c = n + 1;
1118                 n = strchr(c, '>');
1119                 /* Lose the part after the > */
1120                 if (n) 
1121                         *n = '\0';
1122         }
1123         /* Make sure it's a SIP URL */
1124         if (strncasecmp(c, "sip:", 4)) {
1125                 ast_log(LOG_NOTICE, "'%s' is not a valid SIP contcact\n", c);
1126                 return -1;
1127         }
1128         c += 4;
1129         /* Ditch q */
1130         n = strchr(c, ';');
1131         if (n) 
1132                 *n = '\0';
1133         /* Grab host */
1134         n = strchr(c, '@');
1135         if (!n) {
1136                 n = c;
1137                 c = NULL;
1138         } else {
1139                 *n = '\0';
1140                 n++;
1141         }
1142         pt = strchr(n, ':');
1143         if (pt) {
1144                 *pt = '\0';
1145                 pt++;
1146                 port = atoi(pt);
1147         } else
1148                 port = DEFAULT_SIP_PORT;
1149         /* XXX This could block for a long time XXX */
1150         hp = gethostbyname(n);
1151         if (!hp)  {
1152                 ast_log(LOG_WARNING, "Invalid host '%s'\n", n);
1153                 return -1;
1154         }
1155         memcpy(&oldsin, &p->addr, sizeof(oldsin));
1156         p->addr.sin_family = AF_INET;
1157         memcpy(&p->addr.sin_addr, hp->h_addr, sizeof(p->addr.sin_addr));
1158         p->addr.sin_port = htons(port);
1159         if (c)
1160                 strncpy(p->username, c, sizeof(p->username) - 1);
1161         else
1162                 strcpy(p->username, "");
1163         if (p->expire > -1)
1164                 ast_sched_del(sched, p->expire);
1165         if ((expirey < 1) || (expirey > MAX_EXPIREY))
1166                 expirey = DEFAULT_EXPIREY;
1167         p->expire = ast_sched_add(sched, expirey * 1000, expire_register, p);
1168         pvt->expirey = expirey;
1169         if (memcmp(&p->addr, &oldsin, sizeof(oldsin))) {
1170                 if (option_verbose > 2)
1171                         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);
1172         }
1173         return 0;
1174 }
1175
1176 static int register_verify(struct sip_pvt *p, struct sockaddr_in *sin, struct sip_request *req)
1177 {
1178         int res = -1;
1179         struct sip_peer *peer;
1180         char tmp[256];
1181         char *name, *c;
1182         strncpy(tmp, get_header(req, "To"), sizeof(tmp) - 1);
1183         c = ditch_braces(tmp);
1184         if (strncmp(c, "sip:", 4)) {
1185                 ast_log(LOG_NOTICE, "Invalid to address: '%s' from %s\n", tmp, inet_ntoa(sin->sin_addr));
1186                 return -1;
1187         }
1188         name = c + 4;
1189         c = strchr(name, '@');
1190         if (c) 
1191                 *c = '\0';
1192         ast_pthread_mutex_lock(&peerl.lock);
1193         peer = peerl.peers;
1194         while(peer) {
1195                 if (!strcasecmp(peer->name, name) && peer->dynamic) {
1196                         if (parse_contact(p, peer, req)) 
1197                                 ast_log(LOG_WARNING, "Failed to parse contact info\n");
1198                         else
1199                                 res = 0;
1200                         
1201                 }       
1202                 peer = peer->next;
1203         }
1204         ast_pthread_mutex_unlock(&peerl.lock);
1205         return res;
1206 }
1207
1208 static int get_destination(struct sip_pvt *p)
1209 {
1210         char tmp[256], *c, *a;
1211         strncpy(tmp, get_header(&p->initreq, "To"), sizeof(tmp));
1212         c = ditch_braces(tmp);
1213         if (strncmp(c, "sip:", 4)) {
1214                 ast_log(LOG_WARNING, "Huh?  Not a SIP header (%s)?\n", c);
1215                 return -1;
1216         }
1217         c += 4;
1218         if ((a = strchr(c, '@')) || (a = strchr(c, ';'))) {
1219                 *a = '\0';
1220         }
1221         printf("Looking for %s in %s\n", c, p->context);
1222         if (ast_exists_extension(NULL, p->context, c, 1, NULL)) {
1223                 strncpy(p->exten, c, sizeof(p->exten));
1224                 return 0;
1225         }
1226         return -1;
1227 }
1228
1229 static int check_via(struct sip_pvt *p, struct sip_request *req)
1230 {
1231         char via[256];
1232         char *c, *pt;
1233         struct hostent *hp;
1234         strncpy(via, get_header(req, "Via"), sizeof(via));
1235         c = strchr(via, ' ');
1236         if (c) {
1237                 *c = '\0';
1238                 c++;
1239                 if (strcmp(via, "SIP/2.0/UDP")) {
1240                         ast_log(LOG_WARNING, "Don't know how to respond via '%s'\n", via);
1241                         return -1;
1242                 }
1243                 pt = strchr(c, ':');
1244                 if (pt) {
1245                         *pt = '\0';
1246                         pt++;
1247                 }
1248                 hp = gethostbyname(c);
1249                 if (!hp) {
1250                         ast_log(LOG_WARNING, "'%s' is not a valid host\n", c);
1251                         return -1;
1252                 }
1253                 memset(&p->sa, 0, sizeof(p->sa));
1254                 p->sa.sin_family = AF_INET;
1255                 p->sa.sin_port = htons(pt ? atoi(pt) : DEFAULT_SIP_PORT);
1256                 memcpy(&p->sa.sin_addr, hp->h_addr, sizeof(p->sa.sin_addr));
1257                 printf("Sending to %s : %d\n", inet_ntoa(p->sa.sin_addr), ntohs(p->sa.sin_port));
1258         }
1259         return 0;
1260 }
1261
1262 static void handle_response(struct sip_pvt *p, int resp, char *rest, struct sip_request *req)
1263 {
1264         struct ast_frame f;
1265         memset(&f, 0, sizeof(f));
1266         if (p->outgoing) {
1267                 switch(resp) {
1268                 case 100:
1269                         /* Not important */
1270                         break;
1271                 case 180:
1272                         if (p->owner) {
1273                                 f.frametype = AST_FRAME_CONTROL;
1274                                 f.subclass = AST_CONTROL_RINGING;
1275                                 ast_queue_frame(p->owner, &f, 1);
1276                                 if (p->owner->state != AST_STATE_UP)
1277                                         p->owner->state = AST_STATE_RINGING;
1278                         }
1279                         break;
1280                 case 200:
1281                         process_sdp(p, req);
1282                         if (p->owner) {
1283                                 if (p->owner->state != AST_STATE_UP) {
1284                                         f.frametype = AST_FRAME_CONTROL;
1285                                         f.subclass = AST_CONTROL_ANSWER;
1286                                         p->owner->state = AST_STATE_UP;
1287                                         ast_queue_frame(p->owner, &f, 1);
1288                                         transmit_request(p, "ACK", 0);
1289                                 }
1290                         }
1291                         break;
1292                 default:
1293                         if ((resp >= 400) && (resp < 700)) {
1294                                 if (option_verbose > 2) 
1295                                         ast_verbose(VERBOSE_PREFIX_3 "Got SIP response %d \"%s\" back from %s\n", resp, rest, inet_ntoa(p->sa.sin_addr));
1296                                 p->alreadygone = 1;
1297                                 if (p->rtp) {
1298                                         /* Immediately stop RTP */
1299                                         ast_rtp_destroy(p->rtp);
1300                                         p->rtp = NULL;
1301                                 }
1302                                 /* Send hangup */       
1303                                 if (p->owner)
1304                                         ast_queue_hangup(p->owner, 1);
1305                         } else
1306                                 ast_log(LOG_NOTICE, "Dunno anything about a %d %s response from %s\n", resp, rest, p->owner ? p->owner->name : inet_ntoa(p->sa.sin_addr));
1307                 }
1308         }
1309 }
1310
1311 static int handle_request(struct sip_pvt *p, struct sip_request *req, struct sockaddr_in *sin)
1312 {
1313         struct sip_request resp;
1314         char *cmd;
1315         char *cseq;
1316         char *e;
1317         struct ast_channel *c;
1318         int seqno;
1319         int len;
1320         int ignore=0;
1321         int respid;
1322         /* Clear out potential response */
1323         memset(&resp, 0, sizeof(resp));
1324         /* Get Method and Cseq */
1325         cseq = get_header(req, "Cseq");
1326         cmd = req->header[0];
1327         /* Must have Cseq */
1328         if (!strlen(cmd) || !strlen(cseq))
1329                         return -1;
1330         if (sscanf(cseq, "%i%n", &seqno, &len) != 1) {
1331                 ast_log(LOG_DEBUG, "No seqno in '%s'\n", cmd);
1332                 return -1;
1333         }
1334         if (p->cseq && (p->cseq < seqno)) {
1335                 ast_log(LOG_DEBUG, "Ignoring out of order packet %d\n", seqno);
1336                 return -1;
1337         } else if (p->cseq && (p->cseq != seqno)) {
1338                 /* ignore means "don't do anything with it" but still have to 
1339                    respond appropriately  */
1340                 ignore=1;
1341         }
1342         
1343         /* Get the command */
1344         cseq += len;
1345         while(*cmd && (*cmd < 33))
1346                 cmd++;
1347         if (!*cmd)
1348                 return -1;
1349         e = cmd;
1350         while(*e && (*e > 32))
1351                 e++;
1352         /* Get the command */
1353         if (*e) {
1354                 *e = '\0';
1355                 e++;
1356         }
1357         if (strcmp(cmd, "SIP/2.0"))
1358                 /* Next should follow monotonically increasing */
1359                 p->cseq = seqno + 1;
1360
1361         if (!strcasecmp(cmd, "INVITE")) {
1362                 /* Process the SDP portion */
1363                 if (!ignore) {
1364                         /* Use this as the basis */
1365                         printf("Using latest request as basis request\n");
1366                         copy_request(&p->initreq, req);
1367                         check_via(p, req);
1368                         if (process_sdp(p, req))
1369                                 return -1;
1370                 } else
1371                         printf("Ignoring this request\n");
1372                 if (!p->lastinvite) {
1373                         /* Initialize the context if it hasn't been already */
1374                         if (!strlen(p->context))
1375                                 strncpy(p->context, context, sizeof(p->context));
1376                         if (get_destination(p)) {
1377                                 transmit_response(p, "404 Not Found");
1378                                 sip_destroy(p);
1379                                 p = NULL;
1380                                 c = NULL;
1381                         } else {
1382                                 /* If no extension was specified, use the s one */
1383                                 if (!strlen(p->exten))
1384                                         strncpy(p->exten, "s", sizeof(p->exten));
1385                                 /* First invitation */
1386                                 c = sip_new(p, AST_STATE_RING);
1387                         }
1388                         
1389                 } else 
1390                         c = p->owner;
1391                 if (!ignore && p)
1392                         p->lastinvite = seqno;
1393                 if (c) {
1394                         switch(c->state) {
1395                         case AST_STATE_RING:
1396                                 transmit_response(p, "100 Trying");
1397                                 break;
1398                         case AST_STATE_RINGING:
1399                                 transmit_response(p, "180 Ringing");
1400                                 break;
1401                         case AST_STATE_UP:
1402                                 transmit_response_with_sdp(p, "200 OK");
1403                                 break;
1404                         default:
1405                                 ast_log(LOG_WARNING, "Don't know how to handle INVITE in state %d\n", c->state);
1406                                 transmit_response(p, "100 Trying");
1407                         }
1408                 } else {
1409                         if (p) {
1410                                 ast_log(LOG_NOTICE, "Unable to create/find channel\n");
1411                                 transmit_response(p, "503 Unavailable");
1412                                 sip_destroy(p);
1413                         }
1414                 }
1415         } else if (!strcasecmp(cmd, "CANCEL") || !strcasecmp(cmd, "BYE")) {
1416                 copy_request(&p->initreq, req);
1417                 /* Hangup this channel */
1418                 p->alreadygone = 1;
1419                 if (p->rtp) {
1420                         /* Immediately stop RTP */
1421                         ast_rtp_destroy(p->rtp);
1422                         p->rtp = NULL;
1423                 }
1424                 if (p->owner)
1425                         ast_queue_hangup(p->owner, 1);
1426                 transmit_response(p, "200 OK");
1427         } else if (!strcasecmp(cmd, "REGISTER")) {
1428                 /* Use this as the basis */
1429                 printf("Using latest request as basis request\n");
1430                 copy_request(&p->initreq, req);
1431                 check_via(p, req);
1432                 transmit_response(p, "100 Trying");
1433                 if (register_verify(p, sin, req)) {
1434                         ast_log(LOG_NOTICE, "Registration from '%s' failed for '%s'\n", get_header(req, "To"), inet_ntoa(sin->sin_addr));
1435                         transmit_response(p, "401 Unauthorized");
1436                 } else {
1437                         transmit_response(p, "200 OK");
1438                 }
1439                 sip_destroy(p);
1440         } else if (!strcasecmp(cmd, "ACK")) {
1441                 /* Uhm, I haven't figured out the point of the ACK yet.  Are we
1442                    supposed to retransmit responses until we get an ack? 
1443                    Make sure this is on a valid call */
1444                 if (!p->lastinvite)
1445                         sip_destroy(p);
1446         } else if (!strcasecmp(cmd, "SIP/2.0")) {
1447                 while(*e && (*e < 33)) e++;
1448                 if (sscanf(e, "%i %n", &respid, &len) != 1) {
1449                         ast_log(LOG_WARNING, "Invalid response: '%s'\n", e);
1450                 } else {
1451                         handle_response(p, respid, e + len, req);
1452                 }
1453         } else {
1454                 ast_log(LOG_NOTICE, "Unknown SIP command '%s' from '%s'\n", 
1455                         cmd, inet_ntoa(p->sa.sin_addr));
1456         }
1457         return 0;
1458 }
1459
1460 static int sipsock_read(int *id, int fd, short events, void *ignore)
1461 {
1462         struct sip_request req;
1463         struct sockaddr_in sin;
1464         struct sip_pvt *p;
1465         int res;
1466         int len;
1467         len = sizeof(sin);
1468         res = recvfrom(sipsock, req.data, sizeof(req.data) - 1, 0, (struct sockaddr *)&sin, &len);
1469         if (res < 0) {
1470                 if (errno != ECONNREFUSED)
1471                         ast_log(LOG_WARNING, "Recv error: %s\n", strerror(errno));
1472                 return 1;
1473         }
1474         req.data[res] = '\0';
1475         req.len = res;
1476         printf("Sip read: \n%s\n", req.data);
1477         parse(&req);
1478         if (req.headers < 2) {
1479                 /* Must have at least two headers */
1480                 return 1;
1481         }
1482         /* Process request, with iflock held */
1483         ast_pthread_mutex_lock(&netlock);
1484         p = find_call(&req, &sin);
1485         if (p) {
1486                 handle_request(p, &req, &sin);
1487         }
1488         ast_pthread_mutex_unlock(&netlock);
1489         return 1;
1490 }
1491
1492 static void *do_monitor(void *data)
1493 {
1494         int res;
1495         struct sip_pkt *p;
1496         struct sip_pvt *sip;
1497         sched = sched_context_create();
1498         if (!sched) {
1499                 ast_log(LOG_WARNING, "Unable to create schedule context\n");
1500                 return NULL;
1501         }
1502         io = io_context_create();
1503         if (!io) {
1504                 ast_log(LOG_WARNING, "Unable to create I/O context\n");
1505                 return NULL;
1506         }
1507         
1508         /* Add an I/O event to our UDP socket */
1509         if (sipsock > -1) 
1510                 ast_io_add(io, sipsock, sipsock_read, AST_IO_IN, NULL);
1511         
1512         /* This thread monitors all the frame relay interfaces which are not yet in use
1513            (and thus do not have a separate thread) indefinitely */
1514         /* From here on out, we die whenever asked */
1515         for(;;) {
1516                 /* Check for interfaces needing to be killed */
1517                 ast_pthread_mutex_lock(&iflock);
1518 restartsearch:          
1519                 sip = iflist;
1520                 while(sip) {
1521                         if (sip->needdestroy) {
1522                                 __sip_destroy(sip);
1523                                 goto restartsearch;
1524                         }
1525                         sip = sip->next;
1526                 }
1527                 ast_pthread_mutex_unlock(&iflock);
1528                 /* Don't let anybody kill us right away.  Nobody should lock the interface list
1529                    and wait for the monitor list, but the other way around is okay. */
1530                 ast_pthread_mutex_lock(&monlock);
1531                 /* Lock the network interface */
1532                 ast_pthread_mutex_lock(&netlock);
1533                 p = packets;
1534                 while(p) {
1535                         /* Handle any retransmissions */
1536                         p = p->next;
1537                 }
1538                 /* Okay, now that we know what to do, release the network lock */
1539                 ast_pthread_mutex_unlock(&netlock);
1540                 /* And from now on, we're okay to be killed, so release the monitor lock as well */
1541                 ast_pthread_mutex_unlock(&monlock);
1542                 pthread_testcancel();
1543                 /* Wait for sched or io */
1544                 res = ast_sched_wait(sched);
1545                 res = ast_io_wait(io, res);
1546                 ast_pthread_mutex_lock(&monlock);
1547                 if (res >= 0) 
1548                         ast_sched_runq(sched);
1549                 ast_pthread_mutex_unlock(&monlock);
1550         }
1551         /* Never reached */
1552         return NULL;
1553         
1554 }
1555
1556 static int restart_monitor(void)
1557 {
1558         /* If we're supposed to be stopped -- stay stopped */
1559         if (monitor_thread == -2)
1560                 return 0;
1561         if (ast_pthread_mutex_lock(&monlock)) {
1562                 ast_log(LOG_WARNING, "Unable to lock monitor\n");
1563                 return -1;
1564         }
1565         if (monitor_thread == pthread_self()) {
1566                 ast_pthread_mutex_unlock(&monlock);
1567                 ast_log(LOG_WARNING, "Cannot kill myself\n");
1568                 return -1;
1569         }
1570         if (monitor_thread) {
1571                 /* Wake up the thread */
1572                 pthread_kill(monitor_thread, SIGURG);
1573         } else {
1574                 /* Start a new monitor */
1575                 if (pthread_create(&monitor_thread, NULL, do_monitor, NULL) < 0) {
1576                         ast_pthread_mutex_unlock(&monlock);
1577                         ast_log(LOG_ERROR, "Unable to start monitor thread.\n");
1578                         return -1;
1579                 }
1580         }
1581         ast_pthread_mutex_unlock(&monlock);
1582         return 0;
1583 }
1584
1585 static struct ast_channel *sip_request(char *type, int format, void *data)
1586 {
1587         int oldformat;
1588         struct sip_pvt *p;
1589         struct ast_channel *tmp = NULL;
1590         /* We can only support G.723.1 formatted frames, but we should never
1591            be asked to support anything else anyway, since we've published
1592            our capabilities when we registered. */
1593         oldformat = format;
1594         format &= capability;
1595         if (!format) {
1596                 ast_log(LOG_NOTICE, "Asked to get a channel of unsupported format '%d'\n", format);
1597                 return NULL;
1598         }
1599         p = sip_alloc(NULL, NULL);
1600         if (!p) {
1601                 ast_log(LOG_WARNING, "Unable to build sip pvt data for '%s'\n", (char *)data);
1602                 return NULL;
1603         }
1604         tmp = sip_new(p, AST_STATE_DOWN);
1605         restart_monitor();
1606         return tmp;
1607 }
1608
1609 static struct sip_user *build_user(char *name, struct ast_variable *v)
1610 {
1611         struct sip_user *user;
1612         int format;
1613         user = (struct sip_user *)malloc(sizeof(struct sip_user));
1614         if (user) {
1615                 memset(user, 0, sizeof(struct sip_user));
1616                 strncpy(user->name, name, sizeof(user->name)-1);
1617                 while(v) {
1618                         if (!strcasecmp(v->name, "context")) {
1619                                 strncpy(user->context, v->value, sizeof(user->context));
1620                         } else if (!strcasecmp(v->name, "permit") ||
1621                                            !strcasecmp(v->name, "deny")) {
1622                                 user->ha = ast_append_ha(v->name, v->value, user->ha);
1623                         } else if (!strcasecmp(v->name, "auth")) {
1624                                 strncpy(user->methods, v->value, sizeof(user->methods)-1);
1625                         } else if (!strcasecmp(v->name, "secret")) {
1626                                 strncpy(user->secret, v->value, sizeof(user->secret)-1);
1627                         } else if (!strcasecmp(v->name, "callerid")) {
1628                                 strncpy(user->callerid, v->value, sizeof(user->callerid)-1);
1629                                 user->hascallerid=1;
1630                         } else if (!strcasecmp(v->name, "accountcode")) {
1631                                 strncpy(user->accountcode, v->value, sizeof(user->accountcode)-1);
1632                         } else if (!strcasecmp(v->name, "amaflags")) {
1633                                 format = ast_cdr_amaflags2int(v->value);
1634                                 if (format < 0) {
1635                                         ast_log(LOG_WARNING, "Invalid AMA Flags: %s at line %d\n", v->value, v->lineno);
1636                                 } else {
1637                                         user->amaflags = format;
1638                                 }
1639                         } else if (!strcasecmp(v->name, "insecure")) {
1640                                 user->insecure = ast_true(v->value);
1641                         }
1642                         v = v->next;
1643                 }
1644         }
1645         if (!strlen(user->methods)) {
1646                 if (strlen(user->secret)) 
1647                         strncpy(user->methods, "md5,plaintext", sizeof(user->methods) - 1);
1648         }
1649         return user;
1650 }
1651
1652 static struct sip_peer *build_peer(char *name, struct ast_variable *v)
1653 {
1654         struct sip_peer *peer;
1655         struct sip_peer *prev;
1656         int maskfound=0;
1657         int format;
1658         int found=0;
1659         prev = NULL;
1660         ast_pthread_mutex_lock(&peerl.lock);
1661         peer = peerl.peers;
1662         while(peer) {
1663                 if (!strcasecmp(peer->name, name)) {    
1664                         break;
1665                 }
1666                 prev = peer;
1667                 peer = peer->next;
1668         }
1669         if (peer) {
1670                 found++;
1671                 /* Already in the list, remove it and it will be added back (or FREE'd) */
1672                 if (prev) {
1673                         prev->next = peer->next;
1674                 } else {
1675                         peerl.peers = peer->next;
1676                 }
1677                 ast_pthread_mutex_unlock(&peerl.lock);
1678         } else {
1679                 ast_pthread_mutex_unlock(&peerl.lock);
1680                 peer = malloc(sizeof(struct sip_peer));
1681                 memset(peer, 0, sizeof(struct sip_peer));
1682                 peer->expire = -1;
1683         }
1684         if (peer) {
1685                 if (!found) {
1686                         strncpy(peer->name, name, sizeof(peer->name)-1);
1687                         peer->addr.sin_port = htons(DEFAULT_SIP_PORT);
1688                         peer->expirey = expirey;
1689                 }
1690                 peer->capability = capability;
1691                 while(v) {
1692                         if (!strcasecmp(v->name, "secret")) 
1693                                 strncpy(peer->secret, v->value, sizeof(peer->secret)-1);
1694                         else if (!strcasecmp(v->name, "auth")) 
1695                                 strncpy(peer->methods, v->value, sizeof(peer->methods)-1);
1696                         else if (!strcasecmp(v->name, "host")) {
1697                                 if (!strcasecmp(v->value, "dynamic")) {
1698                                         /* They'll register with us */
1699                                         peer->dynamic = 1;
1700                                         if (!found) {
1701                                                 /* Initialize stuff iff we're not found, otherwise
1702                                                    we keep going with what we had */
1703                                                 memset(&peer->addr.sin_addr, 0, 4);
1704                                                 if (peer->addr.sin_port) {
1705                                                         /* If we've already got a port, make it the default rather than absolute */
1706                                                         peer->defaddr.sin_port = peer->addr.sin_port;
1707                                                         peer->addr.sin_port = 0;
1708                                                 }
1709                                         }
1710                                 } else {
1711                                         /* Non-dynamic.  Make sure we become that way if we're not */
1712                                         if (peer->expire > -1)
1713                                                 ast_sched_del(sched, peer->expire);
1714                                         peer->expire = -1;
1715                                         peer->dynamic = 0;
1716                                         if (ast_get_ip(&peer->addr, v->value)) {
1717                                                 free(peer);
1718                                                 return NULL;
1719                                         }
1720                                 }
1721                                 if (!maskfound)
1722                                         inet_aton("255.255.255.255", &peer->mask);
1723                         } else if (!strcasecmp(v->name, "defaultip")) {
1724                                 if (ast_get_ip(&peer->defaddr, v->value)) {
1725                                         free(peer);
1726                                         return NULL;
1727                                 }
1728                         } else if (!strcasecmp(v->name, "permit") ||
1729                                            !strcasecmp(v->name, "deny")) {
1730                                 peer->ha = ast_append_ha(v->name, v->value, peer->ha);
1731                         } else if (!strcasecmp(v->name, "mask")) {
1732                                 maskfound++;
1733                                 inet_aton(v->value, &peer->mask);
1734                         } else if (!strcasecmp(v->name, "port")) {
1735                                 if (peer->dynamic)
1736                                         peer->defaddr.sin_port = htons(atoi(v->value));
1737                                 else
1738                                         peer->addr.sin_port = htons(atoi(v->value));
1739                         } else if (!strcasecmp(v->name, "username")) {
1740                                 strncpy(peer->username, v->value, sizeof(peer->username)-1);
1741                         } else if (!strcasecmp(v->name, "allow")) {
1742                                 format = ast_getformatbyname(v->value);
1743                                 if (format < 1) 
1744                                         ast_log(LOG_WARNING, "Cannot allow unknown format '%s'\n", v->value);
1745                                 else
1746                                         peer->capability |= format;
1747                         } else if (!strcasecmp(v->name, "disallow")) {
1748                                 format = ast_getformatbyname(v->value);
1749                                 if (format < 1) 
1750                                         ast_log(LOG_WARNING, "Cannot disallow unknown format '%s'\n", v->value);
1751                                 else
1752                                         peer->capability &= ~format;
1753                         } else if (!strcasecmp(v->name, "insecure")) {
1754                                 peer->insecure = ast_true(v->value);
1755                         }
1756
1757                         v=v->next;
1758                 }
1759                 if (!strlen(peer->methods))
1760                         strcpy(peer->methods, "md5,plaintext");
1761                 peer->delme = 0;
1762         }
1763         return peer;
1764 }
1765
1766 int load_module()
1767 {
1768         struct ast_config *cfg;
1769         struct ast_variable *v;
1770         struct sip_peer *peer;
1771         struct sip_user *user;
1772         char *cat;
1773     char *utype;
1774         struct hostent *hp;
1775         
1776         if (gethostname(ourhost, sizeof(ourhost))) {
1777                 ast_log(LOG_WARNING, "Unable to get hostname, SIP disabled\n");
1778                 return 0;
1779         }
1780         hp = gethostbyname(ourhost);
1781         if (!hp) {
1782                 ast_log(LOG_WARNING, "Unable to get our IP address, SIP disabled\n");
1783                 return 0;
1784         }
1785         memcpy(&ourip, hp->h_addr, sizeof(ourip));
1786         cfg = ast_load(config);
1787
1788         /* We *must* have a config file otherwise stop immediately */
1789         if (!cfg) {
1790                 ast_log(LOG_NOTICE, "Unable to load config %s, SIP disabled\n", config);
1791                 return 0;
1792         }
1793         memset(&bindaddr, 0, sizeof(bindaddr));
1794         v = ast_variable_browse(cfg, "general");
1795         while(v) {
1796                 /* Create the interface list */
1797                 if (!strcasecmp(v->name, "context")) {
1798                         strncpy(context, v->value, sizeof(context)-1);
1799                 } else if (!strcasecmp(v->name, "language")) {
1800                         strncpy(language, v->value, sizeof(language)-1);
1801                 } else if (!strcasecmp(v->name, "bindaddr")) {
1802                         if (!(hp = gethostbyname(v->value))) {
1803                                 ast_log(LOG_WARNING, "Invalid address: %s\n", v->value);
1804                         } else {
1805                                 memcpy(&bindaddr.sin_addr, hp->h_addr, sizeof(bindaddr.sin_addr));
1806                         }
1807                 } else if (!strcasecmp(v->name, "port")) {
1808                         if (sscanf(v->value, "%i", &ourport) == 1) {
1809                                 bindaddr.sin_port = htons(ourport);
1810                         } else {
1811                                 ast_log(LOG_WARNING, "Invalid port number '%s' at line %d of %s\n", v->value, v->lineno, config);
1812                         }
1813                 }
1814                 v = v->next;
1815         }
1816         
1817         cat = ast_category_browse(cfg, NULL);
1818         while(cat) {
1819                 if (strcasecmp(cat, "general")) {
1820                         utype = ast_variable_retrieve(cfg, cat, "type");
1821                         if (utype) {
1822                                 if (!strcasecmp(utype, "user") || !strcasecmp(utype, "friend")) {
1823                                         user = build_user(cat, ast_variable_browse(cfg, cat));
1824                                         if (user) {
1825                                                 ast_pthread_mutex_lock(&userl.lock);
1826                                                 user->next = userl.users;
1827                                                 userl.users = user;
1828                                                 ast_pthread_mutex_unlock(&userl.lock);
1829                                         }
1830                                 }
1831                                 if (!strcasecmp(utype, "peer") || !strcasecmp(utype, "friend")) {
1832                                         peer = build_peer(cat, ast_variable_browse(cfg, cat));
1833                                         if (peer) {
1834                                                 ast_pthread_mutex_lock(&peerl.lock);
1835                                                 peer->next = peerl.peers;
1836                                                 peerl.peers = peer;
1837                                                 ast_pthread_mutex_unlock(&peerl.lock);
1838                                         }
1839                                 } else if (strcasecmp(utype, "user")) {
1840                                         ast_log(LOG_WARNING, "Unknown type '%s' for '%s' in %s\n", utype, cat, "sip.conf");
1841                                 }
1842                         } else
1843                                 ast_log(LOG_WARNING, "Section '%s' lacks type\n", cat);
1844                 }
1845                 cat = ast_category_browse(cfg, cat);
1846         }
1847         
1848         if (!ntohs(bindaddr.sin_port))
1849                 bindaddr.sin_port = ntohs(DEFAULT_SIP_PORT);
1850         bindaddr.sin_family = AF_INET;
1851         pthread_mutex_lock(&netlock);
1852         if (sipsock > -1)
1853                 close(sipsock);
1854         sipsock = socket(AF_INET, SOCK_DGRAM, 0);
1855         if (sipsock < 0) {
1856                 ast_log(LOG_WARNING, "Unable to create SIP socket: %s\n", strerror(errno));
1857         } else {
1858                 if (bind(sipsock, (struct sockaddr *)&bindaddr, sizeof(bindaddr)) < 0) {
1859                         ast_log(LOG_WARNING, "Failed to bind to %s:%d: %s\n",
1860                                         inet_ntoa(bindaddr.sin_addr), ntohs(bindaddr.sin_port),
1861                                                 strerror(errno));
1862                         close(sipsock);
1863                         sipsock = -1;
1864                 } else if (option_verbose > 1)
1865                         ast_verbose(VERBOSE_PREFIX_2 "SIP Listening on %s:%d\n", 
1866                                 inet_ntoa(bindaddr.sin_addr), ntohs(bindaddr.sin_port));
1867         }
1868         pthread_mutex_unlock(&netlock);
1869
1870         /* Make sure we can register our sip channel type */
1871         if (ast_channel_register(type, tdesc, capability, sip_request)) {
1872                 ast_log(LOG_ERROR, "Unable to register channel class %s\n", type);
1873                 ast_destroy(cfg);
1874                 return -1;
1875         }
1876         ast_destroy(cfg);
1877         /* And start the monitor for the first time */
1878         restart_monitor();
1879         return 0;
1880 }
1881
1882 int unload_module()
1883 {
1884         struct sip_pvt *p, *pl;
1885         /* First, take us out of the channel loop */
1886         ast_channel_unregister(type);
1887         if (!ast_pthread_mutex_lock(&iflock)) {
1888                 /* Hangup all interfaces if they have an owner */
1889                 p = iflist;
1890                 while(p) {
1891                         if (p->owner)
1892                                 ast_softhangup(p->owner);
1893                         p = p->next;
1894                 }
1895                 iflist = NULL;
1896                 ast_pthread_mutex_unlock(&iflock);
1897         } else {
1898                 ast_log(LOG_WARNING, "Unable to lock the monitor\n");
1899                 return -1;
1900         }
1901         if (!ast_pthread_mutex_lock(&monlock)) {
1902                 if (monitor_thread) {
1903                         pthread_cancel(monitor_thread);
1904                         pthread_kill(monitor_thread, SIGURG);
1905                         pthread_join(monitor_thread, NULL);
1906                 }
1907                 monitor_thread = -2;
1908                 ast_pthread_mutex_unlock(&monlock);
1909         } else {
1910                 ast_log(LOG_WARNING, "Unable to lock the monitor\n");
1911                 return -1;
1912         }
1913
1914         if (!ast_pthread_mutex_lock(&iflock)) {
1915                 /* Destroy all the interfaces and free their memory */
1916                 p = iflist;
1917                 while(p) {
1918                         pl = p;
1919                         p = p->next;
1920                         /* Free associated memory */
1921                         free(pl);
1922                 }
1923                 iflist = NULL;
1924                 ast_pthread_mutex_unlock(&iflock);
1925         } else {
1926                 ast_log(LOG_WARNING, "Unable to lock the monitor\n");
1927                 return -1;
1928         }
1929                 
1930         return 0;
1931 }
1932
1933 int usecount()
1934 {
1935         int res;
1936         ast_pthread_mutex_lock(&usecnt_lock);
1937         res = usecnt;
1938         ast_pthread_mutex_unlock(&usecnt_lock);
1939         return res;
1940 }
1941
1942 char *key()
1943 {
1944         return ASTERISK_GPL_KEY;
1945 }
1946
1947 char *description()
1948 {
1949         return desc;
1950 }
1951