Re-enabled OpenID 1.1 while I work on other things
[citadel.git] / citadel / modules / openid / serv_openid_rp.c
1 /*
2  * This is an implementation of OpenID 2.0 RELYING PARTY SUPPORT CURRENTLY B0RKEN AND BEING DEVEL0PZ0RED
3  *
4  * Copyright (c) 2007-2011 by the citadel.org team
5  *
6  * This program is open source software; you can redistribute it and/or modify
7  * it under the terms of the GNU General Public License as published by
8  * the Free Software Foundation; either version 3 of the License, or
9  * (at your option) any later version.
10  *
11  * This program is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  * GNU General Public License for more details.
15  *
16  * You should have received a copy of the GNU General Public License
17  * along with this program; if not, see <http://www.gnu.org/licenses/>.
18  */
19
20 #include "sysdep.h"
21 #include <stdlib.h>
22 #include <unistd.h>
23 #include <stdio.h>
24 #include <fcntl.h>
25 #include <signal.h>
26 #include <pwd.h>
27 #include <errno.h>
28 #include <sys/types.h>
29
30 #if TIME_WITH_SYS_TIME
31 # include <sys/time.h>
32 # include <time.h>
33 #else
34 # if HAVE_SYS_TIME_H
35 #  include <sys/time.h>
36 # else
37 #  include <time.h>
38 # endif
39 #endif
40
41 #include <sys/wait.h>
42 #include <string.h>
43 #include <limits.h>
44 #include <curl/curl.h>
45 #include <expat.h>
46 #include "ctdl_module.h"
47 #include "config.h"
48 #include "citserver.h"
49 #include "user_ops.h"
50
51 typedef struct _ctdl_openid {
52         StrBuf *claimed_id;
53         StrBuf *server;
54         int verified;
55         HashList *sreg_keys;
56 } ctdl_openid;
57
58 void Free_ctdl_openid(ctdl_openid **FreeMe)
59 {
60         if (*FreeMe == NULL)
61                 return;
62         FreeStrBuf(&(*FreeMe)->claimed_id);
63         FreeStrBuf(&(*FreeMe)->server);
64         DeleteHash(&(*FreeMe)->sreg_keys);
65         free(*FreeMe);
66         *FreeMe = NULL;
67 }
68
69
70 /*
71  * This cleanup function blows away the temporary memory used by this module.
72  */
73 void openid_cleanup_function(void) {
74         struct CitContext *CCC = CC;    /* CachedCitContext - performance boost */
75
76         if (CCC->openid_data != NULL) {
77                 syslog(LOG_DEBUG, "Clearing OpenID session state");
78                 Free_ctdl_openid((ctdl_openid **) &CCC->openid_data);
79         }
80 }
81
82
83 /**************************************************************************/
84 /*                                                                        */
85 /* Functions in this section handle Citadel internal OpenID mapping stuff */
86 /*                                                                        */
87 /**************************************************************************/
88
89
90 /*
91  * The structure of an openid record *key* is:
92  *
93  * |--------------claimed_id-------------|
94  *     (actual length of claimed id)
95  *
96  *
97  * The structure of an openid record *value* is:
98  *
99  * |-----user_number----|------------claimed_id---------------|
100  *    (sizeof long)          (actual length of claimed id)
101  *
102  */
103
104
105
106 /*
107  * Attach an OpenID to a Citadel account
108  */
109 int attach_openid(struct ctdluser *who, StrBuf *claimed_id)
110 {
111         struct cdbdata *cdboi;
112         long fetched_usernum;
113         char *data;
114         int data_len;
115         char buf[2048];
116
117         if (!who) return(1);
118         if (StrLength(claimed_id)==0) return(1);
119
120         /* Check to see if this OpenID is already in the database */
121
122         cdboi = cdb_fetch(CDB_OPENID, ChrPtr(claimed_id), StrLength(claimed_id));
123         if (cdboi != NULL) {
124                 memcpy(&fetched_usernum, cdboi->ptr, sizeof(long));
125                 cdb_free(cdboi);
126
127                 if (fetched_usernum == who->usernum) {
128                         syslog(LOG_INFO, "%s already associated; no action is taken", ChrPtr(claimed_id));
129                         return(0);
130                 }
131                 else {
132                         syslog(LOG_INFO, "%s already belongs to another user", ChrPtr(claimed_id));
133                         return(3);
134                 }
135         }
136
137         /* Not already in the database, so attach it now */
138
139         data_len = sizeof(long) + StrLength(claimed_id) + 1;
140         data = malloc(data_len);
141
142         memcpy(data, &who->usernum, sizeof(long));
143         memcpy(&data[sizeof(long)], ChrPtr(claimed_id), StrLength(claimed_id) + 1);
144
145         cdb_store(CDB_OPENID, ChrPtr(claimed_id), StrLength(claimed_id), data, data_len);
146         free(data);
147
148         snprintf(buf, sizeof buf, "User <%s> (#%ld) has claimed the OpenID URL %s\n",
149                  who->fullname, who->usernum, ChrPtr(claimed_id));
150         CtdlAideMessage(buf, "OpenID claim");
151         syslog(LOG_INFO, "%s", buf);
152         return(0);
153 }
154
155
156
157 /*
158  * When a user is being deleted, we have to delete any OpenID associations
159  */
160 void openid_purge(struct ctdluser *usbuf) {
161         struct cdbdata *cdboi;
162         HashList *keys = NULL;
163         HashPos *HashPos;
164         char *deleteme = NULL;
165         long len;
166         void *Value;
167         const char *Key;
168         long usernum = 0L;
169
170         keys = NewHash(1, NULL);
171         if (!keys) return;
172
173         cdb_rewind(CDB_OPENID);
174         while (cdboi = cdb_next_item(CDB_OPENID), cdboi != NULL) {
175                 if (cdboi->len > sizeof(long)) {
176                         memcpy(&usernum, cdboi->ptr, sizeof(long));
177                         if (usernum == usbuf->usernum) {
178                                 deleteme = strdup(cdboi->ptr + sizeof(long)),
179                                 Put(keys, deleteme, strlen(deleteme), deleteme, NULL);
180                         }
181                 }
182                 cdb_free(cdboi);
183         }
184
185         /* Go through the hash list, deleting keys we stored in it */
186
187         HashPos = GetNewHashPos(keys, 0);
188         while (GetNextHashPos(keys, HashPos, &len, &Key, &Value)!=0)
189         {
190                 syslog(LOG_DEBUG, "Deleting associated OpenID <%s>", (char*)Value);
191                 cdb_delete(CDB_OPENID, Value, strlen(Value));
192                 /* note: don't free(Value) -- deleting the hash list will handle this for us */
193         }
194         DeleteHashPos(&HashPos);
195         DeleteHash(&keys);
196 }
197
198
199 /*
200  * List the OpenIDs associated with the currently logged in account
201  */
202 void cmd_oidl(char *argbuf) {
203         struct cdbdata *cdboi;
204         long usernum = 0L;
205
206         if (CtdlAccessCheck(ac_logged_in)) return;
207         cdb_rewind(CDB_OPENID);
208         cprintf("%d Associated OpenIDs:\n", LISTING_FOLLOWS);
209
210         while (cdboi = cdb_next_item(CDB_OPENID), cdboi != NULL) {
211                 if (cdboi->len > sizeof(long)) {
212                         memcpy(&usernum, cdboi->ptr, sizeof(long));
213                         if (usernum == CC->user.usernum) {
214                                 cprintf("%s\n", cdboi->ptr + sizeof(long));
215                         }
216                 }
217                 cdb_free(cdboi);
218         }
219         cprintf("000\n");
220 }
221
222
223 /*
224  * List ALL OpenIDs in the database
225  */
226 void cmd_oida(char *argbuf) {
227         struct cdbdata *cdboi;
228         long usernum;
229         struct ctdluser usbuf;
230
231         if (CtdlAccessCheck(ac_aide)) return;
232         cdb_rewind(CDB_OPENID);
233         cprintf("%d List of all OpenIDs in the database:\n", LISTING_FOLLOWS);
234
235         while (cdboi = cdb_next_item(CDB_OPENID), cdboi != NULL) {
236                 if (cdboi->len > sizeof(long)) {
237                         memcpy(&usernum, cdboi->ptr, sizeof(long));
238                         if (CtdlGetUserByNumber(&usbuf, usernum) != 0) {
239                                 usbuf.fullname[0] = 0;
240                         } 
241                         cprintf("%s|%ld|%s\n",
242                                 cdboi->ptr + sizeof(long),
243                                 usernum,
244                                 usbuf.fullname
245                         );
246                 }
247                 cdb_free(cdboi);
248         }
249         cprintf("000\n");
250 }
251
252
253 /*
254  * Attempt to register (populate the vCard) the currently-logged-in user
255  * using the data from Simple Registration Extension, if present.
256  */
257 void populate_vcard_from_sreg(HashList *sreg_keys) {
258
259         struct vCard *v;
260         int pop = 0;                    /* number of fields populated */
261         char *data = NULL;
262         char *postcode = NULL;
263         char *country = NULL;
264
265         if (!sreg_keys) return;
266         v = vcard_new();
267         if (!v) return;
268
269         if (GetHash(sreg_keys, "identity", 8, (void *) &data)) {
270                 vcard_add_prop(v, "url;type=openid", data);
271                 ++pop;
272         }
273
274         if (GetHash(sreg_keys, "sreg.email", 10, (void *) &data)) {
275                 vcard_add_prop(v, "email;internet", data);
276                 ++pop;
277         }
278
279         if (GetHash(sreg_keys, "sreg.nickname", 13, (void *) &data)) {
280                 vcard_add_prop(v, "nickname", data);
281                 ++pop;
282         }
283
284         if (GetHash(sreg_keys, "sreg.fullname", 13, (void *) &data)) {
285                 char n[256];
286                 vcard_add_prop(v, "fn", data);
287                 vcard_fn_to_n(n, data, sizeof n);
288                 vcard_add_prop(v, "n", n);
289                 ++pop;
290         }
291
292         if (!GetHash(sreg_keys, "sreg.postcode", 13, (void *) &postcode)) {
293                 postcode = NULL;
294         }
295
296         if (!GetHash(sreg_keys, "sreg.country", 12, (void *) &country)) {
297                 country = NULL;
298         }
299
300         if (postcode || country) {
301                 char adr[256];
302                 snprintf(adr, sizeof adr, ";;;;;%s;%s",
303                         (postcode ? postcode : ""),
304                         (country ? country : "")
305                 );
306                 vcard_add_prop(v, "adr", adr);
307                 ++pop;
308         }
309
310         if (GetHash(sreg_keys, "sreg.dob", 8, (void *) &data)) {
311                 vcard_add_prop(v, "bday", data);
312                 ++pop;
313         }
314
315         if (GetHash(sreg_keys, "sreg.gender", 11, (void *) &data)) {
316                 vcard_add_prop(v, "x-funambol-gender", data);
317                 ++pop;
318         }
319
320         /* Only save the vCard if there is some useful data in it */
321         if (pop > 0) {
322                 char *ser;
323                 ser = vcard_serialize(v);
324                 if (ser) {
325                         CtdlWriteObject(USERCONFIGROOM, "text/x-vcard",
326                                 ser, strlen(ser)+1, &CC->user, 0, 0, 0
327                         );
328                         free(ser);
329                 }
330         }
331         vcard_free(v);
332 }
333
334
335 /*
336  * Create a new user account, manually specifying the name, after successfully
337  * verifying an OpenID (which will of course be attached to the account)
338  */
339 void cmd_oidc(char *argbuf) {
340         ctdl_openid *oiddata = (ctdl_openid *) CC->openid_data;
341
342         if (!oiddata) {
343                 cprintf("%d You have not verified an OpenID yet.\n", ERROR);
344                 return;
345         }
346
347         if (!oiddata->verified) {
348                 cprintf("%d You have not verified an OpenID yet.\n", ERROR);
349                 return;
350         }
351
352         /* We can make the semantics of OIDC exactly the same as NEWU, simply
353          * by _calling_ cmd_newu() and letting it run.  Very clever!
354          */
355         cmd_newu(argbuf);
356
357         /* Now, if this logged us in, we have to attach the OpenID */
358         if (CC->logged_in) {
359                 attach_openid(&CC->user, oiddata->claimed_id);
360                 if (oiddata->sreg_keys != NULL) {
361                         populate_vcard_from_sreg(oiddata->sreg_keys);
362                 }
363         }
364
365 }
366
367
368 /*
369  * Detach an OpenID from the currently logged in account
370  */
371 void cmd_oidd(char *argbuf) {
372         struct cdbdata *cdboi;
373         char id_to_detach[1024];
374         int this_is_mine = 0;
375         long usernum = 0L;
376
377         if (CtdlAccessCheck(ac_logged_in)) return;
378         extract_token(id_to_detach, argbuf, 0, '|', sizeof id_to_detach);
379         if (IsEmptyStr(id_to_detach)) {
380                 cprintf("%d An empty OpenID URL is not allowed.\n", ERROR + ILLEGAL_VALUE);
381         }
382
383         cdb_rewind(CDB_OPENID);
384         while (cdboi = cdb_next_item(CDB_OPENID), cdboi != NULL) {
385                 if (cdboi->len > sizeof(long)) {
386                         memcpy(&usernum, cdboi->ptr, sizeof(long));
387                         if (usernum == CC->user.usernum) {
388                                 this_is_mine = 1;
389                         }
390                 }
391                 cdb_free(cdboi);
392         }
393
394         if (!this_is_mine) {
395                 cprintf("%d That OpenID was not found or not associated with your account.\n",
396                         ERROR + ILLEGAL_VALUE);
397                 return;
398         }
399
400         cdb_delete(CDB_OPENID, id_to_detach, strlen(id_to_detach));
401         cprintf("%d %s detached from your account.\n", CIT_OK, id_to_detach);
402 }
403
404
405
406 /*
407  * Attempt to auto-create a new Citadel account using the nickname from Simple Registration Extension
408  */
409 int openid_create_user_via_sreg(StrBuf *claimed_id, HashList *sreg_keys)
410 {
411         char *desired_name = NULL;
412         char new_password[32];
413         long len;
414
415         if (config.c_auth_mode != AUTHMODE_NATIVE) return(1);
416         if (config.c_disable_newu) return(2);
417         if (CC->logged_in) return(3);
418         if (!GetHash(sreg_keys, "sreg.nickname", 13, (void *) &desired_name)) return(4);
419
420         syslog(LOG_DEBUG, "The desired account name is <%s>", desired_name);
421
422         len = cutuserkey(desired_name);
423         if (!CtdlGetUser(&CC->user, desired_name)) {
424                 syslog(LOG_DEBUG, "<%s> is already taken by another user.", desired_name);
425                 memset(&CC->user, 0, sizeof(struct ctdluser));
426                 return(5);
427         }
428
429         /* The desired account name is available.  Create the account and log it in! */
430         if (create_user(desired_name, len, 1)) return(6);
431
432         snprintf(new_password, sizeof new_password, "%08lx%08lx", random(), random());
433         CtdlSetPassword(new_password);
434         attach_openid(&CC->user, claimed_id);
435         populate_vcard_from_sreg(sreg_keys);
436         return(0);
437 }
438
439
440 /*
441  * If a user account exists which is associated with the Claimed ID, log it in and return zero.
442  * Otherwise it returns nonzero.
443  */
444 int login_via_openid(StrBuf *claimed_id)
445 {
446         struct cdbdata *cdboi;
447         long usernum = 0;
448
449         cdboi = cdb_fetch(CDB_OPENID, ChrPtr(claimed_id), StrLength(claimed_id));
450         if (cdboi == NULL) {
451                 return(-1);
452         }
453
454         memcpy(&usernum, cdboi->ptr, sizeof(long));
455         cdb_free(cdboi);
456
457         if (!CtdlGetUserByNumber(&CC->user, usernum)) {
458                 /* Now become the user we just created */
459                 safestrncpy(CC->curr_user, CC->user.fullname, sizeof CC->curr_user);
460                 do_login();
461                 return(0);
462         }
463         else {
464                 memset(&CC->user, 0, sizeof(struct ctdluser));
465                 return(-1);
466         }
467 }
468
469
470
471
472 /**************************************************************************/
473 /*                                                                        */
474 /* Functions in this section handle OpenID protocol                       */
475 /*                                                                        */
476 /**************************************************************************/
477
478
479 /* 
480  * Locate a <link> tag and, given its 'rel=' parameter, return its 'href' parameter
481  */
482 void extract_link(StrBuf *target_buf, const char *rel, long repllen, StrBuf *source_buf)
483 {
484         int i;
485         const char *ptr;
486         const char *href_start = NULL;
487         const char *href_end = NULL;
488         const char *link_tag_start = NULL;
489         const char *link_tag_end = NULL;
490         const char *rel_start = NULL;
491         const char *rel_end = NULL;
492
493         if (!target_buf) return;
494         if (!rel) return;
495         if (!source_buf) return;
496
497         ptr = ChrPtr(source_buf);
498
499         FlushStrBuf(target_buf);
500         while (ptr = cbmstrcasestr(ptr, "<link"), ptr != NULL) {
501
502                 link_tag_start = ptr;
503                 link_tag_end = strchr(ptr, '>');
504                 if (link_tag_end == NULL)
505                         break;
506                 for (i=0; i < 1; i++ ){
507                         rel_start = cbmstrcasestr(link_tag_start, "rel=");
508                         if ((rel_start == NULL) ||
509                             (rel_start > link_tag_end)) 
510                                 continue;
511
512                         rel_start = strchr(rel_start, '\"');
513                         if ((rel_start == NULL) ||
514                             (rel_start > link_tag_end)) 
515                                 continue;
516                         ++rel_start;
517                         rel_end = strchr(rel_start, '\"');
518                         if ((rel_end == NULL) ||
519                             (rel_end == rel_start) ||
520                             (rel_end >= link_tag_end) ) 
521                                 continue;
522                         if (strncasecmp(rel, rel_start, repllen)!= 0)
523                                 continue; /* didn't match? never mind... */
524                         
525                         href_start = cbmstrcasestr(link_tag_start, "href=");
526                         if ((href_start == NULL) || 
527                             (href_start >= link_tag_end)) 
528                                 continue;
529                         href_start = strchr(href_start, '\"');
530                         if ((href_start == NULL) |
531                             (href_start >= link_tag_end)) 
532                                 continue;
533                         ++href_start;
534                         href_end = strchr(href_start, '\"');
535                         if ((href_end == NULL) || 
536                             (href_end == href_start) ||
537                             (href_start >= link_tag_end)) 
538                                 continue;
539                         StrBufPlain(target_buf, href_start, href_end - href_start);
540                 }
541                 ptr = link_tag_end;     
542         }
543 }
544
545
546 /*
547  * Wrapper for curl_easy_init() that includes the options common to all calls
548  * used in this module. 
549  */
550 CURL *ctdl_openid_curl_easy_init(char *errmsg) {
551         CURL *curl;
552
553         curl = curl_easy_init();
554         if (!curl) {
555                 return(curl);
556         }
557
558         curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 0);
559         curl_easy_setopt(curl, CURLOPT_SSL_VERIFYHOST, 0);
560
561         if (errmsg) {
562                 curl_easy_setopt(curl, CURLOPT_ERRORBUFFER, errmsg);
563         }
564         curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1);
565 #ifdef CURLOPT_HTTP_CONTENT_DECODING
566         curl_easy_setopt(curl, CURLOPT_HTTP_CONTENT_DECODING, 1);
567         curl_easy_setopt(curl, CURLOPT_ENCODING, "");
568 #endif
569         curl_easy_setopt(curl, CURLOPT_USERAGENT, CITADEL);
570         curl_easy_setopt(curl, CURLOPT_TIMEOUT, 30);            /* die after 30 seconds */
571
572         if (
573                 (!IsEmptyStr(config.c_ip_addr))
574                 && (strcmp(config.c_ip_addr, "*"))
575                 && (strcmp(config.c_ip_addr, "::"))
576                 && (strcmp(config.c_ip_addr, "0.0.0.0"))
577         ) {
578                 curl_easy_setopt(curl, CURLOPT_INTERFACE, config.c_ip_addr);
579         }
580
581         return(curl);
582 }
583
584
585 /*
586  * Begin an HTTP fetch (returns number of bytes actually fetched, or -1 for error) using libcurl.
587  */
588 int fetch_http(StrBuf *url, StrBuf **target_buf)
589 {
590         StrBuf *ReplyBuf;
591         CURL *curl;
592         CURLcode result;
593         char *effective_url = NULL;
594         char errmsg[1024] = "";
595
596         if (StrLength(url) <=0 ) return(-1);
597         ReplyBuf = *target_buf = NewStrBuf ();
598         if (ReplyBuf == 0) return(-1);
599
600         curl = ctdl_openid_curl_easy_init(errmsg);
601         if (!curl) return(-1);
602
603         curl_easy_setopt(curl, CURLOPT_URL, ChrPtr(url));
604         curl_easy_setopt(curl, CURLOPT_WRITEDATA, ReplyBuf);
605         curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, CurlFillStrBuf_callback);
606
607         result = curl_easy_perform(curl);
608         if (result) {
609                 syslog(LOG_DEBUG, "libcurl error %d: %s", result, errmsg);
610         }
611         curl_easy_getinfo(curl, CURLINFO_EFFECTIVE_URL, &effective_url);
612         StrBufPlain(url, effective_url, -1);
613         
614         curl_easy_cleanup(curl);
615         return StrLength(ReplyBuf);
616 }
617
618
619
620 struct xrds {
621         int nesting_level;
622         int in_xrd;
623         int current_service_priority;
624         int selected_service_priority;  /* more here later */
625 };
626
627
628 void xrds_xml_start(void *data, const char *supplied_el, const char **attr) {
629         struct xrds *xrds = (struct xrds *) data;
630         int i;
631
632         ++xrds->nesting_level;
633
634         if (!strcasecmp(supplied_el, "XRD")) {
635                 ++xrds->in_xrd;
636                 syslog(LOG_DEBUG, "*** XRD CONTAINER BEGIN ***");
637         }
638
639         else if (!strcasecmp(supplied_el, "service")) {
640                 xrds->current_service_priority = 0;
641                 for (i=0; attr[i] != NULL; i+=2) {
642                         if (!strcasecmp(attr[i], "priority")) {
643                                 xrds->current_service_priority = atoi(attr[i+1]);
644                         }
645                 }
646         }
647 }
648
649
650 void xrds_xml_end(void *data, const char *supplied_el) {
651         struct xrds *xrds = (struct xrds *) data;
652
653         --xrds->nesting_level;
654
655         if (!strcasecmp(supplied_el, "XRD")) {
656                 --xrds->in_xrd;
657                 syslog(LOG_DEBUG, "*** XRD CONTAINER END ***");
658         }
659
660         else if (!strcasecmp(supplied_el, "service")) {
661                 /* this is where we should evaluate the service and do stuff */
662                 xrds->current_service_priority = 0;
663         }
664 }
665
666
667 void xrds_xml_chardata(void *data, const XML_Char *s, int len) {
668         struct xrds *xrds = (struct xrds *) data;
669
670         if (xrds) ;     /* this is only here to silence the warning for now */
671         
672         /* StrBufAppendBufPlain (xrds->CData, s, len, 0); */
673 }
674
675
676 /*
677  * Parse an XRDS document.
678  * If OpenID stuff is discovered, populate FIXME something and return nonzero
679  * If nothing useful happened, return 0.
680  */
681 int parse_xrds_document(StrBuf *ReplyBuf) {
682         struct xrds xrds;
683
684         syslog(LOG_DEBUG, "\033[32m --- XRDS DOCUMENT --- \n%s\033[0m", ChrPtr(ReplyBuf));
685
686         memset(&xrds, 0, sizeof (struct xrds));
687         XML_Parser xp = XML_ParserCreate(NULL);
688         if (xp) {
689                 XML_SetUserData(xp, &xrds);
690                 XML_SetElementHandler(xp, xrds_xml_start, xrds_xml_end);
691                 XML_SetCharacterDataHandler(xp, xrds_xml_chardata);
692                 XML_Parse(xp, ChrPtr(ReplyBuf), StrLength(ReplyBuf), 0);
693                 XML_Parse(xp, "", 0, 1);
694                 XML_ParserFree(xp);
695         }
696         else {
697                 syslog(LOG_ALERT, "Cannot create XML parser");
698         }
699
700         return(0);      /* FIXME return nonzero if something wonderful happened */
701 }
702
703
704
705 /*
706  * Callback function for perform_openid2_discovery()
707  * We're interested in the X-XRDS-Location: header.
708  */
709 size_t yadis_headerfunction(void *ptr, size_t size, size_t nmemb, void *userdata) {
710         char hdr[1024];
711         StrBuf **x_xrds_location = (StrBuf **) userdata;
712
713         memcpy(hdr, ptr, (size*nmemb));
714         hdr[size*nmemb] = 0;
715
716         if (!strncasecmp(hdr, "X-XRDS-Location:", 16)) {
717                 *x_xrds_location = NewStrBufPlain(&hdr[16], ((size*nmemb)-16));
718                 StrBufTrim(*x_xrds_location);
719         }
720
721         return(size * nmemb);
722 }
723
724
725
726 /* Attempt to perform Yadis discovery as specified in Yadis 1.0 section 6.2.5.
727  * 
728  * If Yadis fails, we then attempt HTML discovery using the same document.
729  *
730  * If successful, returns nonzero and calls parse_xrds_document() to act upon the received data.
731  * If fails, returns 0 and does nothing else.
732  */
733 int perform_openid2_discovery(StrBuf *YadisURL) {
734         int docbytes = (-1);
735         StrBuf *ReplyBuf = NULL;
736         int return_value = 0;
737         CURL *curl;
738         CURLcode result;
739         char errmsg[1024] = "";
740         struct curl_slist *my_headers = NULL;
741         StrBuf *x_xrds_location = NULL;
742         ctdl_openid *oiddata = (ctdl_openid *) CC->openid_data;
743
744         if (YadisURL == NULL) return(0);
745         syslog(LOG_DEBUG, "perform_openid2_discovery(%s)", ChrPtr(YadisURL));
746         if (StrLength(YadisURL) == 0) return(0);
747
748         ReplyBuf = NewStrBuf ();
749         if (ReplyBuf == 0) return(0);
750
751         curl = ctdl_openid_curl_easy_init(errmsg);
752         if (!curl) return(0);
753
754         curl_easy_setopt(curl, CURLOPT_URL, ChrPtr(YadisURL));
755         curl_easy_setopt(curl, CURLOPT_WRITEDATA, ReplyBuf);
756         curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, CurlFillStrBuf_callback);
757
758         my_headers = curl_slist_append(my_headers, "Accept:");  /* disable the default Accept: header */
759         my_headers = curl_slist_append(my_headers, "Accept: application/xrds+xml");
760         curl_easy_setopt(curl, CURLOPT_HTTPHEADER, my_headers);
761
762         curl_easy_setopt(curl, CURLOPT_WRITEHEADER, &x_xrds_location);
763         curl_easy_setopt(curl, CURLOPT_HEADERFUNCTION, yadis_headerfunction);
764
765         result = curl_easy_perform(curl);
766         if (result) {
767                 syslog(LOG_DEBUG, "libcurl error %d: %s", result, errmsg);
768         }
769         curl_slist_free_all(my_headers);
770         curl_easy_cleanup(curl);
771         docbytes = StrLength(ReplyBuf);
772
773         /*
774          * The response from the server will be one of:
775          * 
776          * Option 1: An HTML document with a <head> element that includes a <meta> element with http-equiv
777          * attribute, X-XRDS-Location,
778          */
779         /* FIXME handle this somehow */
780
781         /*
782          * Option 2: HTTP response-headers that include an X-XRDS-Location response-header,
783          *           together with a document.
784          * Option 3: HTTP response-headers only, which MAY include an X-XRDS-Location response-header,
785          *           a contenttype response-header specifying MIME media type,
786          *           application/xrds+xml, or both.
787          *
788          * If the X-XRDS-Location header was delivered, we know about it at this point...
789          */
790         if (    (x_xrds_location)
791                 && (strcmp(ChrPtr(x_xrds_location), ChrPtr(YadisURL)))
792         ) {
793                 syslog(LOG_DEBUG, "X-XRDS-Location: %s ... recursing!", ChrPtr(x_xrds_location));
794                 return_value = perform_openid2_discovery(x_xrds_location);
795                 FreeStrBuf(&x_xrds_location);
796         }
797
798         /*
799          * Option 4: the returned web page may *be* an XRDS document.  Try to parse it.
800          */
801         else if (docbytes >= 0) {
802                 return_value = parse_xrds_document(ReplyBuf);
803         }
804
805         /*
806          * Option 5: if all else fails, attempt HTML based discovery.
807          */
808         if (return_value == 0) {
809                 syslog(LOG_DEBUG, "Attempting HTML discovery");
810                 extract_link(oiddata->server, HKEY("openid2.provider"), ReplyBuf);
811                 if (StrLength(oiddata->server) > 0) {
812                         syslog(LOG_DEBUG, "\033[31mHTML DISCO PROVIDER: %s\033[0m", ChrPtr(oiddata->server));
813                 }
814         }
815
816         if (ReplyBuf != NULL) {
817                 FreeStrBuf(&ReplyBuf);
818         }
819         return(return_value);
820 }
821
822
823 /*
824  * Setup an OpenID authentication
825  */
826 void cmd_oids(char *argbuf) {
827         const char *Pos = NULL;
828         StrBuf *ArgBuf = NULL;
829         StrBuf *ReplyBuf = NULL;
830         StrBuf *return_to = NULL;
831         StrBuf *trust_root = NULL;
832         StrBuf *openid_delegate = NULL;
833         StrBuf *RedirectUrl = NULL;
834         struct CitContext *CCC = CC;    /* CachedCitContext - performance boost */
835         ctdl_openid *oiddata;
836
837         Free_ctdl_openid ((ctdl_openid**)&CCC->openid_data);
838
839         CCC->openid_data = oiddata = malloc(sizeof(ctdl_openid));
840         if (oiddata == NULL) {
841                 cprintf("%d malloc failed\n", ERROR + INTERNAL_ERROR);
842                 return;
843         }
844         memset(oiddata, 0, sizeof(ctdl_openid));
845         CCC->openid_data = (void *) oiddata;
846
847         ArgBuf = NewStrBufPlain(argbuf, -1);
848
849         oiddata->verified = 0;
850         oiddata->claimed_id = NewStrBufPlain(NULL, StrLength(ArgBuf));
851         trust_root = NewStrBufPlain(NULL, StrLength(ArgBuf));
852         return_to = NewStrBufPlain(NULL, StrLength(ArgBuf));
853
854         StrBufExtract_NextToken(oiddata->claimed_id, ArgBuf, &Pos, '|');
855         StrBufExtract_NextToken(return_to, ArgBuf, &Pos, '|');
856         StrBufExtract_NextToken(trust_root, ArgBuf, &Pos, '|');
857
858         syslog(LOG_DEBUG, "User-Supplied Identifier is: %s", ChrPtr(oiddata->claimed_id));
859
860
861 #if 0
862         /********** OpenID 2.0 section 7.3 - Discovery **********/
863
864         /* Section 7.3.1 says we have to attempt XRI based discovery.
865          * No one is using this, no one is asking for it, no one wants it.
866          * So we're not even going to bother attempting this mode.
867          */
868
869         /* Attempt section 7.3.2 (Yadis discovery) and section 7.3.3 (HTML discovery);
870          */
871         int yadis_succeeded = perform_openid2_discovery(oiddata->claimed_id);
872 #endif
873
874
875
876         /************ OPENID 1.1 **********/
877
878         if (    (fetch_http(oiddata->claimed_id, &ReplyBuf) > 0)
879                 && (StrLength(ReplyBuf) > 0)
880         ) {
881                 openid_delegate = NewStrBuf();
882                 oiddata->server = NewStrBuf();
883                 extract_link(oiddata->server, HKEY("openid.server"), ReplyBuf);
884                 extract_link(openid_delegate, HKEY("openid.delegate"), ReplyBuf);
885
886                 if (StrLength(oiddata->server) == 0) {
887                         cprintf("%d There is no OpenID identity provider at this URL.\n", ERROR);
888                         FreeStrBuf(&ArgBuf);
889                         FreeStrBuf(&ReplyBuf);
890                         FreeStrBuf(&return_to);
891                         FreeStrBuf(&trust_root);
892                         FreeStrBuf(&openid_delegate);
893                         FreeStrBuf(&RedirectUrl);
894                         return;
895                 }
896
897                 /* Empty delegate is legal; we just use the openid_url instead */
898                 if (StrLength(openid_delegate) == 0) {
899                         StrBufPlain(openid_delegate, SKEY(oiddata->claimed_id));
900                 }
901
902                 /* Assemble a URL to which the user-agent will be redirected. */
903
904                 RedirectUrl = NewStrBufDup(oiddata->server);
905
906                 StrBufAppendBufPlain(RedirectUrl, HKEY("?openid.mode=checkid_setup"
907                                                        "&openid.identity="), 0);
908                 StrBufUrlescAppend(RedirectUrl, openid_delegate, NULL);
909
910                 StrBufAppendBufPlain(RedirectUrl, HKEY("&openid.return_to="), 0);
911                 StrBufUrlescAppend(RedirectUrl, return_to, NULL);
912
913                 StrBufAppendBufPlain(RedirectUrl, HKEY("&openid.trust_root="), 0);
914                 StrBufUrlescAppend(RedirectUrl, trust_root, NULL);
915
916                 StrBufAppendBufPlain(RedirectUrl, HKEY("&openid.sreg.optional="), 0);
917                 StrBufUrlescAppend(RedirectUrl, NULL, "nickname,email,fullname,postcode,country,dob,gender");
918
919                 cprintf("%d %s\n", CIT_OK, ChrPtr(RedirectUrl));
920                 
921                 FreeStrBuf(&ArgBuf);
922                 FreeStrBuf(&ReplyBuf);
923                 FreeStrBuf(&return_to);
924                 FreeStrBuf(&trust_root);
925                 FreeStrBuf(&openid_delegate);
926                 FreeStrBuf(&RedirectUrl);
927
928                 return;
929         }
930
931         FreeStrBuf(&ArgBuf);
932         FreeStrBuf(&ReplyBuf);
933         FreeStrBuf(&return_to);
934         FreeStrBuf(&trust_root);
935         FreeStrBuf(&openid_delegate);
936         FreeStrBuf(&RedirectUrl);
937
938         cprintf("%d Unable to fetch OpenID URL\n", ERROR);
939 }
940
941
942
943
944
945 /*
946  * Finalize an OpenID authentication
947  */
948 void cmd_oidf(char *argbuf) {
949         long len;
950         char buf[2048];
951         char thiskey[1024];
952         char thisdata[1024];
953         HashList *keys = NULL;
954         ctdl_openid *oiddata = (ctdl_openid *) CC->openid_data;
955
956         if (oiddata == NULL) {
957                 cprintf("%d run OIDS first.\n", ERROR + INTERNAL_ERROR);
958                 return;
959         }
960         if (StrLength(oiddata->server) == 0){
961                 cprintf("%d need a remote server to authenticate against\n", ERROR + ILLEGAL_VALUE);
962                 return;
963         }
964         keys = NewHash(1, NULL);
965         if (!keys) {
966                 cprintf("%d NewHash() failed\n", ERROR + INTERNAL_ERROR);
967                 return;
968         }
969         cprintf("%d Transmit OpenID data now\n", START_CHAT_MODE);
970
971         while (client_getln(buf, sizeof buf), strcmp(buf, "000")) {
972                 len = extract_token(thiskey, buf, 0, '|', sizeof thiskey);
973                 if (len < 0)
974                         len = sizeof(thiskey) - 1;
975                 extract_token(thisdata, buf, 1, '|', sizeof thisdata);
976                 syslog(LOG_DEBUG, "%s: ["SIZE_T_FMT"] %s", thiskey, strlen(thisdata), thisdata);
977                 Put(keys, thiskey, len, strdup(thisdata), NULL);
978         }
979
980
981         /* Now that we have all of the parameters, we have to validate the signature against the server */
982         syslog(LOG_DEBUG, "About to validate the signature...");
983
984         CURL *curl;
985         CURLcode res;
986         struct curl_httppost *formpost = NULL;
987         struct curl_httppost *lastptr = NULL;
988         char errmsg[1024] = "";
989         char *o_assoc_handle = NULL;
990         char *o_sig = NULL;
991         char *o_signed = NULL;
992         int num_signed_values;
993         int i;
994         char k_keyname[128];
995         char k_o_keyname[128];
996         char *k_value = NULL;
997         StrBuf *ReplyBuf;
998
999         curl_formadd(&formpost, &lastptr,
1000                 CURLFORM_COPYNAME,      "openid.mode",
1001                 CURLFORM_COPYCONTENTS,  "check_authentication",
1002                 CURLFORM_END);
1003         syslog(LOG_DEBUG, "%25s : %s", "openid.mode", "check_authentication");
1004
1005         if (GetHash(keys, "assoc_handle", 12, (void *) &o_assoc_handle)) {
1006                 curl_formadd(&formpost, &lastptr,
1007                         CURLFORM_COPYNAME,      "openid.assoc_handle",
1008                         CURLFORM_COPYCONTENTS,  o_assoc_handle,
1009                         CURLFORM_END);
1010                 syslog(LOG_DEBUG, "%25s : %s", "openid.assoc_handle", o_assoc_handle);
1011         }
1012
1013         if (GetHash(keys, "sig", 3, (void *) &o_sig)) {
1014                 curl_formadd(&formpost, &lastptr,
1015                         CURLFORM_COPYNAME,      "openid.sig",
1016                         CURLFORM_COPYCONTENTS,  o_sig,
1017                         CURLFORM_END);
1018                         syslog(LOG_DEBUG, "%25s : %s", "openid.sig", o_sig);
1019         }
1020
1021         if (GetHash(keys, "signed", 6, (void *) &o_signed)) {
1022                 curl_formadd(&formpost, &lastptr,
1023                         CURLFORM_COPYNAME,      "openid.signed",
1024                         CURLFORM_COPYCONTENTS,  o_signed,
1025                         CURLFORM_END);
1026                 syslog(LOG_DEBUG, "%25s : %s", "openid.signed", o_signed);
1027
1028                 num_signed_values = num_tokens(o_signed, ',');
1029                 for (i=0; i<num_signed_values; ++i) {
1030                         extract_token(k_keyname, o_signed, i, ',', sizeof k_keyname);
1031                         if (strcasecmp(k_keyname, "mode")) {    // work around phpMyID bug
1032                                 if (GetHash(keys, k_keyname, strlen(k_keyname), (void *) &k_value)) {
1033                                         snprintf(k_o_keyname, sizeof k_o_keyname, "openid.%s", k_keyname);
1034                                         curl_formadd(&formpost, &lastptr,
1035                                                 CURLFORM_COPYNAME,      k_o_keyname,
1036                                                 CURLFORM_COPYCONTENTS,  k_value,
1037                                                 CURLFORM_END);
1038                                         syslog(LOG_DEBUG, "%25s : %s", k_o_keyname, k_value);
1039                                 }
1040                                 else {
1041                                         syslog(LOG_INFO, "OpenID: signed field '%s' is missing",
1042                                                 k_keyname);
1043                                 }
1044                         }
1045                 }
1046         }
1047         
1048         ReplyBuf = NewStrBuf();
1049
1050         curl = ctdl_openid_curl_easy_init(errmsg);
1051         curl_easy_setopt(curl, CURLOPT_URL, ChrPtr(oiddata->server));
1052         curl_easy_setopt(curl, CURLOPT_WRITEDATA, ReplyBuf);
1053         curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, CurlFillStrBuf_callback);
1054         curl_easy_setopt(curl, CURLOPT_HTTPPOST, formpost);
1055
1056         res = curl_easy_perform(curl);
1057         if (res) {
1058                 syslog(LOG_DEBUG, "cmd_oidf() libcurl error %d: %s", res, errmsg);
1059         }
1060         curl_easy_cleanup(curl);
1061         curl_formfree(formpost);
1062
1063         if (cbmstrcasestr(ChrPtr(ReplyBuf), "is_valid:true")) {
1064                 oiddata->verified = 1;
1065         }
1066         FreeStrBuf(&ReplyBuf);
1067
1068         syslog(LOG_DEBUG, "Authentication %s.", (oiddata->verified ? "succeeded" : "failed") );
1069
1070         /* Respond to the client */
1071
1072         if (oiddata->verified) {
1073
1074                 /* If we were already logged in, attach the OpenID to the user's account */
1075                 if (CC->logged_in) {
1076                         if (attach_openid(&CC->user, oiddata->claimed_id) == 0) {
1077                                 cprintf("attach\n");
1078                                 syslog(LOG_DEBUG, "OpenID attach succeeded");
1079                         }
1080                         else {
1081                                 cprintf("fail\n");
1082                                 syslog(LOG_DEBUG, "OpenID attach failed");
1083                         }
1084                 }
1085
1086                 /* Otherwise, a user is attempting to log in using the verified OpenID */       
1087                 else {
1088                         /*
1089                          * Existing user who has claimed this OpenID?
1090                          *
1091                          * Note: if you think that sending the password back over the wire is insecure,
1092                          * check your assumptions.  If someone has successfully asserted an OpenID that
1093                          * is associated with the account, they already have password equivalency and can
1094                          * login, so they could just as easily change the password, etc.
1095                          */
1096                         if (login_via_openid(oiddata->claimed_id) == 0) {
1097                                 cprintf("authenticate\n%s\n%s\n", CC->user.fullname, CC->user.password);
1098                                 logged_in_response();
1099                                 syslog(LOG_DEBUG, "Logged in using previously claimed OpenID");
1100                         }
1101
1102                         /*
1103                          * If this system does not allow self-service new user registration, the
1104                          * remaining modes do not apply, so fail here and now.
1105                          */
1106                         else if (config.c_disable_newu) {
1107                                 cprintf("fail\n");
1108                                 syslog(LOG_DEBUG, "Creating user failed due to local policy");
1109                         }
1110
1111                         /*
1112                          * New user whose OpenID is verified and Simple Registration Extension is in use?
1113                          */
1114                         else if (openid_create_user_via_sreg(oiddata->claimed_id, keys) == 0) {
1115                                 cprintf("authenticate\n%s\n%s\n", CC->user.fullname, CC->user.password);
1116                                 logged_in_response();
1117                                 syslog(LOG_DEBUG, "Successfully auto-created new user");
1118                         }
1119
1120                         /*
1121                          * OpenID is verified, but the desired username either was not specified or
1122                          * conflicts with an existing user.  Manual account creation is required.
1123                          */
1124                         else {
1125                                 char *desired_name = NULL;
1126                                 cprintf("verify_only\n");
1127                                 cprintf("%s\n", ChrPtr(oiddata->claimed_id));
1128                                 if (GetHash(keys, "sreg.nickname", 13, (void *) &desired_name)) {
1129                                         cprintf("%s\n", desired_name);
1130                                 }
1131                                 else {
1132                                         cprintf("\n");
1133                                 }
1134                                 syslog(LOG_DEBUG, "The desired Simple Registration name is already taken.");
1135                         }
1136                 }
1137         }
1138         else {
1139                 cprintf("fail\n");
1140         }
1141         cprintf("000\n");
1142
1143         if (oiddata->sreg_keys != NULL) {
1144                 DeleteHash(&oiddata->sreg_keys);
1145                 oiddata->sreg_keys = NULL;
1146         }
1147         oiddata->sreg_keys = keys;
1148 }
1149
1150
1151
1152 /**************************************************************************/
1153 /*                                                                        */
1154 /* Functions in this section handle module initialization and shutdown    */
1155 /*                                                                        */
1156 /**************************************************************************/
1157
1158
1159
1160
1161 CTDL_MODULE_INIT(openid_rp)
1162 {
1163         if (!threading) {
1164                 curl_global_init(CURL_GLOBAL_ALL);
1165
1166                 /* Only enable the OpenID command set when native mode authentication is in use. */
1167                 if (config.c_auth_mode == AUTHMODE_NATIVE) {
1168                         CtdlRegisterProtoHook(cmd_oids, "OIDS", "Setup OpenID authentication");
1169                         CtdlRegisterProtoHook(cmd_oidf, "OIDF", "Finalize OpenID authentication");
1170                         CtdlRegisterProtoHook(cmd_oidl, "OIDL", "List OpenIDs associated with an account");
1171                         CtdlRegisterProtoHook(cmd_oidd, "OIDD", "Detach an OpenID from an account");
1172                         CtdlRegisterProtoHook(cmd_oidc, "OIDC", "Create new user after validating OpenID");
1173                         CtdlRegisterProtoHook(cmd_oida, "OIDA", "List all OpenIDs in the database");
1174                 }
1175                 CtdlRegisterSessionHook(openid_cleanup_function, EVT_LOGOUT);
1176                 CtdlRegisterUserHook(openid_purge, EVT_PURGEUSER);
1177                 openid_level_supported = 1;     /* This module supports OpenID 1.0 only */
1178         }
1179
1180         /* return our module name for the log */
1181         return "openid_rp";
1182 }