summaryrefslogtreecommitdiff
path: root/main.c
blob: 18b99006b99831ef436e628bfbe3a153abeca1d7 (plain)
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
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
#include <asm-generic/errno-base.h>
#include <asm-generic/errno.h>
#include <netinet/in.h>
#include <stdio.h>
#include <stdio_ext.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <sys/epoll.h>
#include <sys/sendfile.h>
#include <fcntl.h>
#include <unistd.h>
#include <poll.h>

#include <err.h>
#include <errno.h>

#include <pthread.h>
#include <stdarg.h>


void send_answer(FILE * f) {
	fputs("HTTP/1.0 200 OK\n", f);
	fputs("content-type: text/html\n\n", f);
	fputs("<html>", f);
	fputs("<head>", f);
	fputs("<title>test</title>", f);
	fputs("<style>label { display:block }</style>", f);
	fputs("</head>", f);
	fputs("<form action=\"/\" method=\"post\" enctype=\"multipart/form-data\">", f);
	fputs("<label>Line1<br/>\n", f);
	fputs("<textarea type=\"text\" name=\"text\"></textarea>", f);
	fputs("</label><br/>\n", f);
	fputs("<input type=\"file\" name=\"okay\" value=\"ok\" />", f);
	fputs("<input type=\"submit\" name=\"okay\" value=\"ok\" />", f);
	fputs("</form>", f);
	fputs("</html>", f);
}


#define EWOULDBLOCK_DELAY   1000
#define READ_BUFFER_LENGTH  10
#define DEBUG_SLEEP_TIME    50000

static inline int verbose(const char * format, ...) {
	va_list va; va_start(va, format); usleep(DEBUG_SLEEP_TIME); return vprintf(format, va);
}


void read_everything(FILE * f_r, FILE * output) {
	const int read_buffer_length = READ_BUFFER_LENGTH;
	char read_buffer[read_buffer_length];
	for(size_t size = -2 ; ; size = fread(read_buffer, read_buffer_length, 1, f_r)) {
		if(-2 == size || (-1 == size && EWOULDBLOCK == errno)) {
			usleep(EWOULDBLOCK_DELAY); // try again a little later
			continue;
		}

		fwrite(read_buffer, read_buffer_length, 1, output);
		fwrite(read_buffer, read_buffer_length, 1, stdout);

		if (1 != size) { // I expect one nmemb of data
			break;
		}
	}
	fflush(stdout);
	fflush(output);
}

void header_next(const char * key, const char * value) {
	// this sample function will be removed later
	typedef struct {
		const char * name;
		const char * value;
	} NameValue;

	NameValue namevalue[] = {
		{"Content-Type", NULL},
		{"Content-Length", NULL}
	};
	for(int i=0; i < sizeof(namevalue) / sizeof(NameValue); i++) {
		// printf("next name: %s\n", namevalue[i].name);
		if(NULL == namevalue[i].value && 0 == strcasecmp(namevalue[i].name, key)) {
			namevalue[i].value = value;
			break;
		}
	}
}

typedef struct {
	int newline_length; // lenght of one newline in bytes (\n has 1, CR/LF has 2)
	char * method;
	char * boundary;
	size_t boundary_size;
	char * content_type;
	char * content_disposition;
} Http_Header;

