Example #1
0
/*
 * Reads an HTTP request from stream (fd), and writes an HTTP response
 * containing:
 *
 *   1) If user requested an existing file, respond with the file
 *   2) If user requested a directory and index.html exists in the directory,
 *      send the index.html file.
 *   3) If user requested a directory and index.html doesn't exist, send a list
 *      of files in the directory with links to each.
 *   4) Send a 404 Not Found response.
 */
void handle_files_request(int fd) {
  struct http_request*request=http_request_parse(fd);
  char*fullpath,*fullfullpath;
  struct stat st;
  
  if(0==strcmp("GET",request->method)){
    fullpath=conc(server_files_directory,request->path);
    if(0==stat(fullpath,&st)){ // file/dir exists
      if(S_ISREG(st.st_mode)){ // is file
	http_send_file(fd,fullpath);
      }else if(S_ISDIR(st.st_mode)){ // is dir
	fullfullpath=conc(fullpath,"/index.html");
	if(0==stat(fullfullpath,&st)){ // has an index.html
	  http_send_file(fd,fullfullpath);
	}else{ // hasnt. list files
	  DIR*d=opendir(fullpath);
	  struct dirent*di;
	  http_start_response(fd,200);
	  http_send_header(fd,"Content-type","text/html");
	  http_end_headers(fd);
	  while(NULL!=(di=readdir(d)))
	    http_send_anchor(fd,di->d_name);
	}
	free(fullfullpath);
      }
    }else{ // doesnt exist. error 404
      http_start_response(fd,404);
      http_send_header(fd,"Content-type","text/html");
      http_end_headers(fd);
      http_send_string(fd,"<center><p>ERROR 404</p></center>");
    }
    free(fullpath);
  }
}
Example #2
0
/*
 * Reads an HTTP request from stream (fd), and writes an HTTP response
 * containing:
 *
 *   1) If user requested an existing file, respond with the file
 *   2) If user requested a directory and index.html exists in the directory,
 *      send the index.html file.
 *   3) If user requested a directory and index.html doesn't exist, send a list
 *      of files in the directory with links to each.
 *   4) Send a 404 Not Found response.
 */
void handle_files_request(int fd)
{

  /* YOUR CODE HERE */

  struct http_request *request = http_request_parse(fd);

  http_start_response(fd, 200);
  http_send_header(fd, "Content-type", "text/html");
  http_end_headers(fd);
  http_send_string(fd, "<center><h1>Welcome to httpserver!</h1><hr><p>Nothing's here yet.</p></center>");

}
Example #3
0
int kvresponse_send(kvresponse_t *kvres, int sockfd) {
  int code = http_code_for_response_type(kvres->type);
  if (code < 0) return -1;

  struct http_outbound *msg = http_start_response(sockfd, code);
  if (!msg) return -1;

  char lenbuf[10] = "0";
  if (kvres->body)
    sprintf(lenbuf, "%ld", strlen(kvres->body));
  http_add_header(msg, "Content-Length", lenbuf);
  http_end_headers(msg);
  http_add_string(msg, kvres->body);

  return http_send_and_free(msg);
}