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