* openid-Module: don't use static buffers in most places
[citadel.git] / citadel / modules / openid / serv_openid_rp.c
1 /*
2  * $Id$
3  *
4  * This is an implementation of OpenID 1.1 Relying Party support, in stateless mode.
5  *
6  * Copyright (c) 2007-2009 by the citadel.org team
7  *
8  *  This program is free software; you can redistribute it and/or modify
9  *  it under the terms of the GNU General Public License as published by
10  *  the Free Software Foundation; either version 3 of the License, or
11  *  (at your option) any later version.
12  *
13  *  This program is distributed in the hope that it will be useful,
14  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
15  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16  *  GNU General Public License for more details.
17  *
18  *  You should have received a copy of the GNU General Public License
19  *  along with this program; if not, write to the Free Software
20  *  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
21  */
22
23 #include "sysdep.h"
24 #include <stdlib.h>
25 #include <unistd.h>
26 #include <stdio.h>
27 #include <fcntl.h>
28 #include <signal.h>
29 #include <pwd.h>
30 #include <errno.h>
31 #include <sys/types.h>
32
33 #if TIME_WITH_SYS_TIME
34 # include <sys/time.h>
35 # include <time.h>
36 #else
37 # if HAVE_SYS_TIME_H
38 #  include <sys/time.h>
39 # else
40 #  include <time.h>
41 # endif
42 #endif
43
44 #include <sys/wait.h>
45 #include <string.h>
46 #include <limits.h>
47 #include <curl/curl.h>
48 #include "ctdl_module.h"
49 #include "config.h"
50 #include "citserver.h"
51 #include "user_ops.h"
52
53 typedef struct _ctdl_openid {
54         StrBuf *claimed_id;
55         StrBuf *server;
56         int verified;
57         HashList *sreg_keys;
58 } ctdl_openid;
59
60 void Free_ctdl_openid(ctdl_openid **FreeMe)
61 {
62         if (*FreeMe == NULL)
63                 return;
64         FreeStrBuf(&(*FreeMe)->claimed_id);
65         FreeStrBuf(&(*FreeMe)->server);
66         DeleteHash(&(*FreeMe)->sreg_keys);
67         free(*FreeMe);
68         *FreeMe = NULL;
69 }
70
71
72 /*
73  * This cleanup function blows away the temporary memory used by this module.
74  */
75 void openid_cleanup_function(void) {
76         struct CitContext *CCC = CC;    /* CachedCitContext - performance boost */
77
78         if (CCC->openid_data != NULL) {
79                 CtdlLogPrintf(CTDL_DEBUG, "Clearing OpenID session state\n");
80                 Free_ctdl_openid((ctdl_openid **) &CCC->openid_data);
81         }
82 }
83
84
85 /**************************************************************************/
86 /*                                                                        */
87 /* Functions in this section handle Citadel internal OpenID mapping stuff */
88 /*                                                                        */
89 /**************************************************************************/
90
91
92 /*
93  * The structure of an openid record *key* is:
94  *
95  * |--------------claimed_id-------------|
96  *     (actual length of claimed id)
97  *
98  *
99  * The structure of an openid record *value* is:
100  *
101  * |-----user_number----|------------claimed_id---------------|
102  *    (sizeof long)          (actual length of claimed id)
103  *
104  */
105
106
107
108 /*
109  * Attach an OpenID to a Citadel account
110  */
111 int attach_openid(struct ctdluser *who, StrBuf *claimed_id)
112 {
113         struct cdbdata *cdboi;
114         long fetched_usernum;
115         char *data;
116         int data_len;
117         char buf[2048];
118
119         if (!who) return(1);
120         if (StrLength(claimed_id)==0) return(1);
121
122         /* Check to see if this OpenID is already in the database */
123
124         cdboi = cdb_fetch(CDB_OPENID, ChrPtr(claimed_id), StrLength(claimed_id));
125         if (cdboi != NULL) {
126                 memcpy(&fetched_usernum, cdboi->ptr, sizeof(long));
127                 cdb_free(cdboi);
128
129                 if (fetched_usernum == who->usernum) {
130                         CtdlLogPrintf(CTDL_INFO, "%s already associated; no action is taken\n", claimed_id);
131                         return(0);
132                 }
133                 else {
134                         CtdlLogPrintf(CTDL_INFO, "%s already belongs to another user\n", claimed_id);
135                         return(3);
136                 }
137         }
138
139         /* Not already in the database, so attach it now */
140
141         data_len = sizeof(long) + StrLength(claimed_id) + 1;
142         data = malloc(data_len);
143
144         memcpy(data, &who->usernum, sizeof(long));
145         memcpy(&data[sizeof(long)], ChrPtr(claimed_id), StrLength(claimed_id) + 1);
146
147         cdb_store(CDB_OPENID, ChrPtr(claimed_id), StrLength(claimed_id), data, data_len);
148         free(data);
149
150         snprintf(buf, sizeof buf, "User <%s> (#%ld) has claimed the OpenID URL %s\n",
151                  who->fullname, who->usernum, ChrPtr(claimed_id));
152         CtdlAideMessage(buf, "OpenID claim");
153         CtdlLogPrintf(CTDL_INFO, "%s", buf);
154         return(0);
155 }
156
157
158
159 /*
160  * When a user is being deleted, we have to delete any OpenID associations
161  */
162 void openid_purge(struct ctdluser *usbuf) {
163         struct cdbdata *cdboi;
164         HashList *keys = NULL;
165         HashPos *HashPos;
166         char *deleteme = NULL;
167         long len;
168         void *Value;
169         const char *Key;
170         long usernum = 0L;
171
172         keys = NewHash(1, NULL);
173         if (!keys) return;
174
175
176         cdb_rewind(CDB_OPENID);
177         while (cdboi = cdb_next_item(CDB_OPENID), cdboi != NULL) {
178                 if (cdboi->len > sizeof(long)) {
179                         memcpy(&usernum, cdboi->ptr, sizeof(long));
180                         if (usernum == usbuf->usernum) {
181                                 deleteme = strdup(cdboi->ptr + sizeof(long)),
182                                 Put(keys, deleteme, strlen(deleteme), deleteme, NULL);
183                         }
184                 }
185                 cdb_free(cdboi);
186         }
187
188         /* Go through the hash list, deleting keys we stored in it */
189
190         HashPos = GetNewHashPos(keys, 0);
191         while (GetNextHashPos(keys, HashPos, &len, &Key, &Value)!=0)
192         {
193                 CtdlLogPrintf(CTDL_DEBUG, "Deleting associated OpenID <%s>\n", Value);
194                 cdb_delete(CDB_OPENID, Value, strlen(Value));
195                 /* note: don't free(Value) -- deleting the hash list will handle this for us */
196         }
197         DeleteHashPos(&HashPos);
198         DeleteHash(&keys);
199 }
200
201
202
203 /*
204  * List the OpenIDs associated with the currently logged in account
205  */
206 void cmd_oidl(char *argbuf) {
207         struct cdbdata *cdboi;
208         long usernum = 0L;
209
210         if (CtdlAccessCheck(ac_logged_in)) return;
211         cdb_rewind(CDB_OPENID);
212         cprintf("%d Associated OpenIDs:\n", LISTING_FOLLOWS);
213
214         while (cdboi = cdb_next_item(CDB_OPENID), cdboi != NULL) {
215                 if (cdboi->len > sizeof(long)) {
216                         memcpy(&usernum, cdboi->ptr, sizeof(long));
217                         if (usernum == CC->user.usernum) {
218                                 cprintf("%s\n", cdboi->ptr + sizeof(long));
219                         }
220                 }
221                 cdb_free(cdboi);
222         }
223         cprintf("000\n");
224 }
225
226
227 /*
228  * List ALL OpenIDs in the database
229  */
230 void cmd_oida(char *argbuf) {
231         struct cdbdata *cdboi;
232         long usernum;
233         struct ctdluser usbuf;
234
235         if (CtdlAccessCheck(ac_aide)) return;
236         cdb_rewind(CDB_OPENID);
237         cprintf("%d List of all OpenIDs in the database:\n", LISTING_FOLLOWS);
238
239         while (cdboi = cdb_next_item(CDB_OPENID), cdboi != NULL) {
240                 if (cdboi->len > sizeof(long)) {
241                         memcpy(&usernum, cdboi->ptr, sizeof(long));
242                         if (CtdlGetUserByNumber(&usbuf, usernum) != 0) {
243                                 usbuf.fullname[0] = 0;
244                         } 
245                         cprintf("%s|%ld|%s\n",
246                                 cdboi->ptr + sizeof(long),
247                                 usernum,
248                                 usbuf.fullname
249                         );
250                 }
251                 cdb_free(cdboi);
252         }
253         cprintf("000\n");
254 }
255
256
257 /*
258  * Attempt to register (populate the vCard) the currently-logged-in user
259  * using the data from Simple Registration Extension, if present.
260  */
261 void populate_vcard_from_sreg(HashList *sreg_keys) {
262
263         struct vCard *v;
264         int pop = 0;                    /* number of fields populated */
265         char *data = NULL;
266         char *postcode = NULL;
267         char *country = NULL;
268
269         if (!sreg_keys) return;
270         v = vcard_new();
271         if (!v) return;
272
273         if (GetHash(sreg_keys, "identity", 8, (void *) &data)) {
274                 vcard_add_prop(v, "url;type=openid", data);
275                 ++pop;
276         }
277
278         if (GetHash(sreg_keys, "sreg.email", 10, (void *) &data)) {
279                 vcard_add_prop(v, "email;internet", data);
280                 ++pop;
281         }
282
283         if (GetHash(sreg_keys, "sreg.nickname", 13, (void *) &data)) {
284                 vcard_add_prop(v, "nickname", data);
285                 ++pop;
286         }
287
288         if (GetHash(sreg_keys, "sreg.fullname", 13, (void *) &data)) {
289                 char n[256];
290                 vcard_add_prop(v, "fn", data);
291                 vcard_fn_to_n(n, data, sizeof n);
292                 vcard_add_prop(v, "n", n);
293                 ++pop;
294         }
295
296         if (!GetHash(sreg_keys, "sreg.postcode", 13, (void *) &postcode)) {
297                 postcode = NULL;
298         }
299
300         if (!GetHash(sreg_keys, "sreg.country", 12, (void *) &country)) {
301                 country = NULL;
302         }
303
304         if (postcode || country) {
305                 char adr[256];
306                 snprintf(adr, sizeof adr, ";;;;;%s;%s",
307                         (postcode ? postcode : ""),
308                         (country ? country : "")
309                 );
310                 vcard_add_prop(v, "adr", adr);
311                 ++pop;
312         }
313
314         if (GetHash(sreg_keys, "sreg.dob", 8, (void *) &data)) {
315                 vcard_add_prop(v, "bday", data);
316                 ++pop;
317         }
318
319         if (GetHash(sreg_keys, "sreg.gender", 11, (void *) &data)) {
320                 vcard_add_prop(v, "x-funambol-gender", data);
321                 ++pop;
322         }
323
324         /* Only save the vCard if there is some useful data in it */
325         if (pop > 0) {
326                 char *ser;
327                 ser = vcard_serialize(v);
328                 if (ser) {
329                         CtdlWriteObject(USERCONFIGROOM, "text/x-vcard",
330                                 ser, strlen(ser)+1, &CC->user, 0, 0, 0
331                         );
332                         free(ser);
333                 }
334         }
335         vcard_free(v);
336 }
337
338
339 /*
340  * Create a new user account, manually specifying the name, after successfully
341  * verifying an OpenID (which will of course be attached to the account)
342  */
343 void cmd_oidc(char *argbuf) {
344         ctdl_openid *oiddata = (ctdl_openid *) CC->openid_data;
345
346         if (!oiddata) {
347                 cprintf("%d You have not verified an OpenID yet.\n", ERROR);
348                 return;
349         }
350
351         if (!oiddata->verified) {
352                 cprintf("%d You have not verified an OpenID yet.\n", ERROR);
353                 return;
354         }
355
356         /* We can make the semantics of OIDC exactly the same as NEWU, simply
357          * by _calling_ cmd_newu() and letting it run.  Very clever!
358          */
359         cmd_newu(argbuf);
360
361         /* Now, if this logged us in, we have to attach the OpenID */
362         if (CC->logged_in) {
363                 attach_openid(&CC->user, oiddata->claimed_id);
364                 if (oiddata->sreg_keys != NULL) {
365                         populate_vcard_from_sreg(oiddata->sreg_keys);
366                 }
367         }
368
369 }
370
371
372
373
374 /*
375  * Detach an OpenID from the currently logged in account
376  */
377 void cmd_oidd(char *argbuf) {
378         struct cdbdata *cdboi;
379         char id_to_detach[1024];
380         int this_is_mine = 0;
381         long usernum = 0L;
382
383         if (CtdlAccessCheck(ac_logged_in)) return;
384         extract_token(id_to_detach, argbuf, 0, '|', sizeof id_to_detach);
385         if (IsEmptyStr(id_to_detach)) {
386                 cprintf("%d An empty OpenID URL is not allowed.\n", ERROR + ILLEGAL_VALUE);
387         }
388
389         cdb_rewind(CDB_OPENID);
390         while (cdboi = cdb_next_item(CDB_OPENID), cdboi != NULL) {
391                 if (cdboi->len > sizeof(long)) {
392                         memcpy(&usernum, cdboi->ptr, sizeof(long));
393                         if (usernum == CC->user.usernum) {
394                                 this_is_mine = 1;
395                         }
396                 }
397                 cdb_free(cdboi);
398         }
399
400         if (!this_is_mine) {
401                 cprintf("%d That OpenID was not found or not associated with your account.\n",
402                         ERROR + ILLEGAL_VALUE);
403                 return;
404         }
405
406         cdb_delete(CDB_OPENID, id_to_detach, strlen(id_to_detach));
407         cprintf("%d %s detached from your account.\n", CIT_OK, id_to_detach);
408 }
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
420         if (config.c_auth_mode != AUTHMODE_NATIVE) return(1);
421         if (config.c_disable_newu) return(2);
422         if (CC->logged_in) return(3);
423         if (!GetHash(sreg_keys, "sreg.nickname", 13, (void *) &desired_name)) return(4);
424
425         CtdlLogPrintf(CTDL_DEBUG, "The desired account name is <%s>\n", desired_name);
426
427         if (!CtdlGetUser(&CC->user, desired_name)) {
428                 CtdlLogPrintf(CTDL_DEBUG, "<%s> is already taken by another user.\n", desired_name);
429                 memset(&CC->user, 0, sizeof(struct ctdluser));
430                 return(5);
431         }
432
433         /* The desired account name is available.  Create the account and log it in! */
434         if (create_user(desired_name, 1)) return(6);
435
436         snprintf(new_password, sizeof new_password, "%08lx%08lx", random(), random());
437         CtdlSetPassword(new_password);
438         attach_openid(&CC->user, claimed_id);
439         populate_vcard_from_sreg(sreg_keys);
440         return(0);
441 }
442
443
444 /*
445  * If a user account exists which is associated with the Claimed ID, log it in and return zero.
446  * Otherwise it returns nonzero.
447  */
448 int login_via_openid(StrBuf *claimed_id)
449 {
450         struct cdbdata *cdboi;
451         long usernum = 0;
452
453         cdboi = cdb_fetch(CDB_OPENID, ChrPtr(claimed_id), StrLength(claimed_id));
454         if (cdboi == NULL) {
455                 return(-1);
456         }
457
458         memcpy(&usernum, cdboi->ptr, sizeof(long));
459         cdb_free(cdboi);
460
461         if (!CtdlGetUserByNumber(&CC->user, usernum)) {
462                 /* Now become the user we just created */
463                 safestrncpy(CC->curr_user, CC->user.fullname, sizeof CC->curr_user);
464                 do_login();
465                 return(0);
466         }
467         else {
468                 memset(&CC->user, 0, sizeof(struct ctdluser));
469                 return(-1);
470         }
471 }
472
473
474
475
476 /**************************************************************************/
477 /*                                                                        */
478 /* Functions in this section handle OpenID protocol                       */
479 /*                                                                        */
480 /**************************************************************************/
481
482
483 /* 
484  * Locate a <link> tag and, given its 'rel=' parameter, return its 'href' parameter
485  */
486 void extract_link(StrBuf *target_buf, const char *rel, long repllen, StrBuf *source_buf)
487 {
488         int len, i;
489         const char *ptr;
490         const char *href_start = NULL;
491         const char *href_end = NULL;
492         const char *link_tag_start = NULL;
493         const char *link_tag_end = NULL;
494         const char *rel_start = NULL;
495         const char *rel_end = NULL;
496
497         if (!target_buf) return;
498         if (!rel) return;
499         if (!source_buf) return;
500
501         ptr = ChrPtr(source_buf);
502
503         FlushStrBuf(target_buf);
504         while (ptr = bmstrcasestr(ptr, "<link"), ptr != NULL) {
505
506                 link_tag_start = ptr;
507                 link_tag_end = strchr(ptr, '>');
508                 if (link_tag_end == NULL)
509                         break;
510                 for (i=0; i < 1; i++ ){
511                         len = link_tag_end - link_tag_start;
512
513                         rel_start = bmstrcasestr(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 = bmstrcasestr(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  * Begin an HTTP fetch (returns number of bytes actually fetched, or -1 for error) using libcurl.
554  *
555  * If 'normalize_len' is nonzero, the caller is specifying the buffer size of 'url', and is
556  * requesting that the effective (normalized) URL be copied back to it.
557  */
558 int fetch_http(StrBuf *url, StrBuf **target_buf)
559 {
560         StrBuf *ReplyBuf;
561         CURL *curl;
562         CURLcode res;
563         char errmsg[1024] = "";
564         char *effective_url = NULL;
565
566         if (StrLength(url) <=0 ) return(-1);
567         ReplyBuf = *target_buf = NewStrBuf ();
568         if (ReplyBuf == 0) return(-1);
569
570         curl = curl_easy_init();
571         if (!curl) {
572                 CtdlLogPrintf(CTDL_ALERT, "Unable to initialize libcurl.\n");
573                 return(-1);
574         }
575
576         curl_easy_setopt(curl, CURLOPT_URL, ChrPtr(url));
577         curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 0);
578         curl_easy_setopt(curl, CURLOPT_SSL_VERIFYHOST, 0);
579
580         curl_easy_setopt(curl, CURLOPT_WRITEDATA, ReplyBuf);
581         curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, CurlFillStrBuf_callback);
582
583         curl_easy_setopt(curl, CURLOPT_ERRORBUFFER, errmsg);
584         curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1);
585 #ifdef CURLOPT_HTTP_CONTENT_DECODING
586         curl_easy_setopt(curl, CURLOPT_HTTP_CONTENT_DECODING, 1);
587         curl_easy_setopt(curl, CURLOPT_ENCODING, "");
588 #endif
589         curl_easy_setopt(curl, CURLOPT_USERAGENT, CITADEL);
590         curl_easy_setopt(curl, CURLOPT_TIMEOUT, 180);           /* die after 180 seconds */
591         if (!IsEmptyStr(config.c_ip_addr)) {
592                 curl_easy_setopt(curl, CURLOPT_INTERFACE, config.c_ip_addr);
593         }
594         res = curl_easy_perform(curl);
595         if (res) {
596                 CtdlLogPrintf(CTDL_DEBUG, "fetch_http() libcurl error %d: %s\n", res, errmsg);
597         }
598         curl_easy_getinfo(curl, CURLINFO_EFFECTIVE_URL, &effective_url);
599         StrBufPlain(url, effective_url, -1);
600         
601         curl_easy_cleanup(curl);
602         return StrLength(ReplyBuf);
603 }
604
605
606 /*
607  * Setup an OpenID authentication
608  */
609 void cmd_oids(char *argbuf) {
610         const char *Pos = NULL;
611         StrBuf *ArgBuf = NULL;
612         StrBuf *ReplyBuf = NULL;
613         StrBuf *return_to = NULL;
614         StrBuf *trust_root = NULL;
615         StrBuf *openid_delegate = NULL;
616         StrBuf *RedirectUrl = NULL;
617         int i;
618         struct CitContext *CCC = CC;    /* CachedCitContext - performance boost */
619         ctdl_openid *oiddata;
620
621         Free_ctdl_openid ((ctdl_openid**)&CCC->openid_data);
622
623         CCC->openid_data = oiddata = malloc(sizeof(ctdl_openid));
624         if (oiddata == NULL) {
625                 cprintf("%d malloc failed\n", ERROR + INTERNAL_ERROR);
626                 return;
627         }
628         memset(oiddata, 0, sizeof(ctdl_openid));
629         CCC->openid_data = (void *) oiddata;
630
631         ArgBuf = NewStrBufPlain(argbuf, -1);
632
633         oiddata->claimed_id = NewStrBufPlain(NULL, StrLength(ArgBuf));
634         trust_root = NewStrBufPlain(NULL, StrLength(ArgBuf));
635         return_to = NewStrBufPlain(NULL, StrLength(ArgBuf));
636
637         StrBufExtract_NextToken(oiddata->claimed_id, ArgBuf, &Pos, '|');
638         StrBufExtract_NextToken(return_to, ArgBuf, &Pos, '|');
639         StrBufExtract_NextToken(trust_root, ArgBuf, &Pos, '|');
640         
641         oiddata->verified = 0;
642
643         i = fetch_http(oiddata->claimed_id, &ReplyBuf);
644         CtdlLogPrintf(CTDL_DEBUG, "Normalized URL and Claimed ID is: %s\n", 
645                       ChrPtr(oiddata->claimed_id));
646         if ((StrLength(ReplyBuf) > 0) && (i > 0)) {
647
648                 openid_delegate = NewStrBuf();
649                 oiddata->server = NewStrBuf();
650                 extract_link(oiddata->server, HKEY("openid.server"), ReplyBuf);
651                 extract_link(openid_delegate, HKEY("openid.delegate"), ReplyBuf);
652
653                 if (StrLength(oiddata->server) == 0) {
654                         cprintf("%d There is no OpenID identity provider at this URL.\n", ERROR);
655                         FreeStrBuf(&ArgBuf);
656                         FreeStrBuf(&ReplyBuf);
657                         FreeStrBuf(&return_to);
658                         FreeStrBuf(&trust_root);
659                         FreeStrBuf(&openid_delegate);
660                         FreeStrBuf(&RedirectUrl);
661                         return;
662                 }
663
664                 /* Empty delegate is legal; we just use the openid_url instead */
665                 if (StrLength(openid_delegate) == 0) {
666                         StrBufPlain(openid_delegate, SKEY(oiddata->claimed_id));
667                 }
668
669                 /* Assemble a URL to which the user-agent will be redirected. */
670
671                 RedirectUrl = NewStrBufDup(oiddata->server);
672
673                 StrBufAppendBufPlain(RedirectUrl, HKEY("?openid.mode=checkid_setup"
674                                                        "&openid.identity="), 0);
675                 StrBufUrlescAppend(RedirectUrl, openid_delegate, NULL);
676
677                 StrBufAppendBufPlain(RedirectUrl, HKEY("&openid.return_to="), 0);
678                 StrBufUrlescAppend(RedirectUrl, return_to, NULL);
679
680                 StrBufAppendBufPlain(RedirectUrl, HKEY("&openid.trust_root="), 0);
681                 StrBufUrlescAppend(RedirectUrl, trust_root, NULL);
682
683                 StrBufAppendBufPlain(RedirectUrl, HKEY("&openid.sreg.optional="), 0);
684                 StrBufUrlescAppend(RedirectUrl, NULL, "nickname,email,fullname,postcode,country,dob,gender");
685
686                 cprintf("%d %s\n", CIT_OK, ChrPtr(RedirectUrl));
687                 
688                 FreeStrBuf(&ArgBuf);
689                 FreeStrBuf(&ReplyBuf);
690                 FreeStrBuf(&return_to);
691                 FreeStrBuf(&trust_root);
692                 FreeStrBuf(&openid_delegate);
693                 FreeStrBuf(&RedirectUrl);
694
695                 return;
696         }
697         FreeStrBuf(&ArgBuf);
698         FreeStrBuf(&ReplyBuf);
699         FreeStrBuf(&return_to);
700         FreeStrBuf(&trust_root);
701         FreeStrBuf(&openid_delegate);
702         FreeStrBuf(&RedirectUrl);
703
704         cprintf("%d Unable to fetch OpenID URL\n", ERROR);
705 }
706
707
708
709
710
711 /*
712  * Finalize an OpenID authentication
713  */
714 void cmd_oidf(char *argbuf) {
715         char buf[2048];
716         char thiskey[1024];
717         char thisdata[1024];
718         HashList *keys = NULL;
719         ctdl_openid *oiddata = (ctdl_openid *) CC->openid_data;
720
721         if (oiddata == NULL) {
722                 cprintf("%d run OIDS first.\n", ERROR + INTERNAL_ERROR);
723                 return;
724         }
725         if (StrLength(oiddata->server) == 0){
726                 cprintf("%d need a remote server to authenticate against\n", ERROR + ILLEGAL_VALUE);
727                 return;
728         }
729         keys = NewHash(1, NULL);
730         if (!keys) {
731                 cprintf("%d NewHash() failed\n", ERROR + INTERNAL_ERROR);
732                 return;
733         }
734         cprintf("%d Transmit OpenID data now\n", START_CHAT_MODE);
735
736         while (client_getln(buf, sizeof buf), strcmp(buf, "000")) {
737                 extract_token(thiskey, buf, 0, '|', sizeof thiskey);
738                 extract_token(thisdata, buf, 1, '|', sizeof thisdata);
739                 CtdlLogPrintf(CTDL_DEBUG, "%s: [%d] %s\n", thiskey, strlen(thisdata), thisdata);
740                 Put(keys, thiskey, strlen(thiskey), strdup(thisdata), NULL);
741         }
742
743
744         /* Now that we have all of the parameters, we have to validate the signature against the server */
745         CtdlLogPrintf(CTDL_DEBUG, "About to validate the signature...\n");
746
747         CURL *curl;
748         CURLcode res;
749         struct curl_httppost *formpost = NULL;
750         struct curl_httppost *lastptr = NULL;
751         char errmsg[1024] = "";
752         char *o_assoc_handle = NULL;
753         char *o_sig = NULL;
754         char *o_signed = NULL;
755         int num_signed_values;
756         int i;
757         char k_keyname[128];
758         char k_o_keyname[128];
759         char *k_value = NULL;
760         StrBuf *ReplyBuf;
761
762         curl_formadd(&formpost, &lastptr,
763                 CURLFORM_COPYNAME,      "openid.mode",
764                 CURLFORM_COPYCONTENTS,  "check_authentication",
765                 CURLFORM_END);
766         CtdlLogPrintf(CTDL_DEBUG, "%25s : %s\n", "openid.mode", "check_authentication");
767
768         if (GetHash(keys, "assoc_handle", 12, (void *) &o_assoc_handle)) {
769                 curl_formadd(&formpost, &lastptr,
770                         CURLFORM_COPYNAME,      "openid.assoc_handle",
771                         CURLFORM_COPYCONTENTS,  o_assoc_handle,
772                         CURLFORM_END);
773                 CtdlLogPrintf(CTDL_DEBUG, "%25s : %s\n", "openid.assoc_handle", o_assoc_handle);
774         }
775
776         if (GetHash(keys, "sig", 3, (void *) &o_sig)) {
777                 curl_formadd(&formpost, &lastptr,
778                         CURLFORM_COPYNAME,      "openid.sig",
779                         CURLFORM_COPYCONTENTS,  o_sig,
780                         CURLFORM_END);
781                         CtdlLogPrintf(CTDL_DEBUG, "%25s : %s\n", "openid.sig", o_sig);
782         }
783
784         if (GetHash(keys, "signed", 6, (void *) &o_signed)) {
785                 curl_formadd(&formpost, &lastptr,
786                         CURLFORM_COPYNAME,      "openid.signed",
787                         CURLFORM_COPYCONTENTS,  o_signed,
788                         CURLFORM_END);
789                 CtdlLogPrintf(CTDL_DEBUG, "%25s : %s\n", "openid.signed", o_signed);
790
791                 num_signed_values = num_tokens(o_signed, ',');
792                 for (i=0; i<num_signed_values; ++i) {
793                         extract_token(k_keyname, o_signed, i, ',', sizeof k_keyname);
794                         if (strcasecmp(k_keyname, "mode")) {    // work around phpMyID bug
795                                 if (GetHash(keys, k_keyname, strlen(k_keyname), (void *) &k_value)) {
796                                         snprintf(k_o_keyname, sizeof k_o_keyname, "openid.%s", k_keyname);
797                                         curl_formadd(&formpost, &lastptr,
798                                                 CURLFORM_COPYNAME,      k_o_keyname,
799                                                 CURLFORM_COPYCONTENTS,  k_value,
800                                                 CURLFORM_END);
801                                         CtdlLogPrintf(CTDL_DEBUG, "%25s : %s\n", k_o_keyname, k_value);
802                                 }
803                                 else {
804                                         CtdlLogPrintf(CTDL_INFO, "OpenID: signed field '%s' is missing\n",
805                                                 k_keyname);
806                                 }
807                         }
808                 }
809         }
810         
811         ReplyBuf = NewStrBuf();
812
813         curl = curl_easy_init();
814         curl_easy_setopt(curl, CURLOPT_URL, ChrPtr(oiddata->server));
815         curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 0);
816         curl_easy_setopt(curl, CURLOPT_SSL_VERIFYHOST, 0);
817
818         curl_easy_setopt(curl, CURLOPT_WRITEDATA, ReplyBuf);
819         curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, CurlFillStrBuf_callback);
820         curl_easy_setopt(curl, CURLOPT_HTTPPOST, formpost);
821         curl_easy_setopt(curl, CURLOPT_ERRORBUFFER, errmsg);
822         curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1);
823 #ifdef CURLOPT_HTTP_CONTENT_DECODING
824         curl_easy_setopt(curl, CURLOPT_HTTP_CONTENT_DECODING, 1);
825         curl_easy_setopt(curl, CURLOPT_ENCODING, "");
826 #endif
827         curl_easy_setopt(curl, CURLOPT_USERAGENT, CITADEL);
828         curl_easy_setopt(curl, CURLOPT_TIMEOUT, 180);           /* die after 180 seconds */
829         if (!IsEmptyStr(config.c_ip_addr)) {
830                 curl_easy_setopt(curl, CURLOPT_INTERFACE, config.c_ip_addr);
831         }
832
833         res = curl_easy_perform(curl);
834         if (res) {
835                 CtdlLogPrintf(CTDL_DEBUG, "cmd_oidf() libcurl error %d: %s\n", res, errmsg);
836         }
837         curl_easy_cleanup(curl);
838         curl_formfree(formpost);
839
840         if (bmstrcasestr(ChrPtr(ReplyBuf), "is_valid:true")) {
841                 oiddata->verified = 1;
842         }
843         FreeStrBuf(&ReplyBuf);
844
845         CtdlLogPrintf(CTDL_DEBUG, "Authentication %s.\n", (oiddata->verified ? "succeeded" : "failed") );
846
847         /* Respond to the client */
848
849         if (oiddata->verified) {
850
851                 /* If we were already logged in, attach the OpenID to the user's account */
852                 if (CC->logged_in) {
853                         if (attach_openid(&CC->user, oiddata->claimed_id) == 0) {
854                                 cprintf("attach\n");
855                                 CtdlLogPrintf(CTDL_DEBUG, "OpenID attach succeeded\n");
856                         }
857                         else {
858                                 cprintf("fail\n");
859                                 CtdlLogPrintf(CTDL_DEBUG, "OpenID attach failed\n");
860                         }
861                 }
862
863                 /* Otherwise, a user is attempting to log in using the verified OpenID */       
864                 else {
865                         /*
866                          * Existing user who has claimed this OpenID?
867                          *
868                          * Note: if you think that sending the password back over the wire is insecure,
869                          * check your assumptions.  If someone has successfully asserted an OpenID that
870                          * is associated with the account, they already have password equivalency and can
871                          * login, so they could just as easily change the password, etc.
872                          */
873                         if (login_via_openid(oiddata->claimed_id) == 0) {
874                                 cprintf("authenticate\n%s\n%s\n", CC->user.fullname, CC->user.password);
875                                 logged_in_response();
876                                 CtdlLogPrintf(CTDL_DEBUG, "Logged in using previously claimed OpenID\n");
877                         }
878
879                         /*
880                          * If this system does not allow self-service new user registration, the
881                          * remaining modes do not apply, so fail here and now.
882                          */
883                         else if (config.c_disable_newu) {
884                                 cprintf("fail\n");
885                                 CtdlLogPrintf(CTDL_DEBUG, "Creating user failed due to local policy\n");
886                         }
887
888                         /*
889                          * New user whose OpenID is verified and Simple Registration Extension is in use?
890                          */
891                         else if (openid_create_user_via_sreg(oiddata->claimed_id, keys) == 0) {
892                                 cprintf("authenticate\n%s\n%s\n", CC->user.fullname, CC->user.password);
893                                 logged_in_response();
894                                 CtdlLogPrintf(CTDL_DEBUG, "Successfully auto-created new user\n");
895                         }
896
897                         /*
898                          * OpenID is verified, but the desired username either was not specified or
899                          * conflicts with an existing user.  Manual account creation is required.
900                          */
901                         else {
902                                 char *desired_name = NULL;
903                                 cprintf("verify_only\n");
904                                 cprintf("%s\n", ChrPtr(oiddata->claimed_id));
905                                 if (GetHash(keys, "sreg.nickname", 13, (void *) &desired_name)) {
906                                         cprintf("%s\n", desired_name);
907                                 }
908                                 else {
909                                         cprintf("\n");
910                                 }
911                                 CtdlLogPrintf(CTDL_DEBUG, "The desired Simple Registration name is already taken.\n");
912                         }
913                 }
914         }
915         else {
916                 cprintf("fail\n");
917         }
918         cprintf("000\n");
919
920         if (oiddata->sreg_keys != NULL) {
921                 DeleteHash(&oiddata->sreg_keys);
922                 oiddata->sreg_keys = NULL;
923         }
924         oiddata->sreg_keys = keys;
925 }
926
927
928
929 /**************************************************************************/
930 /*                                                                        */
931 /* Functions in this section handle module initialization and shutdown    */
932 /*                                                                        */
933 /**************************************************************************/
934
935
936
937
938 CTDL_MODULE_INIT(openid_rp)
939 {
940         if (!threading) {
941                 curl_global_init(CURL_GLOBAL_ALL);
942
943                 /* Only enable the OpenID command set when native mode authentication is in use. */
944                 if (config.c_auth_mode == AUTHMODE_NATIVE) {
945                         CtdlRegisterProtoHook(cmd_oids, "OIDS", "Setup OpenID authentication");
946                         CtdlRegisterProtoHook(cmd_oidf, "OIDF", "Finalize OpenID authentication");
947                         CtdlRegisterProtoHook(cmd_oidl, "OIDL", "List OpenIDs associated with an account");
948                         CtdlRegisterProtoHook(cmd_oidd, "OIDD", "Detach an OpenID from an account");
949                         CtdlRegisterProtoHook(cmd_oidc, "OIDC", "Create new user after validating OpenID");
950                         CtdlRegisterProtoHook(cmd_oida, "OIDA", "List all OpenIDs in the database");
951                 }
952                 CtdlRegisterSessionHook(openid_cleanup_function, EVT_LOGOUT);
953                 CtdlRegisterUserHook(openid_purge, EVT_PURGEUSER);
954         }
955
956         /* return our Subversion id for the Log */
957         return "$Id$";
958 }