summaryrefslogtreecommitdiff
path: root/main.c
blob: 6613df02600f4d81618e2b4cf20be4024f778f05 (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
#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>



void send_answer(void * new_socket) {
	FILE * f = fdopen((size_t) new_socket, "w");
	puts("> sending answer...");
	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>\n\0", f);
	fflush(f);
	puts("> answer sent.");
	fclose(f);
}


// #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)
// };


void * next_customer(void * new_socket) {
	if (new_socket == 0) return NULL;

	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.");


	puts("> file closed.");
	//close((size_t) new_socket);
	// pthread_exit(EXIT_SUCCESS);
	return NULL;
}

void serve(int server_fd)
{
  struct sockaddr_in address;
  int addrlen = sizeof(address);
  warn("waiting for connections on %d", server_fd);

  for(size_t new_socket = 0
      ; 1 ; new_socket=accept(server_fd, (struct sockaddr*) &address, (socklen_t*) &addrlen))
  {
    warn("next: %ld\n", new_socket);
		// set non blocking mode...
		fcntl((size_t) new_socket, F_SETFL,
			fcntl((size_t) new_socket, F_GETFL) | O_NONBLOCK);

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

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

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

  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);

  return 0;
}

// vim: shiftwidth=2 tabstop=2 number
..