142 protocol_status(sn, rq, 200, NULL); |
145 protocol_status(sn, rq, 200, NULL); |
143 http_start_response(sn, rq); |
146 http_start_response(sn, rq); |
144 net_write(sn->csd, "Hello World!\n", 13); |
147 net_write(sn->csd, "Hello World!\n", 13); |
145 return REQ_PROCEED; |
148 return REQ_PROCEED; |
146 } |
149 } |
|
150 |
|
151 int service_index(pblock *pb, Session *sn, Request *rq) { |
|
152 printf("service_index\n"); |
|
153 |
|
154 char *ppath = pblock_findkeyval(pb_key_ppath, rq->vars); |
|
155 char *uri = pblock_findkeyval(pb_key_uri, rq->reqpb); |
|
156 |
|
157 sstr_t r_uri = sstr(uri); |
|
158 |
|
159 /* open the file */ |
|
160 int fd = open(ppath, O_RDONLY); |
|
161 if(fd < 0) { |
|
162 perror("service_index: open"); |
|
163 |
|
164 int status = 500; |
|
165 switch(errno) { |
|
166 case EACCES: { |
|
167 status = 403; |
|
168 break; |
|
169 } |
|
170 case ENOENT: { |
|
171 status = 404; |
|
172 break; |
|
173 } |
|
174 } |
|
175 protocol_status(sn, rq, status, NULL); |
|
176 printf("REQ_ABORTED\n"); |
|
177 return REQ_ABORTED; |
|
178 } |
|
179 |
|
180 DIR *dir = fdopendir(fd); |
|
181 if(dir == NULL) { |
|
182 protocol_status(sn, rq, 500, NULL); |
|
183 printf("DIR is null\n"); |
|
184 return REQ_ABORTED; |
|
185 } |
|
186 |
|
187 sbuf_t *out = sbuf_new(1024); /* output buffer */ |
|
188 |
|
189 /* write html header */ |
|
190 sbuf_puts(out, "<html>\n<head>\n<title>Index of "); |
|
191 sbuf_puts(out, uri); |
|
192 sbuf_puts(out, "</title>\n</head><body>\n<h1>Index of "); |
|
193 sbuf_puts(out, uri); |
|
194 sbuf_puts(out, "</h1><hr>\n\n"); |
|
195 |
|
196 struct dirent *f; |
|
197 while((f = readdir(dir)) != NULL) { |
|
198 if(strcmp(f->d_name, ".") == 0 || strcmp(f->d_name, "..") == 0) { |
|
199 continue; |
|
200 } |
|
201 |
|
202 sstr_t filename = sstr(f->d_name); |
|
203 |
|
204 sbuf_puts(out, "<a href=\""); |
|
205 sbuf_append(out, r_uri); |
|
206 sbuf_append(out, filename); |
|
207 sbuf_puts(out, "\">"); |
|
208 sbuf_append(out, filename); |
|
209 sbuf_puts(out, "</a><br>\n"); |
|
210 } |
|
211 |
|
212 sbuf_puts(out, "\n</body>\n</html>\n"); |
|
213 |
|
214 /* send stuff to client */ |
|
215 pblock_removekey(pb_key_content_type, rq->srvhdrs); |
|
216 pblock_kvinsert(pb_key_content_type, "text/html", 9, rq->srvhdrs); |
|
217 pblock_nninsert("content-length", out->length, rq->srvhdrs); |
|
218 protocol_status(sn, rq, 200, NULL); |
|
219 http_start_response(sn, rq); |
|
220 |
|
221 net_write(sn->csd, out->ptr, out->length); |
|
222 |
|
223 /* close */ |
|
224 closedir(dir); |
|
225 |
|
226 return REQ_PROCEED; |
|
227 } |