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