fileutil.cpp 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282
  1. /*
  2. * Copyright 2005 - 2016 Zarafa and its licensors
  3. *
  4. * This program is free software: you can redistribute it and/or modify
  5. * it under the terms of the GNU Affero General Public License, version 3,
  6. * as published by the Free Software Foundation.
  7. *
  8. * This program is distributed in the hope that it will be useful,
  9. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  11. * GNU Affero General Public License for more details.
  12. *
  13. * You should have received a copy of the GNU Affero General Public License
  14. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  15. *
  16. */
  17. #include <kopano/platform.h>
  18. #include <kopano/stringutil.h>
  19. #include <kopano/charset/convert.h>
  20. #include <memory>
  21. #include <string>
  22. #include <cerrno>
  23. #include <cstring>
  24. #include <kopano/ECIConv.h>
  25. #include <kopano/ECLogger.h>
  26. #include <mapicode.h>
  27. #include <mapidefs.h>
  28. #include <sys/mman.h>
  29. #include <sys/socket.h>
  30. #include <sys/stat.h>
  31. #include <arpa/inet.h>
  32. #include "fileutil.h"
  33. #define BLOCKSIZE 65536
  34. namespace KC {
  35. /**
  36. * Reads the contents of a file, and writes it to the output file
  37. * while converting Unix \n enters to DOS \r\n enters.
  38. *
  39. * @todo this function prints errors to screen using perror(), which should be removed
  40. * @todo this function doesn't return the filepointer in case of an error, but also doesn't unlink the tempfile either.
  41. *
  42. * @param[in] fin input file to read strings from
  43. * @param[out] fout new filepointer to a temporary file
  44. *
  45. * @return MAPI error code
  46. */
  47. HRESULT HrFileLFtoCRLF(FILE *fin, FILE** fout)
  48. {
  49. char bufferin[BLOCKSIZE / 2];
  50. char bufferout[BLOCKSIZE+1];
  51. size_t sizebufferout;
  52. FILE* fTmp = NULL;
  53. if(fin == NULL || fout == NULL)
  54. return MAPI_E_INVALID_PARAMETER;
  55. fTmp = tmpfile();
  56. if(fTmp == NULL) {
  57. perror("Unable to create tmp file");
  58. return MAPI_E_CALL_FAILED;
  59. }
  60. while (!feof(fin)) {
  61. size_t readsize = fread(bufferin, 1, BLOCKSIZE / 2, fin);
  62. if (ferror(fin)) {
  63. perror("Read error");//FIXME: What an error?, what now?
  64. fclose(fTmp);
  65. return MAPI_E_CORRUPT_DATA;
  66. }
  67. BufferLFtoCRLF(readsize, bufferin, bufferout, &sizebufferout);
  68. if (fwrite(bufferout, 1, sizebufferout, fTmp) != sizebufferout) {
  69. perror("Write error");//FIXME: What an error?, what now?
  70. fclose(fTmp);
  71. return MAPI_E_CORRUPT_DATA;
  72. }
  73. }
  74. *fout = fTmp;
  75. return hrSuccess;
  76. }
  77. /**
  78. * align to page boundary (4k)
  79. *
  80. * @param size add "padding" to size to make sure it's a multiple 4096 bytes
  81. *
  82. * @return aligned size
  83. */
  84. static inline int mmapsize(unsigned int size)
  85. {
  86. return (((size + 1) >> 12) + 1) << 12;
  87. }
  88. /**
  89. * Load a file, first by trying to use mmap. If that fails, the whole
  90. * file is loaded in memory.
  91. *
  92. * @param[in] f file to read
  93. * @param[out] lppBuffer buffer containing the file contents
  94. * @param[out] lpSize length of the buffer
  95. * @param[out] lpImmap boolean denoting if the buffer is mapped or not (used when freeing the buffer)
  96. *
  97. * @return MAPI error code
  98. */
  99. static HRESULT HrMapFileToBuffer(FILE *f, char **lppBuffer, int *lpSize,
  100. bool *lpImmap)
  101. {
  102. char *lpBuffer = NULL;
  103. int offset = 0;
  104. long ulBufferSize = BLOCKSIZE;
  105. struct stat stat;
  106. int fd = fileno(f);
  107. *lpImmap = false;
  108. /* Try mmap first */
  109. if (fstat(fd, &stat) != 0) {
  110. perror("Stat failed");
  111. return MAPI_E_CALL_FAILED;
  112. }
  113. /* auto-zero-terminate because mmap zeroes bytes after the file */
  114. lpBuffer = (char *)mmap(0, mmapsize(stat.st_size), PROT_READ, MAP_PRIVATE, fd, 0);
  115. if (lpBuffer != MAP_FAILED) {
  116. *lpImmap = true;
  117. *lppBuffer = lpBuffer;
  118. *lpSize = stat.st_size;
  119. return hrSuccess;
  120. }
  121. /* mmap failed (probably reading from STDIN as a stream), just read the file into memory, and return that */
  122. lpBuffer = (char*)malloc(BLOCKSIZE); // will be deleted as soon as possible
  123. while (!feof(f)) {
  124. long ulReadsize = fread(lpBuffer+offset, 1, BLOCKSIZE, f);
  125. if (ferror(f)) {
  126. perror("Read error");
  127. break;
  128. }
  129. offset += ulReadsize;
  130. if (offset + BLOCKSIZE > ulBufferSize) { // Next read could cross buffer boundary, realloc
  131. auto lpRealloc = static_cast<char *>(realloc(lpBuffer, offset + BLOCKSIZE));
  132. if (lpRealloc == NULL) {
  133. free(lpBuffer);
  134. return MAPI_E_NOT_ENOUGH_MEMORY;
  135. }
  136. lpBuffer = lpRealloc;
  137. ulBufferSize += BLOCKSIZE;
  138. }
  139. }
  140. /* Nothing was read */
  141. if (offset == 0) {
  142. free(lpBuffer);
  143. *lppBuffer = NULL;
  144. *lpSize = 0;
  145. return hrSuccess;
  146. }
  147. /* Add terminate character */
  148. lpBuffer[offset] = 0;
  149. *lppBuffer = lpBuffer;
  150. *lpSize = offset;
  151. return hrSuccess;
  152. }
  153. /**
  154. * Free a buffer from HrMapFileToBuffer
  155. *
  156. * @param[in] lpBuffer buffer to free
  157. * @param[in] ulSize size of the buffer
  158. * @param[in] bImmap marker if the buffer is mapped or not
  159. */
  160. static HRESULT HrUnmapFileBuffer(char *lpBuffer, int ulSize, bool bImmap)
  161. {
  162. if (bImmap)
  163. munmap(lpBuffer, mmapsize(ulSize));
  164. else
  165. free(lpBuffer);
  166. return hrSuccess;
  167. }
  168. /**
  169. * Reads a file into a std::string using file mapping if possible.
  170. *
  171. * @todo doesn't the std::string undermine the whole idea of mapping?
  172. * @todo std::string has a length method, so what's with the lpSize parameter?
  173. *
  174. * @param[in] f file to read in memory
  175. * @param[out] lpstrBuffer string containing the file contents, optionally returned (why?)
  176. * @param[out] lpSize size of the buffer, optionally returned
  177. *
  178. * @return
  179. */
  180. HRESULT HrMapFileToString(FILE *f, std::string *lpstrBuffer, int *lpSize)
  181. {
  182. HRESULT hr = hrSuccess;
  183. char *lpBuffer = NULL;
  184. int ulBufferSize = 0;
  185. bool immap = false;
  186. hr = HrMapFileToBuffer(f, &lpBuffer, &ulBufferSize, &immap); // what if message was half read?
  187. if (hr != hrSuccess || !lpBuffer)
  188. goto exit;
  189. if (lpstrBuffer)
  190. *lpstrBuffer = std::string(lpBuffer, ulBufferSize);
  191. if (lpSize)
  192. *lpSize = ulBufferSize;
  193. exit:
  194. if (lpBuffer)
  195. HrUnmapFileBuffer(lpBuffer, ulBufferSize, immap);
  196. return hr;
  197. }
  198. /**
  199. * Duplicate a file, to a given location
  200. *
  201. * @param[in] lpFile Pointer to the source file
  202. * @param[in] strFileName The new filename
  203. *
  204. * @return The result of the duplication of the file
  205. *
  206. * @todo on error delete file?
  207. */
  208. bool DuplicateFile(FILE *lpFile, std::string &strFileName)
  209. {
  210. bool bResult = true;
  211. size_t ulReadsize = 0;
  212. FILE *pfNew = NULL;
  213. std::unique_ptr<char[]> lpBuffer;
  214. // create new file
  215. pfNew = fopen(strFileName.c_str(), "wb");
  216. if(pfNew == NULL) {
  217. ec_log_err("Unable to create file %s: %s", strFileName.c_str(), strerror(errno));
  218. bResult = false;
  219. goto exit;
  220. }
  221. // Set file pointer at the begin.
  222. rewind(lpFile);
  223. lpBuffer.reset(new(std::nothrow) char[BLOCKSIZE]);
  224. if (!lpBuffer) {
  225. ec_log_crit("DuplicateFile is out of memory");
  226. bResult = false;
  227. goto exit;
  228. }
  229. // FIXME use splice
  230. while (!feof(lpFile)) {
  231. ulReadsize = fread(lpBuffer.get(), 1, BLOCKSIZE, lpFile);
  232. if (ferror(lpFile)) {
  233. ec_log_crit("DuplicateFile: fread: %s", strerror(errno));
  234. bResult = false;
  235. goto exit;
  236. }
  237. if (fwrite(lpBuffer.get(), 1, ulReadsize , pfNew) != ulReadsize) {
  238. ec_log_crit("Error during write to \"%s\": %s", strFileName.c_str(), strerror(errno));
  239. bResult = false;
  240. goto exit;
  241. }
  242. }
  243. exit:
  244. if (pfNew)
  245. fclose(pfNew);
  246. return bResult;
  247. }
  248. } /* namespace */