getuserbynumber() now uses a proper indexed database
[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  */
7
8 #include "sysdep.h"
9 #include <stdlib.h>
10 #include <unistd.h>
11 #include <stdio.h>
12 #include <fcntl.h>
13 #include <signal.h>
14 #include <pwd.h>
15 #include <errno.h>
16 #include <sys/types.h>
17
18 #if TIME_WITH_SYS_TIME
19 # include <sys/time.h>
20 # include <time.h>
21 #else
22 # if HAVE_SYS_TIME_H
23 #  include <sys/time.h>
24 # else
25 #  include <time.h>
26 # endif
27 #endif
28
29 #include <sys/wait.h>
30 #include <string.h>
31 #include <limits.h>
32 #include <curl/curl.h>
33 #include "ctdl_module.h"
34 #include "config.h"
35
36 struct ctdl_openid {
37         char claimed_id[1024];
38         char server[1024];
39 };
40
41
42
43
44
45 /**************************************************************************/
46 /*                                                                        */
47 /* Functions in this section handle Citadel internal OpenID mapping stuff */
48 /*                                                                        */
49 /**************************************************************************/
50
51
52 /*
53  * Attach or detach an OpenID to a Citadel account
54  */
55
56 enum {
57         moa_detach,
58         moa_attach
59 };
60
61 int modify_openid_associations(struct ctdluser *who, char *claimed_id, int operation)
62 {
63         if (!who) return(1);
64         if (!claimed_id) return(1);
65         if (IsEmptyStr(claimed_id)) return(1);
66
67         return(2);              // error because we are not done yet FIXME
68 }
69
70
71 /*
72  * When a user is being deleted, we have to delete any OpenID associations
73  */
74 void openid_purge(struct ctdluser *usbuf) {
75         /* FIXME finish this */
76 }
77
78
79
80
81
82
83
84 /**************************************************************************/
85 /*                                                                        */
86 /* Functions in this section handle OpenID protocol                       */
87 /*                                                                        */
88 /**************************************************************************/
89
90
91 /* 
92  * Locate a <link> tag and, given its 'rel=' parameter, return its 'href' parameter
93  */
94 void extract_link(char *target_buf, int target_size, char *rel, char *source_buf)
95 {
96         char *ptr = source_buf;
97
98         if (!target_buf) return;
99         if (!rel) return;
100         if (!source_buf) return;
101
102         target_buf[0] = 0;
103
104         while (ptr = bmstrcasestr(ptr, "<link"), ptr != NULL) {
105
106                 char work_buffer[2048];
107                 char *link_tag_start = NULL;
108                 char *link_tag_end = NULL;
109
110                 char rel_tag[2048];
111                 char href_tag[2048];
112
113                 link_tag_start = ptr;
114                 link_tag_end = strchr(ptr, '>');
115                 rel_tag[0] = 0;
116                 href_tag[0] = 0;
117
118                 if ((link_tag_end) && (link_tag_end > link_tag_start)) {
119                         int len;
120                         len = link_tag_end - link_tag_start;
121                         if (len > sizeof work_buffer) len = sizeof work_buffer;
122                         memcpy(work_buffer, link_tag_start, len);
123                 
124                         char *rel_start = NULL;
125                         char *rel_end = NULL;
126                         rel_start = bmstrcasestr(work_buffer, "rel=");
127                         if (rel_start) {
128                                 rel_start = strchr(rel_start, '\"');
129                                 if (rel_start) {
130                                         ++rel_start;
131                                         rel_end = strchr(rel_start, '\"');
132                                         if ((rel_end) && (rel_end > rel_start)) {
133                                                 safestrncpy(rel_tag, rel_start, rel_end - rel_start + 1);
134                                         }
135                                 }
136                         }
137
138                         char *href_start = NULL;
139                         char *href_end = NULL;
140                         href_start = bmstrcasestr(work_buffer, "href=");
141                         if (href_start) {
142                                 href_start = strchr(href_start, '\"');
143                                 if (href_start) {
144                                         ++href_start;
145                                         href_end = strchr(href_start, '\"');
146                                         if ((href_end) && (href_end > href_start)) {
147                                                 safestrncpy(href_tag, href_start, href_end - href_start + 1);
148                                         }
149                                 }
150                         }
151
152                         if (!strcasecmp(rel, rel_tag)) {
153                                 safestrncpy(target_buf, href_tag, target_size);
154                                 return;
155                         }
156
157                 }
158
159         ++ptr;
160         }
161
162
163 }
164
165
166
167 struct fh_data {
168         char *buf;
169         int total_bytes_received;
170         int maxbytes;
171 };
172
173
174 size_t fh_callback(void *ptr, size_t size, size_t nmemb, void *stream)
175 {
176         struct fh_data *fh = (struct fh_data *) stream;
177         int got_bytes = (size * nmemb);
178
179         if (fh->total_bytes_received + got_bytes > fh->maxbytes) {
180                 got_bytes = fh->maxbytes - fh->total_bytes_received;
181         }
182         if (got_bytes > 0) {
183                 memcpy(&fh->buf[fh->total_bytes_received], ptr, got_bytes);
184                 fh->total_bytes_received += got_bytes;
185         }
186
187         return (size * nmemb);  /* always succeed; libcurl doesn't need to know if we truncated it */
188 }
189
190
191
192 /*
193  * Begin an HTTP fetch (returns number of bytes actually fetched, or -1 for error) using libcurl.
194  *
195  * If 'normalize_len' is nonzero, the caller is specifying the buffer size of 'url', and is
196  * requesting that the effective (normalized) URL be copied back to it.
197  */
198 int fetch_http(char *url, char *target_buf, int maxbytes, int normalize_len)
199 {
200         CURL *curl;
201         CURLcode res;
202         char errmsg[1024] = "";
203         struct fh_data fh = {
204                 target_buf,
205                 0,
206                 maxbytes
207         };
208         char *effective_url = NULL;
209
210         if (!url) return(-1);
211         if (!target_buf) return(-1);
212         memset(target_buf, 0, maxbytes);
213
214         curl = curl_easy_init();
215         if (!curl) {
216                 CtdlLogPrintf(CTDL_ALERT, "Unable to initialize libcurl.\n");
217                 return(-1);
218         }
219
220         curl_easy_setopt(curl, CURLOPT_URL, url);
221         curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 0);
222         curl_easy_setopt(curl, CURLOPT_SSL_VERIFYHOST, 0);
223         curl_easy_setopt(curl, CURLOPT_WRITEDATA, &fh);
224         curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, fh_callback);
225         curl_easy_setopt(curl, CURLOPT_ERRORBUFFER, errmsg);
226         curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1);
227         curl_easy_setopt(curl, CURLOPT_USERAGENT, CITADEL);
228         if (!IsEmptyStr(config.c_ip_addr)) {
229                 curl_easy_setopt(curl, CURLOPT_INTERFACE, config.c_ip_addr);
230         }
231         res = curl_easy_perform(curl);
232         if (res) {
233                 CtdlLogPrintf(CTDL_DEBUG, "fetch_http() libcurl error %d: %s\n", res, errmsg);
234         }
235         if (normalize_len > 0) {
236                 curl_easy_getinfo(curl, CURLINFO_EFFECTIVE_URL, &effective_url);
237                 safestrncpy(url, effective_url, normalize_len);
238         }
239         curl_easy_cleanup(curl);
240         return fh.total_bytes_received;
241 }
242
243
244 /*
245  * Setup an OpenID authentication
246  */
247 void cmd_oids(char *argbuf) {
248         char return_to[1024];
249         char trust_root[1024];
250         int i;
251         char buf[SIZ];
252         struct CitContext *CCC = CC;    /* CachedCitContext - performance boost */
253         struct ctdl_openid *oiddata;
254
255         /* commented out because we may be attempting to attach an OpenID to
256          * an existing account that is logged in
257          *
258         if (CCC->logged_in) {
259                 cprintf("%d Already logged in.\n", ERROR + ALREADY_LOGGED_IN);
260                 return;
261         }
262          */
263
264         if (CCC->openid_data != NULL) {
265                 free(CCC->openid_data);
266         }
267         oiddata = malloc(sizeof(struct ctdl_openid));
268         if (oiddata == NULL) {
269                 cprintf("%d malloc failed\n", ERROR + INTERNAL_ERROR);
270                 return;
271         }
272         memset(oiddata, 0, sizeof(struct ctdl_openid));
273         CCC->openid_data = (void *) oiddata;
274
275         extract_token(oiddata->claimed_id, argbuf, 0, '|', sizeof oiddata->claimed_id);
276         extract_token(return_to, argbuf, 1, '|', sizeof return_to);
277         extract_token(trust_root, argbuf, 2, '|', sizeof trust_root);
278
279         i = fetch_http(oiddata->claimed_id, buf, sizeof buf - 1, sizeof oiddata->claimed_id);
280         CtdlLogPrintf(CTDL_DEBUG, "Normalized URL and Claimed ID is: %s\n", oiddata->claimed_id);
281         buf[sizeof buf - 1] = 0;
282         if (i > 0) {
283                 char openid_delegate[1024];
284
285                 extract_link(oiddata->server, sizeof oiddata->server, "openid.server", buf);
286                 extract_link(openid_delegate, sizeof openid_delegate, "openid.delegate", buf);
287
288                 if (IsEmptyStr(oiddata->server)) {
289                         cprintf("%d There is no OpenID identity provider at this URL.\n", ERROR);
290                         return;
291                 }
292
293                 /* Empty delegate is legal; we just use the openid_url instead */
294                 if (IsEmptyStr(openid_delegate)) {
295                         safestrncpy(openid_delegate, oiddata->claimed_id, sizeof openid_delegate);
296                 }
297
298                 /* Assemble a URL to which the user-agent will be redirected. */
299                 char redirect_string[4096];
300                 char escaped_identity[512];
301                 char escaped_return_to[2048];
302                 char escaped_trust_root[1024];
303                 char escaped_sreg_optional[256];
304
305                 urlesc(escaped_identity, sizeof escaped_identity, openid_delegate);
306                 urlesc(escaped_return_to, sizeof escaped_return_to, return_to);
307                 urlesc(escaped_trust_root, sizeof escaped_trust_root, trust_root);
308                 urlesc(escaped_sreg_optional, sizeof escaped_sreg_optional,
309                         "nickname,email,fullname,postcode,country");
310
311                 snprintf(redirect_string, sizeof redirect_string,
312                         "%s"
313                         "?openid.mode=checkid_setup"
314                         "&openid.identity=%s"
315                         "&openid.return_to=%s"
316                         "&openid.trust_root=%s"
317                         "&openid.sreg.optional=%s"
318                         ,
319                         oiddata->server,
320                         escaped_identity,
321                         escaped_return_to,
322                         escaped_trust_root,
323                         escaped_sreg_optional
324                 );
325                 cprintf("%d %s\n", CIT_OK, redirect_string);
326                 return;
327         }
328
329         cprintf("%d Unable to fetch OpenID URL\n", ERROR);
330 }
331
332
333
334 /*
335  * Callback function to free a pointer (used below in the hash list)
336  */
337 void free_oid_key(void *ptr) {
338         free(ptr);
339 }
340
341
342 /*
343  * Finalize an OpenID authentication
344  */
345 void cmd_oidf(char *argbuf) {
346         char buf[2048];
347         char thiskey[1024];
348         char thisdata[1024];
349         HashList *keys = NULL;
350         HashPos *HashPos;
351         struct ctdl_openid *oiddata = (struct ctdl_openid *) CC->openid_data;
352
353         keys = NewHash(1, NULL);
354         if (!keys) {
355                 cprintf("%d NewHash() failed\n", ERROR + INTERNAL_ERROR);
356                 return;
357         }
358         
359         cprintf("%d Transmit OpenID data now\n", START_CHAT_MODE);
360
361         while (client_getln(buf, sizeof buf), strcmp(buf, "000")) {
362                 extract_token(thiskey, buf, 0, '|', sizeof thiskey);
363                 extract_token(thisdata, buf, 1, '|', sizeof thisdata);
364                 CtdlLogPrintf(CTDL_DEBUG, "%s: [%d] %s\n", thiskey, strlen(thisdata), thisdata);
365                 Put(keys, thiskey, strlen(thiskey), strdup(thisdata), free_oid_key);
366         }
367
368
369         /* Now that we have all of the parameters, we have to validate the signature against the server */
370         CtdlLogPrintf(CTDL_DEBUG, "About to validate the signature...\n");
371
372         CURL *curl;
373         CURLcode res;
374         struct curl_httppost *formpost = NULL;
375         struct curl_httppost *lastptr = NULL;
376         char errmsg[1024] = "";
377         char *o_assoc_handle = NULL;
378         char *o_sig = NULL;
379         char *o_signed = NULL;
380         int num_signed_values;
381         int i;
382         char k_keyname[128];
383         char k_o_keyname[128];
384         char *k_value = NULL;
385         char valbuf[1024];
386
387         struct fh_data fh = {
388                 valbuf,
389                 0,
390                 sizeof valbuf
391         };
392
393         curl_formadd(&formpost, &lastptr,
394                 CURLFORM_COPYNAME,      "openid.mode",
395                 CURLFORM_COPYCONTENTS,  "check_authentication",
396                 CURLFORM_END);
397         CtdlLogPrintf(CTDL_DEBUG, "%25s : %s\n", "openid.mode", "check_authentication");
398
399         if (GetHash(keys, "assoc_handle", 12, (void *) &o_assoc_handle)) {
400                 curl_formadd(&formpost, &lastptr,
401                         CURLFORM_COPYNAME,      "openid.assoc_handle",
402                         CURLFORM_COPYCONTENTS,  o_assoc_handle,
403                         CURLFORM_END);
404                 CtdlLogPrintf(CTDL_DEBUG, "%25s : %s\n", "openid.assoc_handle", o_assoc_handle);
405         }
406
407         if (GetHash(keys, "sig", 3, (void *) &o_sig)) {
408                 curl_formadd(&formpost, &lastptr,
409                         CURLFORM_COPYNAME,      "openid.sig",
410                         CURLFORM_COPYCONTENTS,  o_sig,
411                         CURLFORM_END);
412                         CtdlLogPrintf(CTDL_DEBUG, "%25s : %s\n", "openid.sig", o_sig);
413         }
414
415         if (GetHash(keys, "signed", 6, (void *) &o_signed)) {
416                 curl_formadd(&formpost, &lastptr,
417                         CURLFORM_COPYNAME,      "openid.signed",
418                         CURLFORM_COPYCONTENTS,  o_signed,
419                         CURLFORM_END);
420                 CtdlLogPrintf(CTDL_DEBUG, "%25s : %s\n", "openid.signed", o_signed);
421
422                 num_signed_values = num_tokens(o_signed, ',');
423                 for (i=0; i<num_signed_values; ++i) {
424                         extract_token(k_keyname, o_signed, i, ',', sizeof k_keyname);
425                         if (strcasecmp(k_keyname, "mode")) {    // work around phpMyID bug
426                                 if (GetHash(keys, k_keyname, strlen(k_keyname), (void *) &k_value)) {
427                                         snprintf(k_o_keyname, sizeof k_o_keyname, "openid.%s", k_keyname);
428                                         curl_formadd(&formpost, &lastptr,
429                                                 CURLFORM_COPYNAME,      k_o_keyname,
430                                                 CURLFORM_COPYCONTENTS,  k_value,
431                                                 CURLFORM_END);
432                                         CtdlLogPrintf(CTDL_DEBUG, "%25s : %s\n", k_o_keyname, k_value);
433                                 }
434                                 else {
435                                         CtdlLogPrintf(CTDL_INFO, "OpenID: signed field '%s' is missing\n",
436                                                 k_keyname);
437                                 }
438                         }
439                 }
440         }
441
442         curl = curl_easy_init();
443         curl_easy_setopt(curl, CURLOPT_URL, oiddata->server);
444         curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 0);
445         curl_easy_setopt(curl, CURLOPT_SSL_VERIFYHOST, 0);
446         curl_easy_setopt(curl, CURLOPT_WRITEDATA, &fh);
447         curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, fh_callback);
448         curl_easy_setopt(curl, CURLOPT_HTTPPOST, formpost);
449         curl_easy_setopt(curl, CURLOPT_ERRORBUFFER, errmsg);
450         curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1);
451         curl_easy_setopt(curl, CURLOPT_USERAGENT, CITADEL);
452         if (!IsEmptyStr(config.c_ip_addr)) {
453                 curl_easy_setopt(curl, CURLOPT_INTERFACE, config.c_ip_addr);
454         }
455
456         res = curl_easy_perform(curl);
457         if (res) {
458                 CtdlLogPrintf(CTDL_DEBUG, "cmd_oidf() libcurl error %d: %s\n", res, errmsg);
459         }
460         curl_easy_cleanup(curl);
461         curl_formfree(formpost);
462
463         valbuf[fh.total_bytes_received] = 0;
464         int success = 0;
465
466         if (bmstrcasestr(valbuf, "is_valid:true")) {
467                 success = 1;
468         }
469
470         CtdlLogPrintf(CTDL_DEBUG, "Authentication %s.\n", (success ? "succeeded" : "failed") );
471
472         /* Respond to the client */
473
474         if (success) {
475
476                 /* If we were already logged in, attach the OpenID to the user's account */
477                 if (CC->logged_in) {
478                         if (modify_openid_associations(&CC->user, oiddata->claimed_id, moa_attach) == 0) {
479                                 cprintf("attach\n");
480                         }
481                         else {
482                                 cprintf("fail\n");
483                         }
484                 }
485
486                 /* Otherwise, a user is attempting to log in using the validated OpenID */      
487                 else {
488                         cprintf("fail\n");              // FIXME do the login here!!
489                 }
490
491         }
492         else {
493                 cprintf("fail\n");
494         }
495         cprintf("000\n");
496
497         /* Free the hash list */
498         long len;
499         void *Value;
500         char *Key;
501
502         HashPos = GetNewHashPos();
503         while (GetNextHashPos(keys, HashPos, &len, &Key, &Value)!=0)
504         {
505                 free(Value);
506         }
507         DeleteHashPos(&HashPos);
508 }
509
510
511 // mode = [6]  id_res
512 // identity = [50]  http://uncensored.citadel.org/~ajc/MyID.config.php
513 // assoc_handle = [26]  6ekac3ju181tgepk7v4h9r7ui7
514 // return_to = [42]  http://jemcaterers.net/finish_openid_login
515 // sreg.nickname = [17]  IGnatius T Foobar
516 // sreg.email = [26]  ajc@uncensored.citadel.org
517 // sreg.fullname = [10]  Art Cancro
518 // sreg.postcode = [5]  10549
519 // sreg.country = [2]  US
520 // signed = [102]  mode,identity,assoc_handle,return_to,sreg.nickname,sreg.email,sreg.fullname,sreg.postcode,sreg.country
521 // sig = [28]  vixxxU4MAqWfxxxxCfrHv3TxxxhEw=
522
523
524
525
526 /**************************************************************************/
527 /*                                                                        */
528 /* Functions in this section handle module initialization and shutdown    */
529 /*                                                                        */
530 /**************************************************************************/
531
532
533 /*
534  * This cleanup function blows away the temporary memory used by this module.
535  */
536 void openid_cleanup_function(void) {
537
538         if (CC->openid_data != NULL) {
539                 free(CC->openid_data);
540         }
541 }
542
543
544 CTDL_MODULE_INIT(openid_rp)
545 {
546         if (!threading)
547         {
548                 curl_global_init(CURL_GLOBAL_ALL);
549                 CtdlRegisterProtoHook(cmd_oids, "OIDS", "Setup OpenID authentication");
550                 CtdlRegisterProtoHook(cmd_oidf, "OIDF", "Finalize OpenID authentication");
551                 CtdlRegisterSessionHook(openid_cleanup_function, EVT_STOP);
552                 CtdlRegisterUserHook(openid_purge, EVT_PURGEUSER);
553         }
554
555         /* return our Subversion id for the Log */
556         return "$Id$";
557 }