bes  Updated for version 3.19.1
BESHandlerUtil.cc
1 // -*- mode: c++; c-basic-offset:4 -*-
2 
3 // This file is part of the BES, A C++ implementation of the OPeNDAP Data
4 // Access Protocol.
5 
6 // Copyright (c) 2016 OPeNDAP, Inc.
7 // Author: James Gallagher <jgallagher@opendap.org>
8 //
9 // This library is free software; you can redistribute it and/or
10 // modify it under the terms of the GNU Lesser General Public
11 // License as published by the Free Software Foundation; either
12 // version 2.1 of the License, or (at your option) any later version.
13 //
14 // This library is distributed in the hope that it will be useful,
15 // but WITHOUT ANY WARRANTY; without even the implied warranty of
16 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
17 // Lesser General Public License for more details.
18 //
19 // You should have received a copy of the GNU Lesser General Public
20 // License along with this library; if not, write to the Free Software
21 // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
22 //
23 // You can contact OPeNDAP, Inc. at PO Box 112, Saunderstown, RI. 02874-0112.
24 
25 #include <sys/stat.h>
26 #include <unistd.h>
27 
28 #include <cstdlib>
29 #include <cstring>
30 #include <cerrno>
31 #include <vector>
32 #include <string>
33 
34 #include <BESInternalError.h>
35 
36 #include "BESHandlerUtil.h"
37 #include "BESLog.h"
38 
39 using namespace std;
40 
41 namespace bes {
42 
48 TemporaryFile::~TemporaryFile()
49 {
50  try {
51  if (!close(d_fd))
52  ERROR(string("Error closing temporary file: ").append(&d_name[0]).append(": ").append(strerror(errno)));
53  if (!unlink(&d_name[0]))
54  ERROR(string("Error closing temporary file: ").append(&d_name[0]).append(": ").append(strerror(errno)));
55  }
56  catch (...) {
57  // Do nothing. This just protects against BESLog (i.e., ERROR)
58  // throwing an exception
59  }
60 }
61 
74 TemporaryFile::TemporaryFile(const std::string &path_template)
75 {
76  //string temp_file_name = FONcRequestHandler::temp_dir + "/ncXXXXXX";
77  //vector<char> temp_file(path_template.length() + 1);
78  d_name.reserve(path_template.length() + 1);
79 
80  string::size_type len = path_template.copy(&d_name[0], path_template.length());
81  d_name[len] = '\0';
82 
83  // cover the case where older versions of mkstemp() create the file using
84  // a mode of 666.
85  mode_t original_mode = umask(077);
86  d_fd = mkstemp(&d_name[0]);
87  umask(original_mode);
88 
89  if (d_fd == -1) throw BESInternalError("Failed to open the temporary file.", __FILE__, __LINE__);
90 }
91 
92 } // namespace bes
93 
94 
exception thrown if inernal error encountered