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