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