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