OpenID manual create is now functionally complete.
[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) { /* TODO: make this a define, else it might trick us later */
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
231                 /* Still no good!  Go back to teh dialog to select a username */
232                 const StrBuf *Buf;
233                 putbstr("__claimed_id", NewStrBufDup(sbstr("openid_url")));
234                 Buf = sbstr("name");
235                 if (StrLength(Buf) > 0)
236                         putbstr("__username", NewStrBufDup(Buf));
237                 begin_burst();
238                 output_headers(1, 0, 0, 0, 1, 0);
239                 wc_printf("<html><body>");
240                 do_template("openid_manual_create", NULL);
241                 wc_printf("</body></html>");
242                 end_burst();
243         }
244
245 }
246
247
248 /* 
249  * Perform authentication using OpenID
250  * assemble the checkid_setup request and then redirect to the user's identity provider
251  */
252 void do_openid_login(void)
253 {
254         char buf[4096];
255
256         snprintf(buf, sizeof buf,
257                 "OIDS %s|%s/finalize_openid_login|%s",
258                 bstr("openid_url"),
259                 ChrPtr(site_prefix),
260                 ChrPtr(site_prefix)
261         );
262
263         serv_puts(buf);
264         serv_getln(buf, sizeof buf);
265         if (buf[0] == '2') {
266                 syslog(LOG_DEBUG, "OpenID server contacted; redirecting to %s\n", &buf[4]);
267                 http_redirect(&buf[4]);
268                 return;
269         }
270
271         begin_burst();
272         output_headers(1, 0, 0, 0, 1, 0);
273         wc_printf("<html><body>");
274         escputs(&buf[4]);
275         wc_printf("</body></html>");
276         end_burst();
277 }
278
279
280 /* 
281  * Complete the authentication using OpenID
282  * This function handles the positive or negative assertion from the user's Identity Provider
283  */
284 void finalize_openid_login(void)
285 {
286         StrBuf *Buf;
287         wcsession *WCC = WC;
288         int linecount = 0;
289         StrBuf *result = NULL;
290         StrBuf *username = NULL;
291         StrBuf *password = NULL;
292         StrBuf *logged_in_response = NULL;
293         StrBuf *claimed_id = NULL;
294
295         if (havebstr("openid.mode")) {
296                 if (!strcasecmp(bstr("openid.mode"), "id_res")) {
297                         Buf = NewStrBuf();
298                         serv_puts("OIDF");
299                         StrBuf_ServGetln(Buf);
300                         if (GetServerStatus(Buf, NULL) == 8) {
301                                 urlcontent *u;
302                                 void *U;
303                                 long HKLen;
304                                 const char *HKey;
305                                 HashPos *Cursor;
306                                 
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 (StrBuf_ServGetln(Buf), strcmp(ChrPtr(Buf), "000")) 
319                                 {
320                                         if (linecount == 0) result = NewStrBufDup(Buf);
321                                         if (!strcasecmp(ChrPtr(result), "authenticate")) {
322                                                 if (linecount == 1) {
323                                                         username = NewStrBufDup(Buf);
324                                                 }
325                                                 else if (linecount == 2) {
326                                                         password = NewStrBufDup(Buf);
327                                                 }
328                                                 else if (linecount == 3) {
329                                                         logged_in_response = NewStrBufDup(Buf);
330                                                 }
331                                         }
332                                         else if (!strcasecmp(ChrPtr(result), "verify_only")) {
333                                                 if (linecount == 1) {
334                                                         claimed_id = NewStrBufDup(Buf);
335                                                 }
336                                                 if (linecount == 2) {
337                                                         username = NewStrBufDup(Buf);
338                                                 }
339                                         }
340                                         ++linecount;
341                                 }
342                         }
343                         FreeStrBuf(&Buf);
344                 }
345         }
346
347         /*
348          * Is this an attempt to associate a new OpenID with an account that is already logged in?
349          */
350         if ( (WCC->logged_in) && (havebstr("attach_existing")) ) {
351                 display_openids();
352         }
353
354         /* If this operation logged us in, either by connecting with an existing account or by
355          * auto-creating one using Simple Registration Extension, we're already on our way.
356          */
357         else if (!strcasecmp(ChrPtr(result), "authenticate")) {
358                 become_logged_in(username, password, logged_in_response);
359
360                 /* Did we manage to log in?  If so, continue with the normal flow... */
361                 if (WC->logged_in) {
362                         begin_burst();
363                         output_headers(1, 0, 0, 0, 1, 0);
364                         do_template("authpopup_finished", NULL);
365                         end_burst();
366                 } else {
367                         begin_burst();
368                         output_headers(1, 0, 0, 0, 1, 0);
369                         wc_printf("<html><body>");
370                         wc_printf(_("An error has occurred."));
371                         wc_printf("</body></html>");
372                         end_burst();
373                 }
374         }
375
376         /* The specified OpenID was verified but the desired user name was either not specified via SRE
377          * or conflicts with an existing user.  Either way the user will need to specify a new name.
378          */
379         else if (!strcasecmp(ChrPtr(result), "verify_only")) {
380                 putbstr("__claimed_id", claimed_id);
381                 claimed_id = NULL;
382                 if (StrLength(username) > 0) {
383                         putbstr("__username", username);
384                         username = NULL;
385                 }
386                 begin_burst();
387                 output_headers(1, 0, 0, 0, 1, 0);
388                 wc_printf("<html><body>");
389                 do_template("openid_manual_create", NULL);
390                 wc_printf("</body></html>");
391                 end_burst();
392         }
393
394         /* Something went VERY wrong if we get to this point */
395         else {
396                 syslog(1, "finalize_openid_login() failed to do anything.  This is a code problem.\n");
397                 begin_burst();
398                 output_headers(1, 0, 0, 0, 1, 0);
399                 wc_printf("<html><body>");
400                 wc_printf(_("An error has occurred."));
401                 wc_printf("</body></html>");
402                 end_burst();
403         }
404
405         FreeStrBuf(&result);
406         FreeStrBuf(&username);
407         FreeStrBuf(&password);
408         FreeStrBuf(&claimed_id);
409         FreeStrBuf(&logged_in_response);
410 }
411
412
413 /*
414  * Display a welcome screen to the user.
415  *
416  * If this is the first time login, and the web based setup is enabled, 
417  * lead the user through the setup routines
418  */
419 void do_welcome(void)
420 {
421         StrBuf *Buf;
422 #ifdef XXX_NOT_FINISHED_YET_XXX
423         FILE *fp;
424         int i;
425
426         /**
427          * See if we have to run the first-time setup wizard
428          */
429         if (WC->is_aide) {
430                 if (!setup_wizard) {
431                         int len;
432                         sprintf(wizard_filename, "setupwiz.%s.%s",
433                                 ctdlhost, ctdlport);
434                         len = strlen(wizard_filename);
435                         for (i=0; i<len; ++i) {
436                                 if (    (wizard_filename[i]==' ')
437                                         || (wizard_filename[i] == '/')
438                                 ) {
439                                         wizard_filename[i] = '_';
440                                 }
441                         }
442         
443                         fp = fopen(wizard_filename, "r");
444                         if (fp != NULL) {
445                                 fgets(buf, sizeof buf, fp);
446                                 buf[strlen(buf)-1] = 0;
447                                 fclose(fp);
448                                 if (atoi(buf) == serv_info.serv_rev_level) {
449                                         setup_wizard = 1; /**< already run */
450                                 }
451                         }
452                 }
453
454                 if (!setup_wizard) {
455                         http_redirect("setup_wizard");
456                 }
457         }
458 #endif
459
460         /*
461          * Go to the user's preferred start page
462          */
463         if (!get_preference("startpage", &Buf)) {
464                 Buf = NewStrBuf ();
465                 StrBufPrintf(Buf, "dotskip?room=_BASEROOM_");
466                 set_preference("startpage", Buf, 1);
467         }
468         if (ChrPtr(Buf)[0] == '/') {
469                 StrBufCutLeft(Buf, 1);
470         }
471         if (StrLength(Buf) == 0) {
472                 StrBufAppendBufPlain(Buf, "dotgoto?room=_BASEROOM_", -1, 0);
473         }
474         syslog(9, "Redirecting to user's start page: %s\n", ChrPtr(Buf));
475         http_redirect(ChrPtr(Buf));
476 }
477
478
479 /*
480  * Disconnect from the Citadel server, and end this WebCit session
481  */
482 void end_webcit_session(void) {
483         
484         serv_puts("QUIT");
485         WC->killthis = 1;
486         /* close() of citadel socket will be done by do_housekeeping() */
487 }
488
489 /* 
490  * execute the logout
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 /*
687  * Display form for registration.
688  *
689  * (Set during_login to 1 if this registration is being performed during
690  * new user login and will require chaining to the proper screen.)
691  */
692 void display_reg(int during_login)
693 {
694         folder Room;
695         StrBuf *Buf;
696         message_summary *VCMsg = NULL;
697         wc_mime_attachment *VCAtt = NULL;
698         long vcard_msgnum;
699
700         Buf = NewStrBuf();
701         memset(&Room, 0, sizeof(folder));
702         if (goto_config_room(Buf, &Room) != 0) {
703                 syslog(9, "display_reg() exiting because goto_config_room() failed\n");
704                 if (during_login) {
705                         pop_destination();
706                 }
707                 else {
708                         display_main_menu();
709                 }
710                 FreeStrBuf(&Buf);
711                 FlushFolder(&Room);             
712                 return;
713         }
714         FlushFolder(&Room);
715
716         FreeStrBuf(&Buf);
717         vcard_msgnum = locate_user_vcard_in_this_room(&VCMsg, &VCAtt);
718         if (vcard_msgnum < 0L) {
719                 syslog(9, "display_reg() exiting because locate_user_vcard_in_this_room() failed\n");
720                 if (during_login) {
721                         pop_destination();
722                 }
723                 else {
724                         display_main_menu();
725                 }
726                 return;
727         }
728
729         if (during_login) {
730                 do_edit_vcard(vcard_msgnum, "1", VCMsg, VCAtt, "pop", USERCONFIGROOM);
731         }
732         else {
733                 StrBuf *ReturnTo;
734                 ReturnTo = NewStrBufPlain(HKEY("display_main_menu?go="));
735                 StrBufAppendBuf(ReturnTo, WC->CurRoom.name, 0);
736                 do_edit_vcard(vcard_msgnum, "1", VCMsg, VCAtt, ChrPtr(ReturnTo), USERCONFIGROOM);
737                 FreeStrBuf(&ReturnTo);
738         }
739
740 }
741
742
743
744
745 /*
746  * display form for changing your password
747  */
748 void display_changepw(void)
749 {
750         WCTemplputParams SubTP;
751         char buf[SIZ];
752         StrBuf *Buf;
753         output_headers(1, 1, 1, 0, 0, 0);
754
755         Buf = NewStrBufPlain(_("Change your password"), -1);
756         memset(&SubTP, 0, sizeof(WCTemplputParams));
757         SubTP.Filter.ContextType = CTX_STRBUF;
758         SubTP.Context = Buf;
759         DoTemplate(HKEY("beginbox"), NULL, &SubTP);
760
761         FreeStrBuf(&Buf);
762
763         if (!IsEmptyStr(WC->ImportantMessage)) {
764                 wc_printf("<span class=\"errormsg\">"
765                         "%s</span><br>\n", WC->ImportantMessage);
766                 safestrncpy(WC->ImportantMessage, "", sizeof WC->ImportantMessage);
767         }
768
769         serv_puts("MESG changepw");
770         serv_getln(buf, sizeof buf);
771         if (buf[0] == '1') {
772                 fmout("CENTER");
773         }
774
775         wc_printf("<form name=\"changepwform\" action=\"changepw\" method=\"post\">\n");
776         wc_printf("<input type=\"hidden\" name=\"nonce\" value=\"%d\">\n", WC->nonce);
777         wc_printf("<table class=\"altern\" ");
778         wc_printf("<tr class=\"even\"><td>");
779         wc_printf(_("Enter new password:"));
780         wc_printf("</td><td>");
781         wc_printf("<input type=\"password\" name=\"newpass1\" value=\"\" maxlength=\"20\"></td></tr>\n");
782         wc_printf("<tr class=\"odd\"><td>");
783         wc_printf(_("Enter it again to confirm:"));
784         wc_printf("</td><td>");
785         wc_printf("<input type=\"password\" name=\"newpass2\" value=\"\" maxlength=\"20\"></td></tr>\n");
786         wc_printf("</table>\n");
787
788         wc_printf("<div class=\"buttons\">\n");
789         wc_printf("<input type=\"submit\" name=\"change_action\" value=\"%s\">", _("Change password"));
790         wc_printf("&nbsp;");
791         wc_printf("<input type=\"submit\" name=\"cancel_action\" value=\"%s\">\n", _("Cancel"));
792         wc_printf("</div>\n");
793         wc_printf("</form>\n");
794
795         do_template("endbox", NULL);
796         wDumpContent(1);
797 }
798
799 /*
800  * change password
801  * if passwords match, propagate it to citserver.
802  */
803 void changepw(void)
804 {
805         char buf[SIZ];
806         char newpass1[32], newpass2[32];
807
808         if (!havebstr("change_action")) {
809                 safestrncpy(WC->ImportantMessage, 
810                         _("Cancelled.  Password was not changed."),
811                         sizeof WC->ImportantMessage);
812                 display_main_menu();
813                 return;
814         }
815
816         safestrncpy(newpass1, bstr("newpass1"), sizeof newpass1);
817         safestrncpy(newpass2, bstr("newpass2"), sizeof newpass2);
818
819         if (strcasecmp(newpass1, newpass2)) {
820                 safestrncpy(WC->ImportantMessage, 
821                         _("They don't match.  Password was not changed."),
822                         sizeof WC->ImportantMessage);
823                 display_changepw();
824                 return;
825         }
826
827         if (IsEmptyStr(newpass1)) {
828                 safestrncpy(WC->ImportantMessage, 
829                         _("Blank passwords are not allowed."),
830                         sizeof WC->ImportantMessage);
831                 display_changepw();
832                 return;
833         }
834
835         serv_printf("SETP %s", newpass1);
836         serv_getln(buf, sizeof buf);
837         sprintf(WC->ImportantMessage, "%s", &buf[4]);
838         if (buf[0] == '2') {
839                 if (WC->wc_password == NULL)
840                         WC->wc_password = NewStrBufPlain(buf, -1);
841                 else {
842                         FlushStrBuf(WC->wc_password);
843                         StrBufAppendBufPlain(WC->wc_password,  buf, -1, 0);
844                 }
845                 display_main_menu();
846         }
847         else {
848                 display_changepw();
849         }
850 }
851
852 int ConditionalHaveAccessCreateRoom(StrBuf *Target, WCTemplputParams *TP)
853 {
854         StrBuf *Buf;    
855
856         Buf = NewStrBuf();
857         serv_puts("CRE8 0");
858         StrBuf_ServGetln(Buf);
859
860         if (GetServerStatus(Buf, NULL) == 2) {
861                 StrBufCutLeft(Buf, 4);
862                 AppendImportantMessage(SKEY(Buf));
863                 FreeStrBuf(&Buf);
864                 return 0;
865         }
866         FreeStrBuf(&Buf);
867         return 1;
868 }
869
870 int ConditionalAide(StrBuf *Target, WCTemplputParams *TP)
871 {
872         wcsession *WCC = WC;
873         return (WCC != NULL) ? ((WCC->logged_in == 0)||(WC->is_aide == 0)) : 0;
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
885 void _display_reg(void) {
886         display_reg(0);
887 }
888
889
890 void Header_HandleAuth(StrBuf *Line, ParsedHttpHdrs *hdr)
891 {
892         if (hdr->HR.got_auth == NO_AUTH) /* don't override cookie auth... */
893         {
894                 if (strncasecmp(ChrPtr(Line), "Basic", 5) == 0) {
895                         StrBufCutLeft(Line, 6);
896                         StrBufDecodeBase64(Line);
897                         hdr->HR.plainauth = Line;
898                         hdr->HR.got_auth = AUTH_BASIC;
899                 }
900                 else 
901                         syslog(1, "Authentication scheme not supported! [%s]\n", ChrPtr(Line));
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 void GetAuthBasic(ParsedHttpHdrs *hdr)
922 {
923         const char *Pos = NULL;
924         if (hdr->c_username == NULL)
925                 hdr->c_username = NewStrBufPlain(HKEY(DEFAULT_HTTPAUTH_USER));
926         if (hdr->c_password == NULL)
927                 hdr->c_password = NewStrBufPlain(HKEY(DEFAULT_HTTPAUTH_PASS));
928         StrBufExtract_NextToken(hdr->c_username, hdr->HR.plainauth, &Pos, ':');
929         StrBufExtract_NextToken(hdr->c_password, hdr->HR.plainauth, &Pos, ':');
930 }
931
932 void Header_HandleCookie(StrBuf *Line, ParsedHttpHdrs *hdr)
933 {
934         const char *pch;
935 /*
936   todo: enable this if we can have other sessions than authenticated ones.
937         if (hdr->DontNeedAuth)
938                 return;
939 */
940         pch = strstr(ChrPtr(Line), "webcit=");
941         if (pch == NULL) {
942                 return;
943         }
944
945         hdr->HR.RawCookie = Line;
946         StrBufCutLeft(hdr->HR.RawCookie, (pch - ChrPtr(hdr->HR.RawCookie)) + 7);
947         StrBufDecodeHex(hdr->HR.RawCookie);
948
949         cookie_to_stuff(Line, &hdr->HR.desired_session,
950                         hdr->c_username,
951                         hdr->c_password,
952                         hdr->c_roomname,
953                         hdr->c_language
954         );
955         hdr->HR.got_auth = AUTH_COOKIE;
956 }
957
958 void 
959 HttpNewModule_AUTH
960 (ParsedHttpHdrs *httpreq)
961 {
962         httpreq->c_username = NewStrBufPlain(HKEY(DEFAULT_HTTPAUTH_USER));
963         httpreq->c_password = NewStrBufPlain(HKEY(DEFAULT_HTTPAUTH_PASS));
964         httpreq->c_roomname = NewStrBuf();
965         httpreq->c_language = NewStrBuf();
966 }
967 void 
968 HttpDetachModule_AUTH
969 (ParsedHttpHdrs *httpreq)
970 {
971         FLUSHStrBuf(httpreq->c_username);
972         FLUSHStrBuf(httpreq->c_password);
973         FLUSHStrBuf(httpreq->c_roomname);
974         FLUSHStrBuf(httpreq->c_language);
975 }
976
977 void 
978 HttpDestroyModule_AUTH
979 (ParsedHttpHdrs *httpreq)
980 {
981         FreeStrBuf(&httpreq->c_username);
982         FreeStrBuf(&httpreq->c_password);
983         FreeStrBuf(&httpreq->c_roomname);
984         FreeStrBuf(&httpreq->c_language);
985 }
986
987 void 
988 InitModule_AUTH
989 (void)
990 {
991         initialize_axdefs();
992         RegisterHeaderHandler(HKEY("COOKIE"), Header_HandleCookie);
993         RegisterHeaderHandler(HKEY("AUTHORIZATION"), Header_HandleAuth);
994
995         /* no url pattern at all? Show login. */
996         WebcitAddUrlHandler(HKEY(""), "", 0, do_welcome, ANONYMOUS|COOKIEUNNEEDED);
997
998         /* some of these will be removed soon */
999         WebcitAddUrlHandler(HKEY("do_welcome"), "", 0, do_welcome, ANONYMOUS|COOKIEUNNEEDED);
1000         WebcitAddUrlHandler(HKEY("openid_login"), "", 0, do_openid_login, ANONYMOUS);
1001         WebcitAddUrlHandler(HKEY("finalize_openid_login"), "", 0, finalize_openid_login, ANONYMOUS);
1002         WebcitAddUrlHandler(HKEY("openid_manual_create"), "", 0, openid_manual_create, ANONYMOUS);
1003         WebcitAddUrlHandler(HKEY("validate"), "", 0, validate, 0);
1004         WebcitAddUrlHandler(HKEY("do_welcome"), "", 0, do_welcome, 0);
1005         WebcitAddUrlHandler(HKEY("display_reg"), "", 0, _display_reg, 0);
1006         WebcitAddUrlHandler(HKEY("display_changepw"), "", 0, display_changepw, 0);
1007         WebcitAddUrlHandler(HKEY("changepw"), "", 0, changepw, 0);
1008         WebcitAddUrlHandler(HKEY("termquit"), "", 0, do_logout, 0);
1009         WebcitAddUrlHandler(HKEY("do_logout"), "", 0, do_logout, ANONYMOUS|COOKIEUNNEEDED|FORCE_SESSIONCLOSE);
1010         WebcitAddUrlHandler(HKEY("ajax_login_username_password"), "", 0, ajax_login_username_password, AJAX|ANONYMOUS);
1011         WebcitAddUrlHandler(HKEY("ajax_login_newuser"), "", 0, ajax_login_newuser, AJAX|ANONYMOUS);
1012         RegisterConditional(HKEY("COND:AIDE"), 2, ConditionalAide, CTX_NONE);
1013         RegisterConditional(HKEY("COND:LOGGEDIN"), 2, ConditionalIsLoggedIn, CTX_NONE);
1014         RegisterConditional(HKEY("COND:MAY_CREATE_ROOM"), 2,  ConditionalHaveAccessCreateRoom, CTX_NONE);
1015         return;
1016 }
1017
1018
1019 void 
1020 SessionDestroyModule_AUTH
1021 (wcsession *sess)
1022 {
1023         FreeStrBuf(&sess->wc_username);
1024         FreeStrBuf(&sess->wc_fullname);
1025         FreeStrBuf(&sess->wc_password);
1026         FreeStrBuf(&sess->httpauth_pass);
1027         FreeStrBuf(&sess->cs_inet_email);
1028 }