openid hacks
[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
35 struct ctdl_openid {
36         char claimed_id[1024];
37         char server[1024];
38 };
39
40
41 /* 
42  * Locate a <link> tag and, given its 'rel=' parameter, return its 'href' parameter
43  */
44 void extract_link(char *target_buf, int target_size, char *rel, char *source_buf)
45 {
46         char *ptr = source_buf;
47
48         if (!target_buf) return;
49         if (!rel) return;
50         if (!source_buf) return;
51
52         target_buf[0] = 0;
53
54         while (ptr = bmstrcasestr(ptr, "<link"), ptr != NULL) {
55
56                 char work_buffer[2048];
57                 char *link_tag_start = NULL;
58                 char *link_tag_end = NULL;
59
60                 char rel_tag[2048];
61                 char href_tag[2048];
62
63                 link_tag_start = ptr;
64                 link_tag_end = strchr(ptr, '>');
65                 rel_tag[0] = 0;
66                 href_tag[0] = 0;
67
68                 if ((link_tag_end) && (link_tag_end > link_tag_start)) {
69                         int len;
70                         len = link_tag_end - link_tag_start;
71                         if (len > sizeof work_buffer) len = sizeof work_buffer;
72                         memcpy(work_buffer, link_tag_start, len);
73                 
74                         char *rel_start = NULL;
75                         char *rel_end = NULL;
76                         rel_start = bmstrcasestr(work_buffer, "rel=");
77                         if (rel_start) {
78                                 rel_start = strchr(rel_start, '\"');
79                                 if (rel_start) {
80                                         ++rel_start;
81                                         rel_end = strchr(rel_start, '\"');
82                                         if ((rel_end) && (rel_end > rel_start)) {
83                                                 safestrncpy(rel_tag, rel_start, rel_end - rel_start + 1);
84                                         }
85                                 }
86                         }
87
88                         char *href_start = NULL;
89                         char *href_end = NULL;
90                         href_start = bmstrcasestr(work_buffer, "href=");
91                         if (href_start) {
92                                 href_start = strchr(href_start, '\"');
93                                 if (href_start) {
94                                         ++href_start;
95                                         href_end = strchr(href_start, '\"');
96                                         if ((href_end) && (href_end > href_start)) {
97                                                 safestrncpy(href_tag, href_start, href_end - href_start + 1);
98                                         }
99                                 }
100                         }
101
102                         if (!strcasecmp(rel, rel_tag)) {
103                                 safestrncpy(target_buf, href_tag, target_size);
104                                 return;
105                         }
106
107                 }
108
109         ++ptr;
110         }
111
112
113 }
114
115
116
117 struct fh_data {
118         char *buf;
119         int total_bytes_received;
120         int maxbytes;
121 };
122
123
124 size_t fh_callback(void *ptr, size_t size, size_t nmemb, void *stream)
125 {
126         struct fh_data *fh = (struct fh_data *) stream;
127         int got_bytes = (size * nmemb);
128
129         if (fh->total_bytes_received + got_bytes > fh->maxbytes) {
130                 got_bytes = fh->maxbytes - fh->total_bytes_received;
131         }
132         if (got_bytes > 0) {
133                 memcpy(&fh->buf[fh->total_bytes_received], ptr, got_bytes);
134                 fh->total_bytes_received += got_bytes;
135         }
136
137         return (size * nmemb);  /* always succeed; libcurl doesn't need to know if we truncated it */
138 }
139
140
141
142 /*
143  * Begin an HTTP fetch (returns number of bytes actually fetched, or -1 for error) using libcurl.
144  *
145  * If 'normalize_len' is nonzero, the caller is specifying the buffer size of 'url', and is
146  * requesting that the effective (normalized) URL be copied back to it.
147  */
148 int fetch_http(char *url, char *target_buf, int maxbytes, int normalize_len)
149 {
150         CURL *curl;
151         CURLcode res;
152         char errmsg[1024] = "";
153         struct fh_data fh = {
154                 target_buf,
155                 0,
156                 maxbytes
157         };
158         char *effective_url = NULL;
159
160         if (!url) return(-1);
161         if (!target_buf) return(-1);
162         memset(target_buf, 0, maxbytes);
163
164         curl = curl_easy_init();
165         if (!curl) {
166                 CtdlLogPrintf(CTDL_ALERT, "Unable to initialize libcurl.\n");
167                 return(-1);
168         }
169
170         curl_easy_setopt(curl, CURLOPT_URL, url);
171         curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 0);
172         curl_easy_setopt(curl, CURLOPT_SSL_VERIFYHOST, 0);
173         curl_easy_setopt(curl, CURLOPT_WRITEDATA, &fh);
174         curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, fh_callback);
175         curl_easy_setopt(curl, CURLOPT_ERRORBUFFER, errmsg);
176         curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1);
177         curl_easy_setopt(curl, CURLOPT_USERAGENT, CITADEL);
178         // FIXME set the CURLOPT_INTERFACE
179         res = curl_easy_perform(curl);
180         if (res) {
181                 CtdlLogPrintf(CTDL_DEBUG, "fetch_http() libcurl error %d: %s\n", res, errmsg);
182         }
183         if (normalize_len > 0) {
184                 curl_easy_getinfo(curl, CURLINFO_EFFECTIVE_URL, &effective_url);
185                 safestrncpy(url, effective_url, normalize_len);
186         }
187         curl_easy_cleanup(curl);
188         return fh.total_bytes_received;
189 }
190
191
192 /*
193  * Setup an OpenID authentication
194  */
195 void cmd_oids(char *argbuf) {
196         char return_to[1024];
197         char trust_root[1024];
198         int i;
199         char buf[SIZ];
200         struct CitContext *CCC = CC;    /* CachedCitContext - performance boost */
201         struct ctdl_openid *oiddata;
202
203         if (CCC->logged_in) {
204                 cprintf("%d Already logged in.\n", ERROR + ALREADY_LOGGED_IN);
205                 return;
206         }
207
208         if (CCC->openid_data != NULL) {
209                 free(CCC->openid_data);
210         }
211         oiddata = malloc(sizeof(struct ctdl_openid));
212         if (oiddata == NULL) {
213                 cprintf("%d malloc failed\n", ERROR + INTERNAL_ERROR);
214                 return;
215         }
216         memset(oiddata, 0, sizeof(struct ctdl_openid));
217         CCC->openid_data = (void *) oiddata;
218
219         extract_token(oiddata->claimed_id, argbuf, 0, '|', sizeof oiddata->claimed_id);
220         extract_token(return_to, argbuf, 1, '|', sizeof return_to);
221         extract_token(trust_root, argbuf, 2, '|', sizeof trust_root);
222
223         i = fetch_http(oiddata->claimed_id, buf, sizeof buf - 1, sizeof oiddata->claimed_id);
224         CtdlLogPrintf(CTDL_DEBUG, "Normalized URL and Claimed ID is: %s\n", oiddata->claimed_id);
225         buf[sizeof buf - 1] = 0;
226         if (i > 0) {
227                 char openid_delegate[1024];
228
229                 extract_link(oiddata->server, sizeof oiddata->server, "openid.server", buf);
230                 extract_link(openid_delegate, sizeof openid_delegate, "openid.delegate", buf);
231
232                 if (IsEmptyStr(oiddata->server)) {
233                         cprintf("%d There is no OpenID identity provider at this URL.\n", ERROR);
234                         return;
235                 }
236
237                 /* Empty delegate is legal; we just use the openid_url instead */
238                 if (IsEmptyStr(openid_delegate)) {
239                         safestrncpy(openid_delegate, oiddata->claimed_id, sizeof openid_delegate);
240                 }
241
242                 /* Assemble a URL to which the user-agent will be redirected. */
243                 char redirect_string[4096];
244                 char escaped_identity[512];
245                 char escaped_return_to[2048];
246                 char escaped_trust_root[1024];
247                 char escaped_sreg_optional[256];
248
249                 urlesc(escaped_identity, sizeof escaped_identity, openid_delegate);
250                 urlesc(escaped_return_to, sizeof escaped_return_to, return_to);
251                 urlesc(escaped_trust_root, sizeof escaped_trust_root, trust_root);
252                 urlesc(escaped_sreg_optional, sizeof escaped_sreg_optional,
253                         "nickname,email,fullname,postcode,country");
254
255                 snprintf(redirect_string, sizeof redirect_string,
256                         "%s"
257                         "?openid.mode=checkid_setup"
258                         "&openid.identity=%s"
259                         "&openid.return_to=%s"
260                         "&openid.trust_root=%s"
261                         "&openid.sreg.optional=%s"
262                         ,
263                         oiddata->server,
264                         escaped_identity,
265                         escaped_return_to,
266                         escaped_trust_root,
267                         escaped_sreg_optional
268                 );
269                 cprintf("%d %s\n", CIT_OK, redirect_string);
270                 return;
271         }
272
273         cprintf("%d Unable to fetch OpenID URL\n", ERROR);
274 }
275
276
277
278 /*
279  * Callback function to free a pointer (used below in the hash list)
280  */
281 void free_oid_key(void *ptr) {
282         free(ptr);
283 }
284
285
286 /*
287  * Finalize an OpenID authentication
288  */
289 void cmd_oidf(char *argbuf) {
290         char buf[2048];
291         char thiskey[1024];
292         char thisdata[1024];
293         HashList *keys = NULL;
294         HashPos *HashPos;
295         struct ctdl_openid *oiddata = (struct ctdl_openid *) CC->openid_data;
296
297         keys = NewHash(1, NULL);
298         if (!keys) {
299                 cprintf("%d NewHash() failed\n", ERROR + INTERNAL_ERROR);
300                 return;
301         }
302         
303         cprintf("%d Transmit OpenID data now\n", START_CHAT_MODE);
304
305         while (client_getln(buf, sizeof buf), strcmp(buf, "000")) {
306                 extract_token(thiskey, buf, 0, '|', sizeof thiskey);
307                 extract_token(thisdata, buf, 1, '|', sizeof thisdata);
308                 CtdlLogPrintf(CTDL_DEBUG, "%s: [%d] %s\n", thiskey, strlen(thisdata), thisdata);
309                 Put(keys, thiskey, strlen(thiskey), strdup(thisdata), free_oid_key);
310         }
311
312
313         /* Now that we have all of the parameters, we have to validate the signature against the server */
314         CtdlLogPrintf(CTDL_DEBUG, "About to validate the signature...\n");
315
316         CURL *curl;
317         CURLcode res;
318         struct curl_httppost *formpost = NULL;
319         struct curl_httppost *lastptr = NULL;
320         char errmsg[1024] = "";
321         char *o_assoc_handle = NULL;
322         char *o_sig = NULL;
323         char *o_signed = NULL;
324         int num_signed_values;
325         int i;
326         char k_keyname[128];
327         char k_o_keyname[128];
328         char *k_value = NULL;
329
330         curl_formadd(&formpost, &lastptr,
331                 CURLFORM_COPYNAME,      "openid.mode",
332                 CURLFORM_COPYCONTENTS,  "check_authentication",
333                 CURLFORM_END);
334
335         if (GetHash(keys, "assoc_handle", 12, (void *) &o_assoc_handle)) {
336                 curl_formadd(&formpost, &lastptr,
337                         CURLFORM_COPYNAME,      "openid.assoc_handle",
338                         CURLFORM_COPYCONTENTS,  o_assoc_handle,
339                         CURLFORM_END);
340         }
341
342         if (GetHash(keys, "sig", 3, (void *) &o_sig)) {
343                 curl_formadd(&formpost, &lastptr,
344                         CURLFORM_COPYNAME,      "openid.sig",
345                         CURLFORM_COPYCONTENTS,  o_sig,
346                         CURLFORM_END);
347         }
348
349         if (GetHash(keys, "signed", 6, (void *) &o_signed)) {
350                 curl_formadd(&formpost, &lastptr,
351                         CURLFORM_COPYNAME,      "openid.signed",
352                         CURLFORM_COPYCONTENTS,  o_signed,
353                         CURLFORM_END);
354
355                 num_signed_values = num_tokens(o_signed, ',');
356                 for (i=0; i<num_signed_values; ++i) {
357                         extract_token(k_keyname, o_signed, i, ',', sizeof k_keyname);
358                         if (GetHash(keys, k_keyname, strlen(k_keyname), (void *) &k_value)) {
359                                 snprintf(k_o_keyname, sizeof k_o_keyname, "openid.%s", k_keyname);
360                                 curl_formadd(&formpost, &lastptr,
361                                         CURLFORM_COPYNAME,      k_o_keyname,
362                                         CURLFORM_COPYCONTENTS,  k_value,
363                                         CURLFORM_END);
364                         }
365                 }
366         }
367
368         curl = curl_easy_init();
369         curl_easy_setopt(curl, CURLOPT_URL, oiddata->server);
370         curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 0);
371         curl_easy_setopt(curl, CURLOPT_SSL_VERIFYHOST, 0);
372         // curl_easy_setopt(curl, CURLOPT_WRITEDATA, &fh);
373         // curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, fh_callback);
374         curl_easy_setopt(curl, CURLOPT_HTTPPOST, formpost);
375         curl_easy_setopt(curl, CURLOPT_POST, 1);
376         curl_easy_setopt(curl, CURLOPT_ERRORBUFFER, errmsg);
377         curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1);
378         curl_easy_setopt(curl, CURLOPT_USERAGENT, CITADEL);
379         // FIXME set the CURLOPT_INTERFACE
380         res = curl_easy_perform(curl);
381         if (res) {
382                 CtdlLogPrintf(CTDL_DEBUG, "cmd_oidf() libcurl error %d: %s\n", res, errmsg);
383         }
384         curl_easy_cleanup(curl);
385         curl_formfree(formpost);
386
387         /* FIXME do something with the results */
388
389         /* Respond to the client */
390         cprintf("message|FIXME finish this\n");
391         cprintf("000\n");
392
393         /* Free the hash list */
394         long len;
395         void *Value;
396         char *Key;
397
398         HashPos = GetNewHashPos();
399         while (GetNextHashPos(keys, HashPos, &len, &Key, &Value)!=0)
400         {
401                 free(Value);
402         }
403         DeleteHashPos(&HashPos);
404 }
405
406
407 // mode = [6]  id_res
408 // identity = [50]  http://uncensored.citadel.org/~ajc/MyID.config.php
409 // assoc_handle = [26]  6ekac3ju181tgepk7v4h9r7ui7
410 // return_to = [42]  http://jemcaterers.net/finish_openid_login
411 // sreg.nickname = [17]  IGnatius T Foobar
412 // sreg.email = [26]  ajc@uncensored.citadel.org
413 // sreg.fullname = [10]  Art Cancro
414 // sreg.postcode = [5]  10549
415 // sreg.country = [2]  US
416 // signed = [102]  mode,identity,assoc_handle,return_to,sreg.nickname,sreg.email,sreg.fullname,sreg.postcode,sreg.country
417 // sig = [28]  vixxxU4MAqWfxxxxCfrHv3TxxxhEw=
418
419
420 /*
421  * This cleanup function blows away the temporary memory used by this module.
422  */
423 void openid_cleanup_function(void) {
424
425         if (CC->openid_data != NULL) {
426                 free(CC->openid_data);
427         }
428 }
429
430
431
432 CTDL_MODULE_INIT(openid_rp)
433 {
434         if (!threading)
435         {
436                 curl_global_init(CURL_GLOBAL_ALL);
437                 CtdlRegisterProtoHook(cmd_oids, "OIDS", "Setup OpenID authentication");
438                 CtdlRegisterProtoHook(cmd_oidf, "OIDF", "Finalize OpenID authentication");
439                 CtdlRegisterSessionHook(openid_cleanup_function, EVT_STOP);
440         }
441
442         /* return our Subversion id for the Log */
443         return "$Id$";
444 }