* When not using native auth mode, do not enable the OpenID server command set.
[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         HashList *sreg_keys;
43 };
44
45
46
47
48
49 /**************************************************************************/
50 /*                                                                        */
51 /* Functions in this section handle Citadel internal OpenID mapping stuff */
52 /*                                                                        */
53 /**************************************************************************/
54
55
56 /*
57  * The structure of an openid record *key* is:
58  *
59  * |--------------claimed_id-------------|
60  *     (actual length of claimed id)
61  *
62  *
63  * The structure of an openid record *value* is:
64  *
65  * |-----user_number----|------------claimed_id---------------|
66  *    (sizeof long)          (actual length of claimed id)
67  *
68  */
69
70
71
72 /*
73  * Attach an OpenID to a Citadel account
74  */
75 int attach_openid(struct ctdluser *who, char *claimed_id)
76 {
77         struct cdbdata *cdboi;
78         long fetched_usernum;
79         char *data;
80         int data_len;
81
82         if (!who) return(1);
83         if (!claimed_id) return(1);
84         if (IsEmptyStr(claimed_id)) return(1);
85
86         /* Check to see if this OpenID is already in the database */
87
88         cdboi = cdb_fetch(CDB_OPENID, claimed_id, strlen(claimed_id));
89         if (cdboi != NULL) {
90                 memcpy(&fetched_usernum, cdboi->ptr, sizeof(long));
91                 cdb_free(cdboi);
92
93                 if (fetched_usernum == who->usernum) {
94                         CtdlLogPrintf(CTDL_INFO, "%s already associated; no action is taken\n", claimed_id);
95                         return(0);
96                 }
97                 else {
98                         CtdlLogPrintf(CTDL_INFO, "%s already belongs to another user\n", claimed_id);
99                         return(3);
100                 }
101         }
102
103         /* Not already in the database, so attach it now */
104
105         data_len = sizeof(long) + strlen(claimed_id) + 1;
106         data = malloc(data_len);
107
108         memcpy(data, &who->usernum, sizeof(long));
109         memcpy(&data[sizeof(long)], claimed_id, strlen(claimed_id) + 1);
110
111         cdb_store(CDB_OPENID, claimed_id, strlen(claimed_id), data, data_len);
112         free(data);
113
114         CtdlLogPrintf(CTDL_INFO, "%s has been attached to %s (%ld)\n",
115                 claimed_id, who->fullname, who->usernum);
116         return(0);
117 }
118
119
120
121 /*
122  * When a user is being deleted, we have to delete any OpenID associations
123  */
124 void openid_purge(struct ctdluser *usbuf) {
125         struct cdbdata *cdboi;
126         HashList *keys = NULL;
127         HashPos *HashPos;
128         char *deleteme = NULL;
129         long len;
130         void *Value;
131         char *Key;
132
133         keys = NewHash(1, NULL);
134         if (!keys) return;
135
136
137         cdb_rewind(CDB_OPENID);
138         while (cdboi = cdb_next_item(CDB_OPENID), cdboi != NULL) {
139                 if (cdboi->len > sizeof(long)) {
140                         if (((long)*(cdboi->ptr)) == usbuf->usernum) {
141                                 deleteme = strdup(cdboi->ptr + sizeof(long)),
142                                 Put(keys, deleteme, strlen(deleteme), deleteme, generic_free_handler);
143                         }
144                 }
145                 cdb_free(cdboi);
146         }
147
148         /* Go through the hash list, deleting keys we stored in it */
149
150         HashPos = GetNewHashPos();
151         while (GetNextHashPos(keys, HashPos, &len, &Key, &Value)!=0)
152         {
153                 CtdlLogPrintf(CTDL_DEBUG, "Deleting associated OpenID <%s>\n", Value);
154                 cdb_delete(CDB_OPENID, Value, strlen(Value));
155                 /* note: don't free(Value) -- deleting the hash list will handle this for us */
156         }
157         DeleteHashPos(&HashPos);
158         DeleteHash(&keys);
159 }
160
161
162
163 /*
164  * List the OpenIDs associated with the currently logged in account
165  */
166 void cmd_oidl(char *argbuf) {
167         struct cdbdata *cdboi;
168
169         if (CtdlAccessCheck(ac_logged_in)) return;
170         cdb_rewind(CDB_OPENID);
171         cprintf("%d Associated OpenIDs:\n", LISTING_FOLLOWS);
172
173         while (cdboi = cdb_next_item(CDB_OPENID), cdboi != NULL) {
174                 if (cdboi->len > sizeof(long)) {
175                         if (((long)*(cdboi->ptr)) == CC->user.usernum) {
176                                 cprintf("%s\n", cdboi->ptr + sizeof(long));
177                         }
178                 }
179                 cdb_free(cdboi);
180         }
181         cprintf("000\n");
182 }
183
184
185 /*
186  * Attempt to register (populate the vCard) the currently-logged-in user
187  * using the data from Simple Registration Extension, if present.
188  */
189 void populate_vcard_from_sreg(HashList *sreg_keys) {
190
191         struct vCard *v;
192         int pop = 0;                    /* number of fields populated */
193         char *data = NULL;
194         char *postcode = NULL;
195         char *country = NULL;
196
197         if (!sreg_keys) return;
198         v = vcard_new();
199         if (!v) return;
200
201         if (GetHash(sreg_keys, "identity", 8, (void *) &data)) {
202                 vcard_add_prop(v, "url;type=openid", data);
203                 ++pop;
204         }
205
206         if (GetHash(sreg_keys, "sreg.email", 10, (void *) &data)) {
207                 vcard_add_prop(v, "email;internet", data);
208                 ++pop;
209         }
210
211         if (GetHash(sreg_keys, "sreg.nickname", 13, (void *) &data)) {
212                 vcard_add_prop(v, "nickname", data);
213                 ++pop;
214         }
215
216         if (GetHash(sreg_keys, "sreg.fullname", 13, (void *) &data)) {
217                 char n[256];
218                 vcard_add_prop(v, "fn", data);
219                 vcard_fn_to_n(n, data, sizeof n);
220                 vcard_add_prop(v, "n", n);
221                 ++pop;
222         }
223
224         if (!GetHash(sreg_keys, "sreg.postcode", 13, (void *) &postcode)) {
225                 postcode = NULL;
226         }
227
228         if (!GetHash(sreg_keys, "sreg.country", 12, (void *) &country)) {
229                 country = NULL;
230         }
231
232         if (postcode || country) {
233                 char adr[256];
234                 snprintf(adr, sizeof adr, ";;;;;%s;%s",
235                         (postcode ? postcode : ""),
236                         (country ? country : "")
237                 );
238                 vcard_add_prop(v, "adr", adr);
239                 ++pop;
240         }
241
242         if (GetHash(sreg_keys, "sreg.dob", 8, (void *) &data)) {
243                 vcard_add_prop(v, "bday", data);
244                 ++pop;
245         }
246
247         if (GetHash(sreg_keys, "sreg.gender", 11, (void *) &data)) {
248                 vcard_add_prop(v, "x-funambol-gender", data);
249                 ++pop;
250         }
251
252         /* Only save the vCard if there is some useful data in it */
253         if (pop > 0) {
254                 char temp[PATH_MAX];
255                 FILE *fp;
256                 char *ser;
257         
258                 CtdlMakeTempFileName(temp, sizeof temp);
259                 ser = vcard_serialize(v);
260                 if (ser) {
261                         fp = fopen(temp, "w");
262                         if (fp) {
263                                 fwrite(ser, strlen(ser), 1, fp);
264                                 fclose(fp);
265                                 CtdlWriteObject(USERCONFIGROOM, "text/x-vcard", temp, &CC->user, 0, 0, 0);
266                                 unlink(temp);
267                         }
268                         free(ser);
269                 }
270         }
271         vcard_free(v);
272 }
273
274
275 /*
276  * Create a new user account, manually specifying the name, after successfully
277  * verifying an OpenID (which will of course be attached to the account)
278  */
279 void cmd_oidc(char *argbuf) {
280         struct ctdl_openid *oiddata = (struct ctdl_openid *) CC->openid_data;
281
282         if (!oiddata->verified) {
283                 cprintf("%d You have not verified an OpenID yet.\n", ERROR);
284                 return;
285         }
286
287         /* We can make the semantics of OIDC exactly the same as NEWU, simply
288          * by _calling_ cmd_newu() and letting it run.  Very clever!
289          */
290         cmd_newu(argbuf);
291
292         /* Now, if this logged us in, we have to attach the OpenID */
293         if (CC->logged_in) {
294                 attach_openid(&CC->user, oiddata->claimed_id);
295                 if (oiddata->sreg_keys != NULL) {
296                         populate_vcard_from_sreg(oiddata->sreg_keys);
297                 }
298         }
299
300 }
301
302
303
304
305 /*
306  * Detach an OpenID from the currently logged in account
307  */
308 void cmd_oidd(char *argbuf) {
309         struct cdbdata *cdboi;
310         char id_to_detach[1024];
311         int this_is_mine = 0;
312
313         if (CtdlAccessCheck(ac_logged_in)) return;
314         extract_token(id_to_detach, argbuf, 0, '|', sizeof id_to_detach);
315         if (IsEmptyStr(id_to_detach)) {
316                 cprintf("%d An empty OpenID URL is not allowed.\n", ERROR + ILLEGAL_VALUE);
317         }
318
319         cdb_rewind(CDB_OPENID);
320         while (cdboi = cdb_next_item(CDB_OPENID), cdboi != NULL) {
321                 if (cdboi->len > sizeof(long)) {
322                         if (((long)*(cdboi->ptr)) == CC->user.usernum) {
323                                 this_is_mine = 1;
324                         }
325                 }
326                 cdb_free(cdboi);
327         }
328
329         if (!this_is_mine) {
330                 cprintf("%d That OpenID was not found or not associated with your account.\n",
331                         ERROR + ILLEGAL_VALUE);
332                 return;
333         }
334
335         cdb_delete(CDB_OPENID, id_to_detach, strlen(id_to_detach));
336         cprintf("%d %s detached from your account.\n", CIT_OK, id_to_detach);
337 }
338
339
340
341 /*
342  * Attempt to auto-create a new Citadel account using the nickname from Simple Registration Extension
343  */
344 int openid_create_user_via_sreg(char *claimed_id, HashList *sreg_keys)
345 {
346         char *desired_name = NULL;
347         char new_password[32];
348
349         if (config.c_auth_mode != AUTHMODE_NATIVE) return(1);
350         if (config.c_disable_newu) return(2);
351         if (CC->logged_in) return(3);
352         if (!GetHash(sreg_keys, "sreg.nickname", 13, (void *) &desired_name)) return(4);
353
354         CtdlLogPrintf(CTDL_DEBUG, "The desired account name is <%s>\n", desired_name);
355
356         if (!getuser(&CC->user, desired_name)) {
357                 CtdlLogPrintf(CTDL_DEBUG, "<%s> is already taken by another user.\n", desired_name);
358                 memset(&CC->user, 0, sizeof(struct ctdluser));
359                 return(5);
360         }
361
362         /* The desired account name is available.  Create the account and log it in! */
363         if (create_user(desired_name, 1)) return(6);
364
365         snprintf(new_password, sizeof new_password, "%08lx%08lx", random(), random());
366         CtdlSetPassword(new_password);
367         attach_openid(&CC->user, claimed_id);
368         populate_vcard_from_sreg(sreg_keys);
369         return(0);
370 }
371
372
373 /*
374  * If a user account exists which is associated with the Claimed ID, log it in and return zero.
375  * Otherwise it returns nonzero.
376  */
377 int login_via_openid(char *claimed_id)
378 {
379         struct cdbdata *cdboi;
380         long usernum = 0;
381
382         cdboi = cdb_fetch(CDB_OPENID, claimed_id, strlen(claimed_id));
383         if (cdboi == NULL) {
384                 return(-1);
385         }
386
387         memcpy(&usernum, cdboi->ptr, sizeof(long));
388         cdb_free(cdboi);
389
390         if (!getuserbynumber(&CC->user, usernum)) {
391                 /* Now become the user we just created */
392                 safestrncpy(CC->curr_user, CC->user.fullname, sizeof CC->curr_user);
393                 do_login();
394                 return(0);
395         }
396         else {
397                 memset(&CC->user, 0, sizeof(struct ctdluser));
398                 return(-1);
399         }
400 }
401
402
403
404
405 /**************************************************************************/
406 /*                                                                        */
407 /* Functions in this section handle OpenID protocol                       */
408 /*                                                                        */
409 /**************************************************************************/
410
411
412 /* 
413  * Locate a <link> tag and, given its 'rel=' parameter, return its 'href' parameter
414  */
415 void extract_link(char *target_buf, int target_size, char *rel, char *source_buf)
416 {
417         char *ptr = source_buf;
418
419         if (!target_buf) return;
420         if (!rel) return;
421         if (!source_buf) return;
422
423         target_buf[0] = 0;
424
425         while (ptr = bmstrcasestr(ptr, "<link"), ptr != NULL) {
426
427                 char work_buffer[2048];
428                 char *link_tag_start = NULL;
429                 char *link_tag_end = NULL;
430
431                 char rel_tag[2048];
432                 char href_tag[2048];
433
434                 link_tag_start = ptr;
435                 link_tag_end = strchr(ptr, '>');
436                 rel_tag[0] = 0;
437                 href_tag[0] = 0;
438
439                 if ((link_tag_end) && (link_tag_end > link_tag_start)) {
440                         int len;
441                         len = link_tag_end - link_tag_start;
442                         if (len > sizeof work_buffer) len = sizeof work_buffer;
443                         memcpy(work_buffer, link_tag_start, len);
444                 
445                         char *rel_start = NULL;
446                         char *rel_end = NULL;
447                         rel_start = bmstrcasestr(work_buffer, "rel=");
448                         if (rel_start) {
449                                 rel_start = strchr(rel_start, '\"');
450                                 if (rel_start) {
451                                         ++rel_start;
452                                         rel_end = strchr(rel_start, '\"');
453                                         if ((rel_end) && (rel_end > rel_start)) {
454                                                 safestrncpy(rel_tag, rel_start, rel_end - rel_start + 1);
455                                         }
456                                 }
457                         }
458
459                         char *href_start = NULL;
460                         char *href_end = NULL;
461                         href_start = bmstrcasestr(work_buffer, "href=");
462                         if (href_start) {
463                                 href_start = strchr(href_start, '\"');
464                                 if (href_start) {
465                                         ++href_start;
466                                         href_end = strchr(href_start, '\"');
467                                         if ((href_end) && (href_end > href_start)) {
468                                                 safestrncpy(href_tag, href_start, href_end - href_start + 1);
469                                         }
470                                 }
471                         }
472
473                         if (!strcasecmp(rel, rel_tag)) {
474                                 safestrncpy(target_buf, href_tag, target_size);
475                                 return;
476                         }
477
478                 }
479
480         ++ptr;
481         }
482
483
484 }
485
486
487
488 struct fh_data {
489         char *buf;
490         int total_bytes_received;
491         int maxbytes;
492 };
493
494
495 size_t fh_callback(void *ptr, size_t size, size_t nmemb, void *stream)
496 {
497         struct fh_data *fh = (struct fh_data *) stream;
498         int got_bytes = (size * nmemb);
499
500         if (fh->total_bytes_received + got_bytes > fh->maxbytes) {
501                 got_bytes = fh->maxbytes - fh->total_bytes_received;
502         }
503         if (got_bytes > 0) {
504                 memcpy(&fh->buf[fh->total_bytes_received], ptr, got_bytes);
505                 fh->total_bytes_received += got_bytes;
506         }
507
508         return (size * nmemb);  /* always succeed; libcurl doesn't need to know if we truncated it */
509 }
510
511
512
513 /*
514  * Begin an HTTP fetch (returns number of bytes actually fetched, or -1 for error) using libcurl.
515  *
516  * If 'normalize_len' is nonzero, the caller is specifying the buffer size of 'url', and is
517  * requesting that the effective (normalized) URL be copied back to it.
518  */
519 int fetch_http(char *url, char *target_buf, int maxbytes, int normalize_len)
520 {
521         CURL *curl;
522         CURLcode res;
523         char errmsg[1024] = "";
524         struct fh_data fh = {
525                 target_buf,
526                 0,
527                 maxbytes
528         };
529         char *effective_url = NULL;
530
531         if (!url) return(-1);
532         if (!target_buf) return(-1);
533         memset(target_buf, 0, maxbytes);
534
535         curl = curl_easy_init();
536         if (!curl) {
537                 CtdlLogPrintf(CTDL_ALERT, "Unable to initialize libcurl.\n");
538                 return(-1);
539         }
540
541         curl_easy_setopt(curl, CURLOPT_URL, url);
542         curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 0);
543         curl_easy_setopt(curl, CURLOPT_SSL_VERIFYHOST, 0);
544         curl_easy_setopt(curl, CURLOPT_WRITEDATA, &fh);
545         curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, fh_callback);
546         curl_easy_setopt(curl, CURLOPT_ERRORBUFFER, errmsg);
547         curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1);
548         curl_easy_setopt(curl, CURLOPT_USERAGENT, CITADEL);
549         if (!IsEmptyStr(config.c_ip_addr)) {
550                 curl_easy_setopt(curl, CURLOPT_INTERFACE, config.c_ip_addr);
551         }
552         res = curl_easy_perform(curl);
553         if (res) {
554                 CtdlLogPrintf(CTDL_DEBUG, "fetch_http() libcurl error %d: %s\n", res, errmsg);
555         }
556         if (normalize_len > 0) {
557                 curl_easy_getinfo(curl, CURLINFO_EFFECTIVE_URL, &effective_url);
558                 safestrncpy(url, effective_url, normalize_len);
559         }
560         curl_easy_cleanup(curl);
561         return fh.total_bytes_received;
562 }
563
564
565 /*
566  * Setup an OpenID authentication
567  */
568 void cmd_oids(char *argbuf) {
569         char return_to[1024];
570         char trust_root[1024];
571         int i;
572         char buf[SIZ];
573         struct CitContext *CCC = CC;    /* CachedCitContext - performance boost */
574         struct ctdl_openid *oiddata;
575
576         oiddata = (struct ctdl_openid *) CCC->openid_data;
577
578         if (oiddata != NULL) {
579                 if (oiddata->sreg_keys != NULL) {
580                         DeleteHash(&oiddata->sreg_keys);
581                         oiddata->sreg_keys = NULL;
582                 }
583                 free(CCC->openid_data);
584         }
585         oiddata = malloc(sizeof(struct ctdl_openid));
586         if (oiddata == NULL) {
587                 cprintf("%d malloc failed\n", ERROR + INTERNAL_ERROR);
588                 return;
589         }
590         memset(oiddata, 0, sizeof(struct ctdl_openid));
591         CCC->openid_data = (void *) oiddata;
592
593         extract_token(oiddata->claimed_id, argbuf, 0, '|', sizeof oiddata->claimed_id);
594         extract_token(return_to, argbuf, 1, '|', sizeof return_to);
595         extract_token(trust_root, argbuf, 2, '|', sizeof trust_root);
596         oiddata->verified = 0;
597
598         i = fetch_http(oiddata->claimed_id, buf, sizeof buf - 1, sizeof oiddata->claimed_id);
599         CtdlLogPrintf(CTDL_DEBUG, "Normalized URL and Claimed ID is: %s\n", oiddata->claimed_id);
600         buf[sizeof buf - 1] = 0;
601         if (i > 0) {
602                 char openid_delegate[1024];
603
604                 extract_link(oiddata->server, sizeof oiddata->server, "openid.server", buf);
605                 extract_link(openid_delegate, sizeof openid_delegate, "openid.delegate", buf);
606
607                 if (IsEmptyStr(oiddata->server)) {
608                         cprintf("%d There is no OpenID identity provider at this URL.\n", ERROR);
609                         return;
610                 }
611
612                 /* Empty delegate is legal; we just use the openid_url instead */
613                 if (IsEmptyStr(openid_delegate)) {
614                         safestrncpy(openid_delegate, oiddata->claimed_id, sizeof openid_delegate);
615                 }
616
617                 /* Assemble a URL to which the user-agent will be redirected. */
618                 char redirect_string[4096];
619                 char escaped_identity[512];
620                 char escaped_return_to[2048];
621                 char escaped_trust_root[1024];
622                 char escaped_sreg_optional[256];
623
624                 urlesc(escaped_identity, sizeof escaped_identity, openid_delegate);
625                 urlesc(escaped_return_to, sizeof escaped_return_to, return_to);
626                 urlesc(escaped_trust_root, sizeof escaped_trust_root, trust_root);
627                 urlesc(escaped_sreg_optional, sizeof escaped_sreg_optional,
628                         "nickname,email,fullname,postcode,country,dob,gender");
629
630                 snprintf(redirect_string, sizeof redirect_string,
631                         "%s"
632                         "?openid.mode=checkid_setup"
633                         "&openid.identity=%s"
634                         "&openid.return_to=%s"
635                         "&openid.trust_root=%s"
636                         "&openid.sreg.optional=%s"
637                         ,
638                         oiddata->server,
639                         escaped_identity,
640                         escaped_return_to,
641                         escaped_trust_root,
642                         escaped_sreg_optional
643                 );
644                 cprintf("%d %s\n", CIT_OK, redirect_string);
645                 return;
646         }
647
648         cprintf("%d Unable to fetch OpenID URL\n", ERROR);
649 }
650
651
652
653
654
655 /*
656  * Finalize an OpenID authentication
657  */
658 void cmd_oidf(char *argbuf) {
659         char buf[2048];
660         char thiskey[1024];
661         char thisdata[1024];
662         HashList *keys = NULL;
663         struct ctdl_openid *oiddata = (struct ctdl_openid *) CC->openid_data;
664
665         keys = NewHash(1, NULL);
666         if (!keys) {
667                 cprintf("%d NewHash() failed\n", ERROR + INTERNAL_ERROR);
668                 return;
669         }
670         
671         cprintf("%d Transmit OpenID data now\n", START_CHAT_MODE);
672
673         while (client_getln(buf, sizeof buf), strcmp(buf, "000")) {
674                 extract_token(thiskey, buf, 0, '|', sizeof thiskey);
675                 extract_token(thisdata, buf, 1, '|', sizeof thisdata);
676                 CtdlLogPrintf(CTDL_DEBUG, "%s: [%d] %s\n", thiskey, strlen(thisdata), thisdata);
677                 Put(keys, thiskey, strlen(thiskey), strdup(thisdata), generic_free_handler);
678         }
679
680
681         /* Now that we have all of the parameters, we have to validate the signature against the server */
682         CtdlLogPrintf(CTDL_DEBUG, "About to validate the signature...\n");
683
684         CURL *curl;
685         CURLcode res;
686         struct curl_httppost *formpost = NULL;
687         struct curl_httppost *lastptr = NULL;
688         char errmsg[1024] = "";
689         char *o_assoc_handle = NULL;
690         char *o_sig = NULL;
691         char *o_signed = NULL;
692         int num_signed_values;
693         int i;
694         char k_keyname[128];
695         char k_o_keyname[128];
696         char *k_value = NULL;
697         char valbuf[1024];
698
699         struct fh_data fh = {
700                 valbuf,
701                 0,
702                 sizeof valbuf
703         };
704
705         curl_formadd(&formpost, &lastptr,
706                 CURLFORM_COPYNAME,      "openid.mode",
707                 CURLFORM_COPYCONTENTS,  "check_authentication",
708                 CURLFORM_END);
709         CtdlLogPrintf(CTDL_DEBUG, "%25s : %s\n", "openid.mode", "check_authentication");
710
711         if (GetHash(keys, "assoc_handle", 12, (void *) &o_assoc_handle)) {
712                 curl_formadd(&formpost, &lastptr,
713                         CURLFORM_COPYNAME,      "openid.assoc_handle",
714                         CURLFORM_COPYCONTENTS,  o_assoc_handle,
715                         CURLFORM_END);
716                 CtdlLogPrintf(CTDL_DEBUG, "%25s : %s\n", "openid.assoc_handle", o_assoc_handle);
717         }
718
719         if (GetHash(keys, "sig", 3, (void *) &o_sig)) {
720                 curl_formadd(&formpost, &lastptr,
721                         CURLFORM_COPYNAME,      "openid.sig",
722                         CURLFORM_COPYCONTENTS,  o_sig,
723                         CURLFORM_END);
724                         CtdlLogPrintf(CTDL_DEBUG, "%25s : %s\n", "openid.sig", o_sig);
725         }
726
727         if (GetHash(keys, "signed", 6, (void *) &o_signed)) {
728                 curl_formadd(&formpost, &lastptr,
729                         CURLFORM_COPYNAME,      "openid.signed",
730                         CURLFORM_COPYCONTENTS,  o_signed,
731                         CURLFORM_END);
732                 CtdlLogPrintf(CTDL_DEBUG, "%25s : %s\n", "openid.signed", o_signed);
733
734                 num_signed_values = num_tokens(o_signed, ',');
735                 for (i=0; i<num_signed_values; ++i) {
736                         extract_token(k_keyname, o_signed, i, ',', sizeof k_keyname);
737                         if (strcasecmp(k_keyname, "mode")) {    // work around phpMyID bug
738                                 if (GetHash(keys, k_keyname, strlen(k_keyname), (void *) &k_value)) {
739                                         snprintf(k_o_keyname, sizeof k_o_keyname, "openid.%s", k_keyname);
740                                         curl_formadd(&formpost, &lastptr,
741                                                 CURLFORM_COPYNAME,      k_o_keyname,
742                                                 CURLFORM_COPYCONTENTS,  k_value,
743                                                 CURLFORM_END);
744                                         CtdlLogPrintf(CTDL_DEBUG, "%25s : %s\n", k_o_keyname, k_value);
745                                 }
746                                 else {
747                                         CtdlLogPrintf(CTDL_INFO, "OpenID: signed field '%s' is missing\n",
748                                                 k_keyname);
749                                 }
750                         }
751                 }
752         }
753
754         curl = curl_easy_init();
755         curl_easy_setopt(curl, CURLOPT_URL, oiddata->server);
756         curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 0);
757         curl_easy_setopt(curl, CURLOPT_SSL_VERIFYHOST, 0);
758         curl_easy_setopt(curl, CURLOPT_WRITEDATA, &fh);
759         curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, fh_callback);
760         curl_easy_setopt(curl, CURLOPT_HTTPPOST, formpost);
761         curl_easy_setopt(curl, CURLOPT_ERRORBUFFER, errmsg);
762         curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1);
763         curl_easy_setopt(curl, CURLOPT_USERAGENT, CITADEL);
764         if (!IsEmptyStr(config.c_ip_addr)) {
765                 curl_easy_setopt(curl, CURLOPT_INTERFACE, config.c_ip_addr);
766         }
767
768         res = curl_easy_perform(curl);
769         if (res) {
770                 CtdlLogPrintf(CTDL_DEBUG, "cmd_oidf() libcurl error %d: %s\n", res, errmsg);
771         }
772         curl_easy_cleanup(curl);
773         curl_formfree(formpost);
774
775         valbuf[fh.total_bytes_received] = 0;
776
777         if (bmstrcasestr(valbuf, "is_valid:true")) {
778                 oiddata->verified = 1;
779         }
780
781         CtdlLogPrintf(CTDL_DEBUG, "Authentication %s.\n", (oiddata->verified ? "succeeded" : "failed") );
782
783         /* Respond to the client */
784
785         if (oiddata->verified) {
786
787                 /* If we were already logged in, attach the OpenID to the user's account */
788                 if (CC->logged_in) {
789                         if (attach_openid(&CC->user, oiddata->claimed_id) == 0) {
790                                 cprintf("attach\n");
791                         }
792                         else {
793                                 cprintf("fail\n");
794                         }
795                 }
796
797                 /* Otherwise, a user is attempting to log in using the verified OpenID */       
798                 else {
799                         /*
800                          * Existing user who has claimed this OpenID?
801                          *
802                          * Note: if you think that sending the password back over the wire is insecure,
803                          * check your assumptions.  If someone has successfully asserted an OpenID that
804                          * is associated with the account, they already have password equivalency and can
805                          * login, so they could just as easily change the password, etc.
806                          */
807                         if (login_via_openid(oiddata->claimed_id) == 0) {
808                                 cprintf("authenticate\n%s\n%s\n", CC->user.fullname, CC->user.password);
809                                 logged_in_response();
810                         }
811
812                         /*
813                          * If this system does not allow self-service new user registration, the
814                          * remaining modes do not apply, so fail here and now.
815                          */
816                         else if (config.c_disable_newu) {
817                                 cprintf("fail\n");
818                         }
819
820                         /*
821                          * New user whose OpenID is verified and Simple Registration Extension is in use?
822                          */
823                         else if (openid_create_user_via_sreg(oiddata->claimed_id, keys) == 0) {
824                                 cprintf("authenticate\n%s\n%s\n", CC->user.fullname, CC->user.password);
825                                 logged_in_response();
826                         }
827
828                         /*
829                          * OpenID is verified, but the desired username either was not specified or
830                          * conflicts with an existing user.  Manual account creation is required.
831                          */
832                         else {
833                                 char *desired_name = NULL;
834                                 cprintf("verify_only\n");
835                                 cprintf("%s\n", oiddata->claimed_id);
836                                 if (GetHash(keys, "sreg.nickname", 13, (void *) &desired_name)) {
837                                         cprintf("%s\n", desired_name);
838                                 }
839                                 else {
840                                         cprintf("\n");
841                                 }
842                         }
843                 }
844         }
845         else {
846                 cprintf("fail\n");
847         }
848         cprintf("000\n");
849
850         if (oiddata->sreg_keys != NULL) {
851                 DeleteHash(&oiddata->sreg_keys);
852                 oiddata->sreg_keys = NULL;
853         }
854         oiddata->sreg_keys = keys;
855 }
856
857
858
859 /**************************************************************************/
860 /*                                                                        */
861 /* Functions in this section handle module initialization and shutdown    */
862 /*                                                                        */
863 /**************************************************************************/
864
865
866 /*
867  * This cleanup function blows away the temporary memory used by this module.
868  */
869 void openid_cleanup_function(void) {
870         struct ctdl_openid *oiddata = (struct ctdl_openid *) CC->openid_data;
871
872         if (oiddata != NULL) {
873                 CtdlLogPrintf(CTDL_DEBUG, "Clearing OpenID session state\n");
874                 if (oiddata->sreg_keys != NULL) {
875                         DeleteHash(&oiddata->sreg_keys);
876                         oiddata->sreg_keys = NULL;
877                 }
878                 free(oiddata);
879         }
880 }
881
882
883 CTDL_MODULE_INIT(openid_rp)
884 {
885         if (!threading) {
886                 curl_global_init(CURL_GLOBAL_ALL);
887
888                 /* Only enable the OpenID command set when native mode authentication is in use. */
889                 if (config.c_auth_mode == AUTHMODE_NATIVE) {
890                         CtdlRegisterProtoHook(cmd_oids, "OIDS", "Setup OpenID authentication");
891                         CtdlRegisterProtoHook(cmd_oidf, "OIDF", "Finalize OpenID authentication");
892                         CtdlRegisterProtoHook(cmd_oidl, "OIDL", "List OpenIDs associated with an account");
893                         CtdlRegisterProtoHook(cmd_oidd, "OIDD", "Detach an OpenID from an account");
894                         CtdlRegisterProtoHook(cmd_oidc, "OIDC", "Create new user after validating OpenID");
895                 }
896                 CtdlRegisterSessionHook(openid_cleanup_function, EVT_LOGOUT);
897                 CtdlRegisterUserHook(openid_purge, EVT_PURGEUSER);
898         }
899
900         /* return our Subversion id for the Log */
901         return "$Id$";
902 }