#include #include #include #include #include #include #include "log.h" #define GOPHERROOT "/tmp/gopherroot" #define GOPHERHOST "localhost" #define GOPHERPORT "70" static int sendall(int fd, const char *buf, size_t len) { size_t sent = 0; ssize_t n; while (sent < len) { n = send(fd, buf + sent, len - sent, 0); if (n == -1) { perror("send"); return -1; } sent += n; } return 0; } static int print_indexfile(int fd, const char *path) { FILE *f; char buf[512]; f = fopen(path, "r"); if (f == NULL) { perror("fopen"); return -1; } while (!feof(f)) { if (fgets(buf, sizeof(buf), f) == NULL) continue; if (sendall(fd, buf, strlen(buf)) == -1) { logmsg(LOG_INFO, "failed to send data"); return -1; fclose(f); } } fclose(f); return 0; } static int print_dir(int fd, const char *path) { DIR *root; struct dirent *node; char *buf; int type; size_t buflen; root = opendir(path); if (root == NULL) { perror("opendir"); return -1; } while ((node = readdir(root)) != NULL) { buflen = sizeof(type) + strlen(node->d_name) + strlen(GOPHERROOT) + strlen(GOPHERHOST) + strlen(GOPHERPORT) + 6; if ((buf = malloc(buflen)) == NULL) { perror("malloc"); return -1; } switch (node->d_type) { case 4: type = 1; break; case 8: type = 0; break; } sprintf(buf, "%d%s %s %s %s\r\n", type, node->d_name, GOPHERROOT, "localhost", "3000"); if (sendall(fd, buf, buflen) == -1) { logmsg(LOG_INFO, "failed to send data"); free(buf); return -1; } free(buf); } closedir(root); return 0; } int handle_path(int fd, const char *path) { const char *data; if (strcmp(path, "") == 0 || strcmp(path, "/") == 0) { if (print_indexfile(fd, "index.gph") == -1) { logmsg(LOG_INFO, "failed to send data"); return -1; } } else if (strcmp(path, "/list") == 0) { if (print_dir(fd, GOPHERROOT) == -1) { logmsg(LOG_INFO, "failed to send data"); return -1; } } else { data = ""; if (sendall(fd, data, strlen(data)) == -1) { logmsg(LOG_INFO, "failed to send data"); return -1; } } return 0; }