summaryrefslogtreecommitdiff
path: root/main.c
blob: 2bf2e144dde185b092a1149f5078376578506c7a (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
#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;
		} else if (1 != size) { // I expect one nmemb of data
			break;
		}

		fwrite(read_buffer, read_buffer_length, 1, output);
	}
	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;
		}
	}
}

void * next_customer(size_t new_socket) {
	FILE * f_r = fdopen((size_t) new_socket, "r");
	FILE * f_w = fdopen((size_t) new_socket, "w");

	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);
	verbose("\n\n########################################## Content Parser");


	// token parser...
	const char * boundary = NULL;
	size_t boundary_length = 0;
	char * search = NULL;
	char * key = output_buffer;

	char * saveptr = NULL;
	char * content_start = NULL;
	char * content_end = NULL;

	while(key ? key[0] != '\0' : 1) {
		verbose("> [!] Next iteration with search '%s'\n", search);
		for(char *
				token = strtok_r(NULL == saveptr ? output_buffer : saveptr, NULL == search ? "\n\r" : search, &saveptr);
				token != NULL;
				token = strtok_r(NULL, search, &saveptr))
		{

			if(!search) { // first round: HTTP status code
				verbose("> First Iteration: HTTP sanity check of: %s\n", token);
				search = ":";
				continue;
			}

			if(!key) {
				search = "\r\n"; // we found a key and expect the value to be between here and EOL
				key = &token[strspn(token, search)]; // also remove leading spaces

				if(0 == strncmp(token, "\n\r\n", 3)
				|| 0 == strncmp(token, "\n\n", 2)) {
					search = "\r\n";
					break;
				}
			} else { // value

				token += strspn(token, ": ");
				const char * value = token;

				const char pattern[] = "multipart/form-data; boundary=";
				if(!boundary && strstr(key, "Content-Type") && strncmp(value, pattern, sizeof(pattern))) {
					boundary = &value[sizeof(pattern) + strspn(&value[sizeof(pattern)], "-")];
					boundary_length = strlen(boundary);
					verbose("> [!] boundary detected '%s' ", boundary);
				}

				header_next(key, value);

				verbose("> [%ld] \"%s\" :: \"%s\"\n", key - output_buffer, key, value); fflush(stdout);

				search = ":";
				key = NULL;
			}
		}

		if(!key)
			break;
		// printf("We are now here: %ld\n", key - output_buffer);
		verbose("We are now here: %s\n", key);

		// jump over the content...
		content_start = key;
		while((key = memchr(key, '\n', output_buffer_length - (key - output_buffer)))) {
			if(!key) {
				verbose("out at %p\n", key);
				break;
			} else {
				key++;
			}

			if(key[0] == '-') {
				if(0 == strncmp(&key[strspn(key, "-")], boundary, boundary_length)) {
					verbose("> boundary found.");

					if(key[-1] == '\n') key--;
					if(key[-1] == '\r') key--;

					content_end = key;
					key += strspn(key, "\r\n-");
					key += boundary_length;
					key += strspn(key, "\r\n");
					saveptr = key;
					key = NULL;
					search = ":";
					break;
				}
			}
		}

		verbose("content is %p - %p = %ld in size\n", content_end, content_start, content_end - content_start);
		if(content_end - content_start > 1000) {
			FILE * f_w = fopen("/tmp/test.gif", "w");
			fwrite(content_start, content_end - content_start, 1, f_w);
			fclose(f_w);
			puts("FILE WRITTEN");
		}

		// printf("We have gone to %ld\n", key - output_buffer); fflush(stdout);
		if(key && key[0] == '\0') // final boundary reached?
			break;

		// usleep(100000);
	}

	verbose("> sending answer...");
	send_answer(f_w);

	fclose(f_w);
	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
..