Rewritten Netrc using stdio instead of stream.

pull/1/head
Tatsuhiro Tsujikawa 2011-08-05 23:11:57 +09:00
parent 13158de0d3
commit 07874696c5
2 changed files with 26 additions and 15 deletions

View File

@ -34,7 +34,8 @@
/* copyright --> */ /* copyright --> */
#include "Netrc.h" #include "Netrc.h"
#include <fstream> #include <cstdio>
#include <cstring>
#include <algorithm> #include <algorithm>
#include "DlAbortEx.h" #include "DlAbortEx.h"
@ -117,24 +118,29 @@ void Netrc::addAuthenticator(const SharedHandle<Authenticator>& authenticator)
authenticators_.push_back(authenticator); authenticators_.push_back(authenticator);
} }
void Netrc::skipMacdef(std::ifstream& f) const namespace {
void skipMacdef(FILE* fp)
{ {
std::string line; char buf[4096];
while(getline(f, line)) { while(1) {
if(line == A2STR::CR_C || line.empty()) { if(!fgets(buf, sizeof(buf), fp)) {
break;
}
if(buf[0] == '\n' || buf[0] == '\r') {
break; break;
} }
} }
} }
} // namespace
void Netrc::parse(const std::string& path) void Netrc::parse(const std::string& path)
{ {
authenticators_.clear(); authenticators_.clear();
std::ifstream f(path.c_str(), std::ios::binary); FILE* fp = a2fopen(utf8ToWChar(path).c_str(), "rb");
if(!fp) {
if(!f) { throw DL_ABORT_EX(fmt("Cannot open file: %s", utf8ToNative(path).c_str()));
throw DL_ABORT_EX(fmt("File not found: %s", path.c_str()));
} }
auto_delete_r<FILE*, int> deleter(fp, fclose);
enum STATE { enum STATE {
GET_TOKEN, GET_TOKEN,
@ -145,9 +151,17 @@ void Netrc::parse(const std::string& path)
SET_MACDEF SET_MACDEF
}; };
SharedHandle<Authenticator> authenticator; SharedHandle<Authenticator> authenticator;
std::string line;
STATE state = GET_TOKEN; STATE state = GET_TOKEN;
while(getline(f, line)) { char buf[4096];
while(1) {
if(!fgets(buf, sizeof(buf), fp)) {
break;
}
size_t len = strlen(buf);
if(buf[len-1] == '\n') {
buf[len-1] = '\0';
}
std::string line(buf);
if(util::startsWith(line, "#")) { if(util::startsWith(line, "#")) {
continue; continue;
} }
@ -190,7 +204,7 @@ void Netrc::parse(const std::string& path)
} else if(state == SET_ACCOUNT) { } else if(state == SET_ACCOUNT) {
authenticator->setAccount(token); authenticator->setAccount(token);
} else if(state == SET_MACDEF) { } else if(state == SET_MACDEF) {
skipMacdef(f); skipMacdef(fp);
} }
state = GET_TOKEN; state = GET_TOKEN;
} }

View File

@ -39,7 +39,6 @@
#include <string> #include <string>
#include <vector> #include <vector>
#include <iosfwd>
#include "SharedHandle.h" #include "SharedHandle.h"
@ -119,8 +118,6 @@ private:
void storeAuthenticator(const SharedHandle<Authenticator>& authenticator); void storeAuthenticator(const SharedHandle<Authenticator>& authenticator);
std::string getRequiredNextToken(std::ifstream& f) const; std::string getRequiredNextToken(std::ifstream& f) const;
void skipMacdef(std::ifstream& f) const;
public: public:
Netrc(); Netrc();