summaryrefslogtreecommitdiffabout
path: root/lib
Unidiff
Diffstat (limited to 'lib') (more/less context) (ignore whitespace changes)
-rw-r--r--lib/consumer.cc6
-rw-r--r--lib/util.cc6
2 files changed, 6 insertions, 6 deletions
diff --git a/lib/consumer.cc b/lib/consumer.cc
index 66db7dd..9f7530f 100644
--- a/lib/consumer.cc
+++ b/lib/consumer.cc
@@ -1,413 +1,413 @@
1#include <algorithm> 1#include <algorithm>
2#include <cassert> 2#include <cassert>
3#include <cstring> 3#include <cstring>
4#include <opkele/util.h> 4#include <opkele/util.h>
5#include <opkele/curl.h> 5#include <opkele/curl.h>
6#include <opkele/exception.h> 6#include <opkele/exception.h>
7#include <opkele/data.h> 7#include <opkele/data.h>
8#include <opkele/consumer.h> 8#include <opkele/consumer.h>
9#include <openssl/sha.h> 9#include <openssl/sha.h>
10#include <openssl/hmac.h> 10#include <openssl/hmac.h>
11#include <iostream> 11#include <iostream>
12 12
13#include "config.h" 13#include "config.h"
14 14
15#include <pcre.h> 15#include <pcre.h>
16 16
17namespace opkele { 17namespace opkele {
18 using namespace std; 18 using namespace std;
19 using util::curl_t; 19 using util::curl_t;
20 20
21 template<int lim> 21 template<int lim>
22 class curl_fetch_string_t : public curl_t { 22 class curl_fetch_string_t : public curl_t {
23 public: 23 public:
24 curl_fetch_string_t(CURL *c) 24 curl_fetch_string_t(CURL *c)
25 : curl_t(c) { } 25 : curl_t(c) { }
26 ~curl_fetch_string_t() throw() { } 26 ~curl_fetch_string_t() throw() { }
27 27
28 string response; 28 string response;
29 29
30 size_t write(void *p,size_t size,size_t nmemb) { 30 size_t write(void *p,size_t size,size_t nmemb) {
31 size_t bytes = size*nmemb; 31 size_t bytes = size*nmemb;
32 size_t get = min(lim-response.length(),bytes); 32 size_t get = min(lim-response.length(),bytes);
33 response.append((const char *)p,get); 33 response.append((const char *)p,get);
34 return get; 34 return get;
35 } 35 }
36 }; 36 };
37 37
38 typedef curl_fetch_string_t<16384> curl_pick_t; 38 typedef curl_fetch_string_t<16384> curl_pick_t;
39 39
40 class pcre_matches_t { 40 class pcre_matches_t {
41 public: 41 public:
42 int *_ov; 42 int *_ov;
43 int _s; 43 int _s;
44 44
45 pcre_matches_t() : _ov(0), _s(0) { } 45 pcre_matches_t() : _ov(0), _s(0) { }
46 pcre_matches_t(int s) : _ov(0), _s(s) { 46 pcre_matches_t(int s) : _ov(0), _s(s) {
47 if(_s&1) ++_s; 47 if(_s&1) ++_s;
48 _s += _s>>1; 48 _s += _s>>1;
49 _ov = new int[_s]; 49 _ov = new int[_s];
50 } 50 }
51 ~pcre_matches_t() throw() { if(_ov) delete[] _ov; } 51 ~pcre_matches_t() throw() { if(_ov) delete[] _ov; }
52 52
53 int begin(int i) const { return _ov[i<<1]; } 53 int begin(int i) const { return _ov[i<<1]; }
54 int end(int i) const { return _ov[(i<<1)+1]; } 54 int end(int i) const { return _ov[(i<<1)+1]; }
55 int length(int i) const { int t=i<<1; return _ov[t+1]-_ov[t]; } 55 int length(int i) const { int t=i<<1; return _ov[t+1]-_ov[t]; }
56 }; 56 };
57 57
58 class pcre_t { 58 class pcre_t {
59 public: 59 public:
60 pcre *_p; 60 pcre *_p;
61 61
62 pcre_t() : _p(0) { } 62 pcre_t() : _p(0) { }
63 pcre_t(pcre *p) : _p(p) { } 63 pcre_t(pcre *p) : _p(p) { }
64 pcre_t(const char *re,int opts) : _p(0) { 64 pcre_t(const char *re,int opts) : _p(0) {
65 static const char *errptr; static int erroffset; 65 static const char *errptr; static int erroffset;
66 _p = pcre_compile(re,opts,&errptr,&erroffset,NULL); 66 _p = pcre_compile(re,opts,&errptr,&erroffset,NULL);
67 if(!_p) 67 if(!_p)
68 throw internal_error(OPKELE_CP_ string("Failed to compile regexp: ")+errptr); 68 throw internal_error(OPKELE_CP_ string("Failed to compile regexp: ")+errptr);
69 } 69 }
70 ~pcre_t() throw() { if(_p) (*pcre_free)(_p); } 70 ~pcre_t() throw() { if(_p) (*pcre_free)(_p); }
71 71
72 pcre_t& operator=(pcre *p) { if(_p) (*pcre_free)(_p); _p=p; return *this; } 72 pcre_t& operator=(pcre *p) { if(_p) (*pcre_free)(_p); _p=p; return *this; }
73 73
74 operator const pcre*(void) const { return _p; } 74 operator const pcre*(void) const { return _p; }
75 operator pcre*(void) { return _p; } 75 operator pcre*(void) { return _p; }
76 76
77 int exec(const string& s,pcre_matches_t& m) { 77 int exec(const string& s,pcre_matches_t& m) {
78 if(!_p) 78 if(!_p)
79 throw internal_error(OPKELE_CP_ "Trying to execute absent regexp"); 79 throw internal_error(OPKELE_CP_ "Trying to execute absent regexp");
80 return pcre_exec(_p,NULL,s.c_str(),s.length(),0,0,m._ov,m._s); 80 return pcre_exec(_p,NULL,s.c_str(),s.length(),0,0,m._ov,m._s);
81 } 81 }
82 }; 82 };
83 83
84 assoc_t consumer_t::associate(const string& server) { 84 assoc_t consumer_t::associate(const string& server) {
85 util::dh_t dh = DH_new(); 85 util::dh_t dh = DH_new();
86 if(!dh) 86 if(!dh)
87 throw exception_openssl(OPKELE_CP_ "failed to DH_new()"); 87 throw exception_openssl(OPKELE_CP_ "failed to DH_new()");
88 dh->p = util::dec_to_bignum(data::_default_p); 88 dh->p = util::dec_to_bignum(data::_default_p);
89 dh->g = util::dec_to_bignum(data::_default_g); 89 dh->g = util::dec_to_bignum(data::_default_g);
90 if(!DH_generate_key(dh)) 90 if(!DH_generate_key(dh))
91 throw exception_openssl(OPKELE_CP_ "failed to DH_generate_key()"); 91 throw exception_openssl(OPKELE_CP_ "failed to DH_generate_key()");
92 string request = 92 string request =
93 "openid.mode=associate" 93 "openid.mode=associate"
94 "&openid.assoc_type=HMAC-SHA1" 94 "&openid.assoc_type=HMAC-SHA1"
95 "&openid.session_type=DH-SHA1" 95 "&openid.session_type=DH-SHA1"
96 "&openid.dh_consumer_public="; 96 "&openid.dh_consumer_public=";
97 request += util::url_encode(util::bignum_to_base64(dh->pub_key)); 97 request += util::url_encode(util::bignum_to_base64(dh->pub_key));
98 curl_pick_t curl = curl_pick_t::easy_init(); 98 curl_pick_t curl = curl_pick_t::easy_init();
99 if(!curl) 99 if(!curl)
100 throw exception_curl(OPKELE_CP_ "failed to initialize curl"); 100 throw exception_curl(OPKELE_CP_ "failed to initialize curl");
101 CURLcode r; 101 CURLcode r;
102 (r=curl.misc_sets()) 102 (r=curl.misc_sets())
103 || (r=curl.easy_setopt(CURLOPT_URL,server.c_str())) 103 || (r=curl.easy_setopt(CURLOPT_URL,server.c_str()))
104 || (r=curl.easy_setopt(CURLOPT_POST,1)) 104 || (r=curl.easy_setopt(CURLOPT_POST,1))
105 || (r=curl.easy_setopt(CURLOPT_POSTFIELDS,request.data())) 105 || (r=curl.easy_setopt(CURLOPT_POSTFIELDS,request.data()))
106 || (r=curl.easy_setopt(CURLOPT_POSTFIELDSIZE,request.length())) 106 || (r=curl.easy_setopt(CURLOPT_POSTFIELDSIZE,request.length()))
107 || (r=curl.set_write()) 107 || (r=curl.set_write())
108 ; 108 ;
109 if(r) 109 if(r)
110 throw exception_curl(OPKELE_CP_ "failed to set curly options",r); 110 throw exception_curl(OPKELE_CP_ "failed to set curly options",r);
111 if( (r=curl.easy_perform()) ) 111 if( (r=curl.easy_perform()) )
112 throw exception_curl(OPKELE_CP_ "failed to perform curly request",r); 112 throw exception_curl(OPKELE_CP_ "failed to perform curly request",r);
113 params_t p; p.parse_keyvalues(curl.response); 113 params_t p; p.parse_keyvalues(curl.response);
114 if(p.has_param("assoc_type") && p.get_param("assoc_type")!="HMAC-SHA1") 114 if(p.has_param("assoc_type") && p.get_param("assoc_type")!="HMAC-SHA1")
115 throw bad_input(OPKELE_CP_ "unsupported assoc_type"); 115 throw bad_input(OPKELE_CP_ "unsupported assoc_type");
116 string st; 116 string st;
117 if(p.has_param("session_type")) st = p.get_param("session_type"); 117 if(p.has_param("session_type")) st = p.get_param("session_type");
118 if((!st.empty()) && st!="DH-SHA1") 118 if((!st.empty()) && st!="DH-SHA1")
119 throw bad_input(OPKELE_CP_ "unsupported session_type"); 119 throw bad_input(OPKELE_CP_ "unsupported session_type");
120 secret_t secret; 120 secret_t secret;
121 if(st.empty()) { 121 if(st.empty()) {
122 secret.from_base64(p.get_param("mac_key")); 122 secret.from_base64(p.get_param("mac_key"));
123 }else{ 123 }else{
124 util::bignum_t s_pub = util::base64_to_bignum(p.get_param("dh_server_public")); 124 util::bignum_t s_pub = util::base64_to_bignum(p.get_param("dh_server_public"));
125 vector<unsigned char> ck(DH_size(dh)+1); 125 vector<unsigned char> ck(DH_size(dh)+1);
126 unsigned char *ckptr = &(ck.front())+1; 126 unsigned char *ckptr = &(ck.front())+1;
127 int cklen = DH_compute_key(ckptr,s_pub,dh); 127 int cklen = DH_compute_key(ckptr,s_pub,dh);
128 if(cklen<0) 128 if(cklen<0)
129 throw exception_openssl(OPKELE_CP_ "failed to DH_compute_key()"); 129 throw exception_openssl(OPKELE_CP_ "failed to DH_compute_key()");
130 if(cklen && (*ckptr)&0x80) { 130 if(cklen && (*ckptr)&0x80) {
131 (*(--ckptr)) = 0; ++cklen; 131 (*(--ckptr)) = 0; ++cklen;
132 } 132 }
133 unsigned char key_sha1[SHA_DIGEST_LENGTH]; 133 unsigned char key_sha1[SHA_DIGEST_LENGTH];
134 SHA1(ckptr,cklen,key_sha1); 134 SHA1(ckptr,cklen,key_sha1);
135 secret.enxor_from_base64(key_sha1,p.get_param("enc_mac_key")); 135 secret.enxor_from_base64(key_sha1,p.get_param("enc_mac_key"));
136 } 136 }
137 int expires_in = 0; 137 int expires_in = 0;
138 if(p.has_param("expires_in")) { 138 if(p.has_param("expires_in")) {
139 expires_in = util::string_to_long(p.get_param("expires_in")); 139 expires_in = util::string_to_long(p.get_param("expires_in"));
140 }else if(p.has_param("issued") && p.has_param("expiry")) { 140 }else if(p.has_param("issued") && p.has_param("expiry")) {
141 expires_in = util::w3c_to_time(p.get_param("expiry"))-util::w3c_to_time(p.get_param("issued")); 141 expires_in = util::w3c_to_time(p.get_param("expiry"))-util::w3c_to_time(p.get_param("issued"));
142 }else 142 }else
143 throw bad_input(OPKELE_CP_ "no expiration information"); 143 throw bad_input(OPKELE_CP_ "no expiration information");
144 return store_assoc(server,p.get_param("assoc_handle"),secret,expires_in); 144 return store_assoc(server,p.get_param("assoc_handle"),secret,expires_in);
145 } 145 }
146 146
147 string consumer_t::checkid_immediate(const string& identity,const string& return_to,const string& trust_root,extension_t *ext) { 147 string consumer_t::checkid_immediate(const string& identity,const string& return_to,const string& trust_root,extension_t *ext) {
148 return checkid_(mode_checkid_immediate,identity,return_to,trust_root,ext); 148 return checkid_(mode_checkid_immediate,identity,return_to,trust_root,ext);
149 } 149 }
150 string consumer_t::checkid_setup(const string& identity,const string& return_to,const string& trust_root,extension_t *ext) { 150 string consumer_t::checkid_setup(const string& identity,const string& return_to,const string& trust_root,extension_t *ext) {
151 return checkid_(mode_checkid_setup,identity,return_to,trust_root,ext); 151 return checkid_(mode_checkid_setup,identity,return_to,trust_root,ext);
152 } 152 }
153 string consumer_t::checkid_(mode_t mode,const string& identity,const string& return_to,const string& trust_root,extension_t *ext) { 153 string consumer_t::checkid_(mode_t mode,const string& identity,const string& return_to,const string& trust_root,extension_t *ext) {
154 params_t p; 154 params_t p;
155 if(mode==mode_checkid_immediate) 155 if(mode==mode_checkid_immediate)
156 p["mode"]="checkid_immediate"; 156 p["mode"]="checkid_immediate";
157 else if(mode==mode_checkid_setup) 157 else if(mode==mode_checkid_setup)
158 p["mode"]="checkid_setup"; 158 p["mode"]="checkid_setup";
159 else 159 else
160 throw bad_input(OPKELE_CP_ "unknown checkid_* mode"); 160 throw bad_input(OPKELE_CP_ "unknown checkid_* mode");
161 string iurl = canonicalize(identity); 161 string iurl = canonicalize(identity);
162 string server, delegate; 162 string server, delegate;
163 retrieve_links(iurl,server,delegate); 163 retrieve_links(iurl,server,delegate);
164 p["identity"] = delegate.empty()?iurl:delegate; 164 p["identity"] = delegate.empty()?iurl:delegate;
165 if(!trust_root.empty()) 165 if(!trust_root.empty())
166 p["trust_root"] = trust_root; 166 p["trust_root"] = trust_root;
167 p["return_to"] = return_to; 167 p["return_to"] = return_to;
168 try { 168 try {
169 string ah = find_assoc(server)->handle(); 169 string ah = find_assoc(server)->handle();
170 p["assoc_handle"] = ah; 170 p["assoc_handle"] = ah;
171 }catch(failed_lookup& fl) { 171 }catch(failed_lookup& fl) {
172 string ah = associate(server)->handle(); 172 string ah = associate(server)->handle();
173 p["assoc_handle"] = ah; 173 p["assoc_handle"] = ah;
174 } 174 }
175 if(ext) ext->checkid_hook(p,identity); 175 if(ext) ext->checkid_hook(p,identity);
176 return p.append_query(server); 176 return p.append_query(server);
177 } 177 }
178 178
179 void consumer_t::id_res(const params_t& pin,const string& identity,extension_t *ext) { 179 void consumer_t::id_res(const params_t& pin,const string& identity,extension_t *ext) {
180 if(pin.has_param("openid.user_setup_url")) 180 if(pin.has_param("openid.user_setup_url"))
181 throw id_res_setup(OPKELE_CP_ "assertion failed, setup url provided",pin.get_param("openid.user_setup_url")); 181 throw id_res_setup(OPKELE_CP_ "assertion failed, setup url provided",pin.get_param("openid.user_setup_url"));
182 string server,delegate; 182 string server,delegate;
183 retrieve_links(identity.empty()?pin.get_param("openid.identity"):canonicalize(identity),server,delegate); 183 retrieve_links(identity.empty()?pin.get_param("openid.identity"):canonicalize(identity),server,delegate);
184 params_t ps; 184 params_t ps;
185 try { 185 try {
186 assoc_t assoc = retrieve_assoc(server,pin.get_param("openid.assoc_handle")); 186 assoc_t assoc = retrieve_assoc(server,pin.get_param("openid.assoc_handle"));
187 if(assoc->is_expired()) /* TODO: or should I throw some other exception to force programmer fix his implementation? */ 187 if(assoc->is_expired())
188 throw failed_lookup(OPKELE_CP_ "retrieve_assoc() has returned expired handle"); 188 throw id_res_expired_on_delivery(OPKELE_CP_ "retrieve_assoc() has returned expired handle");
189 const string& sigenc = pin.get_param("openid.sig"); 189 const string& sigenc = pin.get_param("openid.sig");
190 vector<unsigned char> sig; 190 vector<unsigned char> sig;
191 util::decode_base64(sigenc,sig); 191 util::decode_base64(sigenc,sig);
192 const string& slist = pin.get_param("openid.signed"); 192 const string& slist = pin.get_param("openid.signed");
193 string kv; 193 string kv;
194 string::size_type p = 0; 194 string::size_type p = 0;
195 while(true) { 195 while(true) {
196 string::size_type co = slist.find(',',p); 196 string::size_type co = slist.find(',',p);
197 string f = (co==string::npos)?slist.substr(p):slist.substr(p,co-p); 197 string f = (co==string::npos)?slist.substr(p):slist.substr(p,co-p);
198 kv += f; 198 kv += f;
199 kv += ':'; 199 kv += ':';
200 f.insert(0,"openid."); 200 f.insert(0,"openid.");
201 kv += pin.get_param(f); 201 kv += pin.get_param(f);
202 kv += '\n'; 202 kv += '\n';
203 if(ext) ps[f.substr(sizeof("openid.")-1)] = pin.get_param(f); 203 if(ext) ps[f.substr(sizeof("openid.")-1)] = pin.get_param(f);
204 if(co==string::npos) 204 if(co==string::npos)
205 break; 205 break;
206 p = co+1; 206 p = co+1;
207 } 207 }
208 secret_t secret = assoc->secret(); 208 secret_t secret = assoc->secret();
209 unsigned int md_len = 0; 209 unsigned int md_len = 0;
210 unsigned char *md = HMAC( 210 unsigned char *md = HMAC(
211 EVP_sha1(), 211 EVP_sha1(),
212 &(secret.front()),secret.size(), 212 &(secret.front()),secret.size(),
213 (const unsigned char *)kv.data(),kv.length(), 213 (const unsigned char *)kv.data(),kv.length(),
214 0,&md_len); 214 0,&md_len);
215 if(sig.size()!=md_len || memcmp(&(sig.front()),md,md_len)) 215 if(sig.size()!=md_len || memcmp(&(sig.front()),md,md_len))
216 throw id_res_mismatch(OPKELE_CP_ "signature mismatch"); 216 throw id_res_mismatch(OPKELE_CP_ "signature mismatch");
217 }catch(failed_lookup& e) { /* XXX: more specific? */ 217 }catch(failed_lookup& e) {
218 const string& slist = pin.get_param("openid.signed"); 218 const string& slist = pin.get_param("openid.signed");
219 string::size_type pp = 0; 219 string::size_type pp = 0;
220 params_t p; 220 params_t p;
221 while(true) { 221 while(true) {
222 string::size_type co = slist.find(',',pp); 222 string::size_type co = slist.find(',',pp);
223 string f = "openid."; 223 string f = "openid.";
224 f += (co==string::npos)?slist.substr(pp):slist.substr(pp,co-pp); 224 f += (co==string::npos)?slist.substr(pp):slist.substr(pp,co-pp);
225 p[f] = pin.get_param(f); 225 p[f] = pin.get_param(f);
226 if(co==string::npos) 226 if(co==string::npos)
227 break; 227 break;
228 pp = co+1; 228 pp = co+1;
229 } 229 }
230 p["openid.assoc_handle"] = pin.get_param("openid.assoc_handle"); 230 p["openid.assoc_handle"] = pin.get_param("openid.assoc_handle");
231 p["openid.sig"] = pin.get_param("openid.sig"); 231 p["openid.sig"] = pin.get_param("openid.sig");
232 p["openid.signed"] = pin.get_param("openid.signed"); 232 p["openid.signed"] = pin.get_param("openid.signed");
233 try { 233 try {
234 string ih = pin.get_param("openid.invalidate_handle"); 234 string ih = pin.get_param("openid.invalidate_handle");
235 p["openid.invalidate_handle"] = ih; 235 p["openid.invalidate_handle"] = ih;
236 }catch(failed_lookup& fl) { } 236 }catch(failed_lookup& fl) { }
237 try { 237 try {
238 check_authentication(server,p); 238 check_authentication(server,p);
239 }catch(failed_check_authentication& fca) { 239 }catch(failed_check_authentication& fca) {
240 throw id_res_failed(OPKELE_CP_ "failed to check_authentication()"); 240 throw id_res_failed(OPKELE_CP_ "failed to check_authentication()");
241 } 241 }
242 } 242 }
243 if(ext) ext->id_res_hook(pin,ps,identity); 243 if(ext) ext->id_res_hook(pin,ps,identity);
244 } 244 }
245 245
246 void consumer_t::check_authentication(const string& server,const params_t& p) { 246 void consumer_t::check_authentication(const string& server,const params_t& p) {
247 string request = "openid.mode=check_authentication"; 247 string request = "openid.mode=check_authentication";
248 for(params_t::const_iterator i=p.begin();i!=p.end();++i) { 248 for(params_t::const_iterator i=p.begin();i!=p.end();++i) {
249 if(i->first!="openid.mode") { 249 if(i->first!="openid.mode") {
250 request += '&'; 250 request += '&';
251 request += i->first; 251 request += i->first;
252 request += '='; 252 request += '=';
253 request += util::url_encode(i->second); 253 request += util::url_encode(i->second);
254 } 254 }
255 } 255 }
256 curl_pick_t curl = curl_pick_t::easy_init(); 256 curl_pick_t curl = curl_pick_t::easy_init();
257 if(!curl) 257 if(!curl)
258 throw exception_curl(OPKELE_CP_ "failed to initialize curl"); 258 throw exception_curl(OPKELE_CP_ "failed to initialize curl");
259 CURLcode r; 259 CURLcode r;
260 (r=curl.misc_sets()) 260 (r=curl.misc_sets())
261 || (r=curl.easy_setopt(CURLOPT_URL,server.c_str())) 261 || (r=curl.easy_setopt(CURLOPT_URL,server.c_str()))
262 || (r=curl.easy_setopt(CURLOPT_POST,1)) 262 || (r=curl.easy_setopt(CURLOPT_POST,1))
263 || (r=curl.easy_setopt(CURLOPT_POSTFIELDS,request.data())) 263 || (r=curl.easy_setopt(CURLOPT_POSTFIELDS,request.data()))
264 || (r=curl.easy_setopt(CURLOPT_POSTFIELDSIZE,request.length())) 264 || (r=curl.easy_setopt(CURLOPT_POSTFIELDSIZE,request.length()))
265 || (r=curl.set_write()) 265 || (r=curl.set_write())
266 ; 266 ;
267 if(r) 267 if(r)
268 throw exception_curl(OPKELE_CP_ "failed to set curly options",r); 268 throw exception_curl(OPKELE_CP_ "failed to set curly options",r);
269 if( (r=curl.easy_perform()) ) 269 if( (r=curl.easy_perform()) )
270 throw exception_curl(OPKELE_CP_ "failed to perform curly request",r); 270 throw exception_curl(OPKELE_CP_ "failed to perform curly request",r);
271 params_t pp; pp.parse_keyvalues(curl.response); 271 params_t pp; pp.parse_keyvalues(curl.response);
272 if(pp.has_param("invalidate_handle")) 272 if(pp.has_param("invalidate_handle"))
273 invalidate_assoc(server,pp.get_param("invalidate_handle")); 273 invalidate_assoc(server,pp.get_param("invalidate_handle"));
274 if(pp.has_param("is_valid")) { 274 if(pp.has_param("is_valid")) {
275 if(pp.get_param("is_valid")=="true") 275 if(pp.get_param("is_valid")=="true")
276 return; 276 return;
277 }else if(pp.has_param("lifetime")) { 277 }else if(pp.has_param("lifetime")) {
278 if(util::string_to_long(pp.get_param("lifetime"))) 278 if(util::string_to_long(pp.get_param("lifetime")))
279 return; 279 return;
280 } 280 }
281 throw failed_check_authentication(OPKELE_CP_ "failed to verify response"); 281 throw failed_check_authentication(OPKELE_CP_ "failed to verify response");
282 } 282 }
283 283
284 void consumer_t::retrieve_links(const string& url,string& server,string& delegate) { 284 void consumer_t::retrieve_links(const string& url,string& server,string& delegate) {
285 server.erase(); 285 server.erase();
286 delegate.erase(); 286 delegate.erase();
287 curl_pick_t curl = curl_pick_t::easy_init(); 287 curl_pick_t curl = curl_pick_t::easy_init();
288 if(!curl) 288 if(!curl)
289 throw exception_curl(OPKELE_CP_ "failed to initialize curl"); 289 throw exception_curl(OPKELE_CP_ "failed to initialize curl");
290 string& html = curl.response; 290 string& html = curl.response;
291 CURLcode r; 291 CURLcode r;
292 (r=curl.misc_sets()) 292 (r=curl.misc_sets())
293 || (r=curl.easy_setopt(CURLOPT_URL,url.c_str())) 293 || (r=curl.easy_setopt(CURLOPT_URL,url.c_str()))
294 || (r=curl.set_write()); 294 || (r=curl.set_write());
295 ; 295 ;
296 if(r) 296 if(r)
297 throw exception_curl(OPKELE_CP_ "failed to set curly options",r); 297 throw exception_curl(OPKELE_CP_ "failed to set curly options",r);
298 r = curl.easy_perform(); 298 r = curl.easy_perform();
299 if(r && r!=CURLE_WRITE_ERROR) 299 if(r && r!=CURLE_WRITE_ERROR)
300 throw exception_curl(OPKELE_CP_ "failed to perform curly request",r); 300 throw exception_curl(OPKELE_CP_ "failed to perform curly request",r);
301 static const char *re_bre = "<\\s*body\\b", *re_hdre = "<\\s*head[^>]*>", 301 static const char *re_bre = "<\\s*body\\b", *re_hdre = "<\\s*head[^>]*>",
302 *re_lre = "<\\s*link\\b([^>]+)>", 302 *re_lre = "<\\s*link\\b([^>]+)>",
303 *re_rre = "\\brel\\s*=\\s*['\"]([^'\"]+)['\"]", 303 *re_rre = "\\brel\\s*=\\s*['\"]([^'\"]+)['\"]",
304 *re_hre = "\\bhref\\s*=\\s*['\"]\\s*([^'\"\\s]+)\\s*['\"]"; 304 *re_hre = "\\bhref\\s*=\\s*['\"]\\s*([^'\"\\s]+)\\s*['\"]";
305 pcre_matches_t m1(3), m2(3); 305 pcre_matches_t m1(3), m2(3);
306 pcre_t bre(re_bre,PCRE_CASELESS); 306 pcre_t bre(re_bre,PCRE_CASELESS);
307 if(bre.exec(html,m1)>0) 307 if(bre.exec(html,m1)>0)
308 html.erase(m1.begin(0)); 308 html.erase(m1.begin(0));
309 pcre_t hdre(re_hdre,PCRE_CASELESS); 309 pcre_t hdre(re_hdre,PCRE_CASELESS);
310 if(hdre.exec(html,m1)<=0) 310 if(hdre.exec(html,m1)<=0)
311 throw bad_input(OPKELE_CP_ "failed to find <head>"); 311 throw bad_input(OPKELE_CP_ "failed to find <head>");
312 html.erase(0,m1.end(0)+1); 312 html.erase(0,m1.end(0)+1);
313 pcre_t lre(re_lre,PCRE_CASELESS), rre(re_rre,PCRE_CASELESS), hre(re_hre,PCRE_CASELESS); 313 pcre_t lre(re_lre,PCRE_CASELESS), rre(re_rre,PCRE_CASELESS), hre(re_hre,PCRE_CASELESS);
314 bool gotit = false; 314 bool gotit = false;
315 while( (!gotit) && lre.exec(html,m1)>=2 ) { 315 while( (!gotit) && lre.exec(html,m1)>=2 ) {
316 static const char *whitespace = " \t"; 316 static const char *whitespace = " \t";
317 string attrs(html,m1.begin(1),m1.length(1)); 317 string attrs(html,m1.begin(1),m1.length(1));
318 html.erase(0,m1.end(0)+1); 318 html.erase(0,m1.end(0)+1);
319 if(!( rre.exec(attrs,m1)>=2 && hre.exec(attrs,m2)>=2 )) 319 if(!( rre.exec(attrs,m1)>=2 && hre.exec(attrs,m2)>=2 ))
320 continue; 320 continue;
321 string rels(attrs,m1.begin(1),m1.length(1)); 321 string rels(attrs,m1.begin(1),m1.length(1));
322 for(string::size_type ns = rels.find_first_not_of(whitespace); 322 for(string::size_type ns = rels.find_first_not_of(whitespace);
323 ns!=string::npos; 323 ns!=string::npos;
324 ns=rels.find_first_not_of(whitespace,ns)) { 324 ns=rels.find_first_not_of(whitespace,ns)) {
325 string::size_type s = rels.find_first_of(whitespace,ns); 325 string::size_type s = rels.find_first_of(whitespace,ns);
326 string rel; 326 string rel;
327 if(s==string::npos) { 327 if(s==string::npos) {
328 rel.assign(rels,ns,string::npos); 328 rel.assign(rels,ns,string::npos);
329 ns=string::npos; 329 ns=string::npos;
330 }else{ 330 }else{
331 rel.assign(rels,ns,s-ns); 331 rel.assign(rels,ns,s-ns);
332 ns=s; 332 ns=s;
333 } 333 }
334 if(rel=="openid.server") { 334 if(rel=="openid.server") {
335 server.assign(attrs,m2.begin(1),m2.length(1)); 335 server.assign(attrs,m2.begin(1),m2.length(1));
336 if(!delegate.empty()) { 336 if(!delegate.empty()) {
337 gotit = true; 337 gotit = true;
338 break; 338 break;
339 } 339 }
340 }else if(rel=="openid.delegate") { 340 }else if(rel=="openid.delegate") {
341 delegate.assign(attrs,m2.begin(1),m2.length(1)); 341 delegate.assign(attrs,m2.begin(1),m2.length(1));
342 if(!server.empty()) { 342 if(!server.empty()) {
343 gotit = true; 343 gotit = true;
344 break; 344 break;
345 } 345 }
346 } 346 }
347 } 347 }
348 } 348 }
349 if(server.empty()) 349 if(server.empty())
350 throw failed_assertion(OPKELE_CP_ "The location has no openid.server declaration"); 350 throw failed_assertion(OPKELE_CP_ "The location has no openid.server declaration");
351 } 351 }
352 352
353 assoc_t consumer_t::find_assoc(const string& /* server */) { 353 assoc_t consumer_t::find_assoc(const string& /* server */) {
354 throw failed_lookup(OPKELE_CP_ "no find_assoc() provided"); 354 throw failed_lookup(OPKELE_CP_ "no find_assoc() provided");
355 } 355 }
356 356
357 string consumer_t::normalize(const string& url) { 357 string consumer_t::normalize(const string& url) {
358 string rv = url; 358 string rv = url;
359 // strip leading and trailing spaces 359 // strip leading and trailing spaces
360 string::size_type i = rv.find_first_not_of(" \t\r\n"); 360 string::size_type i = rv.find_first_not_of(" \t\r\n");
361 if(i==string::npos) 361 if(i==string::npos)
362 throw bad_input(OPKELE_CP_ "empty URL"); 362 throw bad_input(OPKELE_CP_ "empty URL");
363 if(i) 363 if(i)
364 rv.erase(0,i); 364 rv.erase(0,i);
365 i = rv.find_last_not_of(" \t\r\n"); 365 i = rv.find_last_not_of(" \t\r\n");
366 assert(i!=string::npos); 366 assert(i!=string::npos);
367 if(i<(rv.length()-1)) 367 if(i<(rv.length()-1))
368 rv.erase(i+1); 368 rv.erase(i+1);
369 // add missing http:// 369 // add missing http://
370 i = rv.find("://"); 370 i = rv.find("://");
371 if(i==string::npos) { // primitive. but do we need more? 371 if(i==string::npos) { // primitive. but do we need more?
372 rv.insert(0,"http://"); 372 rv.insert(0,"http://");
373 i = sizeof("http://")-1; 373 i = sizeof("http://")-1;
374 }else{ 374 }else{
375 i += sizeof("://")-1; 375 i += sizeof("://")-1;
376 } 376 }
377 string::size_type qm = rv.find('?',i); 377 string::size_type qm = rv.find('?',i);
378 string::size_type sl = rv.find('/',i); 378 string::size_type sl = rv.find('/',i);
379 if(qm!=string::npos) { 379 if(qm!=string::npos) {
380 if(sl==string::npos || sl>qm) 380 if(sl==string::npos || sl>qm)
381 rv.insert(qm,1,'/'); 381 rv.insert(qm,1,'/');
382 }else{ 382 }else{
383 if(sl==string::npos) 383 if(sl==string::npos)
384 rv += '/'; 384 rv += '/';
385 } 385 }
386 return rv; 386 return rv;
387 } 387 }
388 388
389 string consumer_t::canonicalize(const string& url) { 389 string consumer_t::canonicalize(const string& url) {
390 string rv = normalize(url); 390 string rv = normalize(url);
391 curl_t curl = curl_t::easy_init(); 391 curl_t curl = curl_t::easy_init();
392 if(!curl) 392 if(!curl)
393 throw exception_curl(OPKELE_CP_ "failed to initialize curl()"); 393 throw exception_curl(OPKELE_CP_ "failed to initialize curl()");
394 string html; 394 string html;
395 CURLcode r; 395 CURLcode r;
396 (r=curl.misc_sets()) 396 (r=curl.misc_sets())
397 || (r=curl.easy_setopt(CURLOPT_URL,rv.c_str())) 397 || (r=curl.easy_setopt(CURLOPT_URL,rv.c_str()))
398 || (r=curl.easy_setopt(CURLOPT_NOBODY,1)) 398 || (r=curl.easy_setopt(CURLOPT_NOBODY,1))
399 ; 399 ;
400 if(r) 400 if(r)
401 throw exception_curl(OPKELE_CP_ "failed to set curly options",r); 401 throw exception_curl(OPKELE_CP_ "failed to set curly options",r);
402 r = curl.easy_perform(); 402 r = curl.easy_perform();
403 if(r) 403 if(r)
404 throw exception_curl(OPKELE_CP_ "failed to perform curly request",r); 404 throw exception_curl(OPKELE_CP_ "failed to perform curly request",r);
405 const char *eu = 0; 405 const char *eu = 0;
406 r = curl.easy_getinfo(CURLINFO_EFFECTIVE_URL,&eu); 406 r = curl.easy_getinfo(CURLINFO_EFFECTIVE_URL,&eu);
407 if(r) 407 if(r)
408 throw exception_curl(OPKELE_CP_ "failed to get CURLINFO_EFFECTIVE_URL",r); 408 throw exception_curl(OPKELE_CP_ "failed to get CURLINFO_EFFECTIVE_URL",r);
409 rv = eu; 409 rv = eu;
410 return normalize(rv); 410 return normalize(rv);
411 } 411 }
412 412
413} 413}
diff --git a/lib/util.cc b/lib/util.cc
index 83f0eef..4600576 100644
--- a/lib/util.cc
+++ b/lib/util.cc
@@ -1,305 +1,305 @@
1#include <errno.h> 1#include <errno.h>
2#include <cassert> 2#include <cassert>
3#include <cctype> 3#include <cctype>
4#include <cstring> 4#include <cstring>
5#include <vector> 5#include <vector>
6#include <string> 6#include <string>
7#include <stack> 7#include <stack>
8#include <openssl/bio.h> 8#include <openssl/bio.h>
9#include <openssl/evp.h> 9#include <openssl/evp.h>
10#include <curl/curl.h> 10#include <curl/curl.h>
11#include "opkele/util.h" 11#include "opkele/util.h"
12#include "opkele/exception.h" 12#include "opkele/exception.h"
13 13
14namespace opkele { 14namespace opkele {
15 using namespace std; 15 using namespace std;
16 16
17 namespace util { 17 namespace util {
18 18
19 /* 19 /*
20 * base64 20 * base64
21 */ 21 */
22 string encode_base64(const void *data,size_t length) { 22 string encode_base64(const void *data,size_t length) {
23 BIO *b64 = 0, *bmem = 0; 23 BIO *b64 = 0, *bmem = 0;
24 try { 24 try {
25 b64 = BIO_new(BIO_f_base64()); 25 b64 = BIO_new(BIO_f_base64());
26 if(!b64) 26 if(!b64)
27 throw exception_openssl(OPKELE_CP_ "failed to BIO_new() base64 encoder"); 27 throw exception_openssl(OPKELE_CP_ "failed to BIO_new() base64 encoder");
28 BIO_set_flags(b64,BIO_FLAGS_BASE64_NO_NL); 28 BIO_set_flags(b64,BIO_FLAGS_BASE64_NO_NL);
29 bmem = BIO_new(BIO_s_mem()); 29 bmem = BIO_new(BIO_s_mem());
30 BIO_set_flags(b64,BIO_CLOSE); 30 BIO_set_flags(b64,BIO_CLOSE);
31 if(!bmem) 31 if(!bmem)
32 throw exception_openssl(OPKELE_CP_ "failed to BIO_new() memory buffer"); 32 throw exception_openssl(OPKELE_CP_ "failed to BIO_new() memory buffer");
33 BIO_push(b64,bmem); 33 BIO_push(b64,bmem);
34 if(((size_t)BIO_write(b64,data,length))!=length) 34 if(((size_t)BIO_write(b64,data,length))!=length)
35 throw exception_openssl(OPKELE_CP_ "failed to BIO_write()"); 35 throw exception_openssl(OPKELE_CP_ "failed to BIO_write()");
36 if(BIO_flush(b64)!=1) 36 if(BIO_flush(b64)!=1)
37 throw exception_openssl(OPKELE_CP_ "failed to BIO_flush()"); 37 throw exception_openssl(OPKELE_CP_ "failed to BIO_flush()");
38 char *rvd; 38 char *rvd;
39 long rvl = BIO_get_mem_data(bmem,&rvd); 39 long rvl = BIO_get_mem_data(bmem,&rvd);
40 string rv(rvd,rvl); 40 string rv(rvd,rvl);
41 BIO_free_all(b64); 41 BIO_free_all(b64);
42 return rv; 42 return rv;
43 }catch(...) { 43 }catch(...) {
44 if(b64) BIO_free_all(b64); 44 if(b64) BIO_free_all(b64);
45 throw; 45 throw;
46 } 46 }
47 } 47 }
48 48
49 void decode_base64(const string& data,vector<unsigned char>& rv) { 49 void decode_base64(const string& data,vector<unsigned char>& rv) {
50 BIO *b64 = 0, *bmem = 0; 50 BIO *b64 = 0, *bmem = 0;
51 rv.clear(); 51 rv.clear();
52 try { 52 try {
53 bmem = BIO_new_mem_buf((void*)data.data(),data.size()); 53 bmem = BIO_new_mem_buf((void*)data.data(),data.size());
54 if(!bmem) 54 if(!bmem)
55 throw exception_openssl(OPKELE_CP_ "failed to BIO_new_mem_buf()"); 55 throw exception_openssl(OPKELE_CP_ "failed to BIO_new_mem_buf()");
56 b64 = BIO_new(BIO_f_base64()); 56 b64 = BIO_new(BIO_f_base64());
57 if(!b64) 57 if(!b64)
58 throw exception_openssl(OPKELE_CP_ "failed to BIO_new() base64 decoder"); 58 throw exception_openssl(OPKELE_CP_ "failed to BIO_new() base64 decoder");
59 BIO_set_flags(b64,BIO_FLAGS_BASE64_NO_NL); 59 BIO_set_flags(b64,BIO_FLAGS_BASE64_NO_NL);
60 BIO_push(b64,bmem); 60 BIO_push(b64,bmem);
61 unsigned char tmp[512]; 61 unsigned char tmp[512];
62 size_t rb = 0; 62 size_t rb = 0;
63 while((rb=BIO_read(b64,tmp,sizeof(tmp)))>0) 63 while((rb=BIO_read(b64,tmp,sizeof(tmp)))>0)
64 rv.insert(rv.end(),tmp,&tmp[rb]); 64 rv.insert(rv.end(),tmp,&tmp[rb]);
65 BIO_free_all(b64); 65 BIO_free_all(b64);
66 }catch(...) { 66 }catch(...) {
67 if(b64) BIO_free_all(b64); 67 if(b64) BIO_free_all(b64);
68 throw; 68 throw;
69 } 69 }
70 } 70 }
71 71
72 /* 72 /*
73 * big numerics 73 * big numerics
74 */ 74 */
75 75
76 BIGNUM *base64_to_bignum(const string& b64) { 76 BIGNUM *base64_to_bignum(const string& b64) {
77 vector<unsigned char> bin; 77 vector<unsigned char> bin;
78 decode_base64(b64,bin); 78 decode_base64(b64,bin);
79 BIGNUM *rv = BN_bin2bn(&(bin.front()),bin.size(),0); 79 BIGNUM *rv = BN_bin2bn(&(bin.front()),bin.size(),0);
80 if(!rv) 80 if(!rv)
81 throw failed_conversion(OPKELE_CP_ "failed to BN_bin2bn()"); 81 throw failed_conversion(OPKELE_CP_ "failed to BN_bin2bn()");
82 return rv; 82 return rv;
83 } 83 }
84 84
85 BIGNUM *dec_to_bignum(const string& dec) { 85 BIGNUM *dec_to_bignum(const string& dec) {
86 BIGNUM *rv = 0; 86 BIGNUM *rv = 0;
87 if(!BN_dec2bn(&rv,dec.c_str())) 87 if(!BN_dec2bn(&rv,dec.c_str()))
88 throw failed_conversion(OPKELE_CP_ "failed to BN_dec2bn()"); 88 throw failed_conversion(OPKELE_CP_ "failed to BN_dec2bn()");
89 return rv; 89 return rv;
90 } 90 }
91 91
92 string bignum_to_base64(const BIGNUM *bn) { 92 string bignum_to_base64(const BIGNUM *bn) {
93 vector<unsigned char> bin(BN_num_bytes(bn)+1); 93 vector<unsigned char> bin(BN_num_bytes(bn)+1);
94 unsigned char *binptr = &(bin.front())+1; 94 unsigned char *binptr = &(bin.front())+1;
95 int l = BN_bn2bin(bn,binptr); 95 int l = BN_bn2bin(bn,binptr);
96 if(l && (*binptr)&0x80){ 96 if(l && (*binptr)&0x80){
97 (*(--binptr)) = 0; ++l; 97 (*(--binptr)) = 0; ++l;
98 } 98 }
99 return encode_base64(binptr,l); 99 return encode_base64(binptr,l);
100 } 100 }
101 101
102 /* 102 /*
103 * w3c times 103 * w3c times
104 */ 104 */
105 105
106 string time_to_w3c(time_t t) { 106 string time_to_w3c(time_t t) {
107 struct tm tm_t; 107 struct tm tm_t;
108 if(!gmtime_r(&t,&tm_t)) 108 if(!gmtime_r(&t,&tm_t))
109 throw failed_conversion(OPKELE_CP_ "failed to BN_dec2bn()"); 109 throw failed_conversion(OPKELE_CP_ "failed to BN_dec2bn()");
110 char rv[25]; 110 char rv[25];
111 if(!strftime(rv,sizeof(rv)-1,"%Y-%m-%dT%H:%M:%SZ",&tm_t)) 111 if(!strftime(rv,sizeof(rv)-1,"%Y-%m-%dT%H:%M:%SZ",&tm_t))
112 throw failed_conversion(OPKELE_CP_ "failed to strftime()"); 112 throw failed_conversion(OPKELE_CP_ "failed to strftime()");
113 return rv; 113 return rv;
114 } 114 }
115 115
116 time_t w3c_to_time(const string& w) { 116 time_t w3c_to_time(const string& w) {
117 struct tm tm_t; 117 struct tm tm_t;
118 memset(&tm_t,0,sizeof(tm_t)); 118 memset(&tm_t,0,sizeof(tm_t));
119 if( 119 if(
120 sscanf( 120 sscanf(
121 w.c_str(), 121 w.c_str(),
122 "%04d-%02d-%02dT%02d:%02d:%02dZ", 122 "%04d-%02d-%02dT%02d:%02d:%02dZ",
123 &tm_t.tm_year,&tm_t.tm_mon,&tm_t.tm_mday, 123 &tm_t.tm_year,&tm_t.tm_mon,&tm_t.tm_mday,
124 &tm_t.tm_hour,&tm_t.tm_min,&tm_t.tm_sec 124 &tm_t.tm_hour,&tm_t.tm_min,&tm_t.tm_sec
125 ) != 6 ) 125 ) != 6 )
126 throw failed_conversion(OPKELE_CP_ "failed to sscanf()"); 126 throw failed_conversion(OPKELE_CP_ "failed to sscanf()");
127 tm_t.tm_mon--; 127 tm_t.tm_mon--;
128 tm_t.tm_year-=1900; 128 tm_t.tm_year-=1900;
129 time_t rv = mktime(&tm_t); 129 time_t rv = mktime(&tm_t);
130 if(rv==(time_t)-1) 130 if(rv==(time_t)-1)
131 throw failed_conversion(OPKELE_CP_ "failed to mktime()"); 131 throw failed_conversion(OPKELE_CP_ "failed to mktime()");
132 return rv; 132 return rv;
133 } 133 }
134 134
135 /* 135 /*
136 * 136 *
137 */ 137 */
138 138
139 string url_encode(const string& str) { 139 string url_encode(const string& str) {
140 char * t = curl_escape(str.c_str(),str.length()); 140 char * t = curl_escape(str.c_str(),str.length());
141 if(!t) 141 if(!t)
142 throw failed_conversion(OPKELE_CP_ "failed to curl_escape()"); 142 throw failed_conversion(OPKELE_CP_ "failed to curl_escape()");
143 string rv(t); 143 string rv(t);
144 curl_free(t); 144 curl_free(t);
145 return rv; 145 return rv;
146 } 146 }
147 147
148 string long_to_string(long l) { 148 string long_to_string(long l) {
149 char rv[32]; 149 char rv[32];
150 int r=snprintf(rv,sizeof(rv),"%ld",l); 150 int r=snprintf(rv,sizeof(rv),"%ld",l);
151 if(r<0 || r>=(int)sizeof(rv)) 151 if(r<0 || r>=(int)sizeof(rv))
152 throw failed_conversion(OPKELE_CP_ "failed to snprintf()"); 152 throw failed_conversion(OPKELE_CP_ "failed to snprintf()");
153 return rv; 153 return rv;
154 } 154 }
155 155
156 long string_to_long(const string& s) { 156 long string_to_long(const string& s) {
157 char *endptr = 0; 157 char *endptr = 0;
158 long rv = strtol(s.c_str(),&endptr,10); 158 long rv = strtol(s.c_str(),&endptr,10);
159 if((!endptr) || endptr==s.c_str()) 159 if((!endptr) || endptr==s.c_str())
160 throw failed_conversion(OPKELE_CP_ "failed to strtol()"); 160 throw failed_conversion(OPKELE_CP_ "failed to strtol()");
161 return rv; 161 return rv;
162 } 162 }
163 163
164 /* 164 /*
165 * Normalize URL according to the rules, described in rfc 3986, section 6 165 * Normalize URL according to the rules, described in rfc 3986, section 6
166 * 166 *
167 * - uppercase hext triplets (e.g. %ab -> %AB) 167 * - uppercase hext triplets (e.g. %ab -> %AB)
168 * - lowercase scheme and host 168 * - lowercase scheme and host
169 * - decode %-encoded characters, specified as unreserved in rfc 3986, section 2.3, 169 * - decode %-encoded characters, specified as unreserved in rfc 3986, section 2.3,
170 * that is - [:alpha:][:digit:]._~- 170 * that is - [:alpha:][:digit:]._~-
171 * - remove dot segments 171 * - remove dot segments
172 * - remove empty and default ports 172 * - remove empty and default ports
173 * - if there's no path component, add '/' 173 * - if there's no path component, add '/'
174 */ 174 */
175 string rfc_3986_normalize_uri(const string& uri) { 175 string rfc_3986_normalize_uri(const string& uri) {
176 static const char *whitespace = " \t\r\n"; 176 static const char *whitespace = " \t\r\n";
177 string rv; 177 string rv;
178 string::size_type ns = uri.find_first_not_of(whitespace); 178 string::size_type ns = uri.find_first_not_of(whitespace);
179 if(ns==string::npos) 179 if(ns==string::npos)
180 throw bad_input(OPKELE_CP_ "Can't normalize empty URI"); 180 throw bad_input(OPKELE_CP_ "Can't normalize empty URI");
181 string::size_type colon = uri.find(':',ns); 181 string::size_type colon = uri.find(':',ns);
182 if(colon==string::npos) 182 if(colon==string::npos)
183 throw bad_input(OPKELE_CP_ "No scheme specified in URI"); 183 throw bad_input(OPKELE_CP_ "No scheme specified in URI");
184 transform( 184 transform(
185 uri.begin()+ns, uri.begin()+colon+1, 185 uri.begin()+ns, uri.begin()+colon+1,
186 back_inserter(rv), ::tolower ); 186 back_inserter(rv), ::tolower );
187 bool s; 187 bool s;
188 string::size_type ul = uri.find_last_not_of(whitespace)+1; 188 string::size_type ul = uri.find_last_not_of(whitespace)+1;
189 if(ul <= (colon+3)) 189 if(ul <= (colon+3))
190 throw bad_input(OPKELE_CP_ "Unexpected end of URI being normalized encountered"); 190 throw bad_input(OPKELE_CP_ "Unexpected end of URI being normalized encountered");
191 if(uri[colon+1]!='/' || uri[colon+2]!='/') 191 if(uri[colon+1]!='/' || uri[colon+2]!='/')
192 throw bad_input(OPKELE_CP_ "Unexpected input in URI being normalized after scheme component"); 192 throw bad_input(OPKELE_CP_ "Unexpected input in URI being normalized after scheme component");
193 if(rv=="http:") 193 if(rv=="http:")
194 s = false; 194 s = false;
195 else if(rv=="https:") 195 else if(rv=="https:")
196 s = true; 196 s = true;
197 else{ 197 else{
198 /* TODO: support more schemes. 198 /* TODO: support more schemes.
199 * e.g. xri. How do we normalize 199 * e.g. xri. How do we normalize
200 * xri? 200 * xri?
201 */ 201 */
202 rv.append(uri,colon+1,ul-colon-1); 202 rv.append(uri,colon+1,ul-colon-1);
203 return rv; 203 return rv;
204 } 204 }
205 rv += "//"; 205 rv += "//";
206 string::size_type interesting = uri.find_first_of(":/#?",colon+3); 206 string::size_type interesting = uri.find_first_of(":/#?",colon+3);
207 if(interesting==string::npos) { 207 if(interesting==string::npos) {
208 transform( 208 transform(
209 uri.begin()+colon+3,uri.begin()+ul, 209 uri.begin()+colon+3,uri.begin()+ul,
210 back_inserter(rv), ::tolower ); 210 back_inserter(rv), ::tolower );
211 rv += '/'; return rv; 211 rv += '/'; return rv;
212 } 212 }
213 transform( 213 transform(
214 uri.begin()+colon+3,uri.begin()+interesting, 214 uri.begin()+colon+3,uri.begin()+interesting,
215 back_inserter(rv), ::tolower ); 215 back_inserter(rv), ::tolower );
216 bool qf = false; 216 bool qf = false;
217 char ic = uri[interesting]; 217 char ic = uri[interesting];
218 if(ic==':') { 218 if(ic==':') {
219 string::size_type ni = uri.find_first_of("/#?%",interesting+1); 219 string::size_type ni = uri.find_first_of("/#?%",interesting+1);
220 const char *nptr = uri.data()+interesting+1; 220 const char *nptr = uri.data()+interesting+1;
221 char *eptr = 0; 221 char *eptr = 0;
222 long port = strtol(nptr,&eptr,10); 222 long port = strtol(nptr,&eptr,10);
223 if( (port>0) && (port<65535) && port!=(s?443:80) ) { 223 if( (port>0) && (port<65535) && port!=(s?443:80) ) {
224 char tmp[6]; 224 char tmp[8];
225 snprintf(tmp,sizeof(tmp),"%ld",port); 225 snprintf(tmp,sizeof(tmp),":%ld",port);
226 rv += ':'; rv += tmp; 226 rv += tmp;
227 } 227 }
228 if(ni==string::npos) { 228 if(ni==string::npos) {
229 rv += '/'; return rv; 229 rv += '/'; return rv;
230 } 230 }
231 interesting = ni; 231 interesting = ni;
232 }else if(ic!='/') { 232 }else if(ic!='/') {
233 rv += '/'; rv += ic; 233 rv += '/'; rv += ic;
234 qf = true; 234 qf = true;
235 ++interesting; 235 ++interesting;
236 } 236 }
237 string::size_type n = interesting; 237 string::size_type n = interesting;
238 char tmp[3] = { 0,0,0 }; 238 char tmp[3] = { 0,0,0 };
239 stack<string::size_type> psegs; psegs.push(rv.length()); 239 stack<string::size_type> psegs; psegs.push(rv.length());
240 string pseg; 240 string pseg;
241 for(;n<ul;) { 241 for(;n<ul;) {
242 string::size_type unsafe = uri.find_first_of(qf?"%":"%/?#",n); 242 string::size_type unsafe = uri.find_first_of(qf?"%":"%/?#",n);
243 if(unsafe==string::npos) { 243 if(unsafe==string::npos) {
244 pseg.append(uri,n,ul-n-1); n = ul-1; 244 pseg.append(uri,n,ul-n-1); n = ul-1;
245 }else{ 245 }else{
246 pseg.append(uri,n,unsafe-n); 246 pseg.append(uri,n,unsafe-n);
247 n = unsafe; 247 n = unsafe;
248 } 248 }
249 char c = uri[n++]; 249 char c = uri[n++];
250 if(c=='%') { 250 if(c=='%') {
251 if((n+1)>=ul) 251 if((n+1)>=ul)
252 throw bad_input(OPKELE_CP_ "Unexpected end of URI encountered while parsing percent-encoded character"); 252 throw bad_input(OPKELE_CP_ "Unexpected end of URI encountered while parsing percent-encoded character");
253 tmp[0] = uri[n++]; 253 tmp[0] = uri[n++];
254 tmp[1] = uri[n++]; 254 tmp[1] = uri[n++];
255 if(!( isxdigit(tmp[0]) && isxdigit(tmp[1]) )) 255 if(!( isxdigit(tmp[0]) && isxdigit(tmp[1]) ))
256 throw bad_input(OPKELE_CP_ "Invalid percent-encoded character in URI being normalized"); 256 throw bad_input(OPKELE_CP_ "Invalid percent-encoded character in URI being normalized");
257 int cc = strtol(tmp,0,16); 257 int cc = strtol(tmp,0,16);
258 if( isalpha(cc) || isdigit(cc) || strchr("._~-",cc) ) 258 if( isalpha(cc) || isdigit(cc) || strchr("._~-",cc) )
259 pseg += cc; 259 pseg += cc;
260 else{ 260 else{
261 pseg += '%'; 261 pseg += '%';
262 pseg += toupper(tmp[0]); pseg += toupper(tmp[1]); 262 pseg += toupper(tmp[0]); pseg += toupper(tmp[1]);
263 } 263 }
264 }else if(qf) { 264 }else if(qf) {
265 rv += pseg; rv += c; 265 rv += pseg; rv += c;
266 pseg.clear(); 266 pseg.clear();
267 }else if(n>=ul || strchr("?/#",c)) { 267 }else if(n>=ul || strchr("?/#",c)) {
268 if(pseg.empty() || pseg==".") { 268 if(pseg.empty() || pseg==".") {
269 }else if(pseg=="..") { 269 }else if(pseg=="..") {
270 if(psegs.size()>1) { 270 if(psegs.size()>1) {
271 rv.resize(psegs.top()); psegs.pop(); 271 rv.resize(psegs.top()); psegs.pop();
272 } 272 }
273 }else{ 273 }else{
274 psegs.push(rv.length()); 274 psegs.push(rv.length());
275 if(c!='/') { 275 if(c!='/') {
276 pseg += c; 276 pseg += c;
277 qf = true; 277 qf = true;
278 } 278 }
279 rv += '/'; rv += pseg; 279 rv += '/'; rv += pseg;
280 } 280 }
281 if(c=='/' && (n>=ul || strchr("?#",uri[n])) ) { 281 if(c=='/' && (n>=ul || strchr("?#",uri[n])) ) {
282 rv += '/'; 282 rv += '/';
283 if(n<ul) 283 if(n<ul)
284 qf = true; 284 qf = true;
285 }else if(strchr("?#",c)) { 285 }else if(strchr("?#",c)) {
286 if(psegs.size()==1 && psegs.top()==rv.length()) 286 if(psegs.size()==1 && psegs.top()==rv.length())
287 rv += '/'; 287 rv += '/';
288 if(pseg.empty()) 288 if(pseg.empty())
289 rv += c; 289 rv += c;
290 qf = true; 290 qf = true;
291 } 291 }
292 pseg.clear(); 292 pseg.clear();
293 }else{ 293 }else{
294 pseg += c; 294 pseg += c;
295 } 295 }
296 } 296 }
297 if(!pseg.empty()) { 297 if(!pseg.empty()) {
298 rv += '/'; rv += pseg; 298 rv += '/'; rv += pseg;
299 } 299 }
300 return rv; 300 return rv;
301 } 301 }
302 302
303 } 303 }
304 304
305} 305}