forked from bmuller/mod_auth_openid
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhttp_helpers.cpp
328 lines (293 loc) · 12.2 KB
/
http_helpers.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
/*
Copyright (C) 2007-2010 Butterfat, LLC (http://butterfat.net)
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the "Software"), to deal in the Software without
restriction, including without limitation the rights to use,
copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following
conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
Created by bmuller <[email protected]>
*/
#include "mod_auth_openid.h"
namespace modauthopenid {
using namespace std;
int http_sendstring(request_rec *r, string s, int success_rvalue) {
// no idea why the following line only sometimes worked.....
//apr_table_setn(r->headers_out, "Content-Type", "text/html");
ap_set_content_type(r, "text/html");
const char *c_s = s.c_str();
conn_rec *c = r->connection;
apr_bucket *b;
apr_bucket_brigade *bb = apr_brigade_create(r->pool, c->bucket_alloc);
b = apr_bucket_transient_create(c_s, strlen(c_s), c->bucket_alloc);
APR_BRIGADE_INSERT_TAIL(bb, b);
b = apr_bucket_eos_create(c->bucket_alloc);
APR_BRIGADE_INSERT_TAIL(bb, b);
if (ap_pass_brigade(r->output_filters, bb) != APR_SUCCESS)
return HTTP_INTERNAL_SERVER_ERROR;
return success_rvalue;
};
int send_form_post(request_rec *r, string location) {
string::size_type last = location.find('?', 0);
string url = (last != string::npos) ? location.substr(0, last) : location;
params_t params;
if(url.size() < location.size())
params = parse_query_string(location.substr(url.size()+1));
string inputs = "";
map<string,string>::iterator iter;
for(iter = params.begin(); iter != params.end(); iter++) {
string key(iter->first);
inputs += "<input type=\"hidden\" name=\"" + key + "\" value=\"" + params[key] + "\" />";
}
string result =
"<html><head><title>redirection</title></head><body onload=\"document.getElementById('form').submit();\">"
"This page will automatically redirect you to your identity provider. "
"If you are not immediately redirected, click the submit button below."
"<form id=\"form\" action=\"" + url + "\" method=\"post\">" + inputs + "<input type=\"submit\" value=\"submit\">"
"</form></body></html>";
// return HTTP_UNAUTHORIZED so that no further modules can produce output
return http_sendstring(r, result, HTTP_UNAUTHORIZED);
};
int http_redirect(request_rec *r, string location) {
// Because IE is retarded, we have to do a form post if the URL is too big (over 2048 characters)
if(location.size() > 2000) {
debug("Redirecting via POST to: " + location);
return send_form_post(r, location);
} else {
debug("Redirecting via HTTP_MOVED_TEMPORARILY to: " + location);
apr_table_set(r->headers_out, "Location", location.c_str());
apr_table_setn(r->headers_out, "Cache-Control", "no-cache");
return HTTP_MOVED_TEMPORARILY;
}
};
int show_html_input(request_rec *r, string msg) {
opkele::params_t params;
if(r->args != NULL)
params = parse_query_string(string(r->args));
string identity = params.has_param("openid_identifier") ? params.get_param("openid_identifier") : "";
remove_openid_vars(params);
map<string,string>::iterator iter;
string args = "";
string key, value;
for(iter = params.begin(); iter != params.end(); iter++) {
key = html_escape(iter->first);
value = html_escape(iter->second);
args += "<input type=\"hidden\" name=\"" + key + "\" value = \"" + value + "\" />";
}
string result =
"<html><head><title>Protected Location</title><style type=\"text/css\">"
"#msg { border: 1px solid #ff0000; background: #ffaaaa; font-weight: bold; padding: 10px; }\n"
"a { text-decoration: none; }\n"
"a:hover { text-decoration: underline; }\n"
"#desc { border: 1px solid #000; background: #ccc; padding: 10px; }\n"
"#sig { text-align: center; font-style: italic; margin-top: 50px; color: #777; font-size: .7em; }\n"
"#sig a { color: #222; }\n"
".loginbox { background: url(http://www.openid.net/login-bg.gif) no-repeat; background-color: #fff; " // logo location is in 1.1 spec, should stay same
" background-position: 0 50%; color: #000; padding-left: 18px; }\n"
"form { margin: 15px; }\n"
"</style></head><body>"
"<h1>Protected Location</h1>"
"<p id=\"desc\">This site is protected and requires that you identify yourself with an "
"<a href=\"http://openid.net\">OpenID</a> url. To find out how it works, see "
"<a href=\"http://openid.net/what/\">http://openid.net/what/</a>. You can sign up for "
"an identity on one of the sites listed <a href=\"http://openid.net/get/\">here</a>.</p>"
+ (msg.empty()?"":"<div id=\"msg\">"+msg+"</div>") +
"<form action=\"\" method=\"get\">"
"<b>Identity URL:</b> <input type=\"text\" name=\"openid_identifier\" value=\""+identity+"\" size=\"30\" class=\"loginbox\" />"
"<input type=\"submit\" value=\"Log In\" />" + args +
"</form>"
"<div id=\"sig\">protected by <a href=\"" + PACKAGE_URL + "\">" + PACKAGE_STRING + "</a></div>"
"<body></html>";
// return HTTP_UNAUTHORIZED so that no further modules can produce output
return http_sendstring(r, result, HTTP_UNAUTHORIZED);
};
void get_session_id(request_rec *r, string cookie_name, string& session_id) {
const char * cookies_c = apr_table_get(r->headers_in, "Cookie");
if(cookies_c == NULL)
return;
string cookies(cookies_c);
vector<string> pairs = explode(cookies, ";");
for(string::size_type i = 0; i < pairs.size(); i++) {
vector<string> pair = explode(pairs[i], "=");
if(pair.size() == 2) {
string key = pair[0];
strip(key);
string value = pair[1];
strip(value);
debug("cookie sent by client: \""+key+"\"=\""+value+"\"");
if(key == cookie_name) {
session_id = pair[1];
return;
}
}
}
};
// get the base directory of the url
void base_dir(string path, string& s) {
// guaranteed that path will at least be "/" - but just to be safe...
if(path.size() == 0)
return;
string::size_type q = path.find('?', 0);
int i;
if(q != string::npos)
i = path.find_last_of('/', q);
else
i = path.find_last_of('/');
s = path.substr(0, i+1);
};
// assuming the url given will begin with http(s):// - worst case, return blank string
string get_queryless_url(string url) {
if(url.size() < 8)
return "";
if(url.find("http://",0) != string::npos || url.find("https://",0) != string::npos) {
string::size_type last = url.find('?', 8);
if(last != string::npos)
return url.substr(0, last);
return url;
}
return "";
};
void remove_openid_vars(params_t& params) {
map<string,string>::iterator iter;
for(iter = params.begin(); iter != params.end(); iter++) {
string param_key(iter->first);
// if starts with openid. or modauthopenid. (for the nonce) or openid_identifier (the login) remove it
if((param_key.substr(0, 7) == "openid." || param_key.substr(0, 14) == "modauthopenid." || param_key == "openid_identifier")) {
params.erase(param_key);
// stupid map iterator screws up if we just continue the iteration...
// so recursion to the rescue - we'll delete them one at a time
remove_openid_vars(params);
return;
}
}
};
void get_extension_params(params_t& extparams, params_t& params) {
map<string,string>::iterator iter;
extparams.reset_fields();
for(iter = params.begin(); iter != params.end(); iter++) {
string param_key(iter->first);
vector<string> parts = explode(param_key, ".");
// if there is more than one "." in the param name then we're
// dealing with an extension parameter
if(parts.size() > 2)
extparams[param_key] = params[param_key];
}
};
// for each key/value in params_one, set params_two[key] = value
void merge_params(params_t& params_one, params_t& params_two) {
map<string,string>::iterator iter;
for(iter = params_one.begin(); iter != params_one.end(); iter++) {
string param_key(iter->first);
params_two[param_key] = params_one[param_key];
}
};
// This isn't a true html_escape function, but rather escapes just enough to get by for
// quoted values - <blah name="stuff to be escaped">
string html_escape(string s) {
s = str_replace("\"", """, s);
s = str_replace("<", "<", s);
s = str_replace(">", ">", s);
return s;
};
string url_decode(const string& str) {
char * t = curl_unescape(str.c_str(),str.length());
if(!t)
throw failed_conversion(OPKELE_CP_ "failed to curl_unescape()");
string rv(t);
curl_free(t);
return rv;
};
params_t parse_query_string(const string& str) {
params_t p;
if(str.size() == 0) return p;
vector<string> pairs = explode(str, "&");
for(unsigned int i=0; i < pairs.size(); i++) {
string::size_type loc = pairs[i].find( "=", 0 );
// if loc found and loc isn't last char in string
if( loc != string::npos && loc != str.size()-1) {
string key = url_decode(pairs[i].substr(0, loc));
string value = url_decode(pairs[i].substr(loc+1));
p[key] = value;
}
}
return p;
};
void make_cookie_value(string& cookie_value, const string& name, const string& session_id, const string& path, int cookie_lifespan) {
if(cookie_lifespan == 0) {
cookie_value = name + "=" + session_id + "; path=" + path;
} else {
time_t t;
t = time(NULL) + cookie_lifespan;
struct tm *tmp;
tmp = gmtime(&t);
char expires[200];
strftime(expires, sizeof(expires), "%a, %d-%b-%Y %H:%M:%S GMT", tmp);
cookie_value = name + "=" + session_id + "; expires=" + string(expires) + "; path=" + path;
}
};
// Get the post query string from a HTTP POST
bool get_post_data(request_rec *r, string& qs) {
// check to make sure the right content type was used
const char *type = apr_table_get(r->headers_in, "Content-Type");
if (strcasecmp(type, DEFAULT_POST_ENCTYPE) != 0)
return false;
apr_bucket_brigade *bb = apr_brigade_create(r->pool, r->connection->bucket_alloc);
apr_status_t ret;
int seen_eos, child_stopped_reading;
seen_eos = child_stopped_reading = 0;
char *query_string = NULL;
do {
ret = ap_get_brigade(r->input_filters, bb, AP_MODE_READBYTES, APR_BLOCK_READ, 8192);
if(ret != APR_SUCCESS)
return false;
apr_bucket *bucket;
for(bucket=APR_BRIGADE_FIRST(bb); bucket!=APR_BRIGADE_SENTINEL(bb); bucket=APR_BUCKET_NEXT(bucket)) {
apr_size_t len;
const char *data;
if(APR_BUCKET_IS_EOS(bucket)) {
seen_eos = 1;
break;
}
if(APR_BUCKET_IS_FLUSH(bucket))
continue;
if(child_stopped_reading)
continue;
ret = apr_bucket_read(bucket, &data, &len, APR_BLOCK_READ);
if(ret != APR_SUCCESS) {
child_stopped_reading = 1;
} else {
if (query_string == NULL)
query_string = apr_pstrdup(r->pool, data);
else
query_string = apr_pstrcat(r->pool, query_string, data, NULL);
}
}
apr_brigade_cleanup(bb);
} while (!seen_eos);
qs = (query_string == NULL) ? "" : string(query_string);
return true;
};
// Get request parameters - whether POST or GET
void get_request_params(request_rec *r, params_t& params) {
string query;
if(r->method_number == M_GET && r->args != NULL) {
debug("Request GET params: " + string(r->args));
params = parse_query_string(string(r->args));
} else if(r->method_number == M_POST && get_post_data(r, query)) {
debug("Request POST params: " + query);
params = parse_query_string(query);
}
};
}