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