void * next_customer(size_t new_socket) {
	FILE * f_r = fdopen((size_t) new_socket, "rw");

	char * output_buffer = NULL;
	size_t output_buffer_length = 0;
	FILE * output = open_memstream(&output_buffer, &output_buffer_length);

	verbose("\n\n########################################## Content Reader [%d]\n", f_r);
	read_everything(f_r, output);
	shutdown(new_socket, SHUT_RD); // shutdown the reading half of the connection
	verbose("\n\n########################################## Content Parser\n");

	// token parser...
	char * key = output_buffer;

	char * saveptr = NULL;

	char * start = output_buffer;
	char * end = NULL;
	char * search = "\r\n";

	Http_Header http_header;
	http_header.boundary_size = 0;
	http_header.newline_length = 1;
	http_header.method = NULL;
	http_header.boundary = NULL;
	http_header.content_disposition = NULL;
	http_header.content_type = NULL;

	char * name = NULL;
	// while(NULL != (end = strpbrk(start, search))) {
	while(NULL != (end = strpbrk(start, search))) {
		// verbose("\033[31m[%ld|%ld|%ld]\033[0m\n", start - output_buffer, end - start, end - output_buffer);

		size_t matchlen = strspn(end, search);
		switch(end[0]) {
			case ':':
				end[0] = '\0';
				end++;

				name = start;

				if (0 == strcasecmp("Content-Type", start)) {
					search = "\r\n;";
				} else {
					search = "\r\n";
				}
				break;
			case ';':
				{
					start += strspn(start, "; ");

					const char s_multipart_form_data[] = "boundary=";
					if(NULL == http_header.boundary && 0 < strcasecmp(start, s_multipart_form_data))
					{
						http_header.boundary = end + sizeof(s_multipart_form_data) + 1;
						http_header.boundary += strspn(http_header.boundary, "-");
						// verbose("GESCHAFFT %s [%ld] QQQQ %s\n", http_header.boundary, http_header.boundary_size, end);
						search = "\r\n";
						continue;
					}
					break;
				}
			case '\r': // fallthrough
			case '\n':
				end[0] = '\0';
				search = ":"; // we will continue to search for headers


				if(NULL == name) {
					if(NULL == http_header.method) {
						verbose("[%ld]> HTTP REQUEST LINE :: %s \n", matchlen, start);
						http_header.method = start;
						http_header.newline_length = matchlen;
					} else {
						verbose("[...]\n"); // if we want to intentially skip something, we land here by setting name = NUL;
						break;
					}
				} else { // we know that name is not NULL and can work with it
					if (0 == strcasecmp("Content-Disposition", name))
					{ http_header.content_disposition = start; }
				}

				verbose("\033[32m[%ld]> '% 20s' = '%s'\033[0m\n", matchlen, name, start);

				if(matchlen > http_header.newline_length) {
					verbose("> END HEADERS, because there were %d newlines; boundary='%s'[%ld]\n", matchlen / http_header.newline_length, http_header.boundary, http_header.boundary_size);
					end += matchlen;

					// if it was the first header, we calculate the boundary size and expect more headers to come after a boundary
					if(http_header.boundary && http_header.boundary_size == 0) {
						verbose("================================================================================\n");
						http_header.boundary_size = strlen(http_header.boundary);
						// skip the first header and boundary...
						start = end;
						start += strspn(start, "-");
						start += http_header.boundary_size;
						start += http_header.newline_length;
						continue;
					} else {
						char * content_start = end;
						while(1)
						{
							size_t size_remaining = (size_t)  output_buffer_length - (end - output_buffer) - 1;
							verbose("%ld remaining.\n", size_remaining); fflush(stdout);

							if(size_remaining <= 0) {
								verbose("> not even the boundary would fit in that what is left.\n");
								break;
							}

							if(NULL == (end = memchr((void*) end, '-', size_remaining))) {
								verbose("no further '-' found\n");
								break;
							}

							char * content_end = end - http_header.newline_length;


							end += strspn(end, "-");
							if(0 == strncmp(end, http_header.boundary, http_header.boundary_size)) {
								size_t file_size = content_end - content_start;
								verbose("> Content ends here, size of the last file is %ld: {begin}", file_size);
								fwrite(content_start, file_size, 1, stdout);
								verbose("{end}\n");


								// puts(" <[last 20 bytes]\n");


								end += http_header.boundary_size;
								matchlen = strspn(end, "\r\n");
								// matchlen = http_header.boundary_size;
								verbose("> end is at %p, matchlen is %ld\n", end, matchlen);


								search = ":";
								break;
							} else {
								// printf("[%ld] kack: %c\n", size_remaining, p[0]); fflush(stdout);
								end = end + 1;
							}
						}
					}
					/*
					char * content_start = end;
					content_start += strspn(content_start, "-");
					// verbose("CONTENT: %s\n", content_start);
					if(0 <= strcmp(content_start, http_header.boundary)) {
						verbose("MATCH for %s // %s\n", http_header.content_type, http_header.content_disposition);

						search = "\r\n";
						matchlen = http_header.boundary_size;
						name = NULL;
					} else {
						verbose("NO MATCH\n");
					}
					*/
					break;
				}
		}

		// verbose("> end is at %p, matchlen is %ld\n", end, matchlen);
		start = end + matchlen;
		// fwrite(start, 42, 1, stdout);
		// printf(" <[first 42 bytes of new start; matchlen was %ld; searching for %s\n", matchlen, search);
	}
	printf("last known position: %p / %p with %s\n", start, end, search);

	if(http_header.boundary)
		verbose("http-boundary: %s", http_header.boundary);

	verbose("> sending answer...");
	send_answer(f_r);
	fclose(f_r);

	verbose("> answer sent.");

	return NULL;
}



