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