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