int serve(int server_fd)
{
  struct sockaddr_in address;
	socklen_t address_len = sizeof(address);
  verbose("waiting for connections on server file descriptor %d", server_fd);

	size_t new_socket = -1;
  while(-1 != (new_socket = accept(server_fd, (struct sockaddr*) &address, &address_len)))
  {
		verbose("> Client %ld is connected via port %d", new_socket, address.sin_port);

		// set non blocking mode...
		fcntl(
			(size_t) new_socket,
			F_SETFL,
			fcntl((size_t) new_socket, F_GETFL) | O_NONBLOCK
		);

		next_customer(new_socket);

		/*
		if(fork()) {
			close(new_socket);
		} else {
			close(server_fd); // give the server free
			next_customer(new_socket);
			shutdown(new_socket, SHUT_RDWR);
			exit(0);
		}
		*/

		// pthread_t thread_id;
		// pthread_create(&thread_id, NULL, next_customer, (void*) new_socket);
		// pthread_join(thread_id, NULL);
  }

	err(errno, "error serving");
}

#define PORT 8080
int main(int argc, char const *argv[])
{
  int server_fd = -1, opt = 1;

  struct sockaddr_in address = {
		.sin_family              = AF_INET,
		.sin_addr.s_addr         = INADDR_ANY,
		.sin_port                = htons(PORT)
	};

	// I <3 C
  0 == (server_fd = socket(AF_INET, SOCK_STREAM, 0))
  ? err(errno, NULL)
  : setsockopt(server_fd, SOL_SOCKET, SO_REUSEADDR | SO_REUSEPORT, &opt, sizeof(opt))
  ? err(errno, "setsockopt failed on socket with fileno %d", server_fd)
  : bind(server_fd, (struct sockaddr*) &address, sizeof(address))
  ? err(errno, NULL)
  : listen(server_fd, SOMAXCONN)
  ? err(errno, NULL)
  : serve(server_fd)
	? err(errno, NULL)
	: exit(EXIT_SUCCESS)
	;
  return EXIT_FAILURE;
}

// void * next_customer_old(int new_socket)
// {
//   char *hello = "Hello from server";
//   char buffer[1024] = {0};
//   int valread = read(new_socket, buffer, 1024);
//   printf("%s %d\n", buffer, valread);
//
//   send(new_socket, hello, strlen(hello), 0);
//
//   printf("Hello message sent\n");
//   return NULL;
// }

// IDEA ...
//
// #define FOREACH_HEADER(HEADER) \
// 	HEADER("Content-Type: multipart/form-data; boundary=")
// #define GENERATE_HEADERS(H) sizeof(H), H
//
// typedef struct {
// 	const int length;
// 	const char * string;
// } length_value;
//
// const length_value headers[] = {
// 	FOREACH_HEADER(GENERATE_HEADERS)
// };
//


// READ WITH recv ...
	/*
	for(size_t size = -1 ; ; (size = recv(new_socket, read_buffer, read_buffer_length, 0))) {
		if(-1 == size) {
			usleep(10000);
			printf("size: %ld\n", size);
			if(EWOULDBLOCK == errno){
				continue;
			} else if (size == 0 || size < read_buffer_length) {
				break;
			}
		} else {
			read_buffer[size] = '\0';

			fwrite(read_buffer, size, 1, output);
			fwrite(read_buffer, size, 1, stdout);

			// if(output_buffer_length > 4
			// && (strspn(&output_buffer[output_buffer_length - 2], "\n") == 2
			// ||  strspn(&output_buffer[output_buffer_length - 4], "\r\n") == 4))
			// 	break;
		}
	}*/


