Back to home page

Project CMSSW displayed by LXR

 
 

    


File indexing completed on 2021-02-14 12:47:03

0001 #include "PasswordReader.h"
0002 
0003 #include <iostream>
0004 #include <fstream>
0005 #include <algorithm>
0006 
0007 #include "FWCore/Utilities/interface/Exception.h"
0008 
0009 using namespace std;
0010 
0011 void PasswordReader::readPassword(const std::string& fileName, const std::string& user, std::string& password) {
0012   ifstream f(fileName.c_str());
0013   if (!f.good()) {
0014     throw cms::Exception("File") << "Failed to open file " << fileName
0015                                  << " for reading condition "
0016                                     "database password\n";
0017   }
0018   string line;
0019   bool found = false;
0020   int nstatements = 0;  //number of lines other than empty and comment lines
0021   while (f.good() && !found) {
0022     size_t pos = 0;
0023     getline(f, line);
0024     trim(line, " \t");
0025     if (line[0] == '#' || line.empty()) {  //comment line
0026       continue;
0027     }
0028     ++nstatements;
0029     string u = tokenize(line, ":/ \t", pos);
0030     if (u == user) {  //user found
0031       password = tokenize(line, ":/ \t", pos);
0032       found = true;
0033     }
0034   }
0035   if (!found && nstatements == 1) {  //login not found in the file
0036     //let's check if file does not contain a single password, w/o login
0037     f.clear();
0038     f.seekg(0, ios::beg);
0039     getline(f, line);
0040     trim(line, " \t");
0041     if (line.find_first_of(": \t") == string::npos) {  //no login/password delimiter
0042       //looks like a single password file
0043       password = line;
0044       found = true;
0045     }
0046   }
0047   if (!found) {
0048     throw cms::Exception("Database") << " Password for condition database user '" << user << "' not found in"
0049                                      << " password file " << fileName << "\n";
0050   }
0051 }
0052 
0053 std::string PasswordReader::tokenize(const string& s, const string& delim, size_t& pos) const {
0054   size_t pos0 = pos;
0055   size_t len = s.size();
0056   //eats delimeters at beginning of the string
0057   while (pos0 < s.size() && find(delim.begin(), delim.end(), s[pos0]) != delim.end()) {
0058     ++pos0;
0059   }
0060   if (pos0 >= len || pos0 == string::npos)
0061     return "";
0062   pos = s.find_first_of(delim, pos0);
0063   return s.substr(pos0, (pos > 0 ? pos : s.size()) - pos0);
0064 }
0065 
0066 std::string PasswordReader::trim(const std::string& s, const std::string& chars) const {
0067   std::string::size_type pos0 = s.find_first_not_of(chars);
0068   if (pos0 == std::string::npos) {
0069     pos0 = 0;
0070   }
0071   string::size_type pos1 = s.find_last_not_of(chars) + 1;
0072   if (pos1 == std::string::npos) {
0073     pos1 = pos0;
0074   }
0075   return s.substr(pos0, pos1 - pos0);
0076 }