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