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