aboutsummaryrefslogtreecommitdiff
path: root/admin.c
blob: 2bd4b6ba690e17a8223bc1ee9c6100b4ce33439c (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
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
// Copyright 2021 Jeremias Stotter
//
// This file is part of ´JBlog´.
//
// ´JBlog´ is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// ´JBlog´ is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with ´JBlog´.  If not, see <http://www.gnu.org/licenses/>.

#define _POSIX_C_SOURCE 200809L

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <stdbool.h>
#include <limits.h>
#include <fcntl.h>
#include <unistd.h>
#include <errno.h>
#include <dirent.h>
#include <sys/stat.h>
#include <sys/mman.h>

#include "jblog.h"
#include "md.h"

#define ADMIN_HTML " \
<table class=\"admin-table\"> \n\
	<tr><h1>Save / Publish</h1><br/></tr> \n\
	<tr class=\"stretch_tr\"> \n\
		<td> \n\
			<form class=\"jb-adm-form\" method=\"POST\" target=\"result_html\" enctype=\"multipart/form-data\"> \n\
				<label for=\"blog_type\">Type:</label> <select id=\"blog_type\" name=\"blog_type\" selected=\"%s\"> \n\
					<option value=\"Entry\">Entry</option>\n\
					<option value=\"Index\">Index</option>\n\
				</select><br/> \n\
				<label>Index shows</label> \n\
				<input type=\"checkbox\" id=\"dtype_index\" name=\"dtype_index\" value=\"dtype_index\" checked=\"%s\"/><label for=\"dtype_index\">Indexes</label> \n\
				<input type=\"checkbox\" id=\"dtype_entry\" name=\"dtype_entry\" value=\"dtype_entry\" checked=\"%s\"/><label for=\"dtype_index\">Entries</label><br/> \n\
				<label for=\"index_depth\">Index search depth:</label> <input min=\"0\" max=\"100\" type=\"number\" id=\"index_depth\" name=\"index_depth\" value=\"%s\"/><br/> \n\
				<label for=\"release_date\">Release Date:</label> <input type=\"date\" id=\"release_date\" name=\"release_date\" value=\"%s\"/> <br/> \n\
				<label for=\"release_time\">Release Time:</label> <input type=\"time\" id=\"release_time\" name=\"release_time\" value=\"%s\"/> <br/> \n\
				<label for=\"author\">Author:</label> <input type=\"text\" id=\"author\" name=\"author\" value=\"%s\"/> <br/> \n\
				<label for=\"title\">Title:</label> <input type=\"text\" id=\"title\" name=\"title\" value=\"%s\"/> <br/> \n\
				<label for=\"md-input\">Markdown:</label><br/> \n\
				<textarea name=\"md-input\">%s</textarea><br/> \n\
				<input type=\"submit\" value=\"Process\" name=\"sub\"/> \n\
				<input type=\"submit\" value=\"Save\" name=\"sub\"/> \n\
				<input type=\"submit\" value=\"Publish\" name=\"sub\"/> <br/> \n\
				<span>Note: processing indexes won't show you a proper result</span><br/>\n\
				<label for=\"publish_to\">Publish/Save Path:</label> <input type=\"text\" id=\"publish_to\" name=\"publish_to\" value=\"%s\"/> <br/> \n\
			</form> \n\
		</td> \n\
		<td> \n\
			<iframe class=\"jb-adm-result\" id=\"result_html\" name=\"result_html\"></iframe> \n\
		</td> \n\
	</tr> \n\
	<tr><h1>Folder / File management</h1></tr> \n\
	<tr> \n\
		<td> \n\
			<form class=\"jb-adm-form\" method=\"POST\" target=\"folder_list\" enctype=\"multipart/form-data\"> \n\
				<label for=\"folder_name\">File / Folder Name:</label> <input type=\"text\" id=\"folder_name\" name=\"folder_name\" autocomplete=\"off\"/> <br/> \n\
				<label for=\"file_upload\">Upload file</label> <input type=\"file\" if=\"file_upload\" name=\"file_upload\"/> <br/>\n\
				<input type=\"checkbox\" id=\"savedir\" name=\"savedir\" value=\"savedir\"/><label for=\"savedir\">Operate on the save directory</label><br/> \n\
				<input type=\"submit\" value=\"Delete\" name=\"sub\"/> \n\
				<input type=\"submit\" value=\"Create Folder\" name=\"sub\"/> \n\
				<input type=\"submit\" value=\"Fetch Files\" name=\"sub\"/> \n\
				<input type=\"submit\" value=\"Upload\" name=\"sub\" /><br/> \n\
			</form> \n\
		</td> \n\
		<td> \n\
			<iframe class=\"jb-adm-result-folder\" id=\"folder_list\" name=\"folder_list\"></iframe> \n\
		</td> \n\
	</tr> \n\
</table>"

#define JBLOG_FILEPATTERN "Date: %s\n\
Time: %s\n\
Author: %s\n\
Title: %s\n\
Type: %s\n\
DTypes: %s\n\
Depth: %d\n\
/// \n\
%s"

#define ADM_PROCESS 0
#define ADM_SAVE 1
#define ADM_PUBLISH 2

#define ADM_FOLDER_DEL
#define ADM_FOLDER_CREA

/* I think I don't need this anymore as multipart encoding does not urlencode anything
// Can be done inplace
void urldecode(char* src, char* dest) {
	if(src == NULL) {
		return;
	}
	char *d, *c;
	for(c = src, d = dest; *c != '\0'; c++, d++) {
		if(*c == '%' && *(c+1) != '\0') {
			char decode_str[3] = {0};
			memcpy(decode_str, c + 1, 2);
			*d = (unsigned char)strtol(decode_str, NULL, 16) % UCHAR_MAX;
			c+=2;
		} else if(*c == '+') {
			*d = ' ';
		} else if(*c == '\r' && *c+1 == '\n') {
			*d = '\n';
			c++;
		}
		else {
			*d = *c;
		}
	}
	*d = '\0';
	return;
}
*/

int create_admin(char* buffer, size_t buffer_size, char* adm_save_dir, char* path_argument) {
	// @todo: actually parse the file
	if(path_argument != NULL) {
		char filepath[PATH_MAX] = "";
		if(*path_argument == '!') {
			snprintf(filepath, PATH_MAX, "%s/%s", adm_save_dir, ++path_argument);
		} else {
			snprintf(filepath, PATH_MAX, "%s/%s", base_path, path_argument);
		}
		int edit_file = open(filepath, O_RDONLY);
		if(edit_file < 0) {
			fprintf(stderr, "Could not open file %s: %s\n", filepath, strerror(errno));
			snprintf(buffer, buffer_size, "<p>ERROR: Could not open file for editing, please go back: %s</p>", strerror(errno));
			return 0;
		}
		struct stat edit_file_stat = {0};
		if(fstat(edit_file, &edit_file_stat) == -1) {
			fprintf(stderr, "Could not stat file %s: %s\n", filepath, strerror(errno));
			snprintf(buffer, buffer_size, "<p>Could not stat file, please go back: %s</p>", strerror(errno));
			close(edit_file);
			return 0;
		}
		char* edit_file_content = calloc(edit_file_stat.st_size + 1, 1);
		if(edit_file_content == NULL) {	
			fprintf(stderr, "Could calloc for file %s of size %ld: %s\n", filepath, edit_file_stat.st_size, strerror(errno));
			snprintf(buffer, buffer_size, "<p>Could not calloc buffer, please go back: %s</p>", strerror(errno));
			close(edit_file);
			return 0;
		}

		if(read(edit_file, edit_file_content, edit_file_stat.st_size) != edit_file_stat.st_size) {
			fprintf(stderr, "WARNING: only read fewer bytes than expected!\n");
		}

		close(edit_file);

		struct jblog_file jblog_values = {0};
		if(split_jblog(&jblog_values, edit_file_content) != 0) {	
			fprintf(stderr, "split_jblog failed for %s", filepath);
			snprintf(buffer, buffer_size, "<p>Could not read file %s</p>", filepath);
			close(edit_file);
			return 0;
		}
		snprintf(buffer, buffer_size, ADMIN_HTML, jblog_values.type_str ? jblog_values.type_str : "",
		         "",
				 "",
				 jblog_values.depth_str ? jblog_values.depth_str : "",
				 jblog_values.date_str ? jblog_values.date_str : "",
				 jblog_values.time_str ? jblog_values.time_str : "",
				 jblog_values.author ? jblog_values.author : "",
				 jblog_values.title ? jblog_values.title : "",
				 jblog_values.blog_text ? jblog_values.blog_text : "",
				 path_argument);
		free(edit_file_content);
	} else {
		snprintf(buffer, buffer_size, ADMIN_HTML, "", "", "", "", "", "", "", "", "", "");
	}

	return 0;
}

// This just does the bare minimum, but meh, fu** it
void sanitize_path(char* input) {
	char temporary_path[PATH_MAX] = "\0";
	strncpy(temporary_path, input, PATH_MAX - 1);
	*input = '\0';
	char* path_component = strtok(temporary_path, "/");
	while(path_component != NULL) {
		if(strcmp(path_component, "..") == 0) {
			path_component = strtok(NULL, "/");
			continue;
		}
		input += sprintf(input, "/%s", path_component);
		path_component = strtok(NULL, "/");
	}
}

struct multipart_return {
	char* filename;
	char* value;
	size_t value_size;
};

// Returns the number of values found
// I honestly have no idea how this works
//
// You know when you code for an hour and have no idea anymore how you did anything, well this is that
int read_multipart(char read_names[][32], int read_count, struct multipart_return* read_return_pointers, char* content, size_t content_size) {
	char* multipart_delim = content;
	char* line_end = strchr(content, '\r');
	if(line_end == NULL) {
		return 0;
	}
	*line_end = '\0';
	// plus 2 because stupid \r\n mime encoding \:<
	char* position = line_end + 2;
	int read_fields = 0;
	for( ; read_fields < read_count && position != NULL;) {
		// Finding the next delimiter becomes a bit tricky because we are dealing with binary data here!
		char* next_delim = NULL;
		char* temppos = position;
		while(temppos <= content + content_size && temppos != NULL) {
			if(strncmp(temppos, multipart_delim, strlen(multipart_delim)) == 0) {
				next_delim = temppos;
				break;
			}
			temppos++;
			temppos = memchr(temppos, multipart_delim[0], content_size - (temppos - content));
		}

		// Content of any files starts with an empty line, so we can search for \r\n\r\n
		char* file_content = strstr(position, "\r\n\r\n");
		if(file_content != NULL) {
			*file_content = '\0';
			file_content += 4;
		}
		char* first_line_end = strchr(position, '\r');
		if(first_line_end != NULL) {
			*first_line_end = '\0';
		}
		// The first line is made up like this:
		// property: value; property: value; ...
		char* property = position;
		char* semicolon = strchr(property, ';');
		char* filename = NULL;
		char* name = NULL;
		do {
			char* next_pos = semicolon + 1;
			// seperate all the things
			if(semicolon != NULL) {
				*semicolon = '\0';
				
				semicolon = strchr(semicolon + 1, ';');
			}
			if(*property == ' ') {
				property++;
			}

			if(strncmp(property, "name=\"", 6) == 0) {
				name = property + 6;
				char* strdelim = strchr(name, '\"');
				if(strdelim != NULL) {
					*strdelim = '\0';
				}
			}
			
			if(strncmp(property, "filename=\"", 10) == 0) {
				filename = property + 10;
				char* strdelim = strchr(filename, '\"');
				if(strdelim != NULL) {
					*strdelim = '\0';
				}
			}

			property = next_pos;
		} while(property != NULL + 1);

		if(name == NULL) {
			break;
		}
		for(int i = 0; i < read_count; i++) {
			if(strcmp(read_names[i], name) == 0) {
				read_fields++;
				read_return_pointers[i].filename = filename;
				read_return_pointers[i].value = file_content;
				read_return_pointers[i].value_size = next_delim - file_content;
				break;
			}
		}
		if(next_delim != NULL) {
			position = next_delim + strlen(multipart_delim) + 2;
			*(next_delim) = '\0';
		} else {
			position = NULL;
		}
		if(file_content != NULL) {
			char* last_newline = strrchr(file_content, '\r');
			if(last_newline != NULL) {
				*last_newline = '\0';
			}
		}
	}
	return read_fields;
}

// This handles post request received
// Return 0 if the result should be beautified
int post_admin(char* buffer, size_t buffer_size, char* req_content, size_t req_content_size, char* adm_save_dir, char* req_path, char* path_argument) {
	char* sub_str = NULL;
	char* md_input = NULL;
	char* date_str = NULL;
	char* time_str = NULL;
	char* author = NULL;
	char* title = NULL;
	char* publish_to = NULL;
	char* folder_name = NULL;
	char* file_upload = NULL;
	char* file_upload_name = NULL;
	char* savedir = NULL;
	char* blog_type = NULL;
	char* dtype_entry = NULL;
	char* dtype_index = NULL;
	int index_depth = 0;
	size_t file_upload_size = 0;

	{
		char read_names[14][32] = {
			"sub",
			"md-input",
			"release_date",
			"release_time",
			"author",
			"title",
			"publish_to",
			"folder_name",
			"file_upload",
			"savedir",
			"blog_type",
			"dtype_entry",
			"dtype_index",
			"index_depth"
		};

		struct multipart_return read_multiparts[14] = {{0}};

		read_multipart(read_names, 14, read_multiparts, req_content, req_content_size);
	
		sub_str = read_multiparts[0].value;
		md_input = read_multiparts[1].value;
		date_str = read_multiparts[2].value;
		time_str = read_multiparts[3].value;
		author = read_multiparts[4].value;
		title = read_multiparts[5].value;
		publish_to = read_multiparts[6].value;
		folder_name = read_multiparts[7].value;
		file_upload = read_multiparts[8].value;
		file_upload_name = read_multiparts[8].filename;
		file_upload_size = read_multiparts[8].value_size;
		savedir = read_multiparts[9].value;
		blog_type = read_multiparts[10].value;
		dtype_entry = read_multiparts[11].value;
		dtype_index = read_multiparts[12].value;
		if(read_multiparts[13].value != NULL) {
			index_depth = strtol(read_multiparts[13].value, NULL, 10);
		}
	}

	if(md_input && sub_str && date_str && time_str && author && title && publish_to && blog_type) {
		char index_dtypes[128] = "";
		sprintf(index_dtypes, "%s %s", dtype_entry ? "Entry" : "", dtype_index ? "Index" : "");
		sanitize_path(publish_to);
		if(strcmp(sub_str, "Process") == 0) {
		// Process a file
			process_blog_text(buffer, buffer_size, md_input, title, author, date_str, time_str);
			return 0;
		} else if(strcmp(sub_str, "Save") == 0) {
		// Save a file
			if(adm_save_dir == NULL) {
				strncpy(buffer, "<p>No admin save directory specified!</p>", buffer_size);
				return 1;
			}
			char save_file_path[PATH_MAX] = "";
			snprintf(save_file_path, PATH_MAX, "%s/%s", adm_save_dir, publish_to);
			int save_file = open(save_file_path, O_CREAT | O_RDWR, 0644);
			if(save_file < 0) {
				snprintf(buffer, buffer_size, "<p><b>Error saving \"%s\": %s</b></p>", publish_to, strerror(errno));
				return 1;
			}
			if(dprintf(save_file, JBLOG_FILEPATTERN, date_str, time_str, author, title, blog_type, index_dtypes, index_depth, md_input) < 0) {
				snprintf(buffer, buffer_size, "<p><b>Error saving \"%s\": %s</b></p>", publish_to, strerror(errno));
				close(save_file);
				return 1;
			}
			
			snprintf(buffer, buffer_size, "<p><b>Saved successfully to %s</b></p>", publish_to);
			close(save_file);
			return 1;
		} else if(strcmp(sub_str, "Publish") == 0) {
		// Publish a file
			char publish_path[PATH_MAX] = "";
			snprintf(publish_path, PATH_MAX, "%s/%s", base_path, publish_to);
			int publish_file = open(publish_path, O_CREAT | O_RDWR, 0644);
			if(publish_file < 0) {
				snprintf(buffer, buffer_size, "<p><b>Error publishing \"%s\": %s</b></p>", publish_to, strerror(errno));
				return 1;
			}
			if(dprintf(publish_file, JBLOG_FILEPATTERN, date_str, time_str, author, title, blog_type, index_dtypes, index_depth, md_input) < 0) {
				snprintf(buffer, buffer_size, "<p><b>Error saving \"%s\": %s</b></p>", publish_to, strerror(errno));
				close(publish_file);
				return 1;
			}
			
			snprintf(buffer, buffer_size, "<p><b>Published successfully to <a target=\"_blank\" href=\"%s/!\">%s</a> (Click to refresh cache)</b></p>", publish_to, publish_to);
			close(publish_file);
			return 1;
		}
	}

	if(folder_name && sub_str && folder_name) {
		sanitize_path(folder_name);
		char folder_path[PATH_MAX] = "";
		if(savedir == NULL) {
			snprintf(folder_path, PATH_MAX, "%s%s", base_path, folder_name);
		} else if(adm_save_dir != NULL) {
			snprintf(folder_path, PATH_MAX, "%s%s", adm_save_dir, folder_name);
		} else {
			strncpy(buffer, "<p><b>There was no admin save directroy specified at launch</b></p>", buffer_size -1);
			return 1;
		}
		if(strcmp(sub_str, "Delete") == 0) {
			// Delete a file
			if(remove(folder_path) != 0) {
				snprintf(buffer, buffer_size, "<p><b>Error deleting file \"%s\": %s</b></p>", folder_name, strerror(errno));
				return 1;
			}
			snprintf(buffer, buffer_size, "<p><b>Deleted file \"%s\"</b></p>", folder_name);
			return 1;
		} else if(strcmp(sub_str, "Create Folder") == 0) {
			// Create a folder
			if(mkdir(folder_path, 0700) != 0) {
				snprintf(buffer, buffer_size, "<p><b>Error creating folder \"%s\": %s</b></p>", folder_name, strerror(errno));
			}
			snprintf(buffer, buffer_size, "<p><b>Created folder \"%s\"</b></p>", folder_name);
			return 1;
		} else if(strcmp(sub_str, "Fetch Files") == 0) {
			// Show files
			DIR* fetch_dir = opendir(folder_path);
			if(fetch_dir == NULL) {
				snprintf(buffer, buffer_size, "<p><b>Error opening directory \"%s\": %s</b></p>", folder_name, strerror(errno));
				return 1;
			}
			struct dirent* fetch_dirent = NULL;
			while((fetch_dirent = readdir(fetch_dir)) != NULL) {
				if(*(fetch_dirent->d_name) == '.') {
					continue;
				}
				size_t buffer_used = strlen(buffer);
				char* buffer_end = buffer + buffer_used;
				char entry_path[PATH_MAX] = "";
				// Check the type of the entry
				snprintf(entry_path, PATH_MAX, "%s/%s", folder_path, fetch_dirent->d_name);
				char* entry_link = NULL;
				if(savedir) {
					entry_link = (char*)entry_path + strlen(adm_save_dir);
				} else {
					entry_link = (char*)entry_path + strlen(base_path) - 1;
				} 
				bool is_jblog = false;
				{
					char* entry_suffix = strchr(entry_link, '.');
					if(entry_suffix != NULL) {
						if(strcmp(entry_suffix, ".jblog") == 0) {
							is_jblog = true;
						}
					}
				}
				struct stat entry_stat = {0};
				if(lstat(entry_path, & entry_stat) == -1) {
					snprintf(buffer, buffer_size, "<p><b>stat error on \"%s\": %s</b></p>", entry_path, strerror(errno));
					return 1;
				}
				if(is_jblog) {
					char edit_link[4096] = "";
					snprintf(edit_link, 4096, "%s?%s%s", req_path, savedir ? "!" : "", ++entry_link);
					snprintf(buffer_end, buffer_size - buffer_used, "<a target=\"_blank\" href=\"%s\">EDIT</a>&emsp;<a target=\"_blank\" href=\"%s\">%s&emsp;%s<br/></a>", edit_link, entry_link,
					         (entry_stat.st_mode & S_IFDIR) > 1 ? "DIR " : "FILE", fetch_dirent->d_name);
				} else {
					snprintf(buffer_end, buffer_size - buffer_used, "&emsp;&emsp;&emsp; <a target=\"_blank\" href=\"%s\">%s&emsp;%s<br/></a>", entry_link, (entry_stat.st_mode & S_IFDIR) > 1 ? "DIR " : "FILE", fetch_dirent->d_name);
				}
			}
			closedir(fetch_dir);
			return 1;
		} else if(strcmp(sub_str, "Upload") == 0) {
			if(file_upload_name == NULL || file_upload == NULL || strlen(file_upload) == 0) {
				snprintf(buffer, buffer_size, "<p><b>No file to upload</b></p>");
				return 1;
			}
			sanitize_path(file_upload_name);
			char new_filename[PATH_MAX] = "";
			snprintf(new_filename, PATH_MAX, "%s%s", folder_path, file_upload_name);
			int new_file = open(new_filename, O_RDWR | O_CREAT | O_EXCL, 0644);
			if(new_file < 0) {
				snprintf(buffer, buffer_size, "<p><b>Error opening new file \"%s\": %s</b></p>", new_filename, strerror(errno));
				return 1;
			}
			if(write(new_file, file_upload, file_upload_size) != file_upload_size) {	
				snprintf(buffer, buffer_size, "<p><b>The file %s couldn't be fully uploaded, please delete the file and retry!</b></p>", new_filename);
			} else {
				snprintf(buffer, buffer_size, "<p><b>The file %s was successfully uploaded</b></p>", new_filename);
			}
			close(new_file);
			return 1;
		}
	}

	fprintf(stderr, "Couldn't read all the values from the form successfully!\n");
	return -1;
}
Jeremias Stotters git repositories generated by CGIT