Begin caching OpenID data in the session; we'll need it later
[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 got_bytes;
138 }
139
140
141
142 /*
143  * Begin an HTTP fetch (returns number of bytes actually fetched, or -1 for error)
144  * We first try 'curl' or 'wget' because they have more robust HTTP handling, and also
145  * support HTTPS.  If neither one works, we fall back to a built in mini HTTP client.
146  */
147 int fetch_http(char *url, char *target_buf, int maxbytes)
148 {
149         CURL *curl;
150         CURLcode res;
151         char errmsg[1024] = "";
152         struct fh_data fh = {
153                 target_buf,
154                 0,
155                 maxbytes
156         };
157
158         if (!url) return(-1);
159         if (!target_buf) return(-1);
160         memset(target_buf, 0, maxbytes);
161
162         curl = curl_easy_init();
163         if (!curl) {
164                 CtdlLogPrintf(CTDL_ALERT, "Unable to initialize libcurl.\n");
165                 return(-1);
166         }
167
168         curl_easy_setopt(curl, CURLOPT_URL, url);
169         curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 0);
170         curl_easy_setopt(curl, CURLOPT_SSL_VERIFYHOST, 0);
171         curl_easy_setopt(curl, CURLOPT_WRITEDATA, &fh);
172         curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, fh_callback);
173         curl_easy_setopt(curl, CURLOPT_ERRORBUFFER, errmsg);
174         curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1);
175         res = curl_easy_perform(curl);
176         if (res) {
177                 CtdlLogPrintf(CTDL_DEBUG, "fetch_http() libcurl error %d: %s\n", res, errmsg);
178         }
179         curl_easy_cleanup(curl);
180         return fh.total_bytes_received;
181 }
182
183
184 /*
185  * Setup an OpenID authentication
186  */
187 void cmd_oids(char *argbuf) {
188         char return_to[1024];
189         char trust_root[1024];
190         int i;
191         char buf[SIZ];
192         struct CitContext *CCC = CC;    /* CachedCitContext - performance boost */
193         struct ctdl_openid *oiddata;
194
195         if (CCC->logged_in) {
196                 cprintf("%d Already logged in.\n", ERROR + ALREADY_LOGGED_IN);
197                 return;
198         }
199
200         if (CCC->openid_data != NULL) {
201                 free(CCC->openid_data);
202         }
203         oiddata = malloc(sizeof(struct ctdl_openid));
204         if (oiddata == NULL) {
205                 cprintf("%d malloc failed\n", ERROR + INTERNAL_ERROR);
206                 return;
207         }
208         memset(oiddata, 0, sizeof(struct ctdl_openid));
209         CCC->openid_data = (void *) oiddata;
210
211         extract_token(oiddata->claimed_id, argbuf, 0, '|', sizeof oiddata->claimed_id);
212         extract_token(return_to, argbuf, 1, '|', sizeof return_to);
213         extract_token(trust_root, argbuf, 2, '|', sizeof trust_root);
214
215         CtdlLogPrintf(CTDL_DEBUG, "Asking %s for server and delegate\n", oiddata->claimed_id);
216         i = fetch_http(oiddata->claimed_id, buf, sizeof buf - 1);
217         buf[sizeof buf - 1] = 0;
218         if (i > 0) {
219                 char openid_delegate[1024];
220
221                 extract_link(oiddata->server, sizeof oiddata->server, "openid.server", buf);
222                 extract_link(openid_delegate, sizeof openid_delegate, "openid.delegate", buf);
223
224                 if (IsEmptyStr(oiddata->server)) {
225                         cprintf("%d There is no OpenID identity provider at this URL.\n", ERROR);
226                         return;
227                 }
228
229                 /* Empty delegate is legal; we just use the openid_url instead */
230                 if (IsEmptyStr(openid_delegate)) {
231                         safestrncpy(openid_delegate, oiddata->claimed_id, sizeof openid_delegate);
232                 }
233
234                 /* Assemble a URL to which the user-agent will be redirected. */
235                 char redirect_string[4096];
236                 char escaped_identity[512];
237                 char escaped_return_to[2048];
238                 char escaped_trust_root[1024];
239                 char escaped_sreg_optional[256];
240
241                 urlesc(escaped_identity, sizeof escaped_identity, openid_delegate);
242                 urlesc(escaped_return_to, sizeof escaped_return_to, return_to);
243                 urlesc(escaped_trust_root, sizeof escaped_trust_root, trust_root);
244                 urlesc(escaped_sreg_optional, sizeof escaped_sreg_optional,
245                         "nickname,email,fullname,postcode,country");
246
247                 snprintf(redirect_string, sizeof redirect_string,
248                         "%s"
249                         "?openid.mode=checkid_setup"
250                         "&openid.identity=%s"
251                         "&openid.return_to=%s"
252                         "&openid.trust_root=%s"
253                         "&openid.sreg.optional=%s"
254                         ,
255                         oiddata->server,
256                         escaped_identity,
257                         escaped_return_to,
258                         escaped_trust_root,
259                         escaped_sreg_optional
260                 );
261                 cprintf("%d %s\n", CIT_OK, redirect_string);
262                 return;
263         }
264
265         cprintf("%d Unable to fetch OpenID URL\n", ERROR);
266 }
267
268
269
270 /*
271  * Callback function to free a pointer (used below in the hash list)
272  */
273 void free_oid_key(void *ptr) {
274         free(ptr);
275 }
276
277
278 /*
279  * Finalize an OpenID authentication
280  */
281 void cmd_oidf(char *argbuf) {
282         char buf[2048];
283         char thiskey[1024];
284         char thisdata[1024];
285         HashList *keys = NULL;
286         HashPos *HashPos;
287
288         keys = NewHash(1, NULL);
289         if (!keys) {
290                 cprintf("%d NewHash() failed\n", ERROR + INTERNAL_ERROR);
291                 return;
292         }
293         
294         cprintf("%d Transmit OpenID data now\n", START_CHAT_MODE);
295
296         while (client_getln(buf, sizeof buf), strcmp(buf, "000")) {
297                 extract_token(thiskey, buf, 0, '|', sizeof thiskey);
298                 extract_token(thisdata, buf, 1, '|', sizeof thisdata);
299                 CtdlLogPrintf(CTDL_DEBUG, "%s: [%d] %s\n", thiskey, strlen(thisdata), thisdata);
300                 Put(keys, thiskey, strlen(thiskey), strdup(thisdata), free_oid_key);
301         }
302
303
304         /* Now that we have all of the parameters, we have to validate the signature against the server */
305
306         CURL *curl;
307         CURLcode res;
308         struct curl_httppost *formpost = NULL;
309         struct curl_httppost *lastptr = NULL;
310         char errmsg[1024] = "";
311
312         curl_formadd(&formpost, &lastptr,
313                 CURLFORM_COPYNAME,      "openid.mode",
314                 CURLFORM_COPYCONTENTS,  "check_authentication",
315                 CURLFORM_END);
316
317         curl = curl_easy_init();
318         // curl_easy_setopt(curl, CURLOPT_URL, FIXME );         /* FIXME need to bring this over */
319         curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 0);
320         curl_easy_setopt(curl, CURLOPT_SSL_VERIFYHOST, 0);
321         // curl_easy_setopt(curl, CURLOPT_WRITEDATA, &fh);
322         // curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, fh_callback);
323         curl_easy_setopt(curl, CURLOPT_HTTPPOST, formpost);
324         curl_easy_setopt(curl, CURLOPT_ERRORBUFFER, errmsg);
325         curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1);
326         res = curl_easy_perform(curl);
327         if (res) {
328                 CtdlLogPrintf(CTDL_DEBUG, "cmd_oidf() libcurl error %d: %s\n", res, errmsg);
329         }
330         curl_easy_cleanup(curl);
331         curl_formfree(formpost);
332
333         /* FIXME do something with the results */
334
335         /* Respond to the client */
336         cprintf("message|FIXME finish this\n");
337         cprintf("000\n");
338
339         /* Free the hash list */
340         long len;
341         void *Value;
342         char *Key;
343
344         HashPos = GetNewHashPos();
345         while (GetNextHashPos(keys, HashPos, &len, &Key, &Value)!=0)
346         {
347                 free(Value);
348         }
349         DeleteHashPos(&HashPos);
350 }
351
352
353 // mode = [6]  id_res
354 // identity = [50]  http://uncensored.citadel.org/~ajc/MyID.config.php
355 // assoc_handle = [26]  6ekac3ju181tgepk7v4h9r7ui7
356 // return_to = [42]  http://jemcaterers.net/finish_openid_login
357 // sreg.nickname = [17]  IGnatius T Foobar
358 // sreg.email = [26]  ajc@uncensored.citadel.org
359 // sreg.fullname = [10]  Art Cancro
360 // sreg.postcode = [5]  10549
361 // sreg.country = [2]  US
362 // signed = [102]  mode,identity,assoc_handle,return_to,sreg.nickname,sreg.email,sreg.fullname,sreg.postcode,sreg.country
363 // sig = [28]  vixxxU4MAqWfxxxxCfrHv3TxxxhEw=
364
365
366 /*
367  * This cleanup function blows away the temporary memory used by this module.
368  */
369 void openid_cleanup_function(void) {
370
371         if (CC->openid_data != NULL) {
372                 free(CC->openid_data);
373         }
374 }
375
376
377
378 CTDL_MODULE_INIT(openid_rp)
379 {
380         if (!threading)
381         {
382                 curl_global_init(CURL_GLOBAL_ALL);
383                 CtdlRegisterProtoHook(cmd_oids, "OIDS", "Setup OpenID authentication");
384                 CtdlRegisterProtoHook(cmd_oidf, "OIDF", "Finalize OpenID authentication");
385                 CtdlRegisterSessionHook(openid_cleanup_function, EVT_STOP);
386         }
387
388         /* return our Subversion id for the Log */
389         return "$Id$";
390 }