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