/* A simple minimalistic httpd server * Copyright (c) Mohammed Sameer . * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ #include #include #include #include int main (int argc, char *argv[]) { int sockfd, newsockfd, clilen; int portno = 80; char buffer[256]; struct sockaddr_in serv_addr, cli_addr; int n; FILE *f = NULL; char *tmp = NULL; int enc = 0; char *root = "/var/www/"; char *file = (char *) malloc (sizeof (char) * 100); if (!file) { fprintf (stderr, "Couldn't allocate memory\n"); return 1; } if (argc >= 2) { enc = 1; } sockfd = socket (AF_INET, SOCK_STREAM, 0); if (sockfd < 0) { fprintf (stderr, "Couldn't open socket\n"); return 1; } bzero ((char *) &serv_addr, sizeof (serv_addr)); serv_addr.sin_family = AF_INET; serv_addr.sin_addr.s_addr = INADDR_ANY; serv_addr.sin_port = htons (portno); if (bind (sockfd, (struct sockaddr *) &serv_addr, sizeof (serv_addr)) < 0) { fprintf (stderr, "Couldn't bind socket\n"); return 1; } listen (sockfd, 5); clilen = sizeof (cli_addr); newsockfd = accept (sockfd, (struct sockaddr *) &cli_addr, &clilen); if (newsockfd < 0) { fprintf (stderr, "Couldn't accept connection\n"); return 1; } bzero (buffer, 256); n = read (newsockfd, buffer, 255); if (n < 0) { fprintf (stderr, "Couldn't read from socket\n"); return 1; } tmp = buffer; tmp += 4; n = 0; while (1) { if (buffer[n + 4] == ' ') { break; } ++n; } strncpy (file, &buffer[4], n); printf ("Got: %s\n File: %s\n", buffer, file); tmp = (char *) malloc (sizeof (char) * 100); if (!tmp) { fprintf (stderr, "Couldn't allocate memory\n"); return 1; } sprintf (tmp, "%s/%s", root, file); f = fopen (tmp, "r"); if (!f) { fprintf (stderr, "Couldn't open file\n"); return 1; } if (enc == 1) { n = write (newsockfd, "HTTP/1.1 200 OK\nContent-Type: text/html; charset=windows-1252\n\n", 64); if (n < 0) { fprintf (stderr, "Couldn't writing to socket\n"); return 1; } } while (fread (buffer, 255, 1, f)) { n = write (newsockfd, buffer, strlen (buffer)); if (n < 0) { fprintf (stderr, "Couldn't writing to socket\n"); return 1; } } return 0; }