1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
|
#include <sys/socket.h>
#include <sys/types.h>
#include <dirent.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#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;
}
|