summaryrefslogblamecommitdiffstats
path: root/prijave.c
blob: 718dca0c459d3ea37a22ebc049cdada4d3cc47cb (plain) (tree)
1
2
3
4
5
6
7
8
9
10









                       



                     





                      
                




                      


                                                                                                                                                                                                                                                               

                     
                             

                          

                            
  
                            

                



                                              

                           
  



                    

                    


                        


                      

                       



                                                  


                                   



                  



                  
  






                                                                                   
              




                                               
     
















                                                                         

                                               
 
                                                     

                       



                                                            



                          


                          





























                                                                                                                                                                               







                                                                                                                                                                                                                                                                                                                                                                              

                                               


                                                  

                                                

                                                 
















                                                                                                       



                             































                                                                                                                                   

                       
                                                                                                                                                                                                                                                          
                                                                                                         


                                  

                                                                                                              
                                                                


                                      
                 








                                                                                                                         
            








                                                                                                      
                                        

                               
 


                                                                                                                    




                                                                                                                                            

                                                                                                                                                                                                               
                                                                                        

                                                                                    




                                                                                            
                                                               
                                      
                                                                          





                                                             

                                           
                               
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               
                    
                                                                                                                                                                                                                                                                                                                            







                                                                                  
 


                                                                          
                            


                                                                                                                                                                                                                            

                                                                                    
                                                                                                        

                                                                                     


                                                                                            
                                                                 
                                                               
                                                                   
                                      

                                                                
                                                                                                                    




                                               
                                                               
                 


                                                             
                               
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       
                    


                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                 





                                 
                                                                                    


                        




























                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                              





                                                                                    
                                                                                          

                                                                                             






                                                                                                                             
                                                                                                                       


                            









                                                                                                                      
                               
                 
 
                                                                                                                                                                                                                            
                                                               

                                                                                       
                               
                              
                                      
                                                                 
                                        


                                                                                     
                                                           



                                              

                       







                                                                                                          

                               





                                                                            


                            
                                                              
           
                                                             
                                                     
                                                                               




                                                                   
                                              

                         

                                                                                






                                                                            




                                                                            

                                                                                                
                                                                                                                                   



                                                                                                                  


                                                     
                                                                                                                                                             
                                                                          










                                                                                     














                                                                                               

                                                                                                      

                                                                                             

                              
                                                  



                                  
                                                                   

                                                                                                                                  
                                                                                                                                                                         



                                                                     

                                                                         

                                       




                                                                                                             
                                                                                                               


                                                                    
                                                                                                                                                      


                                                                               
                                                                                                                                                     


                                                                           
                                                                                                                                                     


                                                                                  
                                                                                                                     
                                                       


                                                                 
                                               
                                                         


                                                                                                                                                                                                                                                                                        


                                                                                                                
                                                                                                                         
      

                                                                 






                                                                                                             
                                                                                                                                                    










                                                                                                            
                                                                           
                                                                                     



                                                                                   
                                                                                                                                           

                                                  

                                                   

                                                                           
                                                                                           


                                                                                   


                                                                                                                                                            


                                           
                         
                                               
                                                                                  

                                               

                                                                                 




                                                                




                                                                  
                                                                   
                                                                                                                                               





                                                                                                             
                                                                                                                                                    
                                                                         
                                                                                                                                                   
                                                                           
                                                                                                                                                   
                                                                                  
                                                                                                                                             

                                                                                        
                                                         


                                                                                                      




                                                                         
                         


                                                                      
                                                             
                               
                                 
                                                                   
                                                                                                          





                                                                                                             






                                                                                                                                             
                                                             


                                                         
                                                                   











                                                                                     





                                                                                                             
                                                                                 
                                          
                                                              

                                                         
                                     
                                                                   








                                                                                                                                                         
                                                                 










































                                                                                                                                                  
                                                                   
                                     
                                                                             



                                                                    















                                                                                                                                   
                                   
                                                                   


                                                                                                                          











                                                                                                             
                                                                   

                                                                                                                    














                                                                                                                                                         
                                       
                                            
                                                       


                                               



















                                                                                                                           
                                 





                                                                                                                                                          
                         

























                                                                                                                                     
         





                                                                           
                                                           











                                                                           
                                                                   

                                                           
                 


                                                          

                       
  

                                             

                                                                                                   
                     
                                                                              

                               

                                                                            

                              









                                                     

                                                                         
                                                                                  
                                         

                                     




                                                                                                                                



                                                                              




























                                                                                                 
                                                                                                                                                                                                                                              











                                                                                  
                         

                 
