* do_login(): if we're already logged in, don't show st00pit shit, but the main-menu...
[citadel.git] / webcit / auth.c
1 /*
2  * $Id$
3  *
4  * WebcitAuth; Handles authentication of users to a Citadel server.
5  *
6  * Copyright (c) 1996-2010 by the citadel.org team
7  *
8  * This program is free software; you can redistribute it and/or modify
9  * it under the terms of the GNU General Public License as published by
10  * the Free Software Foundation; either version 3 of the License, or
11  * (at your option) any later version.
12  *
13  * This program is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16  * GNU General Public License for more details.
17  *
18  * You should have received a copy of the GNU General Public License
19  * along with this program; if not, write to the Free Software
20  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
21  */
22
23 #include "webcit.h"
24 #include "webserver.h"
25 #include <ctype.h>
26
27 extern uint32_t hashlittle( const void *key, size_t length, uint32_t initval);
28
29 void display_reg(int during_login);
30
31 /*
32  * Access level definitions.  This is initialized from a function rather than a
33  * static array so that the strings may be localized.
34  */
35 char *axdefs[7]; 
36
37 void initialize_axdefs(void) {
38         axdefs[0] = _("Deleted");       /* an erased user */
39         axdefs[1] = _("New User");      /* a new user */
40         axdefs[2] = _("Problem User");  /* a trouble maker */
41         axdefs[3] = _("Local User");    /* user with normal privileges */
42         axdefs[4] = _("Network User");  /* a user that may access network resources */
43         axdefs[5] = _("Preferred User");/* a moderator */
44         axdefs[6] = _("Aide");          /* chief */
45 }
46
47
48
49 /* 
50  * Display the login screen
51  * mesg = the error message if last attempt failed.
52  */
53 void display_login(void)
54 {
55         begin_burst();
56         output_headers(1, 0, 0, 0, 1, 0);
57         do_template("login", NULL);
58         end_burst();
59 }
60
61
62
63
64 /* 
65  * Display the openid-enabled login screen
66  * mesg = the error message if last attempt failed.
67  */
68 void display_openid_login(char *mesg)
69 {
70   begin_burst();
71   output_headers(1, 0, 0, 0, 1, 0);
72   do_template("openid_login", NULL);
73   end_burst();
74 }
75
76
77 void display_openid_name_request(const StrBuf *claimed_id, const StrBuf *username) 
78 {
79         StrBuf *Buf = NULL;
80
81         output_headers(1, 1, 2, 0, 0, 0);
82         wc_printf("<div id=\"login_screen\">\n");
83
84         Buf = NewStrBufPlain(NULL, StrLength(claimed_id));
85         StrEscAppend(Buf, claimed_id, NULL, 0, 0);
86         svprintf(HKEY("VERIFIED"), WCS_STRING, _("Your OpenID <tt>%s</tt> was successfully verified."),
87                  ChrPtr(Buf));
88         SVPutBuf("CLAIMED_ID", Buf, 0);
89
90
91         if (StrLength(username) > 0) {
92                         Buf = NewStrBufPlain(NULL, StrLength(username));
93                         StrEscAppend(Buf, username, NULL, 0, 0);
94                         svprintf(HKEY("REASON"), WCS_STRING,
95                                  _("However, the user name '%s' conflicts with an existing user."), 
96                                  ChrPtr(Buf));
97                         FreeStrBuf(&Buf);
98         }
99         else {
100                 svput("REASON", WCS_STRING, "");
101         }
102
103         svput("ACTION_REQUESTED", WCS_STRING, _("Please specify the user name you would like to use."));
104
105         svput("USERNAME_BOX", WCS_STRING, _("User name:"));
106         svput("NEWUSER_BUTTON", WCS_STRING, _("New User"));
107         svput("EXIT_BUTTON", WCS_STRING, _("Exit"));
108
109         svprintf(HKEY("BOXTITLE"), WCS_STRING, _("%s - powered by <a href=\"http://www.citadel.org\">Citadel</a>"),
110                  ChrPtr(WC->serv_info->serv_humannode));
111
112         do_template("openid_manual_create", NULL);
113         wDumpContent(2);
114 }
115
116
117
118 /* Initialize the session
119  *
120  * This function needs to get called whenever the session changes from
121  * not-logged-in to logged-in, either by an explicit login by the user or
122  * by a timed-out session automatically re-establishing with a little help
123  * from the browser cookie.  Either way, we need to load access controls and
124  * preferences from the server.
125  *
126  * user                 the username
127  * pass                 his password
128  * serv_response        The parameters returned from a Citadel USER or NEWU command
129  */
130 void become_logged_in(const StrBuf *user, const StrBuf *pass, StrBuf *serv_response)
131 {
132         wcsession *WCC = WC;
133         StrBuf *Buf;
134         StrBuf *FloorDiv;
135
136         WCC->logged_in = 1;
137
138         if (WCC->wc_fullname == NULL)
139                 WCC->wc_fullname = NewStrBufPlain(NULL, StrLength(serv_response));
140         StrBufExtract_token(WCC->wc_fullname, serv_response, 0, '|');
141         StrBufCutLeft(WCC->wc_fullname, 4 );
142         
143         if (WCC->wc_username == NULL)
144                 WCC->wc_username = NewStrBufDup(user);
145         else {
146                 FlushStrBuf(WCC->wc_username);
147                 StrBufAppendBuf(WCC->wc_username, user, 0);
148         }
149
150         if (WCC->wc_password == NULL)
151                 WCC->wc_password = NewStrBufDup(pass);
152         else {
153                 FlushStrBuf(WCC->wc_password);
154                 StrBufAppendBuf(WCC->wc_password, pass, 0);
155         }
156
157         WCC->axlevel = StrBufExtract_int(serv_response, 1, '|');
158         if (WCC->axlevel >= 6) { /* TODO: make this a define, else it might trick us later */
159                 WCC->is_aide = 1;
160         }
161
162         load_preferences();
163
164         Buf = NewStrBuf();
165         serv_puts("CHEK");
166         StrBuf_ServGetln(Buf);
167         if (GetServerStatus(Buf, NULL) == 2) {
168                 const char *pch;
169
170                 pch = ChrPtr(Buf) + 4;
171                 /*WCC->new_mail  =*/ StrBufExtractNext_long(Buf, &pch, '|');
172                 WCC->need_regi = StrBufExtractNext_long(Buf, &pch, '|');
173                 WCC->need_vali = StrBufExtractNext_long(Buf, &pch, '|');
174                 if (WCC->cs_inet_email == NULL)
175                         WCC->cs_inet_email  = NewStrBuf();
176                 StrBufExtract_NextToken(WCC->cs_inet_email, Buf, &pch, '|');
177         }
178         get_preference("floordiv_expanded", &FloorDiv);
179         WCC->floordiv_expanded = FloorDiv;
180         FreeStrBuf(&Buf);
181 }
182
183
184 /* 
185  * Perform authentication using a user name and password
186  */
187 void do_login(void)
188 {
189         wcsession *WCC = WC;
190         StrBuf *Buf;
191         long ret, rc;
192
193         if (havebstr("language")) {
194                 set_selected_language(bstr("language"));
195                 go_selected_language();
196         }
197
198         if (havebstr("exit_action")) {
199                 do_logout();
200                 return;
201         }
202         Buf = NewStrBuf();
203         if (havebstr("login_action")) {
204                 serv_printf("USER %s", bstr("name"));
205                 StrBuf_ServGetln(Buf);
206                 rc = GetServerStatus(Buf, &ret);
207                 StrBufCutLeft(Buf, 4);
208                 switch (rc) {
209                 case 3:
210                         serv_printf("PASS %s", bstr("pass"));
211                         StrBuf_ServGetln(Buf);
212                         if (GetServerStatus(Buf, NULL) == 2) {
213                                 become_logged_in(sbstr("name"), sbstr("pass"), Buf);
214                         } else {
215                                 StrBufCutLeft(Buf, 4);
216                                 AppendImportantMessage(SKEY(Buf));
217                                 display_login();
218                                 FreeStrBuf(&Buf);
219                                 return;
220                         }
221                         break;
222                 case 5:
223                         if (ret == 541)
224                         {
225                                 AppendImportantMessage(SKEY(Buf));
226                                 display_main_menu();
227                                 return;
228                         }
229                 default:
230                         AppendImportantMessage(SKEY(Buf));
231                         display_login();
232                         FreeStrBuf(&Buf);
233                         return;
234                 }
235         }
236         if (havebstr("newuser_action")) {
237                 if (!havebstr("pass")) {
238                         AppendImportantMessage(_("Blank passwords are not allowed."), -1);
239                         display_login();
240                         FreeStrBuf(&Buf);
241                         return;
242                 }
243                 serv_printf("NEWU %s", bstr("name"));
244                 StrBuf_ServGetln(Buf);
245                 if (GetServerStatus(Buf, NULL) == 2) {
246                         become_logged_in(sbstr("name"), sbstr("pass"), Buf);
247                         serv_printf("SETP %s", bstr("pass"));
248                         StrBuf_ServGetln(Buf); /* Don't care? */
249                 } else {
250                         StrBufCutLeft(Buf, 4);
251                         AppendImportantMessage(SKEY(Buf));
252                         display_login();
253                         FreeStrBuf(&Buf);
254                         return;
255                 }
256         }
257         if (WCC->logged_in) {
258                 if (WCC->need_regi) {
259                         display_reg(1);
260                 } else if (WCC->need_vali) {
261                         validate();
262                 } else {
263                         do_welcome();
264                 }
265         } else {
266                 AppendImportantMessage(_("Your password was not accepted."), -1);
267                 display_login();
268         }
269         FreeStrBuf(&Buf);
270 }
271
272 /* 
273  * Try to create an account manually after an OpenID was verified
274  */
275 void openid_manual_create(void)
276 {
277         StrBuf *Buf;
278
279         if (havebstr("exit_action")) {
280                 do_logout();
281                 return;
282         }
283
284         if (havebstr("newuser_action")) {
285                 Buf = NewStrBuf();
286                 serv_printf("OIDC %s", bstr("name"));
287                 StrBuf_ServGetln(Buf);
288                 if (GetServerStatus(Buf, NULL) == 2) {
289                         StrBuf *gpass;
290
291                         gpass = NewStrBuf();
292                         serv_puts("SETP GENERATE_RANDOM_PASSWORD");
293                         StrBuf_ServGetln(gpass);
294                         StrBufCutLeft(gpass, 4);
295                         become_logged_in(sbstr("name"), gpass, Buf);
296                         FreeStrBuf(&gpass);
297                 }
298                 FreeStrBuf(&Buf);
299         }
300
301         if (WC->logged_in) {
302                 if (WC->need_regi) {
303                         display_reg(1);
304                 } else if (WC->need_vali) {
305                         validate();
306                 } else {
307                         do_welcome();
308                 }
309         } else {
310                 display_openid_name_request(sbstr("openid_url"), sbstr("name"));
311         }
312
313 }
314
315
316 /* 
317  * Perform authentication using OpenID
318  * assemble the checkid_setup request and then redirect to the user's identity provider
319  */
320 void do_openid_login(void)
321 {
322         wcsession *WCC = WC;
323         char buf[4096];
324
325         if (havebstr("language")) {
326                 set_selected_language(bstr("language"));
327                 go_selected_language();
328         }
329
330         if (havebstr("exit_action")) {
331                 do_logout();
332                 return;
333         }
334         if (havebstr("login_action")) {
335                 snprintf(buf, sizeof buf,
336                         "OIDS %s|%s://%s/finalize_openid_login|%s://%s",
337                         bstr("openid_url"),
338                          (is_https ? "https" : "http"), ChrPtr(WCC->Hdr->HR.http_host),
339                          (is_https ? "https" : "http"), ChrPtr(WCC->Hdr->HR.http_host)
340                 );
341
342                 serv_puts(buf);
343                 serv_getln(buf, sizeof buf);
344                 if (buf[0] == '2') {
345                         lprintf(CTDL_DEBUG, "OpenID server contacted; redirecting to %s\n", &buf[4]);
346                         http_redirect(&buf[4]);
347                         return;
348                 }
349                 else {
350                         display_openid_login(&buf[4]);
351                         return;
352                 }
353         }
354
355         /* If we get to this point then something failed. */
356         display_openid_login(_("Your password was not accepted."));
357 }
358
359 /* 
360  * Complete the authentication using OpenID
361  * This function handles the positive or negative assertion from the user's Identity Provider
362  */
363 void finalize_openid_login(void)
364 {
365         StrBuf *Buf;
366         wcsession *WCC = WC;
367         int already_logged_in = (WCC->logged_in) ;
368         int linecount = 0;
369         StrBuf *result = NULL;
370         StrBuf *username = NULL;
371         StrBuf *password = NULL;
372         StrBuf *logged_in_response = NULL;
373         StrBuf *claimed_id = NULL;
374
375         if (havebstr("openid.mode")) {
376                 if (!strcasecmp(bstr("openid.mode"), "id_res")) {
377                         Buf = NewStrBuf();
378                         serv_puts("OIDF");
379                         StrBuf_ServGetln(Buf);
380                         if (GetServerStatus(Buf, NULL) == 8) {
381                                 urlcontent *u;
382                                 void *U;
383                                 long HKLen;
384                                 const char *HKey;
385                                 HashPos *Cursor;
386                                 
387                                 Cursor = GetNewHashPos (WCC->Hdr->urlstrings, 0);
388                                 while (GetNextHashPos(WCC->Hdr->urlstrings, Cursor, &HKLen, &HKey, &U)) {
389                                         u = (urlcontent*) U;
390                                         if (!strncasecmp(u->url_key, "openid.", 7)) {
391                                                 serv_printf("%s|%s", &u->url_key[7], ChrPtr(u->url_data));
392                                         }
393                                 }
394
395                                 serv_puts("000");
396
397                                 linecount = 0;
398                                 while (StrBuf_ServGetln(Buf), strcmp(ChrPtr(Buf), "000")) 
399                                 {
400                                         if (linecount == 0) result = NewStrBufDup(Buf);
401                                         if (!strcasecmp(ChrPtr(result), "authenticate")) {
402                                                 if (linecount == 1) {
403                                                         username = NewStrBufDup(Buf);
404                                                 }
405                                                 else if (linecount == 2) {
406                                                         password = NewStrBufDup(Buf);
407                                                 }
408                                                 else if (linecount == 3) {
409                                                         logged_in_response = NewStrBufDup(Buf);
410                                                 }
411                                         }
412                                         else if (!strcasecmp(ChrPtr(result), "verify_only")) {
413                                                 if (linecount == 1) {
414                                                         claimed_id = NewStrBufDup(Buf);
415                                                 }
416                                                 if (linecount == 2) {
417                                                         username = NewStrBufDup(Buf);
418                                                 }
419                                         }
420                                         ++linecount;
421                                 }
422                         }
423                         FreeStrBuf(&Buf);
424                 }
425         }
426
427         /* If we were already logged in, this was an attempt to associate an OpenID account */
428         if (already_logged_in) {
429                 display_openids();
430                 FreeStrBuf(&result);
431                 FreeStrBuf(&username);
432                 FreeStrBuf(&password);
433                 FreeStrBuf(&claimed_id);
434                 FreeStrBuf(&logged_in_response);
435                 return;
436         }
437
438         /* If this operation logged us in, either by connecting with an existing account or by
439          * auto-creating one using Simple Registration Extension, we're already on our way.
440          */
441         if (!strcasecmp(ChrPtr(result), "authenticate")) {
442                 become_logged_in(username, password, logged_in_response);
443         }
444
445         /* The specified OpenID was verified but the desired user name was either not specified via SRI
446          * or conflicts with an existing user.  Either way the user will need to specify a new name.
447          */
448
449         else if (!strcasecmp(ChrPtr(result), "verify_only")) {
450                 display_openid_name_request(claimed_id, username);
451         }
452
453         /* Did we manage to log in?  If so, continue with the normal flow... */
454         if (WC->logged_in) {
455                 if (WC->need_regi) {
456                         display_reg(1);
457                 } else {
458                         do_welcome();
459                 }
460         } else {
461                 display_openid_login(_("Your password was not accepted."));
462         }
463
464         FreeStrBuf(&result);
465         FreeStrBuf(&username);
466         FreeStrBuf(&password);
467         FreeStrBuf(&claimed_id);
468         FreeStrBuf(&logged_in_response);
469 }
470
471
472 /*
473  * Display a welcome screen to the user.
474  *
475  * If this is the first time login, and the web based setup is enabled, 
476  * lead the user through the setup routines
477  */
478 void do_welcome(void)
479 {
480         StrBuf *Buf;
481 #ifdef XXX_NOT_FINISHED_YET_XXX
482         FILE *fp;
483         int i;
484
485         /**
486          * See if we have to run the first-time setup wizard
487          */
488         if (WC->is_aide) {
489                 if (!setup_wizard) {
490                         int len;
491                         sprintf(wizard_filename, "setupwiz.%s.%s",
492                                 ctdlhost, ctdlport);
493                         len = strlen(wizard_filename);
494                         for (i=0; i<len; ++i) {
495                                 if (    (wizard_filename[i]==' ')
496                                         || (wizard_filename[i] == '/')
497                                 ) {
498                                         wizard_filename[i] = '_';
499                                 }
500                         }
501         
502                         fp = fopen(wizard_filename, "r");
503                         if (fp != NULL) {
504                                 fgets(buf, sizeof buf, fp);
505                                 buf[strlen(buf)-1] = 0;
506                                 fclose(fp);
507                                 if (atoi(buf) == serv_info.serv_rev_level) {
508                                         setup_wizard = 1; /**< already run */
509                                 }
510                         }
511                 }
512
513                 if (!setup_wizard) {
514                         http_redirect("setup_wizard");
515                 }
516         }
517 #endif
518
519         /*
520          * Go to the user's preferred start page
521          */
522         if (!get_preference("startpage", &Buf)) {
523                 Buf = NewStrBuf ();
524                 StrBufPrintf(Buf, "dotskip?room=_BASEROOM_");
525                 set_preference("startpage", Buf, 1);
526         }
527         if (ChrPtr(Buf)[0] == '/') {
528                 StrBufCutLeft(Buf, 1);
529         }
530         if (StrLength(Buf) == 0) {
531                 StrBufAppendBufPlain(Buf, "dotgoto?room=_BASEROOM_", -1, 0);
532         }
533         lprintf(9, "Redirecting to user's start page: %s\n", ChrPtr(Buf));
534         http_redirect(ChrPtr(Buf));
535 }
536
537
538 /*
539  * Disconnect from the Citadel server, and end this WebCit session
540  */
541 void end_webcit_session(void) {
542         
543         serv_puts("QUIT");
544         WC->killthis = 1;
545         /* close() of citadel socket will be done by do_housekeeping() */
546 }
547
548 /* 
549  * execute the logout
550  */
551 void do_logout(void)
552 {
553         wcsession *WCC = WC;
554         char buf[SIZ];
555
556         FlushStrBuf(WCC->wc_username);
557         FlushStrBuf(WCC->wc_password);
558         FlushStrBuf(WCC->CurRoom.name);
559         FlushStrBuf(WCC->wc_fullname);
560
561         /* FIXME: this is to suppress the iconbar displaying, because we aren't
562            actually logged out yet */
563         WCC->logged_in = 0;
564         
565         /** Calling output_headers() this way causes the cookies to be un-set */
566         output_headers(1, 1, 0, 1, 0, 0);
567
568         wc_printf("<div id=\"logout_screen\">");
569         wc_printf("<div class=\"box\">");
570         wc_printf("<div class=\"boxlabel\">");
571         wc_printf(_("Log off"));
572         wc_printf("</div><div class=\"boxcontent\">");  
573         serv_puts("MESG goodbye");
574         serv_getln(buf, sizeof buf);
575
576         if (WCC->serv_sock >= 0) {
577                 if (buf[0] == '1') {
578                         fmout("CENTER");
579                 } else {
580                         wc_printf("Goodbye\n");
581                 }
582         }
583         else {
584                 wc_printf(_("This program was unable to connect or stay "
585                         "connected to the Citadel server.  Please report "
586                         "this problem to your system administrator.")
587                 );
588                 wc_printf("<a href=\"http://www.citadel.org/doku.php/"
589                         "faq:mastering_your_os:net#netstat\">%s</a>", 
590                         _("Read More..."));
591         }
592
593         wc_printf("<hr /><div class=\"buttons\"> "
594                 "<span class=\"button_link\"><a href=\".\">");
595         wc_printf(_("Log in again"));
596         wc_printf("</a></span>");
597
598         /* The "close window" link is commented out because some browsers don't
599          * allow it to work.
600          *
601         wc_printf("&nbsp;&nbsp;&nbsp;<span class=\"button_link\">"
602                 "<a href=\"javascript:window.close();\">");
603         wc_printf(_("Close window"));
604         wc_printf("</a></span>");
605          */
606
607         wc_printf("</div></div></div></div>\n");
608         wDumpContent(2);
609         end_webcit_session();
610 }
611
612
613 /*
614  * validate new users
615  */
616 void validate(void)
617 {
618         char cmd[SIZ];
619         char user[SIZ];
620         char buf[SIZ];
621         int a;
622
623         output_headers(1, 1, 2, 0, 0, 0);
624         wc_printf("<div id=\"banner\">\n");
625         wc_printf("<h1>");
626         wc_printf(_("Validate new users"));
627         wc_printf("</h1>");
628         wc_printf("</div>\n");
629
630         wc_printf("<div id=\"content\" class=\"service\">\n");
631
632         /* If the user just submitted a validation, process it... */
633         safestrncpy(buf, bstr("user"), sizeof buf);
634         if (!IsEmptyStr(buf)) {
635                 if (havebstr("axlevel")) {
636                         serv_printf("VALI %s|%s", buf, bstr("axlevel"));
637                         serv_getln(buf, sizeof buf);
638                         if (buf[0] != '2') {
639                                 wc_printf("<b>%s</b><br>\n", &buf[4]);
640                         }
641                 }
642         }
643
644         /* Now see if any more users require validation. */
645         serv_puts("GNUR");
646         serv_getln(buf, sizeof buf);
647         if (buf[0] == '2') {
648                 wc_printf("<b>");
649                 wc_printf(_("No users require validation at this time."));
650                 wc_printf("</b><br>\n");
651                 wDumpContent(1);
652                 return;
653         }
654         if (buf[0] != '3') {
655                 wc_printf("<b>%s</b><br>\n", &buf[4]);
656                 wDumpContent(1);
657                 return;
658         }
659
660         wc_printf("<div class=\"fix_scrollbar_bug\">"
661                 "<table class=\"auth_validate\"><tr><td>\n");
662         wc_printf("<div id=\"validate\">");
663
664         safestrncpy(user, &buf[4], sizeof user);
665         serv_printf("GREG %s", user);
666         serv_getln(cmd, sizeof cmd);
667         if (cmd[0] == '1') {
668                 a = 0;
669                 do {
670                         serv_getln(buf, sizeof buf);
671                         ++a;
672                         if (a == 1)
673                                 wc_printf("#%s<br><H1>%s</H1>",
674                                         buf, &cmd[4]);
675                         if (a == 2) {
676                                 char *pch;
677                                 int haveChar = 0;
678                                 int haveNum = 0;
679                                 int haveOther = 0;
680                                 int count = 0;
681                                 pch = buf;
682                                 while (!IsEmptyStr(pch))
683                                 {
684                                         if (isdigit(*pch))
685                                                 haveNum = 1;
686                                         else if (isalpha(*pch))
687                                                 haveChar = 1;
688                                         else
689                                                 haveOther = 1;
690                                         pch ++;
691                                 }
692                                 count = pch - buf;
693                                 if (count > 7)
694                                         count = 0;
695                                 switch (count){
696                                 case 0:
697                                         pch = _("very weak");
698                                         break;
699                                 case 1:
700                                         pch = _("weak");
701                                         break;
702                                 case 2:
703                                         pch = _("ok");
704                                         break;
705                                 case 3:
706                                 default:
707                                         pch = _("strong");
708                                 }
709
710                                 wc_printf("PW: %s<br>\n", pch);
711                         }
712                         if (a == 3)
713                                 wc_printf("%s<br>\n", buf);
714                         if (a == 4)
715                                 wc_printf("%s<br>\n", buf);
716                         if (a == 5)
717                                 wc_printf("%s, ", buf);
718                         if (a == 6)
719                                 wc_printf("%s ", buf);
720                         if (a == 7)
721                                 wc_printf("%s<br>\n", buf);
722                         if (a == 8)
723                                 wc_printf("%s<br>\n", buf);
724                         if (a == 9)
725                                 wc_printf(_("Current access level: %d (%s)\n"),
726                                         atoi(buf), axdefs[atoi(buf)]);
727                 } while (strcmp(buf, "000"));
728         } else {
729                 wc_printf("<H1>%s</H1>%s<br />\n", user, &cmd[4]);
730         }
731
732         wc_printf("<hr />");
733         wc_printf(_("Select access level for this user:"));
734         wc_printf("<br />\n");
735         for (a = 0; a <= 6; ++a) {
736                 wc_printf("<a href=\"validate?nonce=%d?user=", WC->nonce);
737                 urlescputs(user);
738                 wc_printf("&axlevel=%d\">%s</A>&nbsp;&nbsp;&nbsp;\n",
739                         a, axdefs[a]);
740         }
741         wc_printf("<br />\n");
742
743         wc_printf("</div>\n");
744         wc_printf("</td></tr></table></div>\n");
745         wDumpContent(1);
746 }
747
748
749
750 /*
751  * Display form for registration.
752  *
753  * (Set during_login to 1 if this registration is being performed during
754  * new user login and will require chaining to the proper screen.)
755  */
756 void display_reg(int during_login)
757 {
758         folder Room;
759         StrBuf *Buf;
760         message_summary *VCMsg = NULL;
761         wc_mime_attachment *VCAtt = NULL;
762         long vcard_msgnum;
763
764         Buf = NewStrBuf();
765         memset(&Room, 0, sizeof(folder));
766         if (goto_config_room(Buf, &Room) != 0) {
767                 lprintf(9, "display_reg() exiting because goto_config_room() failed\n");
768                 if (during_login) {
769                         do_welcome();
770                 }
771                 else {
772                         display_main_menu();
773                 }
774                 FreeStrBuf(&Buf);
775                 FlushFolder(&Room);             
776                 return;
777         }
778         FlushFolder(&Room);
779
780         FreeStrBuf(&Buf);
781         vcard_msgnum = locate_user_vcard_in_this_room(&VCMsg, &VCAtt);
782         if (vcard_msgnum < 0L) {
783                 lprintf(9, "display_reg() exiting because locate_user_vcard_in_this_room() failed\n");
784                 if (during_login) {
785                         do_welcome();
786                 }
787                 else {
788                         display_main_menu();
789                 }
790                 return;
791         }
792
793         if (during_login) {
794                 do_edit_vcard(vcard_msgnum, "1", VCMsg, VCAtt, "do_welcome", USERCONFIGROOM);
795         }
796         else {
797                 StrBuf *ReturnTo;
798                 ReturnTo = NewStrBufPlain(HKEY("display_main_menu?gotofirst="));
799                 StrBufAppendBuf(ReturnTo, WC->CurRoom.name, 0);
800                 do_edit_vcard(vcard_msgnum, "1", VCMsg, VCAtt, ChrPtr(ReturnTo), USERCONFIGROOM);
801                 FreeStrBuf(&ReturnTo);
802         }
803
804         /* FIXME - don't we have to free VCMsg and VCAtt ?? */
805 }
806
807
808
809
810 /*
811  * display form for changing your password
812  */
813 void display_changepw(void)
814 {
815         WCTemplputParams SubTP;
816         char buf[SIZ];
817         StrBuf *Buf;
818         output_headers(1, 1, 1, 0, 0, 0);
819
820         Buf = NewStrBufPlain(_("Change your password"), -1);
821         memset(&SubTP, 0, sizeof(WCTemplputParams));
822         SubTP.Filter.ContextType = CTX_STRBUF;
823         SubTP.Context = Buf;
824         DoTemplate(HKEY("beginbox"), NULL, &SubTP);
825
826         FreeStrBuf(&Buf);
827
828         if (!IsEmptyStr(WC->ImportantMessage)) {
829                 wc_printf("<span class=\"errormsg\">"
830                         "%s</span><br />\n", WC->ImportantMessage);
831                 safestrncpy(WC->ImportantMessage, "", sizeof WC->ImportantMessage);
832         }
833
834         serv_puts("MESG changepw");
835         serv_getln(buf, sizeof buf);
836         if (buf[0] == '1') {
837                 fmout("CENTER");
838         }
839
840         wc_printf("<form name=\"changepwform\" action=\"changepw\" method=\"post\">\n");
841         wc_printf("<input type=\"hidden\" name=\"nonce\" value=\"%d\">\n", WC->nonce);
842         wc_printf("<table class=\"altern\" ");
843         wc_printf("<tr class=\"even\"><td>");
844         wc_printf(_("Enter new password:"));
845         wc_printf("</td><td>");
846         wc_printf("<input type=\"password\" name=\"newpass1\" value=\"\" maxlength=\"20\"></td></tr>\n");
847         wc_printf("<tr class=\"odd\"><td>");
848         wc_printf(_("Enter it again to confirm:"));
849         wc_printf("</td><td>");
850         wc_printf("<input type=\"password\" name=\"newpass2\" value=\"\" maxlength=\"20\"></td></tr>\n");
851         wc_printf("</table>\n");
852
853         wc_printf("<div class=\"buttons\">\n");
854         wc_printf("<input type=\"submit\" name=\"change_action\" value=\"%s\">", _("Change password"));
855         wc_printf("&nbsp;");
856         wc_printf("<input type=\"submit\" name=\"cancel_action\" value=\"%s\">\n", _("Cancel"));
857         wc_printf("</div>\n");
858         wc_printf("</form>\n");
859
860         do_template("endbox", NULL);
861         wDumpContent(1);
862 }
863
864 /*
865  * change password
866  * if passwords match, propagate it to citserver.
867  */
868 void changepw(void)
869 {
870         char buf[SIZ];
871         char newpass1[32], newpass2[32];
872
873         if (!havebstr("change_action")) {
874                 safestrncpy(WC->ImportantMessage, 
875                         _("Cancelled.  Password was not changed."),
876                         sizeof WC->ImportantMessage);
877                 display_main_menu();
878                 return;
879         }
880
881         safestrncpy(newpass1, bstr("newpass1"), sizeof newpass1);
882         safestrncpy(newpass2, bstr("newpass2"), sizeof newpass2);
883
884         if (strcasecmp(newpass1, newpass2)) {
885                 safestrncpy(WC->ImportantMessage, 
886                         _("They don't match.  Password was not changed."),
887                         sizeof WC->ImportantMessage);
888                 display_changepw();
889                 return;
890         }
891
892         if (IsEmptyStr(newpass1)) {
893                 safestrncpy(WC->ImportantMessage, 
894                         _("Blank passwords are not allowed."),
895                         sizeof WC->ImportantMessage);
896                 display_changepw();
897                 return;
898         }
899
900         serv_printf("SETP %s", newpass1);
901         serv_getln(buf, sizeof buf);
902         sprintf(WC->ImportantMessage, "%s", &buf[4]);
903         if (buf[0] == '2') {
904                 if (WC->wc_password == NULL)
905                         WC->wc_password = NewStrBufPlain(buf, -1);
906                 else {
907                         FlushStrBuf(WC->wc_password);
908                         StrBufAppendBufPlain(WC->wc_password,  buf, -1, 0);
909                 }
910                 display_main_menu();
911         }
912         else {
913                 display_changepw();
914         }
915 }
916
917 int ConditionalHaveAccessCreateRoom(StrBuf *Target, WCTemplputParams *TP)
918 {
919         StrBuf *Buf;    
920
921         Buf = NewStrBuf();
922         serv_puts("CRE8 0");
923         StrBuf_ServGetln(Buf);
924
925         if (GetServerStatus(Buf, NULL) == 2) {
926                 StrBufCutLeft(Buf, 4);
927                 AppendImportantMessage(SKEY(Buf));
928                 FreeStrBuf(&Buf);
929                 return 0;
930         }
931         FreeStrBuf(&Buf);
932         return 1;
933 }
934
935 int ConditionalAide(StrBuf *Target, WCTemplputParams *TP)
936 {
937         wcsession *WCC = WC;
938         return (WCC != NULL)? (WC->is_aide == 0) : 0;
939 }
940
941 int ConditionalIsLoggedIn(StrBuf *Target, WCTemplputParams *TP) 
942 {
943         wcsession *WCC = WC;
944         return (WCC != NULL)? (WCC->logged_in == 0) : 0;
945 }
946
947
948 void _display_openid_login(void) {
949         display_openid_login(NULL);
950 }
951
952
953 void _display_reg(void) {
954         display_reg(0);
955 }
956
957
958 void Header_HandleAuth(StrBuf *Line, ParsedHttpHdrs *hdr)
959 {
960         if (hdr->HR.got_auth == NO_AUTH) /* don't override cookie auth... */
961         {
962                 if (strncasecmp(ChrPtr(Line), "Basic", 5) == 0) {
963                         StrBufCutLeft(Line, 6);
964                         StrBufDecodeBase64(Line);
965                         hdr->HR.plainauth = Line;
966                         hdr->HR.got_auth = AUTH_BASIC;
967                 }
968                 else 
969                         lprintf(1, "Authentication scheme not supported! [%s]\n", ChrPtr(Line));
970         }
971 }
972
973 void CheckAuthBasic(ParsedHttpHdrs *hdr)
974 {
975 /*
976   todo: enable this if we can have other sessions than authenticated ones.
977         if (hdr->DontNeedAuth)
978                 return;
979 */
980         StrBufAppendBufPlain(hdr->HR.plainauth, HKEY(":"), 0);
981         StrBufAppendBuf(hdr->HR.plainauth, hdr->HR.user_agent, 0);
982         hdr->HR.SessionKey = hashlittle(SKEY(hdr->HR.plainauth), 89479832);
983 /*
984         lprintf(1, "CheckAuthBasic: calculated sessionkey %ld\n", 
985                 hdr->HR.SessionKey);
986 */
987 }
988
989 void GetAuthBasic(ParsedHttpHdrs *hdr)
990 {
991         const char *Pos = NULL;
992         if (hdr->c_username == NULL)
993                 hdr->c_username = NewStrBufPlain(HKEY(DEFAULT_HTTPAUTH_USER));
994         if (hdr->c_password == NULL)
995                 hdr->c_password = NewStrBufPlain(HKEY(DEFAULT_HTTPAUTH_PASS));
996         StrBufExtract_NextToken(hdr->c_username, hdr->HR.plainauth, &Pos, ':');
997         StrBufExtract_NextToken(hdr->c_password, hdr->HR.plainauth, &Pos, ':');
998 }
999
1000 void Header_HandleCookie(StrBuf *Line, ParsedHttpHdrs *hdr)
1001 {
1002         const char *pch;
1003 /*
1004   todo: enable this if we can have other sessions than authenticated ones.
1005         if (hdr->DontNeedAuth)
1006                 return;
1007 */
1008         pch = strstr(ChrPtr(Line), "webcit=");
1009         if (pch == NULL) {
1010                 return;
1011         }
1012
1013         hdr->HR.RawCookie = Line;
1014         StrBufCutLeft(hdr->HR.RawCookie, (pch - ChrPtr(hdr->HR.RawCookie)) + 7);
1015         StrBufDecodeHex(hdr->HR.RawCookie);
1016
1017         cookie_to_stuff(Line, &hdr->HR.desired_session,
1018                         hdr->c_username,
1019                         hdr->c_password,
1020                         hdr->c_roomname,
1021                         hdr->c_language
1022         );
1023         hdr->HR.got_auth = AUTH_COOKIE;
1024 }
1025
1026 void 
1027 HttpNewModule_AUTH
1028 (ParsedHttpHdrs *httpreq)
1029 {
1030         httpreq->c_username = NewStrBufPlain(HKEY(DEFAULT_HTTPAUTH_USER));
1031         httpreq->c_password = NewStrBufPlain(HKEY(DEFAULT_HTTPAUTH_PASS));
1032         httpreq->c_roomname = NewStrBuf();
1033         httpreq->c_language = NewStrBuf();
1034 }
1035 void 
1036 HttpDetachModule_AUTH
1037 (ParsedHttpHdrs *httpreq)
1038 {
1039         FLUSHStrBuf(httpreq->c_username);
1040         FLUSHStrBuf(httpreq->c_password);
1041         FLUSHStrBuf(httpreq->c_roomname);
1042         FLUSHStrBuf(httpreq->c_language);
1043 }
1044
1045 void 
1046 HttpDestroyModule_AUTH
1047 (ParsedHttpHdrs *httpreq)
1048 {
1049         FreeStrBuf(&httpreq->c_username);
1050         FreeStrBuf(&httpreq->c_password);
1051         FreeStrBuf(&httpreq->c_roomname);
1052         FreeStrBuf(&httpreq->c_language);
1053 }
1054
1055 void 
1056 InitModule_AUTH
1057 (void)
1058 {
1059         initialize_axdefs();
1060         RegisterHeaderHandler(HKEY("COOKIE"), Header_HandleCookie);
1061         RegisterHeaderHandler(HKEY("AUTHORIZATION"), Header_HandleAuth);
1062
1063         WebcitAddUrlHandler(HKEY(""), "", 0, do_welcome, ANONYMOUS|COOKIEUNNEEDED); /* no url pattern at all? Show login. */
1064         WebcitAddUrlHandler(HKEY("do_welcome"), "", 0, do_welcome, ANONYMOUS|COOKIEUNNEEDED);
1065         WebcitAddUrlHandler(HKEY("login"), "", 0, do_login, ANONYMOUS|COOKIEUNNEEDED);
1066         WebcitAddUrlHandler(HKEY("display_openid_login"), "", 0, _display_openid_login, ANONYMOUS);
1067         WebcitAddUrlHandler(HKEY("openid_login"), "", 0, do_openid_login, ANONYMOUS);
1068         WebcitAddUrlHandler(HKEY("finalize_openid_login"), "", 0, finalize_openid_login, ANONYMOUS);
1069         WebcitAddUrlHandler(HKEY("openid_manual_create"), "", 0, openid_manual_create, ANONYMOUS);
1070         WebcitAddUrlHandler(HKEY("do_logout"), "", 0, do_logout, ANONYMOUS|COOKIEUNNEEDED|FORCE_SESSIONCLOSE);
1071         WebcitAddUrlHandler(HKEY("validate"), "", 0, validate, 0);
1072         WebcitAddUrlHandler(HKEY("display_reg"), "", 0, _display_reg, 0);
1073         WebcitAddUrlHandler(HKEY("display_changepw"), "", 0, display_changepw, 0);
1074         WebcitAddUrlHandler(HKEY("changepw"), "", 0, changepw, 0);
1075         WebcitAddUrlHandler(HKEY("termquit"), "", 0, do_logout, 0);
1076
1077         RegisterConditional(HKEY("COND:AIDE"), 2, ConditionalAide, CTX_NONE);
1078         RegisterConditional(HKEY("COND:LOGGEDIN"), 2, ConditionalIsLoggedIn, CTX_NONE);
1079         RegisterConditional(HKEY("COND:MAY_CREATE_ROOM"), 2,  ConditionalHaveAccessCreateRoom, CTX_NONE);
1080         return ;
1081 }
1082
1083
1084 void 
1085 SessionDestroyModule_AUTH
1086 (wcsession *sess)
1087 {
1088         FreeStrBuf(&sess->wc_username);
1089         FreeStrBuf(&sess->wc_fullname);
1090         FreeStrBuf(&sess->wc_password);
1091         FreeStrBuf(&sess->httpauth_pass);
1092         FreeStrBuf(&sess->cs_inet_email);
1093 }