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