-
Notifications
You must be signed in to change notification settings - Fork 1
/
userserv.c
425 lines (376 loc) · 12.6 KB
/
userserv.c
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
#define _GNU_SOURCE
//#define LOGGING
#include <unistd.h>
#include <sys/stat.h>
#include <stdarg.h>
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>
#include <signal.h>
#include <fcntl.h>
#include <pwd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/ip.h>
#include "urlcode.c"
#define BUFFER_SIZE 8192
#define HEADER_LIMIT 200
void logText(char* text);
void fail(char* text);
void logFormat(char* text,...);
#include "readuntil.c"
#include "authenticationtoken.c"
#include "websocketbridge.c"
#include "mimehash.c"
#ifdef LOGGING
#define LOGFILE "/var/log/userserv.log"
void logText(char* text) {
int fd = open(LOGFILE, O_CREAT| O_WRONLY | O_APPEND,0644);
if (fd>=0) {
write(fd,text,strlen(text));
write(fd,"\n",1);
close(fd);
}
}
void logFormat(char* text,...) {
int fd = open(LOGFILE, O_CREAT| O_WRONLY | O_APPEND,0644);
if (fd>=0) {
va_list arglist;
va_start(arglist, text);
vdprintf(fd,text, arglist);
close(fd);
}
}
void fail(char* text) {
char msgBuffer[16384];
sprintf(msgBuffer,"ERROR: %s (errno=%d) exiting process %d",text,errno,getpid());
logText(msgBuffer);
exit(3);
}
#else
void logText(char* text) {}
void logFormat(char* text,...) {}
void fail(char* text) {exit(3);}
#endif
char* loginRedirect="~";
void scrub() {
int i;
for (i=0;i<32;i++) {
close(i);
}
}
void sendHTMLPage(int fd, char* status,char* headers, char* content) {
dprintf(fd,"HTTP/1.1 %s \r\n%sContent-Type: text/html\r\nContent-Length: %zu\r\nConnection:close\r\n\r\n%s", status,headers, strlen(content),content);
}
void sendSimpleHTMLPage(int fd, char* status, char* content) {
dprintf(fd,"HTTP/1.1 %s \r\nContent-Length: %zu\r\nConnection:close\r\n\r\n%s", status, strlen(content),content);
}
void sendFile(int socketfd, char* status, int filefd, char * content_type) {
long length = (long)lseek(filefd, (off_t)0, SEEK_END); /* lseek to the file end to find the length */
lseek(filefd, (off_t)0, SEEK_SET);
dprintf(socketfd,"HTTP/1.1 %s \r\nContent-Type: %s;\r\nContent-Length: %ld\r\nConnection:close\r\n\r\n",status, content_type , length);
char buffer[BUFFER_SIZE];
int bytesRead;
while ((bytesRead = read(filefd,buffer,BUFFER_SIZE)) >0) {
write(socketfd,buffer,bytesRead);
}
}
void sendFileChunked(int socketfd, char* status, int filefd, char* content_type) {
dprintf(socketfd,"HTTP/1.1 %s \r\nContent-Type: %s;\r\nTransfer-Encoding: chunked\r\nConnection:close\r\n\r\n",status, content_type);
char buffer[BUFFER_SIZE];
int bytesRead;
while ((bytesRead = read(filefd,buffer,BUFFER_SIZE)) >0) {
dprintf(socketfd, "%x\r\n",bytesRead);
write(socketfd,buffer,bytesRead);
dprintf(socketfd, "\r\n");
}
dprintf(socketfd, "0\r\n\r\n");
}
char* findHeader(int start, int headerCount, char** headerList, const char* name) {
int walk = start;
int namelen=strlen(name);
while (walk < headerCount) {
if (strncmp(name,headerList[walk],namelen) == 0) {
char* result=headerList[walk]+namelen;
return result+strspn(result," \t");
}
walk+=1;
}
return NULL;
}
void sendLoginPage(int socketfd) {
char* loginPage="<html><head>"
"<style>"
"body{background-color:grey; font-family: sans-serif}"
"input{background-color:white}"
"#loginBox{position:absolute;top:40%; left:0px; right:0px;}"
"input{float:right;width:16em;}"
"#loginBox>form>div{padding: 8px}"
"#loginBox>form{background-color: #dfd;margin: 0 auto; box-shadow:0px 0px 0px 2px black,3px 3px 12px 2px black;width:20em; padding: 40px; border-radius: 8px 64px 8px 64px}"
"</style></head>"
"<body><div id=\"loginBox\">"
"<form action=\"/login\" method=\"post\"><div><label for=\"user\">User Name</label><input type=\"text\" id=\"user\" name=\"user\" /></div><div><label for=\"pass\">Password</label><input type=\"password\" id=\"pass\" name=\"pass\"/></div><div><input type=\"submit\" value=\"login\"></div></form>"
"</div></body></html>";
char* headers = "";
logText("Sending login page");
sendHTMLPage(socketfd,"200 ok",headers,loginPage);
}
char* getContentType(char* filename) {
// returns an allocated string, must be freed;
#ifdef EXTERNAL_MIMETYPE
char buffer[BUFFER_SIZE];
char* command;
asprintf(&command,"mimetype -b \"%s\"",filename);
FILE* fp = popen(command,"r");
free(command);
if (fp == NULL) return strdup("text/plain");
char* r = fgets(buffer,sizeof(buffer),fp);
pclose(fp);
if (r == NULL) return strdup("text/plain");
return strdup(buffer);
#else
char* fname=strrchr(filename,'/');
fname = (fname==NULL)?filename:fname+1;
char* extension = strrchr(fname,'.');
if (extension==NULL) return strdup("text/plain");
struct fext* contentType;
contentType=findExtensionType(extension+1);
if (contentType==NULL) return strdup("text/plain");
return strdup(contentType->content_type);
#endif
}
char* expandFilename(const char* original) {
char* home = getenv("HOME");
logFormat("$HOME is %s\n",home);
if (strcmp(original,"/~")==0) return strdup(home);
if (strncmp(original,"/~/",3)==0) {
char* result;
int len=asprintf(&result,"%s%s",home,original+2);
return(result);
}
return strdup(original);
}
void handleConnection(int socketfd) {
static char buffer[BUFFER_SIZE+1];
static char* headers[HEADER_LIMIT+1];
int i;
int headerCount=0;
//int requestSize = read(socketfd,buffer,BUFFER_SIZE);
int requestSize = readUntil(socketfd,crlfcrlfCheck,buffer,BUFFER_SIZE);
if (requestSize ==0 || requestSize == -1) {
fail("failed to read browser request");
}
logText(buffer);
int done = 0;
char mode = 0; /* */
for (i=0;i<requestSize;i++) {
switch(mode) {
case '\r':
if (buffer[i] == '\n') {
buffer[i-1]=0;
mode=0;
done = (*headers[headerCount]==0) || (headerCount++ == HEADER_LIMIT);
}
break;
case 0:
headers[headerCount]=&buffer[i];
default:
mode=buffer[i];
if (mode==0) done=1; /* catch headers containing zeros */
}
if (done) break;
}
int bodyStart=i+1;
int bodyLength=requestSize-bodyStart;
headers[headerCount]=NULL; /*null terminated list*/
logFormat("%d header lines\n",headerCount);
logText("we got some headers");
for (i=0; i<headerCount;i++) {
logFormat("%d: %s\n",i,headers[i]);
}
logText("That was them headers");
/*
logText("looking for User-Agent:");
char* userAgent=findHeader(0,headerCount,headers,"User-Agent:");
if (userAgent==NULL) {logText("No User-Agent");} else {logText(userAgent);}
*/
char* aCookie = findHeader(0,headerCount,headers,"Cookie:");
int uid=getUserInfo(aCookie);
logFormat("uid of %d\n",uid);
if (uid <= 0) {
if (strncmp("POST /login ",headers[0],12) == 0 ) {
//for a non-logged-in user POST to /login try and read user credentials.
logText("Login request received");
char userpass[300];
struct passwd* pwd = NULL;
strncpy(userpass,&buffer[bodyStart],300);
if (userpass[299] == 0) {
char* user = NULL;
char* pass = NULL;
user = strstr(userpass,"user=")+5;
pass = url_decode(strstr(userpass,"pass=")+5);
char* ampersand;
while((ampersand=strchr(userpass,'&'))!=NULL) {
*ampersand = 0;
}
//logFormat("I think the userName is '%s'\n",user);
//logFormat("I think the passWord is '%s'\n",pass);
pwd = checkUserPass(user,pass);
free(pass);
}
char* resultPage;
if (pwd != NULL) {
logText("setting cookie");
char token[33];
token[32]='\0';
makeAuthenticationToken(pwd->pw_uid,token,32);
char* pageHeaders;
asprintf(&pageHeaders,"Set-Cookie: %s; Secure; HttpOnly\r\nLocation: %s\r\n",token,loginRedirect);
logText(pageHeaders);
resultPage=
"<html><head></head><body"
"<div>Login Successful</div>"
"</body></html>";
sendHTMLPage(socketfd,"303 See Other",pageHeaders,resultPage);
free(pageHeaders);
} else {
resultPage=
"<html><head></head><body"
"<div>Login Failed</div>"
"</body></html>";
sendSimpleHTMLPage(socketfd,"401 Unauthorised",resultPage);
}
} else {
sendLoginPage(socketfd);
}
} else {
struct passwd *pw = getpwuid(uid);
setgid(uid);
setuid(uid);
setenv("HOME",pw->pw_dir,1);
setenv("USER",pw->pw_name,1);
setenv("SHELL",pw->pw_shell,1);
//if we get to here, the request sent a token identifying them as a
//valid user and we have dropped privileges to be that user.
//now we can set about serving the user request.
#ifdef NOTANOS
//support for a notanos websocket server.
char* upgrade = findHeader(0,headerCount,headers,"Upgrade:");
if (upgrade) {
//Try using websockets
char* websocket_key = findHeader(0,headerCount,headers,"Sec-WebSocket-Key:");
char* websocket_protocol = findHeader(0,headerCount,headers,"Sec-WebSocket-Protocol:");
char* websocket_version = findHeader(0,headerCount,headers,"Sec-WebSocket-Version:");
char* origin = findHeader(0,headerCount,headers,"Origin:");
webSocketUpgrade(socketfd,websocket_key,websocket_protocol,websocket_version,origin);
//webSocketUpgrade should never return
}
#endif
if (strncmp("GET ",headers[0],4) == 0 ) {
char* nameStart=headers[0]+4;
int nameLen = strcspn(nameStart," ");
char* urlName=strndup(nameStart,nameLen);
char* fileName=url_decode(urlName);
char* queryStart=strchr(fileName,'?');
if (queryStart != NULL) *queryStart++='\0';
logFormat("url request '%s'\n",urlName);
logFormat("filename request '%s'\n",fileName);
char* newFileName=expandFilename(fileName);
free(fileName); fileName=newFileName;
char* contentType=getContentType(fileName);
struct stat fileInfo;
int res=stat(fileName,&fileInfo);
if (res !=0) {
if (errno == EACCES) {
sendSimpleHTMLPage(socketfd,"403 Forbidden","403: Forbidden");
} else {
sendSimpleHTMLPage(socketfd,"404 Not Found","404: Not Found");
}
} else {
if (S_ISREG(fileInfo.st_mode)) {
int filefd=open(fileName,O_RDONLY);
if (filefd < 0) {
sendSimpleHTMLPage(socketfd,"403 Forbidden","403: Forbidden");
} else {
sendFileChunked(socketfd,"200 OK",filefd,contentType);
close(filefd);
}
}
else if (S_ISDIR(fileInfo.st_mode)) {
char* command;
char* awkline = "BEGIN {printf(\"{\\\"path\\\":\\\"%s\\\",\\n \\\"contents\\\":[\\n\",path)} END{print\"\\n ]\\n};\\n\"} NR > 2 { printf(\",\\n\") } NR >1 { printf(\" {\\\"filename\\\":\\\"%s\\\", \\\"attributes\\\":\\\"%s\\\", \\\"owner\\\":\\\"%s\\\", \\\"size\\\":%s}\", $9, $1, $3, $5) }";
//int commandLength = asprintf(&command,"ls -AlQ %s| awk -v path=%s '%s'",fileName,fileName,awkline);
int commandLength = asprintf(&command,"./jsondir '%s'",fileName);
logText(command);
if (commandLength>0) {
FILE* commandPipe = popen(command,"r");
if (commandPipe) {
int commandfd=(fileno(commandPipe));
sendFileChunked(socketfd,"200 OK",commandfd,"application/json");
pclose(commandPipe);
} else {
sendSimpleHTMLPage(socketfd,"500 Internal Server Error","popen failure");
}
free(command);
} else {
sendSimpleHTMLPage(socketfd,"200 OK","That's a directory");
}
}
}
free(fileName);
free(contentType);
free(urlName);
}
}
logText("done response, closing connection");
sleep(1);
close(socketfd);
exit(1);
}
void serverListen(int port) {
int listenfd = socket(AF_INET, SOCK_STREAM,0);
static struct sockaddr_in serverAddress;
static struct sockaddr_in clientAddress;
serverAddress.sin_family = AF_INET;
//serverAddress.sin_addr.s_addr = htonl(INADDR_ANY);
serverAddress.sin_addr.s_addr = htonl((127<<24)|1); //127.0.0.1
serverAddress.sin_port = htons(port);
if (listenfd<0) fail("Couldn't create listen socket");
if ( bind(listenfd,(struct sockaddr*)&serverAddress,sizeof(serverAddress)) <0 )
fail("couldn't bind socket");
if (listen(listenfd,64) < 0)
fail("listen() failed");
for(;;) {
int length = sizeof(clientAddress);
int socketfd = accept(listenfd,(struct sockaddr *) &clientAddress, &length);
if (socketfd < 0) fail("failure on accept()");
int pid = fork();
if (pid < 0) fail("fork Failed!?");
if (pid == 0) {
close(listenfd);
handleConnection(socketfd);
fail("We should never have gotten to this line of code");
}
close(socketfd);
}
}
void flushOldFiles() {
system("find /var/lib/userserv -type f -mtime +1 -exec rm {} \\;");
}
void init() {
system("mkdir -p /var/lib/userserv -m 700");
flushOldFiles();
char* userRedirect=getenv("WEBLOGIN_REDIRECT");
if (userRedirect) loginRedirect=userRedirect;
}
int main (int argc, char **argv) {
init();
if (fork() !=0 ) return 0;
(void) signal(SIGCLD, SIG_IGN);
(void) signal(SIGHUP, SIG_IGN);
scrub();
logText("Starting");
serverListen(8082);
fail("testing failure");
}