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