handle server which aren't cgi "Status" aware
[cwebfiles.git] / login.c
1 #define _GNU_SOURCE
2
3 #include <stdlib.h>
4 #include <string.h>
5 #include "cwebfiles.h"
6 #include <sys/types.h>
7 #include <sys/stat.h>
8 #include <fcntl.h>
9 #include <time.h>
10 #include <unistd.h>
11 #include <shadow.h>
12 #include <pwd.h>
13 #include <stdio.h>
14
15 extern char **environ;
16
17 #define BADAUTH "invalid user/pass"
18
19 int main() {
20   FASTOUTPUT
21   environ = NULL;
22   setuid(0);
23   
24   char buf[1024];
25   int res = read(0, buf, 1023);
26   if (res == -1) senderr("couldn't read POST data", NOTMYFAULT);
27   buf[res] = 0;
28   char *nl = strchr(buf, '\r');
29   if (nl != NULL) *nl = 0;
30   char *user = buf;
31   char *pass = strchr(buf, ':');
32   if (pass == NULL) senderr("can't find user-pass-seperator", NOTMYFAULT);
33   *pass = 0;
34   pass++;
35   
36   // verify password
37   struct spwd *shadow_entry = getspnam(user);
38   struct passwd *passwd_entry = getpwnam(user);
39   if (passwd_entry == NULL || shadow_entry == NULL) senderr(BADAUTH, NOTMYFAULT);
40   char *enc_pass = crypt(pass, shadow_entry->sp_pwdp);
41   if (enc_pass == NULL) senderr(BADAUTH, NOTMYFAULT);
42   if (strcmp(enc_pass, shadow_entry->sp_pwdp) != 0) senderr(BADAUTH, NOTMYFAULT);
43   
44   // now create a new session
45   // create a cookie
46   unsigned char bincookie[COOKIE_LENGTH/2];
47   grabrand(bincookie, COOKIE_LENGTH/2);
48   char cookie[COOKIE_LENGTH+1];
49   hex(cookie, bincookie, COOKIE_LENGTH/2);
50   cookie[COOKIE_LENGTH] = 0;
51   
52   // set session data
53   strncpy(session.user_name, user, 33);
54   session.start_time = time(NULL);
55   session.uid = passwd_entry->pw_uid;
56   
57   // write out session data to the fs
58   persist_session(cookie);
59   
60   // phew, all done! tell the user everything is fine
61   puts("Status: 200 login successful");
62   puts("X-Frame-Options: DENY");
63   puts("Content-Type: text/plain;charset=utf8");
64   // TODO XXX XXX XXX XXX XXX XXX XXX XXX XXX XXX XXX XXX XXX SET SECURE FLAG!
65   printf("Set-Cookie: " COOKIE_NAME "=%s; HttpOnly\n", cookie);
66   puts("");
67   puts("OK");
68 }