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