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