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