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