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