CurlFtp.cpp 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950
  1. #include "CurlFtp.h"
  2. #include <regex>
  3. #include <iosfwd>
  4. #include <filesystem>
  5. #include <fstream>
  6. #include "fmtlog.h"
  7. #if defined(_WIN32)
  8. #endif /* _WIN32 */
  9. /* ==================================================================================
  10. * *********************************** 全局变量 *************************************
  11. * ==================================================================================
  12. */
  13. /* 是否有初始化实例,主要用于静态函数调用curl_global_cleanup()函数前判断,有实例就不调用 */
  14. static bool hasInstace = false;
  15. /* ==================================================================================
  16. * *********************************** 全局函数 *************************************
  17. * ==================================================================================
  18. */
  19. /**
  20. * @brief 写入回调函数
  21. *
  22. * @param contents curl的数据缓冲区
  23. * @param size 数据大小,单位是size_t
  24. * @param nmemb size_t的单位字节数
  25. * @param userStr 用户提供的字符串,格式可以是任意的
  26. * @return size_t 总共获取到的数据大小,单位是字节
  27. */
  28. static size_t writeStringCallback(void *contents, size_t size, size_t nmemb, std::string *userStr)
  29. {
  30. size_t newLength = size * nmemb;
  31. size_t oldLength = userStr->size();
  32. try
  33. {
  34. userStr->resize(oldLength + newLength);
  35. }
  36. catch(std::bad_alloc &e)
  37. {
  38. //handle memory problem
  39. return 0;
  40. }
  41. std::copy_n((char*)contents, newLength, userStr->begin() + oldLength);
  42. return size * nmemb;
  43. }
  44. /**
  45. * @brief 写入回调函数,listFiles需要调用
  46. *
  47. * @param buffer curl下载回来的数据
  48. * @param size 数据大小
  49. * @param nmemb 数据单位字节数
  50. * @param userp 用户传进来的容器
  51. * @return int 返回拷贝的字节数
  52. */
  53. static int writeStringListCallback(void* buffer, size_t size, size_t nmemb, void* userp)
  54. {
  55. std::vector<std::string>* fileList = static_cast<std::vector<std::string>*>(userp);
  56. std::string line(static_cast<char*>(buffer), size * nmemb);
  57. // printf("line = %s\n", line.c_str());
  58. fileList->push_back(line);
  59. return size * nmemb;
  60. }
  61. /**
  62. * @brief 写入文件回调函数
  63. *
  64. * @param contents 读取到的数据内容
  65. * @param size 数据大小
  66. * @param nmemb 数据单位
  67. * @param pFile 文件指针
  68. * @return size_t 实际读取的大小
  69. */
  70. static size_t writeDataCallBack(void* contents, size_t size, size_t nmemb, std::ostream* pFile)
  71. {
  72. pFile->write(reinterpret_cast<char*>(contents), size * nmemb);
  73. return size * nmemb;
  74. }
  75. /**
  76. * @brief 读取文件回调函数
  77. *
  78. * @param contents 下载到的数据内容
  79. * @param size 数据大小
  80. * @param nmemb 数据单位
  81. * @param pFile 文件指针
  82. * @return size_t 写入的大小
  83. */
  84. static size_t readDataCallBack(void* contents, size_t size, size_t nmemb, std::istream* pFile)
  85. {
  86. pFile->read(reinterpret_cast<char*>(contents), size * nmemb);
  87. /* 获取读取到的字节数,可能读取到文件末尾,所以不能直接使用传入的字节数 */
  88. size_t readSize = pFile->gcount();
  89. return readSize;
  90. }
  91. /**
  92. * @brief 上传和下载进度回调函数,这个函数kennel会被多次调用,即使是没有在下载的时候,因此需要判断传入的数据是否是0
  93. * 必须将 CURLOPT_NOPROGRESS 设为 0 才能真正调用该函数。
  94. *
  95. * @param clientp 通过CURLOPT_XFERINFODATA 设置的指针,libcurl 不会使用它,只会将其从应用程序传递给回调函数。
  96. * 可以通过这个指针将下载的进度传递给应用程序
  97. * @param dltotal 下载的总字节数,上传的时候这个为0
  98. * @param dlnow 已经下载的总字节数
  99. * @param ultotal 需要上传的总字节数,下载的时候这个为0
  100. * @param ulnow 已经上传的总字节数
  101. * @return int
  102. */
  103. static int progress_callback(void *clientp,
  104. curl_off_t dltotal,
  105. curl_off_t dlnow,
  106. curl_off_t ultotal,
  107. curl_off_t ulnow)
  108. {
  109. // FMTLOG_DEBUG("dTotal: {}, dNow: {}, uTotal: {}, uNow: {}", dltotal, dlnow, ultotal, ulnow);
  110. if(dltotal == 0 && ultotal == 0)
  111. {
  112. return 0;
  113. }
  114. /* 正在下载 */
  115. if(dltotal > 0)
  116. {
  117. /* 计算进度,百分比 */
  118. double downloadPercent = (double)dlnow / (double)dltotal * 100;
  119. /* 使用回车刷新这一行 */
  120. FMTLOG_DEBUG_NON("Download Total / now : {} / {}, {:.2f}%\r", dltotal, dlnow, downloadPercent);
  121. }
  122. /* 正在上传 */
  123. else if(ultotal > 0)
  124. {
  125. double uploadPercent = (double)ulnow / (double)ultotal * 100;
  126. FMTLOG_DEBUG_NON("Upload Total / now : {} / {}, {:.2f}%\r", ultotal, ulnow, uploadPercent);
  127. }
  128. return 0;
  129. }
  130. /* 使用Windows API进行编码转换 */
  131. #if defined(_WIN32)
  132. static char* GBToUTF8(const char* gb2312)
  133. {
  134. int len = MultiByteToWideChar(CP_ACP, 0, gb2312, -1, NULL, 0);
  135. wchar_t* wstr = new wchar_t[len+1];
  136. memset(wstr, 0, len+1);
  137. MultiByteToWideChar(CP_ACP, 0, gb2312, -1, wstr, len);
  138. len = WideCharToMultiByte(CP_UTF8, 0, wstr, -1, NULL, 0, NULL, NULL);
  139. char* str = new char[len+1];
  140. memset(str, 0, len+1);
  141. WideCharToMultiByte(CP_UTF8, 0, wstr, -1, str, len, NULL, NULL);
  142. if(wstr) delete[] wstr;
  143. return str;
  144. }
  145. #endif /* _WIN32 */
  146. /**
  147. * @brief 解析字符串文件信息,如果FTP服务器规定好个编码,不需要进行转换
  148. *
  149. * @param strSrc 读取到的字符串
  150. * @param fileList 文件信息列表
  151. * @return true
  152. * @return false
  153. */
  154. static bool parseFileInfo(const std::string& strSrc, std::vector<CF_FileInfo>& fileInfo)
  155. {
  156. #if defined(_WIN32)
  157. // auto str1 = GBToUTF8(strSrc.c_str());
  158. std::string str2 = strSrc;
  159. #else
  160. std::string str2 = strSrc;
  161. #endif /* _WIN32 */
  162. // FMTLOG_DEBUG("\n{}", str2);
  163. /* 正则表达式,匹配多个空格 */
  164. std::regex reg(R"(( )+)");
  165. /* 匹配以非空格开头的字符,空格隔开,中间任意字符,空格隔开,非空格组成的结尾
  166. * (文件类型) ... (文件大小,$5) ... (文件名)
  167. */
  168. std::regex reg1(R"(^([^ ]+) (\d*) (\w*) (\w*) (\d*) (.*) ([^ ]+)$)");
  169. // FMTLOG_INFO("\n-------------------\n");
  170. /* 匹配换行符,分割每一行 */
  171. std::regex reg2(R"(\n)");
  172. /* 匹配文件夹 */
  173. std::regex reg3(R"(^d.*)");
  174. /* 匹配文件 */
  175. std::regex reg4(R"(^-.*$)");
  176. /* -1 表示对正则表达式之前的子序列感兴趣
  177. * 0 表示对正则表达式本身感兴趣,输出的就是换行符 */
  178. std::sregex_token_iterator it2(str2.begin(), str2.end(), reg2, -1);
  179. /* 这里取出每一行 */
  180. for(; it2 != std::sregex_token_iterator(); ++it2)
  181. {
  182. /* 去掉多余的空格 */
  183. auto line = std::regex_replace(it2->str(), reg, " ");
  184. // FMTLOG_INFO("{}", line);
  185. CF_FileInfo fi;
  186. /* 取出文件类型 */
  187. std::string strFileType = std::regex_replace(line, reg1, "$1");
  188. if(std::regex_match(strFileType, reg3))
  189. {
  190. fi.type = CF_FileType::DIR;
  191. }else if (std::regex_match(strFileType, reg4))
  192. {
  193. fi.type = CF_FileType::FILE;
  194. }
  195. /* 取出文件大小 */
  196. std::string strFileSize = std::regex_replace(line, reg1, "$5");
  197. fi.size = std::stoull(strFileSize);
  198. /* 取出文件名 */
  199. std::string strFileName = std::regex_replace(line, reg1, "$7");
  200. fi.name = strFileName;
  201. /* 加入队列 */
  202. fileInfo.push_back(fi);
  203. }
  204. return true;
  205. }
  206. /* ==================================================================================
  207. * *********************************** 成员函数 *************************************
  208. * ================================================================================== */
  209. CurlFtp::CurlFtp()
  210. {
  211. /* 调用初始化函数,这个函数可以重复调用 */
  212. curl_global_init(CURL_GLOBAL_DEFAULT);
  213. /* 初始化curl */
  214. hasInstace = true;
  215. }
  216. CurlFtp::~CurlFtp()
  217. {
  218. /* 清理curl */
  219. curl_global_cleanup();
  220. hasInstace = false;
  221. }
  222. /**
  223. * @brief 列出FTP文件夹
  224. *
  225. * @param ftpUrl 需要列出文件夹的FTP地址
  226. * @param username
  227. * @param password
  228. * @return std::string
  229. */
  230. std::string CurlFtp::listDir(const std::string &ftpUrl, const std::string &username, const std::string &password)
  231. {
  232. CURL *curl;
  233. CURLcode res;
  234. bool result = false;
  235. std::string retList;
  236. /* 1. 初始化curl,这个函数需要在调用任何curl函数之前 */
  237. curl_global_init(CURL_GLOBAL_DEFAULT);
  238. /* 2. 获取一个curl句柄 */
  239. curl = curl_easy_init();
  240. if(curl)
  241. {
  242. /* 3. 设置curl选项 */
  243. curl_easy_setopt(curl, CURLOPT_URL, ftpUrl.c_str());
  244. curl_easy_setopt(curl, CURLOPT_USERNAME, username.c_str());
  245. curl_easy_setopt(curl, CURLOPT_PASSWORD, password.c_str());
  246. // curl_easy_setopt(curl, CURLOPT_DIRLISTONLY, 1L); // We only want the directory listing
  247. curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, writeStringCallback);
  248. curl_easy_setopt(curl, CURLOPT_WRITEDATA, &retList);
  249. /* 4. 发送信息,一直等待知道返回 */
  250. res = curl_easy_perform(curl);
  251. // printf("res = %d\n", res);
  252. if(res != CURLE_OK)
  253. {
  254. fprintf(stderr, "getDirList() failed, error code %d, :%s\n",res, curl_easy_strerror(res));
  255. } else
  256. {
  257. // std::cout << "Directory list: \n" << retList << std::endl;
  258. }
  259. /* 5. 清理curl */
  260. curl_easy_cleanup(curl);
  261. }
  262. if(hasInstace == false)
  263. {
  264. curl_global_cleanup();
  265. }
  266. return retList;
  267. }
  268. /* 列出文件夹中的所有文件 */
  269. bool CurlFtp::listFiles(const std::string &ftpUrl, const std::string &username, const std::string &password, std::vector<std::string>& fileList)
  270. {
  271. CURL *curl;
  272. CURLcode res;
  273. bool result = false;
  274. curl_global_init(CURL_GLOBAL_DEFAULT);
  275. curl = curl_easy_init();
  276. if(curl)
  277. {
  278. curl_easy_setopt(curl, CURLOPT_URL, (ftpUrl).c_str());
  279. curl_easy_setopt(curl, CURLOPT_USERNAME, username.c_str());
  280. curl_easy_setopt(curl, CURLOPT_PASSWORD, password.c_str());
  281. curl_easy_setopt(curl, CURLOPT_DIRLISTONLY, 1L);
  282. curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, writeStringListCallback);
  283. curl_easy_setopt(curl, CURLOPT_WRITEDATA, &fileList);
  284. res = curl_easy_perform(curl);
  285. if(res != CURLE_OK)
  286. {
  287. fprintf(stderr, "Failed to get file list, error code :%d ,%s\n", res, curl_easy_strerror(res));
  288. }
  289. else
  290. {
  291. // for(const std::string& filename : fileList)
  292. // {
  293. // printf("%s\n", filename.c_str());
  294. // }
  295. result = true;
  296. }
  297. curl_easy_cleanup(curl);
  298. }
  299. if(hasInstace == false)
  300. {
  301. curl_global_cleanup();
  302. }
  303. return result;
  304. }
  305. /* 创建文件夹 */
  306. bool CurlFtp::createDir(const std::string &ftpUrl, const std::string &username, const std::string &password, const std::string &dirName)
  307. {
  308. CURL *curl;
  309. CURLcode res;
  310. bool result = false;
  311. curl_global_init(CURL_GLOBAL_DEFAULT);
  312. curl = curl_easy_init();
  313. if(curl)
  314. {
  315. curl_easy_setopt(curl, CURLOPT_URL, ftpUrl.c_str());
  316. curl_easy_setopt(curl, CURLOPT_USERNAME, username.c_str());
  317. curl_easy_setopt(curl, CURLOPT_PASSWORD, password.c_str());
  318. // Create a list of FTP commands to be executed on the server
  319. struct curl_slist *headerlist = NULL;
  320. std::string mkdir = "MKD " + dirName;
  321. headerlist = curl_slist_append(headerlist, mkdir.c_str());
  322. // Set the list of FTP commands to be executed on the server before the transfer
  323. curl_easy_setopt(curl, CURLOPT_QUOTE, headerlist);
  324. // Tell libcurl to not include the body in the output
  325. curl_easy_setopt(curl, CURLOPT_NOBODY, 1L);
  326. res = curl_easy_perform(curl);
  327. if(res != CURLE_OK)
  328. {
  329. fprintf(stderr, "createDir() failed, error code :%d ,%s\n", res, curl_easy_strerror(res));
  330. result = false;
  331. }else
  332. {
  333. result = true;
  334. }
  335. curl_easy_cleanup(curl);
  336. curl_slist_free_all(headerlist);
  337. }
  338. if(hasInstace == false)
  339. {
  340. curl_global_cleanup();
  341. }
  342. return result;
  343. }
  344. /* 设置IP和端口 */
  345. bool CurlFtp::setFtpIPAndPort(const std::string& IP, const int port)
  346. {
  347. /*先判断是否有ftp器前缀,通过正则表达式,取出IP地址和端口号,去掉前缀和后面的'/ */
  348. m_IP = IP;
  349. m_port = port;
  350. m_ftpUrl = "ftp://" + m_IP + ":" + std::to_string(m_port);
  351. FMTLOG_INFO("Set ftpUrl = {}", m_ftpUrl);
  352. return true;
  353. }
  354. /* 设置用户名和密码 */
  355. bool CurlFtp::setFtpUsernameAndPassword(const std::string& username, const std::string& password)
  356. {
  357. m_username = username;
  358. m_password = password;
  359. return true;
  360. }
  361. /* 列出文件列表 */
  362. bool CurlFtp::getFileList(std::string dir, std::vector<std::string>& fileList)
  363. {
  364. if(m_IP.empty())
  365. {
  366. FMTLOG_WARN("IP or port is empty");
  367. return false;
  368. }
  369. /* 检查dir,添加前缀“/” */
  370. auto dirTmp = checkDirPath(dir);
  371. CURL *curl = nullptr;
  372. curl = curl_easy_init();
  373. if(curl == nullptr)
  374. {
  375. FMTLOG_ERROR("curl init failed !");
  376. return false;
  377. }
  378. std::vector<CF_FileInfo> listInfo;
  379. /* 获取文件信息 */
  380. listAll(curl, dirTmp, listInfo);
  381. for(const CF_FileInfo& fi : listInfo)
  382. {
  383. // FMTLOG_INFO("type = {}, size = {}, name = {}", (int)fi.type, fi.size, fi.name);
  384. if(fi.type == CF_FileType::FILE)
  385. {
  386. fileList.push_back(fi.name);
  387. }
  388. }
  389. curl_easy_cleanup(curl);
  390. return true;
  391. }
  392. /* 获取文件夹列表 */
  393. bool CurlFtp::getDirList(std::string dir, std::vector<std::string>& dirList)
  394. {
  395. if(m_IP.empty())
  396. {
  397. FMTLOG_WARN("IP or port is empty");
  398. return false;
  399. }
  400. /* 检查dir,添加前缀“/” */
  401. auto dirTmp = checkDirPath(dir);
  402. CURL *curl = nullptr;
  403. curl = curl_easy_init();
  404. if(curl == nullptr)
  405. {
  406. FMTLOG_ERROR("curl init failed !");
  407. return false;
  408. }
  409. std::vector<CF_FileInfo> listInfo;
  410. /* 获取文件信息 */
  411. listAll(curl, dirTmp, listInfo);
  412. for(const CF_FileInfo& fi : listInfo)
  413. {
  414. // FMTLOG_INFO("type = {}, size = {}, name = {}", (int)fi.type, fi.size, fi.name);
  415. if(fi.type == CF_FileType::DIR)
  416. {
  417. dirList.push_back(fi.name);
  418. }
  419. }
  420. curl_easy_cleanup(curl);
  421. return true;
  422. }
  423. /* 判断文件夹是否存在 */
  424. bool CurlFtp::isDirExist(const std::string& dir)
  425. {
  426. if(m_ftpUrl.empty())
  427. {
  428. FMTLOG_ERROR("ftpUrl is empty");
  429. return false;
  430. }
  431. /* 检查传入的文件夹 */
  432. auto dirTmp = checkDirPath(dir);
  433. CURL* curl = nullptr;
  434. curl = curl_easy_init();
  435. if(curl == nullptr)
  436. {
  437. FMTLOG_ERROR("curl init failed !");
  438. return false;
  439. }
  440. std::string ftpUrl = m_ftpUrl + dirTmp;
  441. curl_easy_setopt(curl, CURLOPT_URL, ftpUrl.c_str());
  442. curl_easy_setopt(curl, CURLOPT_USERNAME, m_username.c_str());
  443. curl_easy_setopt(curl, CURLOPT_PASSWORD, m_password.c_str());
  444. /* 获取文件夹是否存在,不需要接收文件 */
  445. curl_easy_setopt(curl, CURLOPT_NOBODY, 1L);
  446. CURLcode res = curl_easy_perform(curl);
  447. bool result = true;
  448. if(res != CURLE_OK)
  449. {
  450. // FMTLOG_ERROR("Failed to get file list, error code: {} ,{}", (int)res, curl_easy_strerror(res));
  451. result = false;
  452. }
  453. return result;
  454. }
  455. /**
  456. * @brief 创建FTP文件夹,只能创建一层文件夹
  457. *
  458. * @param ftpDir 文件夹路径
  459. * @return true 文件夹创建成功或者文件夹存在
  460. * @return false
  461. */
  462. bool CurlFtp::createDirectory(const std::string& ftpDir)
  463. {
  464. if(m_ftpUrl.empty())
  465. {
  466. FMTLOG_ERROR("ftpUrl is empty");
  467. return false;
  468. }
  469. /* 先检查FTP文件夹是否存在,如果存在直接返回true */
  470. if(isDirExist(ftpDir))
  471. {
  472. return true;
  473. }
  474. /* 检查传入的文件夹格式 */
  475. auto dirTmp = checkDirPath(ftpDir);
  476. CURL *curl = curl_easy_init();
  477. if(curl == nullptr)
  478. {
  479. FMTLOG_ERROR("Create FTP DIR, curl init failed !");
  480. return false;
  481. }
  482. curl_easy_setopt(curl, CURLOPT_URL, m_ftpUrl.c_str());
  483. curl_easy_setopt(curl, CURLOPT_USERNAME, m_username.c_str());
  484. curl_easy_setopt(curl, CURLOPT_PASSWORD, m_password.c_str());
  485. /* 创建FTP头信息 */
  486. struct curl_slist *headerlist = NULL;
  487. std::string mkdir = "MKD " + dirTmp;
  488. headerlist = curl_slist_append(headerlist, mkdir.c_str());
  489. /* 设置FTP命令行选项 */
  490. curl_easy_setopt(curl, CURLOPT_QUOTE, headerlist);
  491. /* 不包含实体 */
  492. curl_easy_setopt(curl, CURLOPT_NOBODY, 1L);
  493. /* 启用跟随重定向 */
  494. curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1L);
  495. /* 设置超时时间 */
  496. curl_easy_setopt(curl, CURLOPT_TIMEOUT, 30L);
  497. curl_easy_setopt(curl, CURLOPT_CONNECTTIMEOUT, 30L);
  498. CURLcode res = curl_easy_perform(curl);
  499. bool result = true;
  500. if(res != CURLE_OK)
  501. {
  502. FMTLOG_ERROR("Failed to create FTP Dir, error code: {} ,{}", (int)res, curl_easy_strerror(res));
  503. result = false;
  504. }else
  505. {
  506. result = true;
  507. }
  508. curl_easy_cleanup(curl);
  509. curl_slist_free_all(headerlist);
  510. return result;
  511. }
  512. /* 创建FTP文件夹,递归创建 */
  513. bool CurlFtp::createDirectories(const std::string& ftpDir)
  514. {
  515. /* 检查路径格式,并去掉第一个 / */
  516. std::string ftpDirTmp = checkDirPath(ftpDir);
  517. std::string ftpDir2 = ftpDirTmp.substr(1, ftpDirTmp.size() -1);
  518. /* 将文件夹分开,取出每一个文件夹名称 */
  519. std::vector<std::string> strList;
  520. std::regex reg(R"(/)");
  521. std::sregex_token_iterator it(ftpDir2.begin(), ftpDir2.end(), reg, -1);
  522. for( ; it != std::sregex_token_iterator(); ++it)
  523. {
  524. strList.push_back(it->str());
  525. }
  526. /* 将每一层拼接起来,逐层递归 */
  527. std::vector<std::string> dirList;
  528. for(const std::string& dir : strList)
  529. {
  530. std::string dirTmp = "/";
  531. if(!dirList.empty())
  532. {
  533. dirTmp = dirList.back();
  534. dirTmp += "/";
  535. }
  536. dirTmp += dir;
  537. dirList.push_back(dirTmp);
  538. }
  539. /* 逐层创建 */
  540. for(const std::string& dir : dirList)
  541. {
  542. // FMTLOG_DEBUG("Create dir: {}", dir);
  543. if(!createDirectory(dir))
  544. {
  545. FMTLOG_ERROR("Failed to create dir: {}", dir);
  546. return false;
  547. }
  548. }
  549. return true;
  550. }
  551. /* 下载文件 */
  552. bool CurlFtp::downloadFile(const std::string& remoteFile, const std::string& localFile)
  553. {
  554. if(m_ftpUrl.empty())
  555. {
  556. FMTLOG_ERROR("ftpUrl is empty");
  557. return false;
  558. }
  559. /* 检查传入的文件是否符合规范 */
  560. std::string remoteFileTmp = checkFilePath(remoteFile);
  561. std::string ftpUrl = m_ftpUrl + remoteFileTmp;
  562. /* 检查本地文件夹是否存在,不存在则创建 */
  563. // std::string localDir = localFile.substr(0, localFile.find_last_of("/")); /* 去掉最后的 / */
  564. std::string localDirTmp = localFile.substr(0, localFile.find_last_of("/"));
  565. if(!checkLocalDir(localDirTmp))
  566. {
  567. FMTLOG_ERROR("Failed to create local dir: {}", localDirTmp);
  568. return false;
  569. }
  570. CURL* curl = nullptr;
  571. curl = curl_easy_init();
  572. if(curl == nullptr)
  573. {
  574. FMTLOG_ERROR("curl init failed !");
  575. return false;
  576. }
  577. /* 打开文件 */
  578. std::ofstream ofs;
  579. ofs.open(localFile, std::ios::out | std::ios::binary | std::ios::trunc);
  580. /* 设置FTP地址 */
  581. curl_easy_setopt(curl, CURLOPT_URL, ftpUrl.c_str());
  582. curl_easy_setopt(curl, CURLOPT_PORT, m_port);
  583. /* 设置用户名和密码 */
  584. curl_easy_setopt(curl, CURLOPT_USERNAME, m_username.c_str());
  585. curl_easy_setopt(curl, CURLOPT_PASSWORD, m_password.c_str());
  586. /* 启用跟随重定向 */
  587. curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1L);
  588. /* 设置回调函数 */
  589. curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, writeDataCallBack);
  590. curl_easy_setopt(curl, CURLOPT_WRITEDATA, &ofs);
  591. /* 设置超时时间 */
  592. // curl_easy_setopt(curl, CURLOPT_TIMEOUT, 30L);
  593. curl_easy_setopt(curl, CURLOPT_CONNECTTIMEOUT, 30L);
  594. /* 设置进度回调函数 */
  595. curl_easy_setopt(curl, CURLOPT_XFERINFOFUNCTION, progress_callback);
  596. curl_easy_setopt(curl, CURLOPT_XFERINFODATA, nullptr);
  597. /* 启用下载进度回调函数 */
  598. curl_easy_setopt(curl, CURLOPT_NOPROGRESS, 0L);
  599. /* 发送请求 */
  600. CURLcode res = curl_easy_perform(curl);
  601. if(res != CURLE_OK)
  602. {
  603. FMTLOG_ERROR("Failed to get file list, error code: {} ,{}", (int)res, curl_easy_strerror(res));
  604. FMTLOG_ERROR("ftpUrl = {}", ftpUrl);
  605. /* 清理下载失败的文件 */
  606. ofs.close();
  607. std::remove(localFile.c_str());
  608. return false;
  609. }
  610. /* 关闭文件,清理curl */
  611. ofs.close();
  612. curl_easy_cleanup(curl);
  613. /* 打印一个换行符 */
  614. FMTLOG_DEBUG_NON("\n");
  615. return true;
  616. }
  617. /**
  618. * @brief 上传文件
  619. *
  620. * @param localFile 本地文件
  621. * @param remoteFile 远程文件
  622. * @return true
  623. * @return false
  624. */
  625. bool CurlFtp::uploadFile(const std::string& localFile, const std::string& remoteFile)
  626. {
  627. if(m_ftpUrl.empty())
  628. {
  629. FMTLOG_ERROR("ftpUrl is empty");
  630. return false;
  631. }
  632. /* 检查本地文件是否存在 */
  633. if(!std::filesystem::exists(localFile))
  634. {
  635. FMTLOG_ERROR("Local file is not exist: {}", localFile);
  636. return false;
  637. }
  638. /* 检查FTP文件名是否符合规范 */
  639. std::string remoteFileTmp = checkFilePath(remoteFile);
  640. std::string remoteDirTmp = remoteFileTmp.substr(0, remoteFileTmp.find_last_of("/"));
  641. /* 检查远程FTP上的文件夹是否存在,不存在则创建 */
  642. if(!isDirExist(remoteDirTmp))
  643. {
  644. if(!createDirectories(remoteDirTmp))
  645. {
  646. // FMTLOG_ERROR("Failed to create remote dir: {}", remoteFileTmp);
  647. return false;
  648. }
  649. }
  650. /* 拼接远程文件的url */
  651. std::string ftpUrl = m_ftpUrl + remoteFileTmp;
  652. /* 打开文件 */
  653. std::ifstream ifs;
  654. ifs.open(localFile, std::ios::in | std::ios::binary);
  655. if(!ifs.is_open())
  656. {
  657. FMTLOG_ERROR("Failed to open local file: {}", localFile);
  658. return false;
  659. }
  660. /* 获取文件大小 */
  661. // auto startPos = ifs.tellg();
  662. ifs.seekg(0, std::ios::end);
  663. auto fileSize = ifs.tellg();
  664. /* 恢复指针到文件头 */
  665. ifs.seekg(0, std::ios::beg);
  666. FMTLOG_DEBUG("File size: {}", (long)fileSize);
  667. CURL* curl = nullptr;
  668. curl = curl_easy_init();
  669. if(curl == nullptr)
  670. {
  671. FMTLOG_ERROR("curl init failed !");
  672. ifs.close();
  673. return false;
  674. }
  675. /* 设置FTP地址 */
  676. curl_easy_setopt(curl, CURLOPT_URL, ftpUrl.c_str());
  677. curl_easy_setopt(curl, CURLOPT_PORT, m_port);
  678. /* 设置用户名和密码 */
  679. curl_easy_setopt(curl, CURLOPT_USERNAME, m_username.c_str());
  680. curl_easy_setopt(curl, CURLOPT_PASSWORD, m_password.c_str());
  681. /* 启用跟随重定向 */
  682. curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1L);
  683. /* 启用上传 */
  684. curl_easy_setopt(curl, CURLOPT_UPLOAD, 1L);
  685. /* 设置回调函数 */
  686. curl_easy_setopt(curl, CURLOPT_READFUNCTION, readDataCallBack);
  687. curl_easy_setopt(curl, CURLOPT_READDATA, &ifs);
  688. /* 设置上传文件的大小 */
  689. curl_easy_setopt(curl, CURLOPT_INFILESIZE_LARGE, (curl_off_t)fileSize);
  690. /* 设置超时时间 */
  691. // curl_easy_setopt(curl, CURLOPT_TIMEOUT, 30L);
  692. curl_easy_setopt(curl, CURLOPT_CONNECTTIMEOUT, 30L);
  693. /* 设置进度回调函数 */
  694. curl_easy_setopt(curl, CURLOPT_XFERINFOFUNCTION, progress_callback);
  695. curl_easy_setopt(curl, CURLOPT_XFERINFODATA, nullptr);
  696. /* 启用下载进度回调函数 */
  697. curl_easy_setopt(curl, CURLOPT_NOPROGRESS, 0L);
  698. /* 发送请求 */
  699. CURLcode res = curl_easy_perform(curl);
  700. bool result = true;
  701. if(res != CURLE_OK)
  702. {
  703. FMTLOG_ERROR("Upload file failed, error code: {} ,{}", (int)res, curl_easy_strerror(res));
  704. FMTLOG_ERROR("ftpUrl = {}", ftpUrl);
  705. result = false;
  706. }
  707. /* 关闭文件,清理curl */
  708. ifs.close();
  709. curl_easy_cleanup(curl);
  710. /* 打印一个换行符 */
  711. FMTLOG_DEBUG_NON("\n");
  712. return result;
  713. }
  714. /**
  715. * @brief 列出文件列表,这个需要的参数很多,无法设置成静态函数
  716. *
  717. * @param curl CURL句柄
  718. * @param dir 文件夹,相对路径,不带有IP和端口号
  719. * @param fileList 返回值,文件列表
  720. * @return true
  721. * @return false
  722. */
  723. bool CurlFtp::listAll(CURL* curl, std::string dir, std::vector<CF_FileInfo>& fileInfoList)
  724. {
  725. if(m_IP.empty())
  726. {
  727. FMTLOG_ERROR("IP is empty");
  728. return false;
  729. }
  730. if(curl == nullptr)
  731. {
  732. FMTLOG_ERROR("curl is nullptr");
  733. return false;
  734. }
  735. bool result = false;
  736. std::string strSrc;
  737. /* 先设置FTP地址 */
  738. std::string ftpUrl = m_ftpUrl + dir;
  739. curl_easy_setopt(curl, CURLOPT_URL, ftpUrl.c_str());
  740. curl_easy_setopt(curl, CURLOPT_PORT, m_port);
  741. /* 设置用户名和密码 */
  742. curl_easy_setopt(curl, CURLOPT_USERNAME, m_username.c_str());
  743. curl_easy_setopt(curl, CURLOPT_PASSWORD, m_password.c_str());
  744. /* 设置列出文件命令,只列出文件名称,不携带信息 */
  745. // curl_easy_setopt(m_curl, CURLOPT_DIRLISTONLY, 1L);
  746. /* 设置回调函数 */
  747. curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, writeStringCallback);
  748. /* 设置需要写入的容器,回调函数的第四个参数 */
  749. curl_easy_setopt(curl, CURLOPT_WRITEDATA, &strSrc);
  750. /* 设置超时时间 */
  751. curl_easy_setopt(curl, CURLOPT_TIMEOUT, 10L);
  752. curl_easy_setopt(curl, CURLOPT_CONNECTTIMEOUT, 10L);
  753. /* 发送请求 */
  754. CURLcode res = curl_easy_perform(curl);
  755. if(res != CURLE_OK)
  756. {
  757. FMTLOG_ERROR("Failed to get file list, error code: {} ,{}", (int)res, curl_easy_strerror(res));
  758. FMTLOG_ERROR("ftpUrl = {}", ftpUrl);
  759. return false;
  760. }
  761. /* 解析字符串 */
  762. parseFileInfo(strSrc, fileInfoList);
  763. return true;
  764. }
  765. /* 检查文件夹路径是否合规,不合规就修改 */
  766. std::string CurlFtp::checkDirPath(const std::string& dir)
  767. {
  768. std::string dirTmp = dir;
  769. /* 检查是否以“/”开头 */
  770. std::regex reg(R"(^/[.]*)");
  771. if(!std::regex_match(dirTmp, reg))
  772. {
  773. dirTmp = "/" + dirTmp;
  774. }
  775. /* 如果有重复的“/”,替换成一个 “/” */
  776. std::regex reg1(R"(//)");
  777. dirTmp = std::regex_replace(dirTmp, reg1, "/");
  778. /* 检查是否以“/”结束 */
  779. std::regex reg2(R"([.]*/$)");
  780. if(!std::regex_match(dirTmp, reg2))
  781. {
  782. dirTmp = dirTmp + "/";
  783. }
  784. return dirTmp;
  785. }
  786. /* 检查文件路径是否合规 */
  787. std::string CurlFtp::checkFilePath(const std::string& file)
  788. {
  789. std::string dirTmp = file;
  790. /* 检查是否以“/”结束,如果是以“/”结尾,返回空字符串,并报错 */
  791. std::regex reg2(R"([.]*/$)");
  792. if(std::regex_match(dirTmp, reg2))
  793. {
  794. FMTLOG_ERROR("File path is not correct, end with '/'");
  795. return std::string();
  796. }
  797. /* 检查是否以“/”开头 */
  798. std::regex reg(R"(^/[.]*)");
  799. if(!std::regex_match(dirTmp, reg))
  800. {
  801. dirTmp = "/" + dirTmp;
  802. }
  803. /* 如果有重复的“/”,替换成一个 “/” */
  804. std::regex reg1(R"(//)");
  805. dirTmp = std::regex_replace(dirTmp, reg1, "/");
  806. return dirTmp;
  807. }
  808. /**
  809. * @brief 检查本地文件夹是否存在,不存在则创建
  810. * 这里默认传入的是文件夹路径,不是文件路径,如果最后有‘/’,会自动去掉
  811. *
  812. * @param localDir 文件夹路径
  813. * @return true
  814. * @return false
  815. */
  816. bool CurlFtp::checkLocalDir(const std::string& localDir)
  817. {
  818. /* 去掉最后的‘/’ */
  819. std::regex reg(R"([.]*/$)");
  820. std::string localDirTmp = std::regex_replace(localDir, reg, "");
  821. /* 检查文件夹是否存在 */
  822. if(std::filesystem::exists(localDirTmp))
  823. {
  824. return true;
  825. }
  826. /* 创建文件夹 */
  827. if(!std::filesystem::create_directories(localDirTmp))
  828. {
  829. FMTLOG_ERROR("Failed to create local dir: {}", localDirTmp);
  830. return false;
  831. }
  832. return true;
  833. }