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