#include "include/httpd.h"
int parse(int i, hash *socket) {
char *a,*b,*c,*d;
if (!strcmp(socket[i].data,"\n")) {
sendpage(i,socket);
printf("Closed Socket\n");
// close(socket[i].socket);
// socket[i].socket = 0;
return -1;
}
if (strstr(socket[i].data,"Connection:")) {
a = strtok(socket[i].data," ");
b = strtok(NULL,"\n");
sprintf(socket[i].connection,b);
}
if (strstr(socket[i].data,"GET")) {
a = strtok(socket[i].data, " ");
b = strtok(NULL,"\n");
if (strstr(b, " ")) {
c = strtok(b, " ");
d = strtok(NULL, "\n");
}
if (!strcmp(b,"/")) {
sprintf(socket[i].location,"/index.html");
}
else {
sprintf(socket[i].location,b);
}
sprintf(socket[i].method,a);
if (strstr(b,"jpg")) { sprintf(socket[i].contenttype,"image/jpeg"); }
else if (strstr(b,"gif")) { sprintf(socket[i].contenttype,"image/gif"); }
else { sprintf(socket[i].contenttype,"text/html"); }
}
return -1;
}
int sendpage(int i,hash *socket) {
int ch,h;
char file[128],header[256];
char *input;
struct stat sb;
struct dirent *dp;
DIR *d;
printf("Sending Page [%i] - File: %s - File2: %c\n", i,socket[i].location,socket[i].location[strlen(socket[i].location)-1]);
if (socket[i].location[strlen(socket[i].location)-1] == '/') {
printf("Gotcha");
socket[i].location[strlen(socket[i].location)-1] = '\0';
}
sprintf(file, "/usr/home/reddawg/htdocs%s",socket[i].location);
if (stat(file,&sb) == -1) {
printf("Sorry File Does Not Exist\n");
sprintf(file,"/home/reddawg/htdocs/notfound.html");
stat(file,&sb);
}
printf("%ld\n",sb.st_mode);
if (sb.st_mode == 16877) {
sprintf(header, "HTTP/1.1 200 OK\nServer: UbieServer/0.1 (FreeBSD)\nConnection: close\nContent-Type: text/html\n\n");
}
else {
sprintf(header, "HTTP/1.1 200 OK\nServer: UbieServer/0.1 (FreeBSD)\nAccept-Ranges: bytes\nContent-Length: %ld\n", sb.st_size);
sprintf(header,"%sConnection: %s\n",header,socket[i].connection);
sprintf(header,"%sContent-Type: %s\n\n",header,socket[i].contenttype);
}
send_to_sock(socket[i].socket,header);
if (sb.st_mode == 16877) {
d = opendir(file);
while ((dp = readdir(d)) != NULL) {
if (!strcmp(dp->d_name,"..")) {
sprintf(file,"<A HREF=\"%s\">Parent Directory</A><BR>\n",socket[i].parentdir);
}
else if (!strcmp(dp->d_name,".")) { sprintf(file,""); }
else {
sprintf(file,"<A HREF=\"%s/%s\">%s</A><BR>\n",socket[i].location,dp->d_name,dp->d_name);
}
printf("Link: %s\n", file);
h = write(socket[i].socket,file,strlen(file));
printf("Dir: %i\n", h);
}
sprintf(socket[i].parentdir,socket[i].location);
closedir(d);
return(0);
}
fd = fopen(file,"rb");
input = malloc(1);
printf("Start Sending %s\n",file);
while((ch = fgetc(fd)) != EOF) {
sprintf(input, "%c", ch);
write(socket[i].socket,input,1);
}
printf("[%i]",strlen(input));
write(socket[i].socket,input,strlen(input));
printf("Done Sending\n");
return 0;
}