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