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