Initial version of 'register new user' dialog
[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  * modal/ajax version of 'login' (username and password)
145  */
146 void ajax_login_username_password(void) {
147         StrBuf *Buf = NewStrBuf();
148
149         serv_printf("USER %s", bstr("name"));
150         StrBuf_ServGetln(Buf);
151         if (GetServerStatus(Buf, NULL) == 3) {
152                 serv_printf("PASS %s", bstr("pass"));
153                 StrBuf_ServGetln(Buf);
154                 if (GetServerStatus(Buf, NULL) == 2) {
155                         become_logged_in(sbstr("name"), sbstr("pass"), Buf);
156                 }
157         }
158
159         /* The client is expecting to read back a citadel protocol response */
160         wc_printf("%s", ChrPtr(Buf));
161         FreeStrBuf(&Buf);
162 }
163
164
165
166 /* 
167  * modal/ajax version of 'new user' (username and password)
168  */
169 void ajax_login_newuser(void) {
170         StrBuf *Buf = NewStrBuf();
171
172         serv_printf("NEWU %s", bstr("name"));
173         StrBuf_ServGetln(Buf);
174         if (GetServerStatus(Buf, NULL) == 2) {
175                 serv_printf("SETP %s", bstr("pass"));
176                 StrBuf_ServGetln(Buf);
177                 if (GetServerStatus(Buf, NULL) == 2) {
178                         become_logged_in(sbstr("name"), sbstr("pass"), Buf);
179                 }
180         }
181
182         /* The client is expecting to read back a citadel protocol response */
183         wc_printf("%s", ChrPtr(Buf));
184         FreeStrBuf(&Buf);
185 }
186
187
188
189 /* 
190  * Try to create an account manually after an OpenID was verified
191  */
192 void openid_manual_create(void)
193 {
194         StrBuf *Buf;
195
196         if (havebstr("exit_action")) {
197                 do_logout();
198                 return;
199         }
200
201         if (havebstr("newuser_action")) {
202                 Buf = NewStrBuf();
203                 serv_printf("OIDC %s", bstr("name"));
204                 StrBuf_ServGetln(Buf);
205                 if (GetServerStatus(Buf, NULL) == 2) {
206                         StrBuf *gpass;
207
208                         gpass = NewStrBuf();
209                         serv_puts("SETP GENERATE_RANDOM_PASSWORD");
210                         StrBuf_ServGetln(gpass);
211                         StrBufCutLeft(gpass, 4);
212                         become_logged_in(sbstr("name"), gpass, Buf);
213                         FreeStrBuf(&gpass);
214                 }
215                 FreeStrBuf(&Buf);
216         }
217
218         if (WC->logged_in) {
219                 if (WC->need_regi) {
220                         display_reg(1);
221                 } else if (WC->need_vali) {
222                         validate();
223                 } else {
224                         do_welcome();
225                 }
226         } else {
227                 const StrBuf *Buf;
228
229                 putbstr("__claimed_id", NewStrBufDup(sbstr("openid_url")));
230                 Buf = sbstr("name");
231                 if (StrLength(Buf) > 0)
232                         putbstr("__username", NewStrBufDup(Buf));
233                 begin_burst();
234                 do_template("openid_manual_create", NULL);
235                 end_burst();
236         }
237
238 }
239
240
241 /* 
242  * Perform authentication using OpenID
243  * assemble the checkid_setup request and then redirect to the user's identity provider
244  */
245 void do_openid_login(void)
246 {
247         char buf[4096];
248
249         snprintf(buf, sizeof buf,
250                 "OIDS %s|%s/finalize_openid_login|%s",
251                 bstr("openid_url"),
252                 ChrPtr(site_prefix),
253                 ChrPtr(site_prefix)
254         );
255
256         serv_puts(buf);
257         serv_getln(buf, sizeof buf);
258         if (buf[0] == '2') {
259                 syslog(LOG_DEBUG, "OpenID server contacted; redirecting to %s\n", &buf[4]);
260                 http_redirect(&buf[4]);
261                 return;
262         }
263
264         begin_burst();
265         output_headers(1, 0, 0, 0, 1, 0);
266         wc_printf("<html><body>");
267         escputs(&buf[4]);
268         wc_printf("</body></html>");
269         end_burst();
270 }
271
272
273 /* 
274  * Complete the authentication using OpenID
275  * This function handles the positive or negative assertion from the user's Identity Provider
276  */
277 void finalize_openid_login(void)
278 {
279         StrBuf *Buf;
280         wcsession *WCC = WC;
281         int already_logged_in = (WCC->logged_in) ;
282         int linecount = 0;
283         StrBuf *result = NULL;
284         StrBuf *username = NULL;
285         StrBuf *password = NULL;
286         StrBuf *logged_in_response = NULL;
287         StrBuf *claimed_id = NULL;
288
289         if (havebstr("openid.mode")) {
290                 if (!strcasecmp(bstr("openid.mode"), "id_res")) {
291                         Buf = NewStrBuf();
292                         serv_puts("OIDF");
293                         StrBuf_ServGetln(Buf);
294                         if (GetServerStatus(Buf, NULL) == 8) {
295                                 urlcontent *u;
296                                 void *U;
297                                 long HKLen;
298                                 const char *HKey;
299                                 HashPos *Cursor;
300                                 
301                                 Cursor = GetNewHashPos (WCC->Hdr->urlstrings, 0);
302                                 while (GetNextHashPos(WCC->Hdr->urlstrings, Cursor, &HKLen, &HKey, &U)) {
303                                         u = (urlcontent*) U;
304                                         if (!strncasecmp(u->url_key, "openid.", 7)) {
305                                                 serv_printf("%s|%s", &u->url_key[7], ChrPtr(u->url_data));
306                                         }
307                                 }
308
309                                 serv_puts("000");
310
311                                 linecount = 0;
312                                 while (StrBuf_ServGetln(Buf), strcmp(ChrPtr(Buf), "000")) 
313                                 {
314                                         if (linecount == 0) result = NewStrBufDup(Buf);
315                                         if (!strcasecmp(ChrPtr(result), "authenticate")) {
316                                                 if (linecount == 1) {
317                                                         username = NewStrBufDup(Buf);
318                                                 }
319                                                 else if (linecount == 2) {
320                                                         password = NewStrBufDup(Buf);
321                                                 }
322                                                 else if (linecount == 3) {
323                                                         logged_in_response = NewStrBufDup(Buf);
324                                                 }
325                                         }
326                                         else if (!strcasecmp(ChrPtr(result), "verify_only")) {
327                                                 if (linecount == 1) {
328                                                         claimed_id = NewStrBufDup(Buf);
329                                                 }
330                                                 if (linecount == 2) {
331                                                         username = NewStrBufDup(Buf);
332                                                 }
333                                         }
334                                         ++linecount;
335                                 }
336                         }
337                         FreeStrBuf(&Buf);
338                 }
339         }
340
341         /* If we were already logged in, this was an attempt to associate an OpenID account 
342         FIXME put this back in
343         if (already_logged_in) {
344                 display_openids();
345                 FreeStrBuf(&result);
346                 FreeStrBuf(&username);
347                 FreeStrBuf(&password);
348                 FreeStrBuf(&claimed_id);
349                 FreeStrBuf(&logged_in_response);
350                 return;
351         }
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         if (!strcasecmp(ChrPtr(result), "authenticate")) {
358                 become_logged_in(username, password, logged_in_response);
359         }
360
361         /* The specified OpenID was verified but the desired user name was either not specified via SRI
362          * or conflicts with an existing user.  Either way the user will need to specify a new name.
363          */
364
365 /*
366         else if (!strcasecmp(ChrPtr(result), "verify_only")) {
367                 putbstr("__claimed_id", claimed_id);
368                 claimed_id = NULL;
369                 if (StrLength(username) > 0) {
370                         putbstr("__username", username);
371                         username = NULL;
372                 }
373                 begin_burst();
374                 do_template("openid_manual_create", NULL);
375                 end_burst();
376         }
377 */
378
379
380
381         /* Did we manage to log in?  If so, continue with the normal flow... */
382         if (WC->logged_in) {
383                 begin_burst();
384                 output_headers(1, 0, 0, 0, 1, 0);
385                 do_template("authpopup_finished", NULL);
386                 end_burst();
387
388                 /* FIXME make all this crap work again
389                 if (WC->need_regi) {
390                         display_reg(1);
391                 } else {
392                         do_welcome();
393                 }
394                 */
395
396         } else {
397                 /* FIXME do something prettier here? */
398                 begin_burst();
399                 output_headers(1, 0, 0, 0, 1, 0);
400                 wc_printf("<html><body>");
401                 wc_printf("error");
402                 wc_printf("</body></html>");
403                 end_burst();
404         }
405
406         FreeStrBuf(&result);
407         FreeStrBuf(&username);
408         FreeStrBuf(&password);
409         FreeStrBuf(&claimed_id);
410         FreeStrBuf(&logged_in_response);
411 }
412
413
414 /*
415  * Display a welcome screen to the user.
416  *
417  * If this is the first time login, and the web based setup is enabled, 
418  * lead the user through the setup routines
419  */
420 void do_welcome(void)
421 {
422         StrBuf *Buf;
423 #ifdef XXX_NOT_FINISHED_YET_XXX
424         FILE *fp;
425         int i;
426
427         /**
428          * See if we have to run the first-time setup wizard
429          */
430         if (WC->is_aide) {
431                 if (!setup_wizard) {
432                         int len;
433                         sprintf(wizard_filename, "setupwiz.%s.%s",
434                                 ctdlhost, ctdlport);
435                         len = strlen(wizard_filename);
436                         for (i=0; i<len; ++i) {
437                                 if (    (wizard_filename[i]==' ')
438                                         || (wizard_filename[i] == '/')
439                                 ) {
440                                         wizard_filename[i] = '_';
441                                 }
442                         }
443         
444                         fp = fopen(wizard_filename, "r");
445                         if (fp != NULL) {
446                                 fgets(buf, sizeof buf, fp);
447                                 buf[strlen(buf)-1] = 0;
448                                 fclose(fp);
449                                 if (atoi(buf) == serv_info.serv_rev_level) {
450                                         setup_wizard = 1; /**< already run */
451                                 }
452                         }
453                 }
454
455                 if (!setup_wizard) {
456                         http_redirect("setup_wizard");
457                 }
458         }
459 #endif
460
461         /*
462          * Go to the user's preferred start page
463          */
464         if (!get_preference("startpage", &Buf)) {
465                 Buf = NewStrBuf ();
466                 StrBufPrintf(Buf, "dotskip?room=_BASEROOM_");
467                 set_preference("startpage", Buf, 1);
468         }
469         if (ChrPtr(Buf)[0] == '/') {
470                 StrBufCutLeft(Buf, 1);
471         }
472         if (StrLength(Buf) == 0) {
473                 StrBufAppendBufPlain(Buf, "dotgoto?room=_BASEROOM_", -1, 0);
474         }
475         syslog(9, "Redirecting to user's start page: %s\n", ChrPtr(Buf));
476         http_redirect(ChrPtr(Buf));
477 }
478
479
480 /*
481  * Disconnect from the Citadel server, and end this WebCit session
482  */
483 void end_webcit_session(void) {
484         
485         serv_puts("QUIT");
486         WC->killthis = 1;
487         /* close() of citadel socket will be done by do_housekeeping() */
488 }
489
490 /* 
491  * execute the logout
492  */
493 void do_logout(void)
494 {
495         wcsession *WCC = WC;
496         char buf[SIZ];
497
498         FlushStrBuf(WCC->wc_username);
499         FlushStrBuf(WCC->wc_password);
500         FlushStrBuf(WCC->wc_fullname);
501
502         serv_puts("LOUT");
503         serv_getln(buf, sizeof buf);
504         WCC->logged_in = 0;
505
506         if (WC->serv_info->serv_supports_guest) {
507                 display_default_landing_page();
508                 return;
509         }
510
511         FlushStrBuf(WCC->CurRoom.name);
512
513         /* Calling output_headers() this way causes the cookies to be un-set */
514         output_headers(1, 1, 0, 1, 0, 0);
515
516         wc_printf("<div id=\"logout_screen\">");
517         wc_printf("<div class=\"box\">");
518         wc_printf("<div class=\"boxlabel\">");
519         wc_printf(_("Log off"));
520         wc_printf("</div><div class=\"boxcontent\">");
521         serv_puts("MESG goodbye");
522         serv_getln(buf, sizeof buf);
523
524         if (WCC->serv_sock >= 0) {
525                 if (buf[0] == '1') {
526                         fmout("'CENTER'");
527                 } else {
528                         wc_printf("Goodbye\n");
529                 }
530         }
531         else {
532                 wc_printf(_("This program was unable to connect or stay "
533                         "connected to the Citadel server.  Please report "
534                         "this problem to your system administrator.")
535                 );
536                 wc_printf("<a href=\"http://www.citadel.org/doku.php/"
537                         "faq:mastering_your_os:net#netstat\">%s</a>",
538                         _("Read More..."));
539         }
540
541         wc_printf("<hr /><div class=\"buttons\"> "
542                 "<span class=\"button_link\"><a href=\".\">");
543         wc_printf(_("Log in again"));
544         wc_printf("</a></span>");
545         wc_printf("</div></div></div>\n");
546         wDumpContent(2);
547         end_webcit_session();
548 }
549
550
551 /*
552  * validate new users
553  */
554 void validate(void)
555 {
556         char cmd[SIZ];
557         char user[SIZ];
558         char buf[SIZ];
559         int a;
560
561         output_headers(1, 1, 2, 0, 0, 0);
562         wc_printf("<div id=\"banner\">\n");
563         wc_printf("<h1>");
564         wc_printf(_("Validate new users"));
565         wc_printf("</h1>");
566         wc_printf("</div>\n");
567
568         wc_printf("<div id=\"content\" class=\"service\">\n");
569
570         /* If the user just submitted a validation, process it... */
571         safestrncpy(buf, bstr("user"), sizeof buf);
572         if (!IsEmptyStr(buf)) {
573                 if (havebstr("axlevel")) {
574                         serv_printf("VALI %s|%s", buf, bstr("axlevel"));
575                         serv_getln(buf, sizeof buf);
576                         if (buf[0] != '2') {
577                                 wc_printf("<b>%s</b><br>\n", &buf[4]);
578                         }
579                 }
580         }
581
582         /* Now see if any more users require validation. */
583         serv_puts("GNUR");
584         serv_getln(buf, sizeof buf);
585         if (buf[0] == '2') {
586                 wc_printf("<b>");
587                 wc_printf(_("No users require validation at this time."));
588                 wc_printf("</b><br>\n");
589                 wDumpContent(1);
590                 return;
591         }
592         if (buf[0] != '3') {
593                 wc_printf("<b>%s</b><br>\n", &buf[4]);
594                 wDumpContent(1);
595                 return;
596         }
597
598         wc_printf("<table class=\"auth_validate\"><tr><td>\n");
599         wc_printf("<div id=\"validate\">");
600
601         safestrncpy(user, &buf[4], sizeof user);
602         serv_printf("GREG %s", user);
603         serv_getln(cmd, sizeof cmd);
604         if (cmd[0] == '1') {
605                 a = 0;
606                 do {
607                         serv_getln(buf, sizeof buf);
608                         ++a;
609                         if (a == 1)
610                                 wc_printf("#%s<br><H1>%s</H1>",
611                                         buf, &cmd[4]);
612                         if (a == 2) {
613                                 char *pch;
614                                 int haveChar = 0;
615                                 int haveNum = 0;
616                                 int haveOther = 0;
617                                 int count = 0;
618                                 pch = buf;
619                                 while (!IsEmptyStr(pch))
620                                 {
621                                         if (isdigit(*pch))
622                                                 haveNum = 1;
623                                         else if (isalpha(*pch))
624                                                 haveChar = 1;
625                                         else
626                                                 haveOther = 1;
627                                         pch ++;
628                                 }
629                                 count = pch - buf;
630                                 if (count > 7)
631                                         count = 0;
632                                 switch (count){
633                                 case 0:
634                                         pch = _("very weak");
635                                         break;
636                                 case 1:
637                                         pch = _("weak");
638                                         break;
639                                 case 2:
640                                         pch = _("ok");
641                                         break;
642                                 case 3:
643                                 default:
644                                         pch = _("strong");
645                                 }
646
647                                 wc_printf("PW: %s<br>\n", pch);
648                         }
649                         if (a == 3)
650                                 wc_printf("%s<br>\n", buf);
651                         if (a == 4)
652                                 wc_printf("%s<br>\n", buf);
653                         if (a == 5)
654                                 wc_printf("%s, ", buf);
655                         if (a == 6)
656                                 wc_printf("%s ", buf);
657                         if (a == 7)
658                                 wc_printf("%s<br>\n", buf);
659                         if (a == 8)
660                                 wc_printf("%s<br>\n", buf);
661                         if (a == 9)
662                                 wc_printf(_("Current access level: %d (%s)\n"),
663                                         atoi(buf), axdefs[atoi(buf)]);
664                 } while (strcmp(buf, "000"));
665         } else {
666                 wc_printf("<H1>%s</H1>%s<br>\n", user, &cmd[4]);
667         }
668
669         wc_printf("<hr />");
670         wc_printf(_("Select access level for this user:"));
671         wc_printf("<br>\n");
672         for (a = 0; a <= 6; ++a) {
673                 wc_printf("<a href=\"validate?nonce=%d?user=", WC->nonce);
674                 urlescputs(user);
675                 wc_printf("&axlevel=%d\">%s</A>&nbsp;&nbsp;&nbsp;\n",
676                         a, axdefs[a]);
677         }
678         wc_printf("<br>\n");
679
680         wc_printf("</div>\n");
681         wc_printf("</td></tr></table>\n");
682         wDumpContent(1);
683 }
684
685
686
687 /*
688  * Display form for registration.
689  *
690  * (Set during_login to 1 if this registration is being performed during
691  * new user login and will require chaining to the proper screen.)
692  */
693 void display_reg(int during_login)
694 {
695         folder Room;
696         StrBuf *Buf;
697         message_summary *VCMsg = NULL;
698         wc_mime_attachment *VCAtt = NULL;
699         long vcard_msgnum;
700
701         Buf = NewStrBuf();
702         memset(&Room, 0, sizeof(folder));
703         if (goto_config_room(Buf, &Room) != 0) {
704                 syslog(9, "display_reg() exiting because goto_config_room() failed\n");
705                 if (during_login) {
706                         do_welcome();
707                 }
708                 else {
709                         display_main_menu();
710                 }
711                 FreeStrBuf(&Buf);
712                 FlushFolder(&Room);             
713                 return;
714         }
715         FlushFolder(&Room);
716
717         FreeStrBuf(&Buf);
718         vcard_msgnum = locate_user_vcard_in_this_room(&VCMsg, &VCAtt);
719         if (vcard_msgnum < 0L) {
720                 syslog(9, "display_reg() exiting because locate_user_vcard_in_this_room() failed\n");
721                 if (during_login) {
722                         do_welcome();
723                 }
724                 else {
725                         display_main_menu();
726                 }
727                 return;
728         }
729
730         if (during_login) {
731                 do_edit_vcard(vcard_msgnum, "1", VCMsg, VCAtt, "do_welcome", USERCONFIGROOM);
732         }
733         else {
734                 StrBuf *ReturnTo;
735                 ReturnTo = NewStrBufPlain(HKEY("display_main_menu?go="));
736                 StrBufAppendBuf(ReturnTo, WC->CurRoom.name, 0);
737                 do_edit_vcard(vcard_msgnum, "1", VCMsg, VCAtt, ChrPtr(ReturnTo), USERCONFIGROOM);
738                 FreeStrBuf(&ReturnTo);
739         }
740
741         /* FIXME - don't we have to free VCMsg and VCAtt ?? */
742 }
743
744
745
746
747 /*
748  * display form for changing your password
749  */
750 void display_changepw(void)
751 {
752         WCTemplputParams SubTP;
753         char buf[SIZ];
754         StrBuf *Buf;
755         output_headers(1, 1, 1, 0, 0, 0);
756
757         Buf = NewStrBufPlain(_("Change your password"), -1);
758         memset(&SubTP, 0, sizeof(WCTemplputParams));
759         SubTP.Filter.ContextType = CTX_STRBUF;
760         SubTP.Context = Buf;
761         DoTemplate(HKEY("beginbox"), NULL, &SubTP);
762
763         FreeStrBuf(&Buf);
764
765         if (!IsEmptyStr(WC->ImportantMessage)) {
766                 wc_printf("<span class=\"errormsg\">"
767                         "%s</span><br>\n", WC->ImportantMessage);
768                 safestrncpy(WC->ImportantMessage, "", sizeof WC->ImportantMessage);
769         }
770
771         serv_puts("MESG changepw");
772         serv_getln(buf, sizeof buf);
773         if (buf[0] == '1') {
774                 fmout("CENTER");
775         }
776
777         wc_printf("<form name=\"changepwform\" action=\"changepw\" method=\"post\">\n");
778         wc_printf("<input type=\"hidden\" name=\"nonce\" value=\"%d\">\n", WC->nonce);
779         wc_printf("<table class=\"altern\" ");
780         wc_printf("<tr class=\"even\"><td>");
781         wc_printf(_("Enter new password:"));
782         wc_printf("</td><td>");
783         wc_printf("<input type=\"password\" name=\"newpass1\" value=\"\" maxlength=\"20\"></td></tr>\n");
784         wc_printf("<tr class=\"odd\"><td>");
785         wc_printf(_("Enter it again to confirm:"));
786         wc_printf("</td><td>");
787         wc_printf("<input type=\"password\" name=\"newpass2\" value=\"\" maxlength=\"20\"></td></tr>\n");
788         wc_printf("</table>\n");
789
790         wc_printf("<div class=\"buttons\">\n");
791         wc_printf("<input type=\"submit\" name=\"change_action\" value=\"%s\">", _("Change password"));
792         wc_printf("&nbsp;");
793         wc_printf("<input type=\"submit\" name=\"cancel_action\" value=\"%s\">\n", _("Cancel"));
794         wc_printf("</div>\n");
795         wc_printf("</form>\n");
796
797         do_template("endbox", NULL);
798         wDumpContent(1);
799 }
800
801 /*
802  * change password
803  * if passwords match, propagate it to citserver.
804  */
805 void changepw(void)
806 {
807         char buf[SIZ];
808         char newpass1[32], newpass2[32];
809
810         if (!havebstr("change_action")) {
811                 safestrncpy(WC->ImportantMessage, 
812                         _("Cancelled.  Password was not changed."),
813                         sizeof WC->ImportantMessage);
814                 display_main_menu();
815                 return;
816         }
817
818         safestrncpy(newpass1, bstr("newpass1"), sizeof newpass1);
819         safestrncpy(newpass2, bstr("newpass2"), sizeof newpass2);
820
821         if (strcasecmp(newpass1, newpass2)) {
822                 safestrncpy(WC->ImportantMessage, 
823                         _("They don't match.  Password was not changed."),
824                         sizeof WC->ImportantMessage);
825                 display_changepw();
826                 return;
827         }
828
829         if (IsEmptyStr(newpass1)) {
830                 safestrncpy(WC->ImportantMessage, 
831                         _("Blank passwords are not allowed."),
832                         sizeof WC->ImportantMessage);
833                 display_changepw();
834                 return;
835         }
836
837         serv_printf("SETP %s", newpass1);
838         serv_getln(buf, sizeof buf);
839         sprintf(WC->ImportantMessage, "%s", &buf[4]);
840         if (buf[0] == '2') {
841                 if (WC->wc_password == NULL)
842                         WC->wc_password = NewStrBufPlain(buf, -1);
843                 else {
844                         FlushStrBuf(WC->wc_password);
845                         StrBufAppendBufPlain(WC->wc_password,  buf, -1, 0);
846                 }
847                 display_main_menu();
848         }
849         else {
850                 display_changepw();
851         }
852 }
853
854 int ConditionalHaveAccessCreateRoom(StrBuf *Target, WCTemplputParams *TP)
855 {
856         StrBuf *Buf;    
857
858         Buf = NewStrBuf();
859         serv_puts("CRE8 0");
860         StrBuf_ServGetln(Buf);
861
862         if (GetServerStatus(Buf, NULL) == 2) {
863                 StrBufCutLeft(Buf, 4);
864                 AppendImportantMessage(SKEY(Buf));
865                 FreeStrBuf(&Buf);
866                 return 0;
867         }
868         FreeStrBuf(&Buf);
869         return 1;
870 }
871
872 int ConditionalAide(StrBuf *Target, WCTemplputParams *TP)
873 {
874         wcsession *WCC = WC;
875         return (WCC != NULL) ? ((WCC->logged_in == 0)||(WC->is_aide == 0)) : 0;
876 }
877
878 int ConditionalIsLoggedIn(StrBuf *Target, WCTemplputParams *TP) 
879 {
880         wcsession *WCC = WC;
881         return (WCC != NULL) ? (WCC->logged_in == 0) : 0;
882
883 }
884
885
886
887 void _display_reg(void) {
888         display_reg(0);
889 }
890
891
892 void Header_HandleAuth(StrBuf *Line, ParsedHttpHdrs *hdr)
893 {
894         if (hdr->HR.got_auth == NO_AUTH) /* don't override cookie auth... */
895         {
896                 if (strncasecmp(ChrPtr(Line), "Basic", 5) == 0) {
897                         StrBufCutLeft(Line, 6);
898                         StrBufDecodeBase64(Line);
899                         hdr->HR.plainauth = Line;
900                         hdr->HR.got_auth = AUTH_BASIC;
901                 }
902                 else 
903                         syslog(1, "Authentication scheme not supported! [%s]\n", ChrPtr(Line));
904         }
905 }
906
907 void CheckAuthBasic(ParsedHttpHdrs *hdr)
908 {
909 /*
910   todo: enable this if we can have other sessions than authenticated ones.
911         if (hdr->DontNeedAuth)
912                 return;
913 */
914         StrBufAppendBufPlain(hdr->HR.plainauth, HKEY(":"), 0);
915         StrBufAppendBuf(hdr->HR.plainauth, hdr->HR.user_agent, 0);
916         hdr->HR.SessionKey = hashlittle(SKEY(hdr->HR.plainauth), 89479832);
917 /*
918         syslog(1, "CheckAuthBasic: calculated sessionkey %ld\n", 
919                 hdr->HR.SessionKey);
920 */
921 }
922
923 void GetAuthBasic(ParsedHttpHdrs *hdr)
924 {
925         const char *Pos = NULL;
926         if (hdr->c_username == NULL)
927                 hdr->c_username = NewStrBufPlain(HKEY(DEFAULT_HTTPAUTH_USER));
928         if (hdr->c_password == NULL)
929                 hdr->c_password = NewStrBufPlain(HKEY(DEFAULT_HTTPAUTH_PASS));
930         StrBufExtract_NextToken(hdr->c_username, hdr->HR.plainauth, &Pos, ':');
931         StrBufExtract_NextToken(hdr->c_password, hdr->HR.plainauth, &Pos, ':');
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 void 
961 HttpNewModule_AUTH
962 (ParsedHttpHdrs *httpreq)
963 {
964         httpreq->c_username = NewStrBufPlain(HKEY(DEFAULT_HTTPAUTH_USER));
965         httpreq->c_password = NewStrBufPlain(HKEY(DEFAULT_HTTPAUTH_PASS));
966         httpreq->c_roomname = NewStrBuf();
967         httpreq->c_language = NewStrBuf();
968 }
969 void 
970 HttpDetachModule_AUTH
971 (ParsedHttpHdrs *httpreq)
972 {
973         FLUSHStrBuf(httpreq->c_username);
974         FLUSHStrBuf(httpreq->c_password);
975         FLUSHStrBuf(httpreq->c_roomname);
976         FLUSHStrBuf(httpreq->c_language);
977 }
978
979 void 
980 HttpDestroyModule_AUTH
981 (ParsedHttpHdrs *httpreq)
982 {
983         FreeStrBuf(&httpreq->c_username);
984         FreeStrBuf(&httpreq->c_password);
985         FreeStrBuf(&httpreq->c_roomname);
986         FreeStrBuf(&httpreq->c_language);
987 }
988
989 void 
990 InitModule_AUTH
991 (void)
992 {
993         initialize_axdefs();
994         RegisterHeaderHandler(HKEY("COOKIE"), Header_HandleCookie);
995         RegisterHeaderHandler(HKEY("AUTHORIZATION"), Header_HandleAuth);
996
997         /* no url pattern at all? Show login. */
998         WebcitAddUrlHandler(HKEY(""), "", 0, do_welcome, ANONYMOUS|COOKIEUNNEEDED);
999
1000         /* some of these will be removed soon */
1001         WebcitAddUrlHandler(HKEY("do_welcome"), "", 0, do_welcome, ANONYMOUS|COOKIEUNNEEDED);
1002         WebcitAddUrlHandler(HKEY("openid_login"), "", 0, do_openid_login, ANONYMOUS);
1003         WebcitAddUrlHandler(HKEY("finalize_openid_login"), "", 0, finalize_openid_login, ANONYMOUS);
1004         WebcitAddUrlHandler(HKEY("openid_manual_create"), "", 0, openid_manual_create, ANONYMOUS);
1005         WebcitAddUrlHandler(HKEY("validate"), "", 0, validate, 0);
1006         WebcitAddUrlHandler(HKEY("do_welcome"), "", 0, do_welcome, 0);
1007         WebcitAddUrlHandler(HKEY("display_reg"), "", 0, _display_reg, 0);
1008         WebcitAddUrlHandler(HKEY("display_changepw"), "", 0, display_changepw, 0);
1009         WebcitAddUrlHandler(HKEY("changepw"), "", 0, changepw, 0);
1010         WebcitAddUrlHandler(HKEY("termquit"), "", 0, do_logout, 0);
1011         WebcitAddUrlHandler(HKEY("do_logout"), "", 0, do_logout, ANONYMOUS|COOKIEUNNEEDED|FORCE_SESSIONCLOSE);
1012         WebcitAddUrlHandler(HKEY("ajax_login_username_password"), "", 0, ajax_login_username_password, AJAX|ANONYMOUS);
1013         WebcitAddUrlHandler(HKEY("ajax_login_newuser"), "", 0, ajax_login_newuser, AJAX|ANONYMOUS);
1014         RegisterConditional(HKEY("COND:AIDE"), 2, ConditionalAide, CTX_NONE);
1015         RegisterConditional(HKEY("COND:LOGGEDIN"), 2, ConditionalIsLoggedIn, CTX_NONE);
1016         RegisterConditional(HKEY("COND:MAY_CREATE_ROOM"), 2,  ConditionalHaveAccessCreateRoom, CTX_NONE);
1017         return;
1018 }
1019
1020
1021 void 
1022 SessionDestroyModule_AUTH
1023 (wcsession *sess)
1024 {
1025         FreeStrBuf(&sess->wc_username);
1026         FreeStrBuf(&sess->wc_fullname);
1027         FreeStrBuf(&sess->wc_password);
1028         FreeStrBuf(&sess->httpauth_pass);
1029         FreeStrBuf(&sess->cs_inet_email);
1030 }