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