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