* Removed some cruft from the login code. Combined the
[citadel.git] / citadel / modules / openid / serv_openid_rp.c
1 /*
2  * $Id$
3  *
4  * This is an implementation of OpenID 1.1 Relying Party support, in stateless mode.
5  *
6  */
7
8 #include "sysdep.h"
9 #include <stdlib.h>
10 #include <unistd.h>
11 #include <stdio.h>
12 #include <fcntl.h>
13 #include <signal.h>
14 #include <pwd.h>
15 #include <errno.h>
16 #include <sys/types.h>
17
18 #if TIME_WITH_SYS_TIME
19 # include <sys/time.h>
20 # include <time.h>
21 #else
22 # if HAVE_SYS_TIME_H
23 #  include <sys/time.h>
24 # else
25 #  include <time.h>
26 # endif
27 #endif
28
29 #include <sys/wait.h>
30 #include <string.h>
31 #include <limits.h>
32 #include <curl/curl.h>
33 #include "ctdl_module.h"
34 #include "config.h"
35 #include "citserver.h"
36 #include "user_ops.h"
37
38 struct ctdl_openid {
39         char claimed_id[1024];
40         char server[1024];
41         int validated;
42 };
43
44
45
46
47
48 /**************************************************************************/
49 /*                                                                        */
50 /* Functions in this section handle Citadel internal OpenID mapping stuff */
51 /*                                                                        */
52 /**************************************************************************/
53
54
55 /*
56  * The structure of an openid record *key* is:
57  *
58  * |--------------claimed_id-------------|
59  *     (actual length of claimed id)
60  *
61  *
62  * The structure of an openid record *value* is:
63  *
64  * |-----user_number----|------------claimed_id---------------|
65  *    (sizeof long)          (actual length of claimed id)
66  *
67  */
68
69
70
71 /*
72  * Attach an OpenID to a Citadel account
73  */
74 int attach_openid(struct ctdluser *who, char *claimed_id)
75 {
76         struct cdbdata *cdboi;
77         long fetched_usernum;
78         char *data;
79         int data_len;
80
81         if (!who) return(1);
82         if (!claimed_id) return(1);
83         if (IsEmptyStr(claimed_id)) return(1);
84
85         /* Check to see if this OpenID is already in the database */
86
87         cdboi = cdb_fetch(CDB_OPENID, claimed_id, strlen(claimed_id));
88         if (cdboi != NULL) {
89                 memcpy(&fetched_usernum, cdboi->ptr, sizeof(long));
90                 cdb_free(cdboi);
91
92                 if (fetched_usernum == who->usernum) {
93                         CtdlLogPrintf(CTDL_INFO, "%s already associated; no action is taken\n", claimed_id);
94                         return(0);
95                 }
96                 else {
97                         CtdlLogPrintf(CTDL_INFO, "%s already belongs to another user\n", claimed_id);
98                         return(3);
99                 }
100         }
101
102         /* Not already in the database, so attach it now */
103
104         data_len = sizeof(long) + strlen(claimed_id) + 1;
105         data = malloc(data_len);
106
107         memcpy(data, &who->usernum, sizeof(long));
108         memcpy(&data[sizeof(long)], claimed_id, strlen(claimed_id) + 1);
109
110         cdb_store(CDB_OPENID, claimed_id, strlen(claimed_id), data, data_len);
111         free(data);
112
113         CtdlLogPrintf(CTDL_INFO, "%s has been associated with %s (%ld)\n",
114                 claimed_id, who->fullname, who->usernum);
115         return(0);
116 }
117
118
119 /*
120  * When a user is being deleted, we have to delete any OpenID associations
121  */
122 void openid_purge(struct ctdluser *usbuf) {
123         struct cdbdata *cdboi;
124         HashList *keys = NULL;
125         HashPos *HashPos;
126         char *deleteme = NULL;
127         long len;
128         void *Value;
129         char *Key;
130
131         keys = NewHash(1, NULL);
132         if (!keys) return;
133
134
135         cdb_rewind(CDB_OPENID);
136         while (cdboi = cdb_next_item(CDB_OPENID), cdboi != NULL) {
137                 if (cdboi->len > sizeof(long)) {
138                         if (((long)*(cdboi->ptr)) == usbuf->usernum) {
139                                 deleteme = strdup(cdboi->ptr + sizeof(long)),
140                                 Put(keys, deleteme, strlen(deleteme), deleteme, generic_free_handler);
141                         }
142                 }
143                 cdb_free(cdboi);
144         }
145
146         /* Go through the hash list, deleting keys we stored in it */
147
148         HashPos = GetNewHashPos();
149         while (GetNextHashPos(keys, HashPos, &len, &Key, &Value)!=0)
150         {
151                 CtdlLogPrintf(CTDL_DEBUG, "Deleting associated OpenID <%s>\n", Value);
152                 cdb_delete(CDB_OPENID, Value, strlen(Value));
153                 /* note: don't free(Value) -- deleting the hash list will handle this for us */
154         }
155         DeleteHashPos(&HashPos);
156         DeleteHash(&keys);
157 }
158
159
160
161 /*
162  * List the OpenIDs associated with the currently logged in account
163  */
164 void cmd_oidl(char *argbuf) {
165         struct cdbdata *cdboi;
166
167         if (CtdlAccessCheck(ac_logged_in)) return;
168         cdb_rewind(CDB_OPENID);
169         cprintf("%d Associated OpenIDs:\n", LISTING_FOLLOWS);
170
171         while (cdboi = cdb_next_item(CDB_OPENID), cdboi != NULL) {
172                 if (cdboi->len > sizeof(long)) {
173                         if (((long)*(cdboi->ptr)) == CC->user.usernum) {
174                                 cprintf("%s\n", cdboi->ptr + sizeof(long));
175                         }
176                 }
177                 cdb_free(cdboi);
178         }
179         cprintf("000\n");
180 }
181
182
183
184 /*
185  * Detach an OpenID from the currently logged in account
186  */
187 void cmd_oidd(char *argbuf) {
188         struct cdbdata *cdboi;
189         char id_to_detach[1024];
190         int this_is_mine = 0;
191
192         if (CtdlAccessCheck(ac_logged_in)) return;
193         extract_token(id_to_detach, argbuf, 0, '|', sizeof id_to_detach);
194         if (IsEmptyStr(id_to_detach)) {
195                 cprintf("%d An empty OpenID URL is not allowed.\n", ERROR + ILLEGAL_VALUE);
196         }
197
198         cdb_rewind(CDB_OPENID);
199         while (cdboi = cdb_next_item(CDB_OPENID), cdboi != NULL) {
200                 if (cdboi->len > sizeof(long)) {
201                         if (((long)*(cdboi->ptr)) == CC->user.usernum) {
202                                 this_is_mine = 1;
203                         }
204                 }
205                 cdb_free(cdboi);
206         }
207
208         if (!this_is_mine) {
209                 cprintf("%d That OpenID was not found or not associated with your account.\n",
210                         ERROR + ILLEGAL_VALUE);
211                 return;
212         }
213
214         cdb_delete(CDB_OPENID, id_to_detach, strlen(id_to_detach));
215         cprintf("%d %s detached from your account.\n", CIT_OK, id_to_detach);
216 }
217
218
219
220 /*
221  * Attempt to auto-create a new Citadel account using the nickname from Simple Registration Extension
222  */
223 int openid_create_user_via_sri(char *claimed_id, HashList *sri_keys)
224 {
225         char *desired_name = NULL;
226         char new_password[32];
227
228         if (config.c_auth_mode != AUTHMODE_NATIVE) return(1);
229         if (config.c_disable_newu) return(2);
230         if (CC->logged_in) return(3);
231         if (!GetHash(sri_keys, "sreg.nickname", 13, (void *) &desired_name)) return(4);
232
233         CtdlLogPrintf(CTDL_DEBUG, "The desired account name is <%s>\n", desired_name);
234
235         if (!getuser(&CC->user, desired_name)) {
236                 CtdlLogPrintf(CTDL_DEBUG, "<%s> is already taken by another user.\n", desired_name);
237                 memset(&CC->user, 0, sizeof(struct ctdluser));
238                 return(5);
239         }
240
241         /* The desired account name is available.  Create the account and log it in! */
242         if (create_user(desired_name, 1)) return(6);
243
244         snprintf(new_password, sizeof new_password, "%08lx%08lx", random(), random());
245         CtdlSetPassword(new_password);
246         attach_openid(&CC->user, claimed_id);
247         return(0);
248 }
249
250 // FIXME we still have to set up the vCard
251
252 // identity = [50]  http://uncensored.citadel.org/~ajc/MyID.config.php
253 // sreg.nickname = [17]  IGnatius T Foobar
254 // sreg.email = [26]  ajc@uncensored.citadel.org
255 // sreg.fullname = [10]  Art Cancro
256 // sreg.postcode = [5]  10549
257 // sreg.country = [2]  US
258
259
260
261 /*
262  * If a user account exists which is associated with the Claimed ID, log it in and return zero.
263  * Otherwise it returns nonzero.
264  */
265 int login_via_openid(char *claimed_id)
266 {
267         struct cdbdata *cdboi;
268         long usernum = 0;
269
270         cdboi = cdb_fetch(CDB_OPENID, claimed_id, strlen(claimed_id));
271         if (cdboi == NULL) {
272                 return(-1);
273         }
274
275         memcpy(&usernum, cdboi->ptr, sizeof(long));
276         cdb_free(cdboi);
277
278         if (!getuserbynumber(&CC->user, usernum)) {
279                 /* Now become the user we just created */
280                 safestrncpy(CC->curr_user, CC->user.fullname, sizeof CC->curr_user);
281                 do_login();
282                 return(0);
283         }
284         else {
285                 memset(&CC->user, 0, sizeof(struct ctdluser));
286                 return(-1);
287         }
288 }
289
290
291
292
293 /**************************************************************************/
294 /*                                                                        */
295 /* Functions in this section handle OpenID protocol                       */
296 /*                                                                        */
297 /**************************************************************************/
298
299
300 /* 
301  * Locate a <link> tag and, given its 'rel=' parameter, return its 'href' parameter
302  */
303 void extract_link(char *target_buf, int target_size, char *rel, char *source_buf)
304 {
305         char *ptr = source_buf;
306
307         if (!target_buf) return;
308         if (!rel) return;
309         if (!source_buf) return;
310
311         target_buf[0] = 0;
312
313         while (ptr = bmstrcasestr(ptr, "<link"), ptr != NULL) {
314
315                 char work_buffer[2048];
316                 char *link_tag_start = NULL;
317                 char *link_tag_end = NULL;
318
319                 char rel_tag[2048];
320                 char href_tag[2048];
321
322                 link_tag_start = ptr;
323                 link_tag_end = strchr(ptr, '>');
324                 rel_tag[0] = 0;
325                 href_tag[0] = 0;
326
327                 if ((link_tag_end) && (link_tag_end > link_tag_start)) {
328                         int len;
329                         len = link_tag_end - link_tag_start;
330                         if (len > sizeof work_buffer) len = sizeof work_buffer;
331                         memcpy(work_buffer, link_tag_start, len);
332                 
333                         char *rel_start = NULL;
334                         char *rel_end = NULL;
335                         rel_start = bmstrcasestr(work_buffer, "rel=");
336                         if (rel_start) {
337                                 rel_start = strchr(rel_start, '\"');
338                                 if (rel_start) {
339                                         ++rel_start;
340                                         rel_end = strchr(rel_start, '\"');
341                                         if ((rel_end) && (rel_end > rel_start)) {
342                                                 safestrncpy(rel_tag, rel_start, rel_end - rel_start + 1);
343                                         }
344                                 }
345                         }
346
347                         char *href_start = NULL;
348                         char *href_end = NULL;
349                         href_start = bmstrcasestr(work_buffer, "href=");
350                         if (href_start) {
351                                 href_start = strchr(href_start, '\"');
352                                 if (href_start) {
353                                         ++href_start;
354                                         href_end = strchr(href_start, '\"');
355                                         if ((href_end) && (href_end > href_start)) {
356                                                 safestrncpy(href_tag, href_start, href_end - href_start + 1);
357                                         }
358                                 }
359                         }
360
361                         if (!strcasecmp(rel, rel_tag)) {
362                                 safestrncpy(target_buf, href_tag, target_size);
363                                 return;
364                         }
365
366                 }
367
368         ++ptr;
369         }
370
371
372 }
373
374
375
376 struct fh_data {
377         char *buf;
378         int total_bytes_received;
379         int maxbytes;
380 };
381
382
383 size_t fh_callback(void *ptr, size_t size, size_t nmemb, void *stream)
384 {
385         struct fh_data *fh = (struct fh_data *) stream;
386         int got_bytes = (size * nmemb);
387
388         if (fh->total_bytes_received + got_bytes > fh->maxbytes) {
389                 got_bytes = fh->maxbytes - fh->total_bytes_received;
390         }
391         if (got_bytes > 0) {
392                 memcpy(&fh->buf[fh->total_bytes_received], ptr, got_bytes);
393                 fh->total_bytes_received += got_bytes;
394         }
395
396         return (size * nmemb);  /* always succeed; libcurl doesn't need to know if we truncated it */
397 }
398
399
400
401 /*
402  * Begin an HTTP fetch (returns number of bytes actually fetched, or -1 for error) using libcurl.
403  *
404  * If 'normalize_len' is nonzero, the caller is specifying the buffer size of 'url', and is
405  * requesting that the effective (normalized) URL be copied back to it.
406  */
407 int fetch_http(char *url, char *target_buf, int maxbytes, int normalize_len)
408 {
409         CURL *curl;
410         CURLcode res;
411         char errmsg[1024] = "";
412         struct fh_data fh = {
413                 target_buf,
414                 0,
415                 maxbytes
416         };
417         char *effective_url = NULL;
418
419         if (!url) return(-1);
420         if (!target_buf) return(-1);
421         memset(target_buf, 0, maxbytes);
422
423         curl = curl_easy_init();
424         if (!curl) {
425                 CtdlLogPrintf(CTDL_ALERT, "Unable to initialize libcurl.\n");
426                 return(-1);
427         }
428
429         curl_easy_setopt(curl, CURLOPT_URL, url);
430         curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 0);
431         curl_easy_setopt(curl, CURLOPT_SSL_VERIFYHOST, 0);
432         curl_easy_setopt(curl, CURLOPT_WRITEDATA, &fh);
433         curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, fh_callback);
434         curl_easy_setopt(curl, CURLOPT_ERRORBUFFER, errmsg);
435         curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1);
436         curl_easy_setopt(curl, CURLOPT_USERAGENT, CITADEL);
437         if (!IsEmptyStr(config.c_ip_addr)) {
438                 curl_easy_setopt(curl, CURLOPT_INTERFACE, config.c_ip_addr);
439         }
440         res = curl_easy_perform(curl);
441         if (res) {
442                 CtdlLogPrintf(CTDL_DEBUG, "fetch_http() libcurl error %d: %s\n", res, errmsg);
443         }
444         if (normalize_len > 0) {
445                 curl_easy_getinfo(curl, CURLINFO_EFFECTIVE_URL, &effective_url);
446                 safestrncpy(url, effective_url, normalize_len);
447         }
448         curl_easy_cleanup(curl);
449         return fh.total_bytes_received;
450 }
451
452
453 /*
454  * Setup an OpenID authentication
455  */
456 void cmd_oids(char *argbuf) {
457         char return_to[1024];
458         char trust_root[1024];
459         int i;
460         char buf[SIZ];
461         struct CitContext *CCC = CC;    /* CachedCitContext - performance boost */
462         struct ctdl_openid *oiddata;
463
464         /* commented out because we may be attempting to attach an OpenID to
465          * an existing account that is logged in
466          *
467         if (CCC->logged_in) {
468                 cprintf("%d Already logged in.\n", ERROR + ALREADY_LOGGED_IN);
469                 return;
470         }
471          */
472
473         if (CCC->openid_data != NULL) {
474                 free(CCC->openid_data);
475         }
476         oiddata = malloc(sizeof(struct ctdl_openid));
477         if (oiddata == NULL) {
478                 cprintf("%d malloc failed\n", ERROR + INTERNAL_ERROR);
479                 return;
480         }
481         memset(oiddata, 0, sizeof(struct ctdl_openid));
482         CCC->openid_data = (void *) oiddata;
483
484         extract_token(oiddata->claimed_id, argbuf, 0, '|', sizeof oiddata->claimed_id);
485         extract_token(return_to, argbuf, 1, '|', sizeof return_to);
486         extract_token(trust_root, argbuf, 2, '|', sizeof trust_root);
487         oiddata->validated = 0;
488
489         i = fetch_http(oiddata->claimed_id, buf, sizeof buf - 1, sizeof oiddata->claimed_id);
490         CtdlLogPrintf(CTDL_DEBUG, "Normalized URL and Claimed ID is: %s\n", oiddata->claimed_id);
491         buf[sizeof buf - 1] = 0;
492         if (i > 0) {
493                 char openid_delegate[1024];
494
495                 extract_link(oiddata->server, sizeof oiddata->server, "openid.server", buf);
496                 extract_link(openid_delegate, sizeof openid_delegate, "openid.delegate", buf);
497
498                 if (IsEmptyStr(oiddata->server)) {
499                         cprintf("%d There is no OpenID identity provider at this URL.\n", ERROR);
500                         return;
501                 }
502
503                 /* Empty delegate is legal; we just use the openid_url instead */
504                 if (IsEmptyStr(openid_delegate)) {
505                         safestrncpy(openid_delegate, oiddata->claimed_id, sizeof openid_delegate);
506                 }
507
508                 /* Assemble a URL to which the user-agent will be redirected. */
509                 char redirect_string[4096];
510                 char escaped_identity[512];
511                 char escaped_return_to[2048];
512                 char escaped_trust_root[1024];
513                 char escaped_sreg_optional[256];
514
515                 urlesc(escaped_identity, sizeof escaped_identity, openid_delegate);
516                 urlesc(escaped_return_to, sizeof escaped_return_to, return_to);
517                 urlesc(escaped_trust_root, sizeof escaped_trust_root, trust_root);
518                 urlesc(escaped_sreg_optional, sizeof escaped_sreg_optional,
519                         "nickname,email,fullname,postcode,country");
520
521                 snprintf(redirect_string, sizeof redirect_string,
522                         "%s"
523                         "?openid.mode=checkid_setup"
524                         "&openid.identity=%s"
525                         "&openid.return_to=%s"
526                         "&openid.trust_root=%s"
527                         "&openid.sreg.optional=%s"
528                         ,
529                         oiddata->server,
530                         escaped_identity,
531                         escaped_return_to,
532                         escaped_trust_root,
533                         escaped_sreg_optional
534                 );
535                 cprintf("%d %s\n", CIT_OK, redirect_string);
536                 return;
537         }
538
539         cprintf("%d Unable to fetch OpenID URL\n", ERROR);
540 }
541
542
543
544
545
546 /*
547  * Finalize an OpenID authentication
548  */
549 void cmd_oidf(char *argbuf) {
550         char buf[2048];
551         char thiskey[1024];
552         char thisdata[1024];
553         HashList *keys = NULL;
554         struct ctdl_openid *oiddata = (struct ctdl_openid *) CC->openid_data;
555
556         keys = NewHash(1, NULL);
557         if (!keys) {
558                 cprintf("%d NewHash() failed\n", ERROR + INTERNAL_ERROR);
559                 return;
560         }
561         
562         cprintf("%d Transmit OpenID data now\n", START_CHAT_MODE);
563
564         while (client_getln(buf, sizeof buf), strcmp(buf, "000")) {
565                 extract_token(thiskey, buf, 0, '|', sizeof thiskey);
566                 extract_token(thisdata, buf, 1, '|', sizeof thisdata);
567                 CtdlLogPrintf(CTDL_DEBUG, "%s: [%d] %s\n", thiskey, strlen(thisdata), thisdata);
568                 Put(keys, thiskey, strlen(thiskey), strdup(thisdata), generic_free_handler);
569         }
570
571
572         /* Now that we have all of the parameters, we have to validate the signature against the server */
573         CtdlLogPrintf(CTDL_DEBUG, "About to validate the signature...\n");
574
575         CURL *curl;
576         CURLcode res;
577         struct curl_httppost *formpost = NULL;
578         struct curl_httppost *lastptr = NULL;
579         char errmsg[1024] = "";
580         char *o_assoc_handle = NULL;
581         char *o_sig = NULL;
582         char *o_signed = NULL;
583         int num_signed_values;
584         int i;
585         char k_keyname[128];
586         char k_o_keyname[128];
587         char *k_value = NULL;
588         char valbuf[1024];
589
590         struct fh_data fh = {
591                 valbuf,
592                 0,
593                 sizeof valbuf
594         };
595
596         curl_formadd(&formpost, &lastptr,
597                 CURLFORM_COPYNAME,      "openid.mode",
598                 CURLFORM_COPYCONTENTS,  "check_authentication",
599                 CURLFORM_END);
600         CtdlLogPrintf(CTDL_DEBUG, "%25s : %s\n", "openid.mode", "check_authentication");
601
602         if (GetHash(keys, "assoc_handle", 12, (void *) &o_assoc_handle)) {
603                 curl_formadd(&formpost, &lastptr,
604                         CURLFORM_COPYNAME,      "openid.assoc_handle",
605                         CURLFORM_COPYCONTENTS,  o_assoc_handle,
606                         CURLFORM_END);
607                 CtdlLogPrintf(CTDL_DEBUG, "%25s : %s\n", "openid.assoc_handle", o_assoc_handle);
608         }
609
610         if (GetHash(keys, "sig", 3, (void *) &o_sig)) {
611                 curl_formadd(&formpost, &lastptr,
612                         CURLFORM_COPYNAME,      "openid.sig",
613                         CURLFORM_COPYCONTENTS,  o_sig,
614                         CURLFORM_END);
615                         CtdlLogPrintf(CTDL_DEBUG, "%25s : %s\n", "openid.sig", o_sig);
616         }
617
618         if (GetHash(keys, "signed", 6, (void *) &o_signed)) {
619                 curl_formadd(&formpost, &lastptr,
620                         CURLFORM_COPYNAME,      "openid.signed",
621                         CURLFORM_COPYCONTENTS,  o_signed,
622                         CURLFORM_END);
623                 CtdlLogPrintf(CTDL_DEBUG, "%25s : %s\n", "openid.signed", o_signed);
624
625                 num_signed_values = num_tokens(o_signed, ',');
626                 for (i=0; i<num_signed_values; ++i) {
627                         extract_token(k_keyname, o_signed, i, ',', sizeof k_keyname);
628                         if (strcasecmp(k_keyname, "mode")) {    // work around phpMyID bug
629                                 if (GetHash(keys, k_keyname, strlen(k_keyname), (void *) &k_value)) {
630                                         snprintf(k_o_keyname, sizeof k_o_keyname, "openid.%s", k_keyname);
631                                         curl_formadd(&formpost, &lastptr,
632                                                 CURLFORM_COPYNAME,      k_o_keyname,
633                                                 CURLFORM_COPYCONTENTS,  k_value,
634                                                 CURLFORM_END);
635                                         CtdlLogPrintf(CTDL_DEBUG, "%25s : %s\n", k_o_keyname, k_value);
636                                 }
637                                 else {
638                                         CtdlLogPrintf(CTDL_INFO, "OpenID: signed field '%s' is missing\n",
639                                                 k_keyname);
640                                 }
641                         }
642                 }
643         }
644
645         curl = curl_easy_init();
646         curl_easy_setopt(curl, CURLOPT_URL, oiddata->server);
647         curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 0);
648         curl_easy_setopt(curl, CURLOPT_SSL_VERIFYHOST, 0);
649         curl_easy_setopt(curl, CURLOPT_WRITEDATA, &fh);
650         curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, fh_callback);
651         curl_easy_setopt(curl, CURLOPT_HTTPPOST, formpost);
652         curl_easy_setopt(curl, CURLOPT_ERRORBUFFER, errmsg);
653         curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1);
654         curl_easy_setopt(curl, CURLOPT_USERAGENT, CITADEL);
655         if (!IsEmptyStr(config.c_ip_addr)) {
656                 curl_easy_setopt(curl, CURLOPT_INTERFACE, config.c_ip_addr);
657         }
658
659         res = curl_easy_perform(curl);
660         if (res) {
661                 CtdlLogPrintf(CTDL_DEBUG, "cmd_oidf() libcurl error %d: %s\n", res, errmsg);
662         }
663         curl_easy_cleanup(curl);
664         curl_formfree(formpost);
665
666         valbuf[fh.total_bytes_received] = 0;
667
668         if (bmstrcasestr(valbuf, "is_valid:true")) {
669                 oiddata->validated = 1;
670         }
671
672         CtdlLogPrintf(CTDL_DEBUG, "Authentication %s.\n", (oiddata->validated ? "succeeded" : "failed") );
673
674         /* Respond to the client */
675
676         if (oiddata->validated) {
677
678                 /* If we were already logged in, attach the OpenID to the user's account */
679                 if (CC->logged_in) {
680                         if (attach_openid(&CC->user, oiddata->claimed_id) == 0) {
681                                 cprintf("attach\n");
682                         }
683                         else {
684                                 cprintf("fail\n");
685                         }
686                 }
687
688                 /* Otherwise, a user is attempting to log in using the validated OpenID */      
689                 else {
690                         /*
691                          * Existing user who has claimed this OpenID?
692                          *
693                          * Note: if you think that sending the password back over the wire is insecure,
694                          * check your assumptions.  If someone has successfully asserted an OpenID that
695                          * is associated with the account, they already have password equivalency and can
696                          * login, so they could just as easily change the password, etc.
697                          */
698                         if (login_via_openid(oiddata->claimed_id) == 0) {
699                                 cprintf("authenticate\n%s\n%s\n", CC->user.fullname, CC->user.password);
700                                 logged_in_response();
701                         }
702
703                         /*
704                          * New user whose OpenID is verified and Simple Registration Extension is in use?
705                          */
706                         else if (openid_create_user_via_sri(oiddata->claimed_id, keys) == 0) {
707                                 cprintf("authenticate\n%s\n%s\n", CC->user.fullname, CC->user.password);
708                                 logged_in_response();
709                         }
710
711                         /* FIXME right here we have to handle manual account creation */
712
713                         else {
714                                 cprintf("fail\n");
715                         }
716                 }
717         }
718         else {
719                 cprintf("fail\n");
720         }
721         cprintf("000\n");
722
723         /*
724          * We will eventually do something with the data in the hash list.
725          *
726         long len;
727         void *Value;
728         char *Key;
729         HashPos *HashPos;
730         HashPos = GetNewHashPos();
731         while (GetNextHashPos(keys, HashPos, &len, &Key, &Value)!=0)
732         {
733         }
734         DeleteHashPos(&HashPos);
735          */
736
737         DeleteHash(&keys);              /* This will free() all the key data for us */
738 }
739
740
741
742 /**************************************************************************/
743 /*                                                                        */
744 /* Functions in this section handle module initialization and shutdown    */
745 /*                                                                        */
746 /**************************************************************************/
747
748
749 /*
750  * This cleanup function blows away the temporary memory used by this module.
751  */
752 void openid_cleanup_function(void) {
753
754         if (CC->openid_data != NULL) {
755                 free(CC->openid_data);
756         }
757 }
758
759
760 CTDL_MODULE_INIT(openid_rp)
761 {
762         if (!threading)
763         {
764                 curl_global_init(CURL_GLOBAL_ALL);
765                 CtdlRegisterProtoHook(cmd_oids, "OIDS", "Setup OpenID authentication");
766                 CtdlRegisterProtoHook(cmd_oidf, "OIDF", "Finalize OpenID authentication");
767                 CtdlRegisterProtoHook(cmd_oidl, "OIDL", "List OpenIDs associated with an account");
768                 CtdlRegisterProtoHook(cmd_oidd, "OIDD", "Detach an OpenID from an account");
769                 CtdlRegisterSessionHook(openid_cleanup_function, EVT_STOP);
770                 CtdlRegisterUserHook(openid_purge, EVT_PURGEUSER);
771         }
772
773         /* return our Subversion id for the Log */
774         return "$Id$";
775 }
776
777
778 /* FIXME ... we have to add the new openid database to serv_vandelay.c */
779