hmmph. adjusted string lengths again
[citadel.git] / citadel / modules / openid / serv_openid_rp.c
1 /*
2  * $Id$
3  *
4  * OpenID 1.1 "relying party" implementation
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
36 struct associate_handle {
37         char claimed_id[256];
38         char assoc_type[32];
39         time_t expiration_time;
40         char assoc_handle[256];
41         char mac_key[128];
42 };
43
44 HashList *HL = NULL;            // hash table of assoc_handle
45
46 /* 
47  * Locate a <link> tag and, given its 'rel=' parameter, return its 'href' parameter
48  */
49 void extract_link(char *target_buf, int target_size, char *rel, char *source_buf)
50 {
51         char *ptr = source_buf;
52
53         if (!target_buf) return;
54         if (!rel) return;
55         if (!source_buf) return;
56
57         target_buf[0] = 0;
58
59         while (ptr = bmstrcasestr(ptr, "<link"), ptr != NULL) {
60
61                 char work_buffer[2048];
62                 char *link_tag_start = NULL;
63                 char *link_tag_end = NULL;
64
65                 char rel_tag[2048];
66                 char href_tag[2048];
67
68                 link_tag_start = ptr;
69                 link_tag_end = strchr(ptr, '>');
70                 rel_tag[0] = 0;
71                 href_tag[0] = 0;
72
73                 if ((link_tag_end) && (link_tag_end > link_tag_start)) {
74                         int len;
75                         len = link_tag_end - link_tag_start;
76                         if (len > sizeof work_buffer) len = sizeof work_buffer;
77                         memcpy(work_buffer, link_tag_start, len);
78                 
79                         char *rel_start = NULL;
80                         char *rel_end = NULL;
81                         rel_start = bmstrcasestr(work_buffer, "rel=");
82                         if (rel_start) {
83                                 rel_start = strchr(rel_start, '\"');
84                                 if (rel_start) {
85                                         ++rel_start;
86                                         rel_end = strchr(rel_start, '\"');
87                                         if ((rel_end) && (rel_end > rel_start)) {
88                                                 safestrncpy(rel_tag, rel_start, rel_end - rel_start + 1);
89                                         }
90                                 }
91                         }
92
93                         char *href_start = NULL;
94                         char *href_end = NULL;
95                         href_start = bmstrcasestr(work_buffer, "href=");
96                         if (href_start) {
97                                 href_start = strchr(href_start, '\"');
98                                 if (href_start) {
99                                         ++href_start;
100                                         href_end = strchr(href_start, '\"');
101                                         if ((href_end) && (href_end > href_start)) {
102                                                 safestrncpy(href_tag, href_start, href_end - href_start + 1);
103                                         }
104                                 }
105                         }
106
107                         if (!strcasecmp(rel, rel_tag)) {
108                                 safestrncpy(target_buf, href_tag, target_size);
109                                 return;
110                         }
111
112                 }
113
114         ++ptr;
115         }
116
117
118 }
119
120
121
122 struct fh_data {
123         char *buf;
124         int total_bytes_received;
125         int maxbytes;
126 };
127
128
129 size_t fh_callback(void *ptr, size_t size, size_t nmemb, void *stream)
130 {
131         struct fh_data *fh = (struct fh_data *) stream;
132         int got_bytes = (size * nmemb);
133
134         if (fh->total_bytes_received + got_bytes > fh->maxbytes) {
135                 got_bytes = fh->maxbytes - fh->total_bytes_received;
136         }
137         if (got_bytes > 0) {
138                 memcpy(&fh->buf[fh->total_bytes_received], ptr, got_bytes);
139                 fh->total_bytes_received += got_bytes;
140         }
141
142         return got_bytes;
143 }
144
145
146
147 /*
148  * Begin an HTTP fetch (returns number of bytes actually fetched, or -1 for error)
149  * We first try 'curl' or 'wget' because they have more robust HTTP handling, and also
150  * support HTTPS.  If neither one works, we fall back to a built in mini HTTP client.
151  */
152 int fetch_http(char *url, char *target_buf, int maxbytes)
153 {
154         CURL *curl;
155         CURLcode res;
156         char errmsg[1024] = "";
157         struct fh_data fh = {
158                 target_buf,
159                 0,
160                 maxbytes
161         };
162
163         if (!url) return(-1);
164         if (!target_buf) return(-1);
165         memset(target_buf, 0, maxbytes);
166
167         curl = curl_easy_init();
168         if (!curl) {
169                 CtdlLogPrintf(CTDL_ALERT, "Unable to initialize libcurl.\n");
170                 return(-1);
171         }
172
173         curl_easy_setopt(curl, CURLOPT_URL, url);
174         curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 0);
175         curl_easy_setopt(curl, CURLOPT_SSL_VERIFYHOST, 0);
176         curl_easy_setopt(curl, CURLOPT_WRITEDATA, &fh);
177         curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, fh_callback);
178         curl_easy_setopt(curl, CURLOPT_ERRORBUFFER, errmsg);
179         curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1);
180         res = curl_easy_perform(curl);
181         if (res) {
182                 CtdlLogPrintf(CTDL_DEBUG, "fetch_http() libcurl error %d: %s\n", res, errmsg);
183         }
184         curl_easy_cleanup(curl);
185         return fh.total_bytes_received;
186 }
187
188
189 #define ASSOCIATE_RESPONSE_SIZE 4096
190
191 /*
192  * libcurl callback function for prepare_openid_associate_request()
193  */
194 size_t associate_callback(void *ptr, size_t size, size_t nmemb, void *stream)
195 {
196         char *response = (char *) stream;
197         int got_bytes = (size * nmemb);
198         int len = strlen(response);
199
200         if ((len + got_bytes + 1) < ASSOCIATE_RESPONSE_SIZE) {
201                 memcpy(&response[len], ptr, got_bytes);
202                 response[len+got_bytes] = 0;
203         }
204
205         return got_bytes;
206 }
207
208
209 /*
210  * Helper function for process_associate_response()
211  * (Delete function for hash table)
212  */
213 void delete_assoc_handle(void *data) {
214         if (data) free(data);
215 }
216
217 /*
218  * Process the response from an "associate" request
219  */
220 struct associate_handle *process_associate_response(char *claimed_id, char *associate_response)
221 {
222         struct associate_handle *h = NULL;
223         char *ptr = associate_response;
224         char thisline[512];
225         char thiskey[256];
226         char thisdata[256];
227
228         h = (struct associate_handle *) malloc(sizeof(struct associate_handle));
229         safestrncpy(h->claimed_id, claimed_id, sizeof h->claimed_id);
230
231         do {
232                 ptr = memreadline(ptr, thisline, sizeof thisline);
233                 extract_token(thiskey, thisline, 0, ':', sizeof thiskey);
234                 extract_token(thisdata, thisline, 1, ':', sizeof thisdata);
235
236                 CtdlLogPrintf(CTDL_DEBUG, "Associate response: key:<%s> data:<%s>\n", thiskey, thisdata);
237
238                 if (!strcasecmp(thiskey, "assoc_type")) {
239                         safestrncpy(h->assoc_type, thisdata, sizeof h->assoc_type);
240                 }
241                 else if (!strcasecmp(thiskey, "expires_in")) {
242                         h->expiration_time = time(NULL) + atol(thisdata);
243                 }
244                 else if (!strcasecmp(thiskey, "assoc_handle")) {
245                         safestrncpy(h->assoc_handle, thisdata, sizeof h->assoc_handle);
246                 }
247                 else if (!strcasecmp(thiskey, "mac_key")) {
248                         safestrncpy(h->mac_key, thisdata, sizeof h->mac_key);
249                 }
250
251         } while (*ptr);
252
253         /* Add this data structure into the hash table */
254         Put(HL, h->assoc_handle, strlen(h->assoc_handle), h, delete_assoc_handle);
255
256         /* FIXME periodically purge the hash table of expired handles */
257
258         return h;
259 }
260
261
262
263 /*
264  * Establish a shared secret with an OpenID Identity Provider by sending
265  * an "associate" request.
266  */
267 struct associate_handle *prepare_openid_associate_request(
268                 char *claimed_id, char *openid_server, char *openid_delegate)
269 {
270         CURL *curl;
271         CURLcode res;
272         struct curl_httppost *formpost=NULL;
273         struct curl_httppost *lastptr=NULL;
274         char associate_response[ASSOCIATE_RESPONSE_SIZE];
275         struct associate_handle *h = NULL;
276
277         memset(associate_response, 0, ASSOCIATE_RESPONSE_SIZE);
278
279         curl_formadd(&formpost,
280                         &lastptr,
281                         CURLFORM_COPYNAME,      "openid.mode",
282                         CURLFORM_COPYCONTENTS,  "associate",
283                         CURLFORM_END
284         );
285
286         curl_formadd(&formpost,
287                         &lastptr,
288                         CURLFORM_COPYNAME,      "openid.session_type",
289                         CURLFORM_COPYCONTENTS,  "",
290                         CURLFORM_END
291         );
292
293         curl = curl_easy_init();
294         if (curl) {
295                 curl_easy_setopt(curl, CURLOPT_URL, openid_server);
296                 curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 0);
297                 curl_easy_setopt(curl, CURLOPT_SSL_VERIFYHOST, 0);
298                 curl_easy_setopt(curl, CURLOPT_WRITEDATA, associate_response);
299                 curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, associate_callback);
300                 curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1);
301                         
302                 curl_easy_setopt(curl, CURLOPT_HTTPPOST, formpost);
303                 res = curl_easy_perform(curl);
304                 h = process_associate_response(claimed_id, associate_response);
305                 curl_easy_cleanup(curl);
306         }
307         curl_formfree(formpost);
308
309         return h;
310 }
311
312
313
314
315
316 /*
317  * Setup an OpenID authentication
318  */
319 void cmd_oids(char *argbuf) {
320         char openid_url[1024];
321         char return_to[1024];
322         char trust_root[1024];
323         int i;
324         char buf[SIZ];
325         struct associate_handle *h = NULL;
326
327         if (CC->logged_in) {
328                 cprintf("%d Already logged in.\n", ERROR + ALREADY_LOGGED_IN);
329                 return;
330         }
331
332         extract_token(openid_url, argbuf, 0, '|', sizeof openid_url);
333         extract_token(return_to, argbuf, 1, '|', sizeof return_to);
334         extract_token(trust_root, argbuf, 2, '|', sizeof trust_root);
335
336         i = fetch_http(openid_url, buf, sizeof buf - 1);
337         buf[sizeof buf - 1] = 0;
338         if (i > 0) {
339                 char openid_server[1024];
340                 char openid_delegate[1024];
341
342                 extract_link(openid_server, sizeof openid_server, "openid.server", buf);
343                 extract_link(openid_delegate, sizeof openid_delegate, "openid.delegate", buf);
344
345                 if (IsEmptyStr(openid_server)) {
346                         cprintf("%d There is no OpenID identity provider at this URL.\n", ERROR);
347                         return;
348                 }
349
350                 /* Empty delegate is legal; we just use the openid_url instead */
351                 if (IsEmptyStr(openid_delegate)) {
352                         safestrncpy(openid_delegate, openid_url, sizeof openid_delegate);
353                 }
354
355                 /*
356                  * Prepare an "associate" request.  This contacts the IdP and fetches
357                  * a data structure containing an assoc_handle plus a shared secret.
358                  */
359                 h = prepare_openid_associate_request(openid_url, openid_server, openid_delegate);
360
361                 /* Assemble a URL to which the user-agent will be redirected. */
362                 char redirect_string[4096];
363                 char escaped_identity[512];
364                 char escaped_return_to[2048];
365                 char escaped_trust_root[1024];
366                 char escaped_sreg_optional[256];
367                 char escaped_assoc_handle[512];
368
369                 urlesc(escaped_identity, sizeof escaped_identity, openid_delegate);
370                 urlesc(escaped_assoc_handle, sizeof escaped_assoc_handle, h->assoc_handle);
371                 urlesc(escaped_return_to, sizeof escaped_return_to, return_to);
372                 urlesc(escaped_trust_root, sizeof escaped_trust_root, trust_root);
373                 urlesc(escaped_sreg_optional, sizeof escaped_sreg_optional,
374                         "nickname,email,fullname,postcode,country");
375
376                 snprintf(redirect_string, sizeof redirect_string,
377                         "%s"
378                         "?openid.mode=checkid_setup"
379                         "&openid.identity=%s"
380                         "&openid.assoc_handle=%s"
381                         "&openid.return_to=%s"
382                         "&openid.trust_root=%s"
383                         "&openid.sreg.optional=%s"
384                         ,
385                         openid_server,
386                         escaped_identity,
387                         escaped_assoc_handle,
388                         escaped_return_to,
389                         escaped_trust_root,
390                         escaped_sreg_optional
391                 );
392                 CtdlLogPrintf(CTDL_DEBUG, "Telling client about assoc_handle <%s>\n", h->assoc_handle);
393                 cprintf("%d %s\n", CIT_OK, redirect_string);
394                 return;
395         }
396
397         cprintf("%d Unable to fetch OpenID URL\n", ERROR);
398 }
399
400
401
402 /*
403  * Finalize an OpenID authentication
404  */
405 void cmd_oidf(char *argbuf) {
406         char assoc_handle[256];
407         struct associate_handle *h = NULL;
408
409         extract_token(assoc_handle, argbuf, 0, '|', sizeof assoc_handle);
410
411         if (GetHash(HL, assoc_handle, strlen(assoc_handle), (void *)&h)) {
412                 cprintf("%d handle %s is good\n", CIT_OK, assoc_handle);
413
414                 // FIXME now do something with it
415
416         }
417         else {
418                 cprintf("%d handle %s not found\n", ERROR, assoc_handle);
419         }
420 }
421
422
423
424
425 CTDL_MODULE_INIT(openid_rp)
426 {
427         if (!threading)
428         {
429                 curl_global_init(CURL_GLOBAL_ALL);
430                 HL = NewHash(1, NULL);
431                 CtdlRegisterProtoHook(cmd_oids, "OIDS", "Setup OpenID authentication");
432                 CtdlRegisterProtoHook(cmd_oidf, "OIDF", "Finalize OpenID authentication");
433         }
434
435         /* return our Subversion id for the Log */
436         return "$Id$";
437 }