// fully working implementation...
/*
void * next_customer(void * new_socket) {

	const int MAX_HEADER_LINE_LENGTH = 1024;
	const int MAX_BOUNDARY_LENGTH = 64;

	char boundary[64] = {0};
	int boundary_size = 0;

	char current_name[64] = {0};

	usleep(100); // wait to avoid poll, epoll or evil select

	char * output_buffer = NULL;
	size_t output_buffer_length = 0;
	FILE * output = open_memstream(&output_buffer, &output_buffer_length);

	FILE * f = fdopen((size_t) new_socket, "r");
	char buffer[MAX_HEADER_LINE_LENGTH];
	char * s = NULL;
	while(1) {
		// printf("[errno: %d] %s", errno, buffer);
		s = fgets(buffer, MAX_HEADER_LINE_LENGTH, f);

		if(boundary[0] != '\0' && buffer[0] == '-') { // first char minus. could be a new chunk of post data
			int i = 0;
			for(i = 1; i < MAX_HEADER_LINE_LENGTH; i++) {
				if(buffer[i] != '-') { // skip all minus
					if(0 == strncmp(&buffer[i], boundary, boundary_size)) {
							fflush(output);
							printf("> name='%s' value='%*s'\n", current_name, (int) output_buffer_length, output_buffer);
							setenv(current_name, output_buffer, 0);
							current_name[0] = '\0';
							rewind(output);
							i = 0;

							puts("================================================================================");
					}
					break;
				}
			}
			if (i == 0) continue;
		}


		if(!s || strspn(buffer, "\n\r") > 0) { // either LF or CR/LF (windows)
			puts("END HEADER\n");
			// s != NULL ? break : continue;
			if(!s) break; else continue; // either eof or only end of (chunk-)header
		}

		const char header_multipart[] = "Content-Type: multipart/form-data; boundary=";
		if (!boundary[0] && 0 == strncasecmp(buffer, header_multipart, sizeof(header_multipart) - 1)) {
			// we could potentially optimize this part with strspn and moving the buffer point, why not?
			for(int i=sizeof(header_multipart); i<MAX_HEADER_LINE_LENGTH; i++)
				if(buffer[i] != '-') {
					strncpy(boundary, &buffer[i], 64);
					boundary_size = strnlen(boundary, 64);
					boundary[boundary_size] = '\0';
					printf("> [%s] %s\n", header_multipart, boundary);
					break;
				}
			continue;
		}

		const char header_disposition[] = "Content-Disposition: form-data; ";
		if (boundary[0] && 0 == strncasecmp(header_disposition, buffer, sizeof(header_disposition) - 1)) {
			printf("> %s :: %s\n", header_disposition, buffer);
			const char header_disposition_name[] = "name=\"";
			s = strstr(&buffer[sizeof(header_disposition) - 1], header_disposition_name);
			if(s) {
				s += sizeof(header_disposition_name) - 1;
				s[strcspn(s, "\"")] = '\0';
				strncpy(current_name, s, 64);
				printf("> /%s.*%s/ :: \"%s\"\n", header_disposition, header_disposition_name, s);
			} else {
				warnx("string not found in \"%s\".", &buffer[sizeof(header_disposition)]);
			}
			continue;
		}// else { printf("FUCK: %*s [%d/%ld]\n", (int) sizeof(header_disposition), buffer, strncasecmp(header_disposition, buffer, sizeof(header_disposition)), sizeof(header_disposition)); }

		printf("> [unknown] %s", buffer);
		fputs(buffer, output);


		// I think another if could now search for "Content-Disposition: form-data; " and store the remaining fields
		// somewhere, e.g. name="okay"; filename="1.gif". Also there may also be a content-type per chunk, which we
		// could also add and erase, where I have currently NEXT CHUNK.
		// After that the text output (printf("%s", buffer)) will only contain content without headers, so that printf
		// can then be replaced with some fwrite to a memstream and we are done :)
	}

	puts("> sending answer...");
	send_answer(new_socket);
	puts("> answer sent.");

	return NULL;
}
*/
// vim: shiftwidth=2 tabstop=2 number foldmethod=marker
..