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