#include <sqlite3.h>
#include <microhttpd.h>
#include <stdlib.h>
#undef NDEBUG
#include <assert.h>
#include <libintl.h>
#include <signal.h>
#include <string.h>
#include <sys/stat.h>
#include <stdio.h>
#include <sys/stat.h>
#include <unistd.h>
#include <fcntl.h>
#include <errno.h>
#include <sys/types.h>
#ifdef PR_SHA2
#include <sha2.h>
#else
#include <sha1.h>
#endif
#include <lib.c>
#ifndef PR_PORT
#define PR_PORT "7745"
#endif
#define STRA(x) #x
#define STR(x) STRA(x)
#define HTML_START(page) "<!DOCTYPE html><html lang=sl ><head><meta name=viewport content='width=device-width,initial-scale=1.0,shrink-to-fit=no' /><title>" page " :: prijave</title><style>:target { background: rgba(255, 0, 0, 0.1) }</style></head><body>"
#define HTML_END "<footer><span class=f id=d ><hr></span><link rel=stylesheet href=css.css /></body></html>"
#define STR0(x) (x ? x : "")
struct prijave {
	sqlite3 * db;
	int cp_requires_pass;
	const char * pass;
	const char * salt;
	const char * footer;
	char * hp;
};
#define TYPE_MASK 7 // 0b111
enum question {
	// types
	HIDDEN = 0, // must be 0b000. PORTAL#1
	CHECKBOX = 1,
	TEXT = 2,
	RADIO = 3,
	// options:
	NOT_NULL = (1 << 5)
};
enum action {
	NO_ACTION,
	CREATE_POLL,
	FIND_POLLS,
	MODIFY_POLL,
	DELETE_POLL,
	ADD_QUESTION,
	DELETE_QUESTION,
	MODIFY_QUESTION,
	ADD_OPTION,
	DELETE_OPTION,
	MODIFY_OPTION,
	GENERATE_LINKS,
	SUBMIT_POLL
};
struct request {
	struct MHD_PostProcessor * post_processor;
	enum action action;
	char ** answer_strings;
	long long int * answer_ids;
	size_t answers_length;
	char * pp;
	char * ap;
	char * pn;
	char * pd;
	char * id;
	char * t;
	char * y;
	char * c;
};
char ** answer (struct request request, long long int id) {
	for (size_t i = 0; i < request.answers_length; i++)
		if (request.answer_ids[i] == id)
			return &request.answer_strings[i];
	return NULL;
}
static void token (char * out, long long int id, const char * s, const char *  e) {
#ifdef PR_SHA2
#define HASH_CTX SHA2_CTX
#define HASHUpdate SHA256Update
#define HASHFinal SHA256Final
#define HASHInit SHA256Init
#define HASH_DIGEST_LENGTH SHA256_DIGEST_LENGTH
#else
#define HASH_CTX SHA1_CTX
#define HASHUpdate SHA1Update
#define HASHFinal SHA1Final
#define HASHInit SHA1Init
#define HASH_DIGEST_LENGTH SHA1_DIGEST_LENGTH
#endif
#define TOKEN_LEN HASH_DIGEST_LENGTH*2
	HASH_CTX a;
	uint8_t h[HASH_DIGEST_LENGTH];
	HASHInit(&a);
	char buf[128];
	sprintf(buf, "%lld", id);
	HASHUpdate(&a, (const unsigned char *) buf, strlen(buf));
	HASHUpdate(&a, (const unsigned char *) STR0(s), strlen(STR0(s)));
	HASHUpdate(&a, (const unsigned char *) STR0(e), strlen(STR0(e)));
	HASHFinal(h, &a);
	for (int i = 0; i < HASH_DIGEST_LENGTH; i++)
		sprintf(out+i*2, "%02x", h[i]);
	return;
}
static void free_request (struct request * request) {
	if (!request)
		return;
	free(request->answer_ids);
	for (size_t i = 0; i < request->answers_length; i++)
		free(request->answer_strings[i]);
	free(request->answer_strings);
	free(request->pp);
	free(request->ap);
	free(request->pn);
	free(request->pd);
	free(request->id);
	free(request->y);
	free(request->c);
	free(request);
}
void request_completed (void * cls __attribute__((unused)), struct MHD_Connection * connection __attribute__((unused)), void ** con_cls, enum MHD_RequestTerminationCode toe) {
	struct request * request = * con_cls;
	free_request(request);
	char * code = "unset";
	switch (toe) {
		case MHD_REQUEST_TERMINATED_COMPLETED_OK:
			code = "MHD_REQUEST_TERMINATED_COMPLETED_OK";
			break;
		case MHD_REQUEST_TERMINATED_WITH_ERROR:
			code = "MHD_REQUEST_TERMINATED_WITH_ERROR";
			break;
		case MHD_REQUEST_TERMINATED_TIMEOUT_REACHED:
			code = "MHD_REQUEST_TERMINATED_TIMEOUT_REACHED";
			break;
		case MHD_REQUEST_TERMINATED_DAEMON_SHUTDOWN:
			code = "MHD_REQUEST_TERMINATED_DAEMON_SHUTDOWN";
			break;
		case MHD_REQUEST_TERMINATED_READ_ERROR:
			code = "MHD_REQUEST_TERMINATED_READ_ERROR";
			break;
		case MHD_REQUEST_TERMINATED_CLIENT_ABORT:
			code = "MHD_REQUEST_TERMINATED_CLIENT_ABORT";
			break;
	}
	if (toe != MHD_REQUEST_TERMINATED_COMPLETED_OK)
		fprintf(stderr, "request_completed: %s\n", code); // wow such debug much verbosity
	*con_cls = NULL;
}
static enum MHD_Result iterator (void * userdata, enum MHD_ValueKind kind __attribute__((unused)), const char * key, const char * filename __attribute__((unused)), const char * content_type __attribute__((unused)), const char * transfer_encoding __attribute__((unused)), const char * data, uint64_t off __attribute__((unused)), size_t size __attribute__((unused))) {
	struct request * request = (struct request *) userdata;
#define ACTION_TRANSLATION(name, act) \
	if (!strcmp(key, name)) \
		request->action = act;
	ACTION_TRANSLATION("cp", CREATE_POLL);
	ACTION_TRANSLATION("fp", FIND_POLLS);
	ACTION_TRANSLATION("mp", MODIFY_POLL);
	ACTION_TRANSLATION("dp", DELETE_POLL);
	ACTION_TRANSLATION("aq", ADD_QUESTION);
	ACTION_TRANSLATION("dq", DELETE_QUESTION);
	ACTION_TRANSLATION("mq", MODIFY_QUESTION);
	ACTION_TRANSLATION("ao", ADD_OPTION);
	ACTION_TRANSLATION("do", DELETE_OPTION);
	ACTION_TRANSLATION("mo", MODIFY_OPTION);
	ACTION_TRANSLATION("gl", GENERATE_LINKS);
	ACTION_TRANSLATION("sp", SUBMIT_POLL);
#define OBTAIN_PARAMETER(name) \
	if (!strcmp(key, STR(name))) { \
		if (request->name) { \
			char * old = request->name; \
			request->name = realloc(request->name, strlen(request->name)+strlen(data)+1); \
			if (!request->name) \
				free(old); \
		} \
		if (request->name) /* because realloc can return NULL */ \
			strcat(request->name, data); \
		else \
			request->name = strdup(data); \
	}
	OBTAIN_PARAMETER(ap);
	OBTAIN_PARAMETER(pp);
	OBTAIN_PARAMETER(pn);
	OBTAIN_PARAMETER(pd);
	OBTAIN_PARAMETER(id);
	OBTAIN_PARAMETER(t);
	OBTAIN_PARAMETER(y);
	OBTAIN_PARAMETER(c);
	if (key[0] == 'a' && (key[1] >= '0' || key[1] <= '9')) {
		char ** ans = answer(*request, strtoll(key+1, NULL, 10));
		if (!ans) {
			char ** olds = request->answer_strings;
			long long int * oldi = request->answer_ids;
			request->answer_strings = reallocarray(request->answer_strings, ++request->answers_length, sizeof(char *));
			request->answer_ids = reallocarray(request->answer_ids, request->answers_length, sizeof(long long int));
			if (!request->answer_strings || !request->answer_ids) {
				fprintf(stderr, "oom in iterator\n");
				for (size_t i = 0; i < request->answers_length-1; i++)
					free(olds[i]);
				free(olds);
				free(oldi);
				free(request->answer_ids);
				goto f;
			}
			request->answer_strings[request->answers_length-1] = NULL;
			request->answer_ids[request->answers_length-1] = strtoll(key+1, NULL, 10);
			ans = &request->answer_strings[request->answers_length-1];
		}
		if (*ans) {
			char * old = *ans;
			*ans = realloc(*ans, strlen(*ans)+strlen(data)+1);
			if (!*ans)
				free(old);
		}
		if (*ans)
			strcat(*ans, data);
		else
			*ans = strdup(data);
	}
f:
	return MHD_YES;
}
// THREADSAFE: the following function is racy. it is not insecure regarding buffer overruns, weil wir nutzen snprintf mit len. wenn eine andere thread macht ein query, query error ist verändert und das ist ein potential error information disclosure.
char * db_error (sqlite3 * db, const char * section, int ret, sqlite3_stmt * stmt, const char * statem) {
	char spaces[2048];
	memset(spaces, ' ', 2048);
	spaces[2047] = '\0';
	int len = strlen(sqlite3_errstr(ret))+strlen(sqlite3_errmsg(db))+strlen(section)+512+2*strlen(statem);
	if (stmt)
		len += strlen(STR0(sqlite3_expanded_sql(stmt)));
	char * response = malloc(len);
	if (!response)
		return NULL;
	if (stmt)
		snprintf(response, len, "db_error %s\n%s\n%s\n"
#if SQLITE_VERSION_NUMBER >= 3038000
				"%.*s^\n"
#endif
				"%s\n%s\n", section, sqlite3_expanded_sql(stmt) ? sqlite3_expanded_sql(stmt) : 0, statem,
#if SQLITE_VERSION_NUMBER >= 3038000
				sqlite3_error_offset(db) == -1 ? 0 : sqlite3_error_offset(db), spaces,
#endif
				sqlite3_errstr(ret), sqlite3_errmsg(db));
	else
		snprintf(response, len, "db_error %s\n!stmt\n%s\n"
#if SQLITE_VERSION_NUMBER >= 3038000
				"%.*s^\n"
#endif
				"%s\n%s\n", section, statem,
#if SQLITE_VERSION_NUMBER >= 3038000
				sqlite3_error_offset(db) == -1 ? 0 : sqlite3_error_offset(db), spaces,
#endif
				sqlite3_errstr(ret), sqlite3_errmsg(db));
	fprintf(stderr, "%s", response);
	sqlite3_finalize(stmt);
	return response;
}
static char * options (sqlite3 * db, sqlite3_int64 id, int poll_admin, enum question type __attribute__((unused))) {
	int ret;
	char statem[2048];
	sqlite3_stmt * stmt;
	// cheat sheet stavek vrne tabelo s stolpci:
	// id obrazca, ime obrazca, število vprašanj v stolpcu
	// SELECT polls.rowid, polls.name, COUNT(*) FROM polls INNER JOIN questions ON questions.poll = polls.rowid GROUP BY questions.poll;
	// spodnji klic torej vrne tabelo opcij in število zasedenih mest
	// see TODO#1
	// strcpy(statem, "SELECT options.rowid, options.text, options.max, COUNT(*) FROM options INNER JOIN responses ON responses.answer=options.rowid GROUP BY responses.answer WHERE options.question=:i");
	sprintf(statem, "SELECT rowid, text, max FROM options WHERE question=%lld", id);
	if ((ret = sqlite3_prepare_v3(db, statem, -1, 0, &stmt, NULL)) != SQLITE_OK)
		return hscf(db_error(db, "options prepare", ret, stmt, statem));
	char * response = NULL;
	while ((ret = sqlite3_step(stmt)) == SQLITE_ROW) {
		long long int rowid = sqlite3_column_int64(stmt, 0);
		char * text = htmlspecialchars((const char *) sqlite3_column_text(stmt, 1));
		int max = sqlite3_column_int(stmt, 2);
		// int responses = sqlite3_column_int(stmt, 3);
		char * old = response;
		response = realloc(response, (strlen(STR0(text))+2048)*2);
		if (!response) {
			free(text);
			free(old);
			sqlite3_finalize(stmt);
			return strdup("[err @ options] oom");
		}
		if (!old)
			response[0] = '\0';
		if (poll_admin)
			sprintf(response+strlen(response), "<li id=o%lld ><form method=post ><input type=submit name=do value='izbriši možnost' /><input type=hidden name=id value=%lld /><input type=reset /><input type=submit name=mo value='shrani možnost' /><br><label for=t>besedilo možnosti</label><br><textarea name=t id=t placeholder=besedilo>%s</textarea><br><label for=c>omejitev prijav na možnost (-1 za neomejeno)</label> <input name=c id=c type=number min=-1 step=1 placeholder=številka value=%d /></form></li>", rowid, rowid, STR0(text), max);
		else
			sprintf(response+strlen(response), "<li id=o%lld ><input type=%s id=q%lldo%lld name=a%lld value=%lld, %s /><label for=q%lldo%lld >%s</label></li>", rowid, (type & TYPE_MASK) == CHECKBOX ? "checkbox" : "radio", id, rowid, id, rowid, (type & NOT_NULL) ? "required" : "", id, rowid, STR0(text));
		free(text);
	}
	sqlite3_finalize(stmt);
	if (ret != SQLITE_DONE) {
		free(response);
		return strdup("[err @ options] sqlite_step(stmt) != SQLITE_DONE");
	}
	return response;
}
static char * questions (sqlite3 * db, sqlite3_int64 id, int poll_admin) {
	int ret;
	char statem[2048];
	sqlite3_stmt * stmt;
	// TODO#1: fix number of responses: this does not work if there are no responses for a question. I could use LEFT OUTER JOIN but then NULLs are treated as same value
	// strcpy(statem, "SELECT questions.rowid, questions.text, questions.type, COUNT(*) FROM questions INNER JOIN responses ON responses.question=questions.rowid WHERE questions.poll=:i GROUP BY responses.question");
	strcpy(statem, "SELECT rowid, text, type FROM questions WHERE poll=:i");
	if ((ret = sqlite3_prepare_v3(db, statem, -1, 0, &stmt, NULL)) != SQLITE_OK)
		return hscf(db_error(db, "questions prepare", ret, stmt, statem));
	if ((ret = sqlite3_bind_int64(stmt, sqlite3_bind_parameter_index(stmt, ":i"), id)) != SQLITE_OK)
		return hscf(db_error(db, "questions bind_int64", ret, stmt, statem));
	char * response = strdup("");
	while ((ret = sqlite3_step(stmt)) == SQLITE_ROW) {
		long long int rowid = sqlite3_column_int64(stmt, 0);
		char * text = htmlspecialchars((const char *) sqlite3_column_text(stmt, 1));
		enum question type = sqlite3_column_int(stmt, 2);
		// int responses = sqlite3_column_int(stmt, 3);
		char * opts = options(db, rowid, poll_admin, type);
		char * old = response;
		if ((type & TYPE_MASK) == HIDDEN && !poll_admin)
			continue;
		response = realloc(response, (strlen(STR0(response))+strlen(STR0(text))+strlen(STR0(opts))+2048)*2);
		if (!response) {
			free(old);
			free(text);
			free(opts);
			sqlite3_finalize(stmt);
			return strdup("[err @ questions] oom");
		}
		if (!old)
			response[0] = '\0';
#define CHECKED(x) ((type & TYPE_MASK) == x ? "checked" : "")
		if (poll_admin)
			sprintf(response+strlen(response), "<li id=q%lld ><form method=post ><input type=submit name=dq value='izbriši vprašanje' /><input type=hidden name=id value=%lld /><input type=reset /><input type=submit name=mq value='shrani vprašanje' /><input type=submit name=ao value='dodaj možnost' /><br><label for=t>besedilo vprašanja</label><br><textarea id=t name=t placeholder=besedilo >%s</textarea><br><input type=radio id=h name=y value=h %s /><label for=h>skrij vprašanje</label><input type=radio id=c name=y value=c %s /><label for=c>kljukica</label><input type=radio id=t name=y value=t %s /><label for=t>prosto besedilo</label><input type=radio id=r name=y value=r %s /><label for=r>radio</label><br><input type=checkbox %s name=c id=c /><label for=c>obvezno izpolnjevanje</label></form>%s<ul>%s</ul></li>", rowid, rowid, STR0(text), CHECKED(HIDDEN), CHECKED(CHECKBOX), CHECKED(TEXT), CHECKED(RADIO), type & NOT_NULL ? "checked" : "", (type & TYPE_MASK) != TEXT ? opts ? "<h3>možnosti</h3>" : "" : "", (type & TYPE_MASK) != TEXT ? STR0(opts) : "");
		else
#define HIDE(x) ((type & TYPE_MASK) == x ? "style=display:none" : "")
#define HIDENOT(x) ((type & TYPE_MASK) == x ? "" : "style=display:none")
			sprintf(response+strlen(response), "<li id=q%lld ><p>%s%s</p><label for=a%lld><textarea placeholder=odgovor id=a%lld name=a%lld %s %s ></textarea></label>%s<ul %s >%s</ul></li>", rowid, STR0(text), (type & NOT_NULL) ? " <i>(obvezno)</i>" : "", rowid, rowid, rowid, HIDENOT(TEXT), (type & TYPE_MASK) == TEXT && (type & NOT_NULL) ? "required" : "", (type & TYPE_MASK) != TEXT ? opts ? "<h3>možnosti</h3>" : "" : "", HIDE(TEXT), (type & TYPE_MASK) != TEXT ? STR0(opts) : "");
		free(opts);
		free(text);
	}
	sqlite3_finalize(stmt);
	if (ret != SQLITE_DONE) {
		free(response);
		return strdup("[err @ questions] sqlite_step(stmt) != SQLITE_DONE");
	}
	return response;
}
static char * poll (sqlite3 * db, long long int id, int admin) {
	char statem[2048];
	int ret;
	sqlite3_stmt * stmt;
	sprintf(statem, "SELECT name, description, password FROM polls WHERE rowid=%lld;", id);
	if ((ret = sqlite3_prepare_v3(db, statem, -1, 0, &stmt, NULL)) != SQLITE_OK)
		return hscf(db_error(db, "poll prepare", ret, stmt, statem));
	if ((ret = sqlite3_step(stmt)) != SQLITE_ROW)
		return hscf(db_error(db, "poll step", ret, stmt, statem));
	char * name = htmlspecialchars((const char *) sqlite3_column_text(stmt, 0));
	char * desc = htmlspecialchars((const char *) sqlite3_column_text(stmt, 1));
	char * poll_pass = htmlspecialchars((const char *) sqlite3_column_text(stmt, 2));
	sqlite3_finalize(stmt);
	char * quests = questions(db, id, admin);
	char * r = malloc((strlen(HTML_START(""))+strlen(STR0(name))*3+strlen(STR0(desc))+strlen(STR0(poll_pass))+strlen(STR0(quests))+2048)*2);
	if (!r || !quests) {
		free(r);
		free(quests);
		free(name);
		free(desc);
		free(poll_pass);
		return strdup("HTTP 502: poll oom");
	}
	if (admin)
		sprintf(r, HTML_START("%s") "<h1>%s</h1><p>za dostop do nastavitev in podatkov obrazca je potreben samo naslov, na katerem ste sedaj, zato si ga shranite.</p><form method=post ><input type=submit name=mp value=shrani /><input type=reset /><input type=submit name=dd value='prenesi podatke'><input type=submit name=aq value='dodaj vprašanje' /><input type=submit name=dp value='izbriši obrazec' /><br><label for=pp>novo geslo - nastavitev novega gesla invalidira naslov za dostop do obrazca (naslovov za reševanje pa ne)</label> <input type=password name=pp id=pp placeholder=geslo value='%s' /><br><label for=pn>ime obrazca</label> <input id=pn name=pn value='%s' placeholder=ime /><br><label for=pd>opis obrazca</label><br><textarea name=pd id=pd placecholder=opis >%s</textarea><br><label for=t>dejanja z elektronskimi naslovi</label><br><textarea name=t id=t placeholder='elektronski naslovi, po en na vrstico'></textarea><br><input type=submit name=gl value='generiraj povezave za reševanje obrazca' /><h2>vprašanja</h2></form><ul>%s</ul>" HTML_END, name, name, poll_pass, name, desc, quests);
	else
		sprintf(r, HTML_START("%s") "<h1>%s</h1><p>%s</p><form method=post ><input type=submit name=sp value='pošlji obrazec' /><input type=reset /><h2>vprašanja</h2><ul>%s</ul><input type=submit name=sp value='pošlji obrazec' /><input type=reset /></form>" HTML_END, name, name, desc, quests);
	return r;
}
static char * auth (struct prijave * prijave, const char * pass, long long int id) {
	int ret;
	char statem[2048];
	if (pass && prijave->pass && !strcmp(pass, prijave->pass))
		return NULL; // system admin password authentication
	sqlite3_stmt * stmt;
	sprintf(statem, "SELECT rowid FROM polls WHERE rowid=%lld AND password=:pw;", id);
	if ((ret = sqlite3_prepare_v3(prijave->db, statem, -1, 0, &stmt, NULL)) != SQLITE_OK)
		return db_error(prijave->db, "502: auth prepare", ret, stmt, statem);
	if ((ret = sqlite3_bind_text(stmt, sqlite3_bind_parameter_index(stmt, ":pw"), pass, -1, SQLITE_STATIC)) != SQLITE_OK)
		return db_error(prijave->db, "502: auth bind_text password", ret, stmt, statem);
	if ((ret = sqlite3_step(stmt)) != SQLITE_ROW)
		return db_error(prijave->db, "403: auth step", ret, stmt, statem);
	sqlite3_finalize(stmt);
	return NULL;
} // returns an error string that must be freed on error or NULL on success
static long long int owner (struct prijave * prijave, const char * owner, const char * thing, long long int thing_id) {
	int ret;
	char statem[2048];
	sqlite3_stmt * stmt;
	sprintf(statem, "SELECT %s FROM %s WHERE rowid=%lld;", owner, thing, thing_id);
	if ((ret = sqlite3_prepare_v3(prijave->db, statem, -1, 0, &stmt, NULL)) != SQLITE_OK) {
		free(db_error(prijave->db, "502: ownership_check prepare", ret, stmt, statem)); // za pisanje v stderr
		return -1;
	}
	if ((ret = sqlite3_step(stmt)) != SQLITE_ROW) {
		free(db_error(prijave->db, "403: ownership_check step", ret, stmt, statem));
		return -2;
	}
	long long int r = sqlite3_column_int64(stmt, 0);
	sqlite3_finalize(stmt);
	return r;
}
static enum MHD_Result httpd (void * userdata, struct MHD_Connection * connection, const char * path, const char * meth, const char * ver __attribute__((unused)), const char * upload, size_t * upload_size, void ** cls) {
	struct prijave * prijave = (struct prijave *) userdata;
	char * response = prijave->hp ? prijave->hp : "HTTP 502: httpd !prijave->hp\n";
	char * content_type = "text/html; charset=UTF-8";
	char * location = NULL;
	int free_location = 0;
	int status_code = MHD_HTTP_OK;
	enum MHD_ResponseMemoryMode rmm = MHD_RESPMEM_PERSISTENT;
	struct request * request = *cls;
	if (strcmp(meth, "GET") && strcmp(meth, "POST")) { // pravzaprav bi bilo
		status_code = MHD_HTTP_NOT_ACCEPTABLE; // bolj prav uporabiti
		response = "HTTP 406\n"; // PUT request, ampak HTML form tega nima /:
		content_type = "text/plain; charset=UTF-8";
		if (request) {
			free_request(request);
			*cls = NULL;
		}
		goto r;
	}
	if (!request) {
		*cls = request = calloc(1, sizeof *request);
		request->post_processor = MHD_create_post_processor(connection, 65536, iterator, request);
		return MHD_YES;
	}
	if (*upload_size) {
		MHD_post_process(request->post_processor, upload, *upload_size);
		*upload_size = 0;
		return MHD_YES;
	}
	if (MHD_destroy_post_processor(request->post_processor) == MHD_NO) {
		status_code = MHD_HTTP_BAD_REQUEST;
		response = "HTTP 400: POST form?\n";
		content_type = "text/plain; charset=UTF-8";
		goto r;
	}
	sqlite3_stmt * stmt;
	int ret;
	char statem[2048];
#define RETURN_ERROR(section) /* racy because of db_error */ \
	{ \
		content_type = "text/plain; charset=UTF-8"; \
		status_code = MHD_HTTP_BAD_GATEWAY; \
		response = db_error(prijave->db, section, ret, stmt, statem); \
		if (!response) { \
			rmm = MHD_RESPMEM_PERSISTENT; \
			response = "HTTP 502: " section " oom\n"; \
			goto r; \
		} \
		rmm = MHD_RESPMEM_MUST_FREE; \
		goto r; \
	}
#define CREATE_TABLE_MORE(table, cols, add) \
	strcpy(statem, "CREATE TABLE IF NOT EXISTS " table " (" cols ")" add); \
	ret = sqlite3_prepare_v3(prijave->db, statem, -1, 0, &stmt, NULL); \
	if (ret != SQLITE_OK) \
		RETURN_ERROR("prepare"); \
	ret = sqlite3_step(stmt); \
	sqlite3_finalize(stmt); \
	if (ret != SQLITE_DONE) \
		RETURN_ERROR("step");
#if SQLITE_VERSION_NUMBER >= 3037000
#define CREATE_TABLE(table, cols) CREATE_TABLE_MORE(table, cols, " STRICT;")
#else
#define CREATE_TABLE(table, cols) CREATE_TABLE_MORE(table, cols, ";")
#endif
	CREATE_TABLE("responses", "email TEXT NOT NULL, question INTEGER NOT NULL, answer ANY");
	CREATE_TABLE("options", "question INTEGER NOT NULL, text TEXT, max INTEGER NOT NULL");
	CREATE_TABLE("questions", "id INTEGER PRIMARY KEY AUTOINCREMENT, poll INTEGER NOT NULL, text TEXT, type INTEGER NOT NULL");
	CREATE_TABLE("polls", "id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT, description TEXT, password TEXT");
	// TODO: CHECK() relation IDs that they exist - poll, question, responses
	// TODO: CHECK() if answer is valid for RADIO/CHECKBOX questions
	// TODO: CHECK() if question type is valid
	if (strstr(path, "css.css")) {
		rmm =  MHD_RESPMEM_MUST_FREE;
#define FORMAT "%s\n%s\n.f:after { content: '%s' }\n"
#define ARGUMENTS prijave->cp_requires_pass ? "" : ".cp_ap { visibility: hidden }", prijave->footer ? "" : ".f { visibility: hidden }", STR0(prijave->footer)
		response = malloc(snprintf(NULL, 0, FORMAT, ARGUMENTS)+1);
		content_type = "text/css; charset=UTF-8";
		if (!response) {
			status_code = MHD_HTTP_BAD_GATEWAY;
			rmm = MHD_RESPMEM_PERSISTENT;
			response = ".f:after { content: 'HTTP 502: css.css oom' }\n";
			goto r;
		}
		sprintf(response, FORMAT, ARGUMENTS);
		status_code = MHD_HTTP_OK;
		goto r;
	}
#define QUERY_FAILED(section) \
	do { \
		response = malloc(strlen(sqlite3_expanded_sql(stmt))+128); \
		content_type = "text/plain; charset=UTF-8"; \
		status_code = MHD_HTTP_FORBIDDEN; \
		rmm = MHD_RESPMEM_MUST_FREE; \
		if (!response) { \
			rmm = MHD_RESPMEM_PERSISTENT; \
			response = "HTTP 403: " section " +oom\n"; \
			goto r; \
		} \
		sprintf(response, "HTTP 403: " section "\n%s\n", sqlite3_expanded_sql(stmt)); \
		sqlite3_finalize(stmt); \
		goto r; \
	} while (0)
	const char * id_string = MHD_lookup_connection_value(connection, MHD_GET_ARGUMENT_KIND, "id");
	const char * pass = MHD_lookup_connection_value(connection, MHD_GET_ARGUMENT_KIND, "p");
	const char * h = MHD_lookup_connection_value(connection, MHD_GET_ARGUMENT_KIND, "h");
	const char * e = MHD_lookup_connection_value(connection, MHD_GET_ARGUMENT_KIND, "e");
	long long int id = -1;
	if (id_string)
		id = strtoll(id_string, NULL, 10);
	switch (request->action) {
		case NO_ACTION:
			break;
		case CREATE_POLL:
			content_type = "text/plain; charset=UTF-8";
			if (prijave->cp_requires_pass && (!request->ap || !prijave->pass || strcmp(request->ap, prijave->pass))) {
				status_code = MHD_HTTP_FORBIDDEN;
				response = "HTTP 403: CREATE_POLL prijave->cp_requires_pass && (!request->ap || !prijave->pass || strcmp(request->ap, prijave->pass))\n";
				goto r;
			}
			response = malloc(128+strlen(request->pp)*3);
			if (!response) {
				status_code = MHD_HTTP_BAD_GATEWAY;
				response = "HTTP 502: CREATE_POLL oom\n";
				goto r;
			}
			strcpy(statem, "INSERT INTO polls (password, name, description) VALUES (:pw, :n, :d)"
#if SQLITE_VERSION_NUMBER >= 3035000
					" RETURNING rowid"
#endif
					);
			if ((ret = sqlite3_prepare_v3(prijave->db, statem, -1, 0, &stmt, NULL)) != SQLITE_OK) {
				free(response);
				RETURN_ERROR("CREATE_POLL prepare");
			}
			if ((ret = sqlite3_bind_text(stmt, sqlite3_bind_parameter_index(stmt, ":pw"), request->pp, -1, SQLITE_STATIC)) != SQLITE_OK) {
				free(response);
				RETURN_ERROR("CREATE_POLL bind_text password");
			}
			if ((ret = sqlite3_bind_text(stmt, sqlite3_bind_parameter_index(stmt, ":n"), request->pn, -1, SQLITE_STATIC)) != SQLITE_OK) {
				free(response);
				RETURN_ERROR("CREATE_POLL bind_text name");
			}
			if ((ret = sqlite3_bind_text(stmt, sqlite3_bind_parameter_index(stmt, ":d"), request->pd, -1, SQLITE_STATIC)) != SQLITE_OK) {
				free(response);
				RETURN_ERROR("CREATE_POLL bind_text description");
			}
			if ((ret = sqlite3_step(stmt)) != SQLITE_DONE && ret != SQLITE_ROW /* for sqlite ^=3.35 */) {
				sqlite3_finalize(stmt);
				free(response);
				RETURN_ERROR("CREATE_POLL step");
			}
			sqlite3_finalize(stmt);
			status_code = MHD_HTTP_SEE_OTHER;
			rmm = MHD_RESPMEM_MUST_FREE;
// THREADSAFE: the following call to sqlite3_last_insert_rowid is racy. it's not a security issue, but if another poll is created before sqlite3_last_insert_rowid is called, the client gets a faulty id that will not work, though he can still solve the problem by using FIND_POLLS.
// better alternative is to use INSERT INTO ... RETURING ... query. but this is only available in sqlite 3.35, so I'll use the legacy option until 3.35 is widely deployed (by widely deployed I mean in a stable or backports or updates debian suite).
#if SQLITE_VERSION_NUMBER >= 3035000
			int written = sprintf(response, "HTTP 201: ?id=%lld&p=", sqlite3_column_int64(stmt, 0));
#else
			int written = sprintf(response, "HTTP 201: ?id=%lld&p=", sqlite3_last_insert_rowid(prijave->db));
#endif
			urlencode(response+written, request->pp);
			location = response+strlen("HTTP 201: ");
			goto r;
		case FIND_POLLS:
			strcpy(statem, "SELECT rowid, name, description FROM polls WHERE password=:pw");
			if (prijave->pass && request->pp && !strcmp(request->pp, request->pp))
				strcat(statem, "OR 1=1;");
			if ((ret = sqlite3_prepare_v3(prijave->db, statem, -1, 0, &stmt, NULL)) != SQLITE_OK)
				RETURN_ERROR("FIND_POLLS prepare");
			if ((ret = sqlite3_bind_text(stmt, sqlite3_bind_parameter_index(stmt, ":pw"), request->pp, -1, SQLITE_STATIC)) != SQLITE_OK)
				RETURN_ERROR("FIND_POLLS bind_text password");
			response = strdup(HTML_START("FIND_POLLS") "<h1>FIND_POLLS</h1><ul>");
			while ((ret = sqlite3_step(stmt)) == SQLITE_ROW) {
				long long int rowid = sqlite3_column_int64(stmt, 0);
				char * name = htmlspecialchars((const char *) sqlite3_column_text(stmt, 1));
				char * desc = htmlspecialchars((const char *) sqlite3_column_text(stmt, 2));
				char * old = response;
				char * pass = malloc(strlen(request->pp)*3+1);
				if (!pass) {
					sqlite3_finalize(stmt);
					free(response);
					status_code = MHD_HTTP_BAD_GATEWAY;
					response = "HTTP 502: FIND_POLLS pass oom\n";
					content_type = "text/plain; charset=UTF-8";
					goto r;
				}
				urlencode(pass, request->pp);
				response = realloc(response, (strlen(response)+strlen(STR0(name))+strlen(STR0(desc))+strlen(pass)+2048)*2);
				if (!response) {
					free(old);
					free(name);
					free(desc);
					sqlite3_finalize(stmt);
					status_code = MHD_HTTP_BAD_GATEWAY;
					response = "HTTP 502: FIND_POLLS while step oom\n";
					content_type = "text/plain; charset=UTF-8";
					goto r;
				}
				if (!old) // in case initial strdup failed
					response[0] = '\0';
				sprintf(response+strlen(response), "<li><a href='?id=%lld&p=%s'>%s</a><p>%s</p></li>", rowid, pass, STR0(name), STR0(desc));
				free(name);
				free(desc);
				free(pass);
			}
			sqlite3_finalize(stmt);
			response = realloc(response, strlen(STR0(response))+2048);
			if (!response) {
				free(response);
				response = "HTTP 502: FIND_POOLS HTML_END oom\n";
			}
			strcat(response, "</ul>" HTML_END);
			if (ret != SQLITE_DONE) {
				free(response);
				RETURN_ERROR("FIND_POLLS step");
			}
			rmm = MHD_RESPMEM_MUST_FREE;
			content_type = "text/html; charset=UTF-8";
			status_code = MHD_HTTP_OK;
			goto r;
		case MODIFY_POLL:
			content_type = "text/plain; charset=UTF-8";
			sprintf(statem, "UPDATE polls SET password=:np, name=:n, description=:d WHERE rowid=%lld AND (password=:pw OR 1=", id);
			if (prijave->pass && pass && !strcmp(prijave->pass, pass))
				strcat(statem, "1)");
			else
				strcat(statem, "0)");
			if ((ret = sqlite3_prepare_v3(prijave->db, statem, -1, 0, &stmt, NULL)) != SQLITE_OK)
				RETURN_ERROR("MODIFY_POLL prepare");
			if ((ret = sqlite3_bind_text(stmt, sqlite3_bind_parameter_index(stmt, ":np"), request->pp, -1, SQLITE_STATIC)) != SQLITE_OK)
				RETURN_ERROR("MODIFY_POLL bind_text np");
			if ((ret = sqlite3_bind_text(stmt, sqlite3_bind_parameter_index(stmt, ":n"), request->pn, -1, SQLITE_STATIC)) != SQLITE_OK)
				RETURN_ERROR("MODIFY_POLL bind_text name");
			if ((ret = sqlite3_bind_text(stmt, sqlite3_bind_parameter_index(stmt, ":d"), request->pd, -1, SQLITE_STATIC)) != SQLITE_OK)
				RETURN_ERROR("MODIFY_POLL bind_text description");
			if ((ret = sqlite3_bind_text(stmt, sqlite3_bind_parameter_index(stmt, ":pw"), pass, -1, SQLITE_STATIC)) != SQLITE_OK)
				RETURN_ERROR("MODIFY_POLL bind_text password");
			location = malloc(64+strlen(request->pp ? request->pp : "x")*3);
			status_code = MHD_HTTP_SEE_OTHER;
			if (location) {
				free_location = 1;
				urlencode(location+sprintf(location, "?id=%lld&p=", id), request->pp);
			} else {
				status_code = MHD_HTTP_BAD_GATEWAY;
				response = "HTTP 502: MODIFY_POLL oom\n";
				sqlite3_finalize(stmt);
				goto r;
			}
			if ((ret = sqlite3_step(stmt)) != SQLITE_DONE)
				QUERY_FAILED("MODIFY_POLL");
			sqlite3_finalize(stmt);
			response = "HTTP 204: MODIFY_POLL\n";
			goto r;
		case DELETE_POLL:
			content_type = "text/plain; charset=UTF-8";
			sprintf(statem, "DELETE FROM polls WHERE rowid=%lld AND (password=:pw OR 1=", id);
			if (prijave->pass && pass && !strcmp(prijave->pass, pass))
				strcat(statem, "1)");
			else
				strcat(statem, "0)");
			if ((ret = sqlite3_prepare_v3(prijave->db, statem, -1, 0, &stmt, NULL)) != SQLITE_OK)
				RETURN_ERROR("DELETE_POLL prepare");
			if ((ret = sqlite3_bind_text(stmt, sqlite3_bind_parameter_index(stmt, ":pw"), pass, -1, SQLITE_STATIC)) != SQLITE_OK)
				RETURN_ERROR("DELETE_POLL bind_text password");
			if ((ret = sqlite3_step(stmt)) != SQLITE_DONE)
				QUERY_FAILED("DELETE_POLL");
			sqlite3_finalize(stmt);
			free_location = 0;
			location = "?dp";
			response = "HTTP 204: DELETE_POLL\n";
			status_code = MHD_HTTP_SEE_OTHER;
			goto r;
		case ADD_QUESTION:
			content_type = "text/plain; charset=UTF-8";
#define PERFORM_AUTH \
			do { \
				char * auth_ret; \
				if ((auth_ret = auth(prijave, pass, id))) { \
					rmm = MHD_RESPMEM_MUST_FREE; \
					response = auth_ret; \
					content_type = "text/plain; charset=UTF-8"; \
					status_code = MHD_HTTP_FORBIDDEN; \
					goto r; \
				} \
			} while (0)
			PERFORM_AUTH;
			sprintf(statem, "INSERT INTO questions (poll, type) VALUES (%lld, %d);", id, HIDDEN);
			if ((ret = sqlite3_prepare_v3(prijave->db, statem, -1, 0, &stmt, NULL)) != SQLITE_OK)
				RETURN_ERROR("ADD_QUESTION prepare");
			if ((ret = sqlite3_step(stmt)) != SQLITE_DONE)
				RETURN_ERROR("ADD_QUESTION step");
			sqlite3_finalize(stmt);
			location = "#d"; // question will always be furthest down
			free_location = 0;
			response = "HTTP 201: ADD_QUESTION\n";
			status_code = MHD_HTTP_SEE_OTHER;
			goto r;
		case DELETE_QUESTION:
			content_type = "text/plain; charset=UTF-8";
			PERFORM_AUTH;
			sprintf(statem, "DELETE FROM questions WHERE rowid=%lld AND poll=%lld", strtoll(request->id ? request->id : "-1", NULL, 10), id);
			if ((ret = sqlite3_prepare_v3(prijave->db, statem, -1, 0, &stmt, NULL)) != SQLITE_OK)
				RETURN_ERROR("DELETE_QUESTION prepare");
			if ((ret = sqlite3_step(stmt)) != SQLITE_DONE)
				RETURN_ERROR("DELETE_QUESTION step");
			sqlite3_finalize(stmt);
			location = "#"; // here we really don't care where we land
			free_location = 0;
			response = "HTTP 204: DELETE_QUESTION\n";
			status_code = MHD_HTTP_SEE_OTHER;
			goto r;
		case MODIFY_QUESTION:
			PERFORM_AUTH;
			enum question type = HIDDEN; // always 0b000; PORTAL#1
			if (request->c)
				type |= NOT_NULL;
			if (request->y) {
				if (request->y[0] == 'c')
					type |= CHECKBOX;
				if (request->y[0] == 't')
					type |= TEXT;
				if (request->y[0] == 'h')
					type |= HIDDEN;
				if (request->y[0] == 'r')
					type |= RADIO;
			}
#define RID strtoll(request->id ? request->id : "-1", NULL, 10)
			sprintf(statem, "UPDATE questions SET text=:t, type=%d WHERE rowid=%lld AND poll=%lld", type, RID, id);
			if ((ret = sqlite3_prepare_v3(prijave->db, statem, -1, 0, &stmt, NULL)) != SQLITE_OK)
				RETURN_ERROR("MODIFY_QUESTION prepare");
			if ((ret = sqlite3_bind_text(stmt, sqlite3_bind_parameter_index(stmt, ":t"), request->t, -1, SQLITE_STATIC)) != SQLITE_OK)
				RETURN_ERROR("MODIFY_QUESTION bind_text text");
			if ((ret = sqlite3_step(stmt)) != SQLITE_DONE)
				RETURN_ERROR("MODIFY_QUESTION step");
			sqlite3_finalize(stmt);
#define PRG_SUCCESS(resp, ...) \
			do { \
				if ((location = malloc(snprintf(NULL, 0, __VA_ARGS__)+128))) { \
					sprintf(location, __VA_ARGS__); \
					free_location = 1; \
				} else { \
					free_location = 0; \
					location = "#oom"; \
				} \
				rmm = MHD_RESPMEM_PERSISTENT; \
				response = resp; \
				content_type = "text/plain; charset=UTF-8"; \
				status_code = MHD_HTTP_SEE_OTHER; \
				goto r; \
			} while (0)
			PRG_SUCCESS("HTTP 204: MODIFY_QUESTION\n", "#q%lld", RID);
		case ADD_OPTION:
			content_type = "text/plain; charset=UTF-8";
			PERFORM_AUTH;
			if (id != owner(prijave, "poll", "questions", RID)) {
				status_code = MHD_HTTP_FORBIDDEN;
				response = "HTTP 403: ADD_OPTION\n";
				goto r;
			}
			sprintf(statem, "INSERT INTO options (question, max) VALUES (%lld, -1)"
#if SQLITE_VERSION_NUMBER >= 3035000
					" RETURNING rowid"
#endif
			, strtoll(request->id ? request->id : "-1", NULL, 10));
			if ((ret = sqlite3_prepare_v3(prijave->db, statem, -1, 0, &stmt, NULL)) != SQLITE_OK)
				RETURN_ERROR("ADD_OPTION prepare");
			if ((ret = sqlite3_step(stmt)) != SQLITE_DONE && ret != SQLITE_ROW)
				RETURN_ERROR("ADD_OPTION step");
#if SQLITE_VERSION_NUMBER >= 3035000
			long long int rowid = sqlite3_column_int64(stmt, 0);
#else
			long long int rowid = sqlite3_last_insert_rowid(prijave->db); // THREADSAFE: this is racy, as mentioned alr
#endif
			sqlite3_finalize(stmt);
			PRG_SUCCESS("HTTP 201: ADD_OPTION\n", "#o%lld", rowid);
		case DELETE_OPTION:
			content_type = "text/plain; charset=UTF-8";
			PERFORM_AUTH;
			long long int q = -1;
			if (id != owner(prijave, "poll", "questions", (q = owner(prijave, "question", "options", RID)))) {
				status_code = MHD_HTTP_FORBIDDEN;
				response = "HTTP 403: DELETE_OPTION\n";
				goto r;
			}
			sprintf(statem, "DELETE FROM options WHERE rowid=%lld", RID);
			if ((ret = sqlite3_prepare_v3(prijave->db, statem, -1, 0, &stmt, NULL)) != SQLITE_OK)
				RETURN_ERROR("DELETE_OPTION prepare");
			if ((ret = sqlite3_step(stmt)) != SQLITE_DONE && ret != SQLITE_ROW)
				RETURN_ERROR("DELETE_OPTION step");
			sqlite3_finalize(stmt);
			PRG_SUCCESS("HTTP 204: DELETE_OPTION\n", "#q%lld", q);
		case MODIFY_OPTION:
			content_type = "text/plain; charset=UTF-8";
			PERFORM_AUTH;
			if (id != owner(prijave, "poll", "questions", owner(prijave, "question", "options", RID))) {
				status_code = MHD_HTTP_FORBIDDEN;
				response = "HTTP 403: MODIFY_OPTION\n";
				goto r;
			}
			sprintf(statem, "UPDATE options SET text=:t, max=%lld WHERE rowid=%lld", strtoll(request->c ? request->c : "-1", NULL, 10), RID);
			if ((ret = sqlite3_prepare_v3(prijave->db, statem, -1, 0, &stmt, NULL)) != SQLITE_OK)
				RETURN_ERROR("MODIFY_OPTION prepare");
			if ((ret = sqlite3_bind_text(stmt, sqlite3_bind_parameter_index(stmt, ":t"), request->t, -1, SQLITE_STATIC)) != SQLITE_OK)
				RETURN_ERROR("MODIFY_OPTION bind_text text");
			if ((ret = sqlite3_step(stmt)) != SQLITE_DONE)
				RETURN_ERROR("MODIFY_OPTION step");
			sqlite3_finalize(stmt);
			PRG_SUCCESS("HTTP 204: MODIFY_OPTION\n", "#o%lld", RID);
		case GENERATE_LINKS:
			PERFORM_AUTH;
			char * saveptr;
			char * delim = "\n";
			if (strchr(request->t, '\r')) {
				delim = "\r\n";
			}
			response = NULL;
			int strings = 1;
			for (int i = 0; request->t[i]; i++)
				strings++;
			if (!(response = malloc(2048+strings*(TOKEN_LEN+512)+strlen(request->t)*3+strlen(request->t)*6))) {
				status_code = MHD_HTTP_BAD_GATEWAY;
				response = "HTTP 502: GENERATE_LINKS oom response\n";
				content_type = "text/plain; charset=UTF-8";
				goto r;
			}
			strcpy(response, HTML_START("GENERATE_LINKS") "<h1>GENERATE_LINKS</h1><ul>");
			written = strlen(HTML_START("GENERATE_LINKS") "<h1>GENERATE_LINKS</h1><ul>");
			char * email = strtok_r(request->t, delim, &saveptr);
			while (email) {
				char * urlencoded = malloc(strlen(email)*3+1);
				char * safeemail = htmlspecialchars(email);
				if (!urlencoded || !safeemail) {
					response = "HTTP 502: GENERATE_LINKS oom while\n";
					content_type = "text/plain; charset=UTF-8";
					status_code = MHD_HTTP_BAD_GATEWAY;
					goto r;
				}
				urlencode(urlencoded, email);
				char tokenbuf[TOKEN_LEN+1];
				token(tokenbuf, id, prijave->salt, email);
				written += sprintf(response+written, "<li><a href=?id=%lld&e=%s&h=%s>%s</a></li>\n", id, urlencoded, tokenbuf, safeemail);
				email = strtok_r(NULL, delim, &saveptr);
				free(urlencoded);
			}
			strcat(response, "</ul>" HTML_END);
			rmm = MHD_RESPMEM_MUST_FREE;
			status_code = MHD_HTTP_OK;
			content_type = "text/html; charset=UTF-8";
			goto r;
		case SUBMIT_POLL:
#define PERFORM_TOKEN \
		do { \
			char tokenbuf[TOKEN_LEN+1]; \
			token(tokenbuf, id, prijave->salt, e); \
			if (strcmp(tokenbuf, h)) { \
				status_code = MHD_HTTP_FORBIDDEN; \
				response = "HTTP 403: strcmp(tokenbuf, h)\n"; \
				content_type = "text/plain; charset=UTF-8"; \
				goto r; \
			} \
		} while (0)
			PERFORM_TOKEN;
			fprintf(stderr, "SUBMIT_POLL\n");
			for (size_t i = 0; i < request->answers_length; i++) {
				fprintf(stderr, "post answer a%lld: %s\n", request->answer_ids[i], STR0(request->answer_strings[i]));
			}
			status_code = MHD_HTTP_BAD_GATEWAY;
			content_type = "text/plain; charset=UTF-8";
			response = "HTTP 502: PERFORM_TOKEN n/i\n";
			goto r;
	}
	if (id_string && e && h) {
		PERFORM_TOKEN;
		response = poll(prijave->db, id, 0);
		if (!response) {
			response = "HTTP 502: !poll(prijave->db, id, 0)\n";
			content_type = "text/plain; charset=UTF-8";
			status_code = MHD_HTTP_BAD_GATEWAY;
			goto r;
		}
		status_code = MHD_HTTP_OK;
		content_type = "text/html; charset=UTF-8";
		rmm = MHD_RESPMEM_MUST_FREE;
		goto r;
	}
	if (id_string && pass) {
		PERFORM_AUTH;
		response = poll(prijave->db, id, 1);
		if (!response) {
			response = "HTTP 502: !poll(prijave->db, id, 1)\n";
			content_type = "text/plain; charset=UTF-8";
			status_code = MHD_HTTP_BAD_GATEWAY;
			goto r;
		}
		status_code = MHD_HTTP_OK;
		content_type = "text/html; charset=UTF-8";
		rmm = MHD_RESPMEM_MUST_FREE;
		goto r;
	}
r:
	;
	struct MHD_Response * httpd_response;
	httpd_response = MHD_create_response_from_buffer(strlen(response), (void *) response, rmm);
	MHD_add_response_header(httpd_response, "Content-Type", content_type);
	if (location)
		MHD_add_response_header(httpd_response, "Location", location);
	if (free_location)
		free(location);
	int r = MHD_queue_response(connection, status_code, httpd_response);
	MHD_destroy_response(httpd_response);
	free_request(request);
	*cls = NULL;
	return r;
}
static void handler (int s __attribute__((unused))) {
	return;
}
int main (void) {
	int r = 0;
	struct prijave prijave;
	memset(&prijave, 0, sizeof prijave);
	umask(00077);
	prijave.cp_requires_pass = getenv("PR_CP_REQUIRES_PASS") ? 1 : 0;
	prijave.footer = getenv("PR_FOOTER");
	prijave.pass = getenv("PR_PASS"); // set to disable anyone to create polls
	prijave.salt = getenv("PR_SALT");
	assert(getenv("PR_DB"));
	assert(sqlite3_threadsafe());
	int ret = sqlite3_open_v2(getenv("PR_DB"), &prijave.db, SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE | SQLITE_OPEN_NOMUTEX
#if SQLITE_VERSION_NUMBER >= 3037000
			| SQLITE_OPEN_EXRESCODE
#endif
			, NULL);
	if (ret != SQLITE_OK) {
		fprintf(stderr, "sqlite3_open_v2: %s\n", sqlite3_errstr(ret));
		goto r;
	}
	if (getenv("PR_HP")) {
		int hp = open(getenv("PR_HP"), O_RDONLY);
		if (hp == -1) {
			perror("open(getenv(\"PR_HP\"), O_RDONLY)");
			prijave.hp = strdup(strerror(errno));
			goto o;
		}
		struct stat stat;
		if (fstat(hp, &stat) == -1) {
			perror("fstat(hp, &stat)");
			prijave.hp = strdup(strerror(errno));
			goto c;
		}
		prijave.hp = malloc(stat.st_size+1);
		if (prijave.hp) {
			int r;
			prijave.hp[(r = read(hp, prijave.hp, stat.st_size)) >= 0 ? r : 0] = '\0';
		} else {
			prijave.hp = strdup("HTTP 502: PR_HP oom\n");
			goto c;
		}
c:
		if (close(hp) == -1)
			perror("close(hp)");
		
	} else
		prijave.hp = strdup("HTTP 404: !getenv(\"PR_HP\")\n");
o:
	;
	struct MHD_Daemon * d = MHD_start_daemon(MHD_USE_INTERNAL_POLLING_THREAD, atoi(getenv("PR_PORT") ? getenv("PR_PORT") : PR_PORT), NULL, NULL, &httpd, &prijave, MHD_OPTION_NOTIFY_COMPLETED, &request_completed, NULL, MHD_OPTION_END);
	if (!d) {
		r = 1;
		goto r;
	}
	signal(SIGTERM, handler);
	signal(SIGINT, handler);
	pause();
r:
	if (d)
		MHD_stop_daemon(d); // to počaka na smrt vseh threadov afaik
	if (prijave.db)
		sqlite3_close_v2(prijave.db); // zato se tudi vsi stmtji izlkopijo
	free(prijave.hp);
	return r;
}