CurlFtp.cpp 38 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299
  1. #include "CurlFtp.h"
  2. #include <regex>
  3. #include <iosfwd>
  4. #include <filesystem>
  5. #include <fstream>
  6. // #include "fmtlog.h"
  7. #include "spdlog/spdlog.h"
  8. #if defined(_WIN32)
  9. #endif /* _WIN32 */
  10. /* ==================================================================================
  11. * *********************************** 全局变量 *************************************
  12. * ==================================================================================
  13. */
  14. /* 是否有初始化实例,主要用于静态函数调用curl_global_cleanup()函数前判断,有实例就不调用 */
  15. static bool hasInstace = false;
  16. /* 记录上传或者下载的时间,thread_local是C++11加入的关键字,表示在每个线程中都有自己的lastTime */
  17. static thread_local std::chrono::system_clock::time_point lastTime;
  18. static thread_local uint64_t dCount;
  19. static thread_local uint64_t uCount;
  20. static thread_local uint64_t dSpeed; /* 保存最后的下载速度 */
  21. static thread_local uint64_t uSpeed; /* 保存最后的上传速度 */
  22. /* ==================================================================================
  23. * *********************************** 全局函数 *************************************
  24. * ==================================================================================
  25. */
  26. /**
  27. * @brief 写入回调函数
  28. *
  29. * @param contents curl的数据缓冲区
  30. * @param size 数据大小,单位是size_t
  31. * @param nmemb size_t的单位字节数
  32. * @param userStr 用户提供的字符串,格式可以是任意的
  33. * @return size_t 总共获取到的数据大小,单位是字节
  34. */
  35. static size_t writeStringCallback(void *contents, size_t size, size_t nmemb, std::string *userStr)
  36. {
  37. size_t newLength = size * nmemb;
  38. size_t oldLength = userStr->size();
  39. try
  40. {
  41. userStr->resize(oldLength + newLength);
  42. }
  43. catch(std::bad_alloc &e)
  44. {
  45. //handle memory problem
  46. return 0;
  47. }
  48. std::copy_n((char*)contents, newLength, userStr->begin() + oldLength);
  49. return size * nmemb;
  50. }
  51. /**
  52. * @brief 写入回调函数,listFiles需要调用
  53. *
  54. * @param buffer curl下载回来的数据
  55. * @param size 数据大小
  56. * @param nmemb 数据单位字节数
  57. * @param userp 用户传进来的容器
  58. * @return int 返回拷贝的字节数
  59. */
  60. static int writeStringListCallback(void* buffer, size_t size, size_t nmemb, void* userp)
  61. {
  62. std::vector<std::string>* fileList = static_cast<std::vector<std::string>*>(userp);
  63. std::string line(static_cast<char*>(buffer), size * nmemb);
  64. // printf("line = %s\n", line.c_str());
  65. fileList->push_back(line);
  66. return size * nmemb;
  67. }
  68. /**
  69. * @brief 写入文件回调函数
  70. *
  71. * @param contents 读取到的数据内容
  72. * @param size 数据大小
  73. * @param nmemb 数据单位
  74. * @param pFile 文件指针
  75. * @return size_t 实际读取的大小
  76. */
  77. static size_t writeFileCallBack(void* contents, size_t size, size_t nmemb, std::ostream* pFile)
  78. {
  79. pFile->write(reinterpret_cast<char*>(contents), size * nmemb);
  80. return size * nmemb;
  81. }
  82. /**
  83. * @brief 写入数据到vector中
  84. *
  85. * @param contents
  86. * @param size
  87. * @param nmemb
  88. * @param vecData
  89. * @return size_t
  90. */
  91. static size_t writeDataCallBack(void* contents, size_t size, size_t nmemb, std::vector<char>* vecData)
  92. {
  93. size_t copySize = size * nmemb;
  94. vecData->insert(vecData->end(), (char*)contents, (char*)contents + copySize);
  95. return copySize;
  96. }
  97. /**
  98. * @brief 读取文件回调函数
  99. *
  100. * @param contents 下载到的数据内容
  101. * @param size 数据大小
  102. * @param nmemb 数据单位
  103. * @param pFile 文件指针
  104. * @return size_t 写入的大小
  105. */
  106. static size_t readFileCallBack(void* contents, size_t size, size_t nmemb, std::istream* pFile)
  107. {
  108. pFile->read(reinterpret_cast<char*>(contents), size * nmemb);
  109. /* 获取读取到的字节数,可能读取到文件末尾,所以不能直接使用传入的字节数 */
  110. size_t readSize = pFile->gcount();
  111. return readSize;
  112. }
  113. /**
  114. * @brief
  115. *
  116. * @param contents ftp需要的目标内容
  117. * @param size 拷贝的数据大小
  118. * @param nmemb 单个数据的字节数
  119. * @param pData 源指针
  120. * @return size_t 已拷贝的数据大小
  121. */
  122. static size_t readDataCallBack(void* contents, size_t size, size_t nmemb, CF_ArrayInfo* pData)
  123. {
  124. if(pData == nullptr)
  125. {
  126. return 0;
  127. }
  128. /* 判断是否还够本次拷贝的字节数 */
  129. size_t copySize = size * nmemb;
  130. if(pData->size - pData->pos < copySize)
  131. {
  132. copySize = pData->size - pData->pos;
  133. }
  134. memcpy(contents, pData->data + pData->pos, copySize);
  135. pData->pos += copySize;
  136. return copySize;
  137. }
  138. /**
  139. * @brief 计算速度
  140. *
  141. * @param speed
  142. * @param retSpeed
  143. * @param unit
  144. */
  145. void computeSpeed(uint64_t speed, double& retSpeed, std::string& unit)
  146. {
  147. double KB = speed / 1024.0;
  148. double MB = KB / 1024.0;
  149. double GB = MB / 1024.0;
  150. if(GB > 1)
  151. {
  152. unit = "GB/S";
  153. retSpeed = GB;
  154. }
  155. else if(MB > 1)
  156. {
  157. unit = "MB/S";
  158. retSpeed = MB;
  159. }
  160. else if(KB > 1)
  161. {
  162. unit = "KB/S";
  163. retSpeed = KB;
  164. }
  165. else {
  166. unit = "B/S";
  167. retSpeed = speed;
  168. }
  169. }
  170. /**
  171. * @brief 打印进度条
  172. *
  173. * @param type 上传还是下载类型
  174. * @param total 总大小,单位字节
  175. * @param now 现在的进度,单位字节
  176. */
  177. void printProgress(CF_TransType type, curl_off_t total, curl_off_t now)
  178. {
  179. std::string transType;
  180. uint64_t count = 0;
  181. if(type == CF_TransType::DOWNLOAD)
  182. {
  183. transType = "Download";
  184. count = now - dCount;
  185. dCount = now;
  186. }
  187. else if (type == CF_TransType::UPLOAD)
  188. {
  189. transType = "Upload";
  190. count = now - uCount;
  191. uCount = now;
  192. }
  193. /* 计算进度,百分比 */
  194. double percent = (double)now / (double)total * 100;
  195. /* 计算单位 */
  196. double tKB = total / 1024.0;
  197. double tMB = tKB / 1024.0;
  198. double tGB = tMB / 1024.0;
  199. /* 计算速度 */
  200. double speed = 0.0;
  201. std::string unit;
  202. computeSpeed(count, speed, unit);
  203. // if(speed == 0.0)
  204. // {
  205. // if(CF_TransType::DOWNLOAD == type)
  206. // {
  207. // speed = dSpeed;
  208. // }else if (CF_TransType::UPLOAD == type) {
  209. // speed = uSpeed;
  210. // }
  211. // }else {
  212. // if(CF_TransType::DOWNLOAD == type)
  213. // {
  214. // dSpeed = speed;
  215. // }else if (CF_TransType::UPLOAD == type) {
  216. // uSpeed = speed;
  217. // }
  218. // }
  219. if(tGB > 1)
  220. {
  221. double dGB = now / 1024.0 / 1024.0 / 1024.0;
  222. double speed = count / 1024.0 / 1024.0;
  223. printf("%s Total / now : %.2fGB / %.2fGB, %.2f%%, Speed:%.2f %s\r", transType.c_str(), tGB, dGB, percent, speed, unit.c_str());
  224. // printf("Download Total / now : {:.2f}GB / {:.2f}GB, {:.2f}%\r", tGB, dGB, percent);
  225. }
  226. else if(tMB > 1)
  227. {
  228. double dMB = now / 1024.0 / 1024.0;
  229. printf("%s Total / now : %.2fMB / %.2fMB, %.2f%%, Speed:%.2f %s\r", transType.c_str(), tMB, dMB, percent, speed, unit.c_str());
  230. // printf("Download Total / now : {:.2f}MB / {:.2f}MB, {:.2f}%\r", tMB, dMB, percent);
  231. }
  232. else if(tKB > 1)
  233. {
  234. double dKB = now / 1024.0;
  235. printf("%s Total / now : %.2fKB / %.2fKB, %.2f%%, Speed:%.2f %s\r", transType.c_str(), tKB, dKB, percent, speed, unit.c_str());
  236. }
  237. else
  238. {
  239. printf("%s Total / now : %ldB / %ldB, %.2f%%, Speed:%.2f %s\r", transType.c_str(), total, now, percent, speed, unit.c_str());
  240. }
  241. fflush(stdout);
  242. }
  243. /**
  244. * @brief 上传和下载进度回调函数,这个函数kennel会被多次调用,即使是没有在下载的时候,因此需要判断传入的数据是否是0
  245. * 必须将 CURLOPT_NOPROGRESS 设为 0 才能真正调用该函数。
  246. *
  247. * @param clientp 通过CURLOPT_XFERINFODATA 设置的指针,libcurl 不会使用它,只会将其从应用程序传递给回调函数。
  248. * 可以通过这个指针将下载的进度传递给应用程序
  249. * @param dltotal 下载的总字节数,上传的时候这个为0
  250. * @param dlnow 已经下载的总字节数
  251. * @param ultotal 需要上传的总字节数,下载的时候这个为0
  252. * @param ulnow 已经上传的总字节数
  253. * @return int 返回0表示正常,非0表示异常
  254. */
  255. static int progress_callback(void *clientp,
  256. curl_off_t dltotal,
  257. curl_off_t dlnow,
  258. curl_off_t ultotal,
  259. curl_off_t ulnow)
  260. {
  261. // SPDLOG_DEBUG("dTotal: {}, dNow: {}, uTotal: {}, uNow: {}", dltotal, dlnow, ultotal, ulnow);
  262. if(dltotal == 0 && ultotal == 0)
  263. {
  264. dCount = 0;
  265. uCount = 0;
  266. dSpeed = 0;
  267. uSpeed = 0;
  268. return 0;
  269. }
  270. std::chrono::system_clock::time_point nowTime = std::chrono::system_clock::now();
  271. auto duration = std::chrono::duration_cast<std::chrono::milliseconds>(nowTime - lastTime).count();
  272. // SPDLOG_DEBUG("duration:{}", duration);
  273. if((duration < 1000) && ((dltotal != dlnow) || (ultotal != ulnow)))
  274. {
  275. return 0;
  276. }
  277. lastTime = nowTime;
  278. /* 正在下载 */
  279. if(dltotal > 0)
  280. {
  281. printProgress(CF_TransType::DOWNLOAD, dltotal, dlnow);
  282. // printf("Download Total / now : {} / {}, {:.2f}%\r", dltotal, dlnow, downloadPercent);
  283. }
  284. /* 正在上传 */
  285. else if(ultotal > 0)
  286. {
  287. printProgress(CF_TransType::UPLOAD, ultotal, ulnow);
  288. // double uploadPercent = (double)ulnow / (double)ultotal * 100;
  289. // printf("Upload Total / now : {} / {}, {:.2f}%\r", ultotal, ulnow, uploadPercent);
  290. }
  291. return 0;
  292. }
  293. /* 使用Windows API进行编码转换 */
  294. #if defined(_WIN32)
  295. static char* GBToUTF8(const char* gb2312)
  296. {
  297. int len = MultiByteToWideChar(CP_ACP, 0, gb2312, -1, NULL, 0);
  298. wchar_t* wstr = new wchar_t[len+1];
  299. memset(wstr, 0, len+1);
  300. MultiByteToWideChar(CP_ACP, 0, gb2312, -1, wstr, len);
  301. len = WideCharToMultiByte(CP_UTF8, 0, wstr, -1, NULL, 0, NULL, NULL);
  302. char* str = new char[len+1];
  303. memset(str, 0, len+1);
  304. WideCharToMultiByte(CP_UTF8, 0, wstr, -1, str, len, NULL, NULL);
  305. if(wstr) delete[] wstr;
  306. return str;
  307. }
  308. #endif /* _WIN32 */
  309. /**
  310. * @brief 解析字符串文件信息,如果FTP服务器规定好个编码,不需要进行转换
  311. *
  312. * @param strSrc 读取到的字符串
  313. * @param fileList 文件信息列表
  314. * @return true
  315. * @return false
  316. */
  317. static bool parseFileInfo(const std::string& strSrc, std::vector<CF_FileInfo>& fileInfo)
  318. {
  319. #if defined(_WIN32)
  320. // auto str1 = GBToUTF8(strSrc.c_str());
  321. std::string str2 = strSrc;
  322. #else
  323. std::string str2 = strSrc;
  324. #endif /* _WIN32 */
  325. // SPDLOG_DEBUG("\n{}", str2);
  326. /* 正则表达式,匹配多个空格 */
  327. std::regex reg(R"(( )+)");
  328. /* 匹配以非空格开头的字符,空格隔开,中间任意字符,空格隔开,非空格组成的结尾
  329. * (文件类型) ... (文件大小,$5) ... (文件名)
  330. */
  331. std::regex reg1(R"(^([^ ]+) (\d*) (\w*) (\w*) (\d*) (.*) ([^ ]+)$)");
  332. // SPDLOG_INFO("\n-------------------\n");
  333. /* 匹配换行符,分割每一行 */
  334. std::regex reg2(R"(\n)");
  335. /* 匹配文件夹 */
  336. std::regex reg3(R"(^d.*)");
  337. /* 匹配文件 */
  338. std::regex reg4(R"(^-.*$)");
  339. /* -1 表示对正则表达式之前的子序列感兴趣
  340. * 0 表示对正则表达式本身感兴趣,输出的就是换行符 */
  341. std::sregex_token_iterator it2(str2.begin(), str2.end(), reg2, -1);
  342. /* 这里取出每一行 */
  343. for(; it2 != std::sregex_token_iterator(); ++it2)
  344. {
  345. /* 去掉多余的空格 */
  346. auto line = std::regex_replace(it2->str(), reg, " ");
  347. // SPDLOG_INFO("{}", line);
  348. CF_FileInfo fi;
  349. /* 取出文件类型 */
  350. std::string strFileType = std::regex_replace(line, reg1, "$1");
  351. if(std::regex_match(strFileType, reg3))
  352. {
  353. fi.type = CF_FileType::DIR;
  354. }else if (std::regex_match(strFileType, reg4))
  355. {
  356. fi.type = CF_FileType::FILE;
  357. }
  358. /* 取出文件大小 */
  359. std::string strFileSize = std::regex_replace(line, reg1, "$5");
  360. fi.size = std::stoull(strFileSize);
  361. /* 取出文件名 */
  362. std::string strFileName = std::regex_replace(line, reg1, "$7");
  363. fi.name = strFileName;
  364. /* 加入队列 */
  365. fileInfo.push_back(fi);
  366. }
  367. return true;
  368. }
  369. /* ==================================================================================
  370. * *********************************** 成员函数 *************************************
  371. * ================================================================================== */
  372. CurlFtp::CurlFtp()
  373. {
  374. /* 调用初始化函数,这个函数可以重复调用 */
  375. curl_global_init(CURL_GLOBAL_DEFAULT);
  376. /* 初始化curl */
  377. hasInstace = true;
  378. }
  379. CurlFtp::~CurlFtp()
  380. {
  381. /* 清理curl */
  382. curl_global_cleanup();
  383. hasInstace = false;
  384. }
  385. /* 设置用户名和密码 */
  386. bool CurlFtp::setUsernameAndPassword(const std::string& username, const std::string& password)
  387. {
  388. m_username = username;
  389. m_password = password;
  390. return true;
  391. }
  392. /* 设置IP和端口 */
  393. bool CurlFtp::setFtpIPAndPort(const std::string& IP, const int port)
  394. {
  395. /*先判断是否有ftp器前缀,通过正则表达式,取出IP地址和端口号,去掉前缀和后面的'/ */
  396. m_IP = IP;
  397. m_port = port;
  398. m_ftpUrl = "ftp://" + m_IP + ":" + std::to_string(m_port);
  399. SPDLOG_INFO("Set ftpUrl = {}", m_ftpUrl);
  400. m_isSftp = false;
  401. return true;
  402. }
  403. /* 设置SFTP的IP和端口 */
  404. bool CurlFtp::setSftpIPAndPort(const std::string& IP, const int port)
  405. {
  406. m_IP = IP;
  407. m_port = port;
  408. m_ftpUrl = "sftp://" + m_IP + ":" + std::to_string(m_port);
  409. SPDLOG_INFO("Set sftpUrl = {}", m_ftpUrl);
  410. m_isSftp = true;
  411. return true;
  412. }
  413. /* 设置是否忽略SSL证书,使用SFTP不建议忽略 */
  414. void CurlFtp::setIgnoreSSLCert(bool isIgnore)
  415. {
  416. m_isIgnoreSSLCert = isIgnore;
  417. }
  418. /* 设置CA证书文件 */
  419. void CurlFtp::setCaCertFile(const std::string& caCertFile)
  420. {
  421. m_caCertFile = caCertFile;
  422. }
  423. /* 设置是否启用CURL的调试信息 */
  424. void CurlFtp::enableCurlDebug(bool isPrint)
  425. {
  426. m_enableCurlDebug = isPrint;
  427. }
  428. /* 列出文件列表 */
  429. bool CurlFtp::getFileList(std::string dir, std::vector<std::string>& fileList)
  430. {
  431. if(m_IP.empty())
  432. {
  433. SPDLOG_WARN("IP or port is empty");
  434. return false;
  435. }
  436. /* 检查dir,添加前缀“/” */
  437. auto dirTmp = checkDirPath(dir);
  438. CURL *curl = nullptr;
  439. curl = curl_easy_init();
  440. if(curl == nullptr)
  441. {
  442. SPDLOG_ERROR("curl init failed !");
  443. return false;
  444. }
  445. std::vector<CF_FileInfo> listInfo;
  446. /* 获取文件信息 */
  447. listAll(curl, dirTmp, listInfo);
  448. for(const CF_FileInfo& fi : listInfo)
  449. {
  450. // SPDLOG_INFO("type = {}, size = {}, name = {}", (int)fi.type, fi.size, fi.name);
  451. if(fi.type == CF_FileType::FILE)
  452. {
  453. fileList.push_back(fi.name);
  454. }
  455. }
  456. curl_easy_cleanup(curl);
  457. return true;
  458. }
  459. /* 获取文件夹列表 */
  460. bool CurlFtp::getDirList(std::string dir, std::vector<std::string>& dirList)
  461. {
  462. if(m_IP.empty())
  463. {
  464. SPDLOG_WARN("IP or port is empty");
  465. return false;
  466. }
  467. /* 检查dir,添加前缀“/” */
  468. auto dirTmp = checkDirPath(dir);
  469. CURL *curl = nullptr;
  470. curl = curl_easy_init();
  471. if(curl == nullptr)
  472. {
  473. SPDLOG_ERROR("curl init failed !");
  474. return false;
  475. }
  476. std::vector<CF_FileInfo> listInfo;
  477. /* 获取文件信息 */
  478. listAll(curl, dirTmp, listInfo);
  479. for(const CF_FileInfo& fi : listInfo)
  480. {
  481. // SPDLOG_INFO("type = {}, size = {}, name = {}", (int)fi.type, fi.size, fi.name);
  482. if(fi.type == CF_FileType::DIR)
  483. {
  484. dirList.push_back(fi.name);
  485. }
  486. }
  487. curl_easy_cleanup(curl);
  488. return true;
  489. }
  490. /* 判断文件夹是否存在 */
  491. bool CurlFtp::isDirExist(const std::string& dir)
  492. {
  493. if(m_ftpUrl.empty())
  494. {
  495. SPDLOG_ERROR("ftpUrl is empty");
  496. return false;
  497. }
  498. /* 检查传入的文件夹 */
  499. auto dirTmp = checkDirPath(dir);
  500. CURL* curl = nullptr;
  501. curl = curl_easy_init();
  502. if(curl == nullptr)
  503. {
  504. SPDLOG_ERROR("curl init failed !");
  505. return false;
  506. }
  507. std::string ftpUrl = m_ftpUrl + dirTmp;
  508. curl_easy_setopt(curl, CURLOPT_URL, ftpUrl.c_str());
  509. curl_easy_setopt(curl, CURLOPT_USERNAME, m_username.c_str());
  510. curl_easy_setopt(curl, CURLOPT_PASSWORD, m_password.c_str());
  511. /* 获取文件夹是否存在,不需要接收文件 */
  512. curl_easy_setopt(curl, CURLOPT_NOBODY, 1L);
  513. // 禁用被动模式(如果需要)
  514. curl_easy_setopt(curl, CURLOPT_FTP_USE_EPSV, 1L);
  515. if(m_enableCurlDebug)
  516. {
  517. /* 启用调试信息 */
  518. curl_easy_setopt(curl, CURLOPT_VERBOSE, 1L);
  519. }
  520. /* 启用持久连接 */
  521. curl_easy_setopt(curl, CURLOPT_TCP_KEEPALIVE, 1L);
  522. CURLcode res = curl_easy_perform(curl);
  523. bool result = true;
  524. if(res != CURLE_OK)
  525. {
  526. // SPDLOG_ERROR("Failed to get file list, error code: {} ,{}", (int)res, curl_easy_strerror(res));
  527. result = false;
  528. }
  529. // bool ret = performCurl(curl);
  530. // if(!ret)
  531. // {
  532. // SPDLOG_ERROR("Failed to create FTP Dir");
  533. // }
  534. return result;
  535. }
  536. /**
  537. * @brief 创建FTP文件夹,只能创建一层文件夹
  538. *
  539. * @param ftpDir 文件夹路径
  540. * @return true 文件夹创建成功或者文件夹存在
  541. * @return false
  542. */
  543. bool CurlFtp::createDirectory(const std::string& ftpDir)
  544. {
  545. if(m_ftpUrl.empty())
  546. {
  547. SPDLOG_ERROR("ftpUrl is empty");
  548. return false;
  549. }
  550. /* 先检查FTP文件夹是否存在,如果存在直接返回true */
  551. if(isDirExist(ftpDir))
  552. {
  553. return true;
  554. }
  555. /* 检查传入的文件夹格式 */
  556. auto dirTmp = checkDirPath(ftpDir);
  557. CURL *curl = curl_easy_init();
  558. if(curl == nullptr)
  559. {
  560. SPDLOG_ERROR("Create FTP DIR, curl init failed !");
  561. return false;
  562. }
  563. curl_easy_setopt(curl, CURLOPT_URL, m_ftpUrl.c_str());
  564. curl_easy_setopt(curl, CURLOPT_USERNAME, m_username.c_str());
  565. curl_easy_setopt(curl, CURLOPT_PASSWORD, m_password.c_str());
  566. /* 创建FTP头信息 */
  567. struct curl_slist *headerlist = NULL;
  568. std::string mkdir = "MKD " + dirTmp;
  569. headerlist = curl_slist_append(headerlist, mkdir.c_str());
  570. /* 设置FTP命令行选项 */
  571. curl_easy_setopt(curl, CURLOPT_QUOTE, headerlist);
  572. /* 不包含实体 */
  573. curl_easy_setopt(curl, CURLOPT_NOBODY, 1L);
  574. /* 启用跟随重定向 */
  575. curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1L);
  576. /* 设置超时时间 */
  577. curl_easy_setopt(curl, CURLOPT_TIMEOUT, 30L);
  578. curl_easy_setopt(curl, CURLOPT_CONNECTTIMEOUT, 30L);
  579. // 禁用被动模式(如果需要)
  580. // curl_easy_setopt(curl, CURLOPT_FTP_USE_EPSV, 1L);
  581. if(m_enableCurlDebug)
  582. {
  583. /* 启用调试信息 */
  584. curl_easy_setopt(curl, CURLOPT_VERBOSE, 1L);
  585. }
  586. // 启用持久连接
  587. curl_easy_setopt(curl, CURLOPT_TCP_KEEPALIVE, 1L);
  588. // CURLcode res = curl_easy_perform(curl);
  589. bool ret = performCurl(curl);
  590. if(!ret)
  591. {
  592. SPDLOG_ERROR("Failed to create FTP Dir");
  593. }
  594. curl_easy_cleanup(curl);
  595. curl_slist_free_all(headerlist);
  596. return ret;
  597. }
  598. /* 创建FTP文件夹,递归创建 */
  599. bool CurlFtp::createDirectories(const std::string& ftpDir)
  600. {
  601. /* 检查路径格式,并去掉第一个 / */
  602. std::string ftpDirTmp = checkDirPath(ftpDir);
  603. std::string ftpDir2 = ftpDirTmp.substr(1, ftpDirTmp.size() -1);
  604. /* 将文件夹分开,取出每一个文件夹名称 */
  605. std::vector<std::string> strList;
  606. std::regex reg(R"(/)");
  607. std::sregex_token_iterator it(ftpDir2.begin(), ftpDir2.end(), reg, -1);
  608. for( ; it != std::sregex_token_iterator(); ++it)
  609. {
  610. strList.push_back(it->str());
  611. }
  612. /* 将每一层拼接起来,逐层递归 */
  613. std::vector<std::string> dirList;
  614. for(const std::string& dir : strList)
  615. {
  616. std::string dirTmp = "/";
  617. if(!dirList.empty())
  618. {
  619. dirTmp = dirList.back();
  620. dirTmp += "/";
  621. }
  622. dirTmp += dir;
  623. dirList.push_back(dirTmp);
  624. }
  625. /* 逐层创建 */
  626. for(const std::string& dir : dirList)
  627. {
  628. // SPDLOG_DEBUG("Create dir: {}", dir);
  629. if(!createDirectory(dir))
  630. {
  631. SPDLOG_ERROR("Failed to create dir: {}", dir);
  632. return false;
  633. }
  634. }
  635. return true;
  636. }
  637. /**
  638. * @brief 下载文件
  639. *
  640. * @param remoteFile
  641. * @param localFile
  642. * @param timeout 超时时间,单位秒
  643. * @return true
  644. * @return false
  645. */
  646. bool CurlFtp::downloadFile(const std::string& remoteFile, const std::string& localFile, size_t timeout)
  647. {
  648. if(m_ftpUrl.empty())
  649. {
  650. SPDLOG_ERROR("ftpUrl is empty");
  651. return false;
  652. }
  653. /* 检查传入的文件是否符合规范 */
  654. std::string remoteFileTmp = checkFilePath(remoteFile);
  655. std::string ftpUrl = m_ftpUrl + remoteFileTmp;
  656. /* 检查本地文件夹是否存在,不存在则创建 */
  657. // std::string localDir = localFile.substr(0, localFile.find_last_of("/")); /* 去掉最后的 / */
  658. std::string localDirTmp = localFile.substr(0, localFile.find_last_of("/"));
  659. if(!checkLocalDir(localDirTmp))
  660. {
  661. SPDLOG_ERROR("Failed to create local dir: {}", localDirTmp);
  662. return false;
  663. }
  664. CURL* curl = nullptr;
  665. curl = curl_easy_init();
  666. if(curl == nullptr)
  667. {
  668. SPDLOG_ERROR("curl init failed !");
  669. return false;
  670. }
  671. /* 打开文件 */
  672. std::ofstream ofs;
  673. ofs.open(localFile, std::ios::out | std::ios::binary | std::ios::trunc);
  674. /* 设置FTP地址 */
  675. curl_easy_setopt(curl, CURLOPT_URL, ftpUrl.c_str());
  676. curl_easy_setopt(curl, CURLOPT_PORT, m_port);
  677. /* 设置用户名和密码 */
  678. // curl_easy_setopt(curl, CURLOPT_USERNAME, m_username.c_str());
  679. // curl_easy_setopt(curl, CURLOPT_PASSWORD, m_password.c_str());
  680. curl_easy_setopt(curl, CURLOPT_USERPWD, (m_username + ":" + m_password).c_str());
  681. /* 启用跟随重定向 */
  682. curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1L);
  683. /* 设置回调函数 */
  684. curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, writeFileCallBack);
  685. curl_easy_setopt(curl, CURLOPT_WRITEDATA, &ofs);
  686. /* 设置超时时间 */
  687. // curl_easy_setopt(curl, CURLOPT_TIMEOUT, 30L);
  688. curl_easy_setopt(curl, CURLOPT_CONNECTTIMEOUT, timeout);
  689. /* 设置进度回调函数 */
  690. curl_easy_setopt(curl, CURLOPT_XFERINFOFUNCTION, progress_callback);
  691. curl_easy_setopt(curl, CURLOPT_XFERINFODATA, nullptr);
  692. /* 启用下载进度回调函数 */
  693. curl_easy_setopt(curl, CURLOPT_NOPROGRESS, 0L);
  694. /* 判断是否是SFTP */
  695. if(m_isSftp)
  696. {
  697. /* 判断是否需要设置CA证书 */
  698. if(m_isIgnoreSSLCert)
  699. {
  700. /* 忽略证书验证 */
  701. curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 0L);
  702. /* 忽略主机名验证 */
  703. curl_easy_setopt(curl, CURLOPT_SSL_VERIFYHOST, 0L);
  704. } else
  705. {
  706. /* 设置CA证书 */
  707. curl_easy_setopt(curl, CURLOPT_CAINFO, m_caCertFile.c_str());
  708. }
  709. }
  710. // 禁用被动模式(如果需要)
  711. curl_easy_setopt(curl, CURLOPT_FTP_USE_EPSV, 1L);
  712. if(m_enableCurlDebug)
  713. {
  714. /* 启用调试信息 */
  715. curl_easy_setopt(curl, CURLOPT_VERBOSE, 1L);
  716. }
  717. /* 启用持久连接 */
  718. curl_easy_setopt(curl, CURLOPT_TCP_KEEPALIVE, 1L);
  719. /* 发送请求 */
  720. CURLcode res = curl_easy_perform(curl);
  721. if(res != CURLE_OK)
  722. {
  723. SPDLOG_ERROR("Failed to get file list, error code: {} ,{}", (int)res, curl_easy_strerror(res));
  724. SPDLOG_ERROR("Url = {}", ftpUrl);
  725. /* 清理下载失败的文件 */
  726. ofs.close();
  727. std::remove(localFile.c_str());
  728. return false;
  729. }
  730. /* 关闭文件,清理curl */
  731. ofs.close();
  732. curl_easy_cleanup(curl);
  733. /* 打印一个换行符 */
  734. // printf("\n");
  735. printf("\n");
  736. return true;
  737. }
  738. /* 下载文件到数组 */
  739. bool CurlFtp::downloadToArray(const std::string& remoteFile, std::vector<char>& arrayInfo, size_t timeout)
  740. {
  741. if(m_ftpUrl.empty())
  742. {
  743. SPDLOG_ERROR("ftpUrl is empty");
  744. return false;
  745. }
  746. /* 检查传入的文件是否符合规范 */
  747. std::string remoteFileTmp = checkFilePath(remoteFile);
  748. std::string ftpUrl = m_ftpUrl + remoteFileTmp;
  749. CURL* curl = nullptr;
  750. curl = curl_easy_init();
  751. if(curl == nullptr)
  752. {
  753. SPDLOG_ERROR("curl init failed !");
  754. return false;
  755. }
  756. /* 设置FTP地址 */
  757. curl_easy_setopt(curl, CURLOPT_URL, ftpUrl.c_str());
  758. curl_easy_setopt(curl, CURLOPT_PORT, m_port);
  759. /* 设置用户名和密码 */
  760. // curl_easy_setopt(curl, CURLOPT_USERNAME, m_username.c_str());
  761. // curl_easy_setopt(curl, CURLOPT_PASSWORD, m_password.c_str());
  762. curl_easy_setopt(curl, CURLOPT_USERPWD, (m_username + ":" + m_password).c_str());
  763. /* 启用跟随重定向 */
  764. curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1L);
  765. /* 设置回调函数 */
  766. curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, writeDataCallBack);
  767. curl_easy_setopt(curl, CURLOPT_WRITEDATA, &arrayInfo);
  768. /* 设置超时时间 */
  769. // curl_easy_setopt(curl, CURLOPT_TIMEOUT, 30L);
  770. curl_easy_setopt(curl, CURLOPT_CONNECTTIMEOUT, timeout);
  771. /* 设置进度回调函数 */
  772. curl_easy_setopt(curl, CURLOPT_XFERINFOFUNCTION, progress_callback);
  773. curl_easy_setopt(curl, CURLOPT_XFERINFODATA, nullptr);
  774. /* 启用下载进度回调函数 */
  775. curl_easy_setopt(curl, CURLOPT_NOPROGRESS, 0L);
  776. /* 判断是否是SFTP */
  777. if(m_isSftp)
  778. {
  779. /* 判断是否需要设置CA证书 */
  780. if(m_isIgnoreSSLCert)
  781. {
  782. /* 忽略证书验证 */
  783. curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 0L);
  784. /* 忽略主机名验证 */
  785. curl_easy_setopt(curl, CURLOPT_SSL_VERIFYHOST, 0L);
  786. } else
  787. {
  788. /* 设置CA证书 */
  789. curl_easy_setopt(curl, CURLOPT_CAINFO, m_caCertFile.c_str());
  790. }
  791. }
  792. // 禁用被动模式(如果需要)
  793. curl_easy_setopt(curl, CURLOPT_FTP_USE_EPSV, 1L);
  794. if(m_enableCurlDebug)
  795. {
  796. /* 启用调试信息 */
  797. curl_easy_setopt(curl, CURLOPT_VERBOSE, 1L);
  798. }
  799. /* 启用持久连接 */
  800. curl_easy_setopt(curl, CURLOPT_TCP_KEEPALIVE, 1L);
  801. /* 发送请求 */
  802. CURLcode res = curl_easy_perform(curl);
  803. if(res != CURLE_OK)
  804. {
  805. SPDLOG_ERROR("Failed to get file list, error code: {} ,{}", (int)res, curl_easy_strerror(res));
  806. SPDLOG_ERROR("Url = {}", ftpUrl);
  807. /* 清理下载失败的文件 */
  808. return false;
  809. }
  810. /* 清理curl */
  811. curl_easy_cleanup(curl);
  812. /* 打印一个换行符 */
  813. // printf("\n");
  814. printf("\n");
  815. return true;
  816. }
  817. /**
  818. * @brief 上传文件
  819. *
  820. * @param localFile 本地文件
  821. * @param remoteFile 远程文件
  822. * @param timeout 超时时间,单位秒
  823. * @return true
  824. * @return false
  825. */
  826. bool CurlFtp::uploadFile(const std::string& localFile, const std::string& remoteFile, size_t timeout, bool isCreateDir)
  827. {
  828. if(m_ftpUrl.empty())
  829. {
  830. SPDLOG_ERROR("Url is empty");
  831. return false;
  832. }
  833. /* 检查本地文件是否存在 */
  834. if(!std::filesystem::exists(localFile))
  835. {
  836. SPDLOG_ERROR("Local file is not exist: {}", localFile);
  837. return false;
  838. }
  839. /* 检查FTP文件名是否符合规范 */
  840. std::string remoteFileTmp = checkFilePath(remoteFile);
  841. std::string remoteDirTmp = remoteFileTmp.substr(0, remoteFileTmp.find_last_of("/"));
  842. /* 检查远程FTP上的文件夹是否存在,不存在则创建 */
  843. if(!isDirExist(remoteDirTmp))
  844. {
  845. if(isCreateDir)
  846. {
  847. if(!createDirectories(remoteDirTmp))
  848. {
  849. // SPDLOG_ERROR("Failed to create remote dir: {}", remoteFileTmp);
  850. return false;
  851. }
  852. }else {
  853. SPDLOG_ERROR("Remote dir is not exist: {}", remoteDirTmp);
  854. return false;
  855. }
  856. }
  857. /* 拼接远程文件的url */
  858. std::string ftpUrl = m_ftpUrl + remoteFileTmp;
  859. /* 打开文件 */
  860. std::ifstream ifs;
  861. ifs.open(localFile, std::ios::in | std::ios::binary);
  862. if(!ifs.is_open())
  863. {
  864. SPDLOG_ERROR("Failed to open local file: {}", localFile);
  865. return false;
  866. }
  867. /* 获取文件大小 */
  868. // auto startPos = ifs.tellg();
  869. ifs.seekg(0, std::ios::end);
  870. auto fileSize = ifs.tellg();
  871. /* 恢复指针到文件头 */
  872. ifs.seekg(0, std::ios::beg);
  873. SPDLOG_DEBUG("File size: {}", (long)fileSize);
  874. CURL* curl = nullptr;
  875. curl = curl_easy_init();
  876. if(curl == nullptr)
  877. {
  878. SPDLOG_ERROR("curl init failed !");
  879. ifs.close();
  880. return false;
  881. }
  882. /* 设置FTP地址 */
  883. curl_easy_setopt(curl, CURLOPT_URL, ftpUrl.c_str());
  884. curl_easy_setopt(curl, CURLOPT_PORT, m_port);
  885. /* 设置用户名和密码 */
  886. curl_easy_setopt(curl, CURLOPT_USERNAME, m_username.c_str());
  887. curl_easy_setopt(curl, CURLOPT_PASSWORD, m_password.c_str());
  888. /* 启用跟随重定向 */
  889. curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1L);
  890. /* 启用上传 */
  891. curl_easy_setopt(curl, CURLOPT_UPLOAD, 1L);
  892. /* 设置回调函数 */
  893. curl_easy_setopt(curl, CURLOPT_READFUNCTION, readFileCallBack);
  894. curl_easy_setopt(curl, CURLOPT_READDATA, &ifs);
  895. /* 设置上传文件的大小 */
  896. curl_easy_setopt(curl, CURLOPT_INFILESIZE_LARGE, (curl_off_t)fileSize);
  897. /* 设置超时时间 */
  898. // curl_easy_setopt(curl, CURLOPT_TIMEOUT, 30L);
  899. curl_easy_setopt(curl, CURLOPT_CONNECTTIMEOUT, timeout);
  900. /* 设置进度回调函数 */
  901. curl_easy_setopt(curl, CURLOPT_XFERINFOFUNCTION, progress_callback);
  902. curl_easy_setopt(curl, CURLOPT_XFERINFODATA, nullptr);
  903. /* 启用下载进度回调函数 */
  904. curl_easy_setopt(curl, CURLOPT_NOPROGRESS, 0L);
  905. // 禁用被动模式(如果需要)
  906. curl_easy_setopt(curl, CURLOPT_FTP_USE_EPSV, 1L);
  907. if(m_enableCurlDebug)
  908. {
  909. /* 启用调试信息 */
  910. curl_easy_setopt(curl, CURLOPT_VERBOSE, 1L);
  911. }
  912. /* 启用持久连接 */
  913. curl_easy_setopt(curl, CURLOPT_TCP_KEEPALIVE, 1L);
  914. /* 发送请求 */
  915. CURLcode res = curl_easy_perform(curl);
  916. bool result = true;
  917. if(res != CURLE_OK)
  918. {
  919. SPDLOG_ERROR("Upload file failed, error code: {} ,{}", (int)res, curl_easy_strerror(res));
  920. SPDLOG_ERROR("Url = {}", ftpUrl);
  921. result = false;
  922. }
  923. /* 关闭文件,清理curl */
  924. ifs.close();
  925. curl_easy_cleanup(curl);
  926. /* 打印一个换行符 */
  927. printf("\n");
  928. return result;
  929. }
  930. /**
  931. * @brief 上传文件,上传数据
  932. * 注意:函数内不会拷贝数据,因此在上传完成前需要保证该指针的有效性,拷贝完成后也不会销毁源数据
  933. * 默认超时时间是30秒,也无法设置
  934. *
  935. * @param srcData 数据指针
  936. * @param size 数据大小
  937. * @param remoteFile 远程文件名,包括地址
  938. * @param timeout 超时时间,单位秒
  939. * @return true
  940. * @return false
  941. */
  942. bool CurlFtp::uploadData(char* srcData, size_t size, const std::string& remoteFile, size_t timeout, bool isCreateDir)
  943. {
  944. if(m_ftpUrl.empty())
  945. {
  946. SPDLOG_ERROR("Url is empty");
  947. return false;
  948. }
  949. /* 初始化本地数据 */
  950. CF_ArrayInfo arrayInfo;
  951. arrayInfo.data = srcData;
  952. arrayInfo.size = size;
  953. arrayInfo.pos = 0;
  954. /* 检查FTP文件名是否符合规范 */
  955. std::string remoteFileTmp = checkFilePath(remoteFile);
  956. std::string remoteDirTmp = remoteFileTmp.substr(0, remoteFileTmp.find_last_of("/"));
  957. /* 检查远程FTP上的文件夹是否存在,不存在则创建 */
  958. if(!isDirExist(remoteDirTmp))
  959. {
  960. if(isCreateDir)
  961. {
  962. if(!createDirectories(remoteDirTmp))
  963. {
  964. // SPDLOG_ERROR("Failed to create remote dir: {}", remoteFileTmp);
  965. return false;
  966. }
  967. }else {
  968. SPDLOG_ERROR("Remote dir is not exist: {}", remoteDirTmp);
  969. return false;
  970. }
  971. }
  972. /* 拼接远程文件的url */
  973. std::string ftpUrl = m_ftpUrl + remoteFileTmp;
  974. SPDLOG_DEBUG("Data size: {}", arrayInfo.size);
  975. CURL* curl = nullptr;
  976. curl = curl_easy_init();
  977. if(curl == nullptr)
  978. {
  979. SPDLOG_ERROR("curl init failed !");
  980. return false;
  981. }
  982. /* 设置FTP地址 */
  983. curl_easy_setopt(curl, CURLOPT_URL, ftpUrl.c_str());
  984. curl_easy_setopt(curl, CURLOPT_PORT, m_port);
  985. /* 设置用户名和密码 */
  986. // curl_easy_setopt(curl, CURLOPT_USERNAME, m_username.c_str());
  987. // curl_easy_setopt(curl, CURLOPT_PASSWORD, m_password.c_str());
  988. curl_easy_setopt(curl, CURLOPT_USERPWD, (m_username + ":" + m_password).c_str());
  989. /* 启用跟随重定向 */
  990. curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1L);
  991. /* 启用上传 */
  992. curl_easy_setopt(curl, CURLOPT_UPLOAD, 1L);
  993. /* 设置回调函数 */
  994. curl_easy_setopt(curl, CURLOPT_READFUNCTION, readDataCallBack);
  995. curl_easy_setopt(curl, CURLOPT_READDATA, &arrayInfo);
  996. /* 设置上传文件的大小 */
  997. curl_easy_setopt(curl, CURLOPT_INFILESIZE_LARGE, (curl_off_t)arrayInfo.size);
  998. /* 设置超时时间 */
  999. // curl_easy_setopt(curl, CURLOPT_TIMEOUT, 30L);
  1000. curl_easy_setopt(curl, CURLOPT_CONNECTTIMEOUT, timeout);
  1001. /* 设置进度回调函数 */
  1002. curl_easy_setopt(curl, CURLOPT_XFERINFOFUNCTION, progress_callback);
  1003. curl_easy_setopt(curl, CURLOPT_XFERINFODATA, nullptr);
  1004. /* 启用下载进度回调函数 */
  1005. curl_easy_setopt(curl, CURLOPT_NOPROGRESS, 0L);
  1006. // 禁用被动模式(如果需要)
  1007. curl_easy_setopt(curl, CURLOPT_FTP_USE_EPSV, 1L);
  1008. if(m_enableCurlDebug)
  1009. {
  1010. /* 启用调试信息 */
  1011. curl_easy_setopt(curl, CURLOPT_VERBOSE, 1L);
  1012. }
  1013. /* 启用持久连接 */
  1014. curl_easy_setopt(curl, CURLOPT_TCP_KEEPALIVE, 1L);
  1015. /* 发送请求 */
  1016. CURLcode res = curl_easy_perform(curl);
  1017. bool result = true;
  1018. if(res != CURLE_OK)
  1019. {
  1020. SPDLOG_ERROR("Upload file failed, error code: {} ,{}", (int)res, curl_easy_strerror(res));
  1021. SPDLOG_ERROR("Url = {}", ftpUrl);
  1022. result = false;
  1023. }
  1024. /* 关闭文件,清理curl */
  1025. curl_easy_cleanup(curl);
  1026. /* 打印一个换行符 */
  1027. printf("\n");
  1028. return result;
  1029. }
  1030. /**
  1031. * @brief 列出文件列表,这个需要的参数很多,无法设置成静态函数
  1032. *
  1033. * @param curl CURL句柄
  1034. * @param dir 文件夹,相对路径,不带有IP和端口号
  1035. * @param fileList 返回值,文件列表
  1036. * @return true
  1037. * @return false
  1038. */
  1039. bool CurlFtp::listAll(CURL* curl, std::string dir, std::vector<CF_FileInfo>& fileInfoList)
  1040. {
  1041. if(m_IP.empty())
  1042. {
  1043. SPDLOG_ERROR("IP is empty");
  1044. return false;
  1045. }
  1046. if(curl == nullptr)
  1047. {
  1048. SPDLOG_ERROR("curl is nullptr");
  1049. return false;
  1050. }
  1051. bool result = false;
  1052. std::string strSrc;
  1053. /* 先设置FTP地址 */
  1054. std::string ftpUrl = m_ftpUrl + dir;
  1055. curl_easy_setopt(curl, CURLOPT_URL, ftpUrl.c_str());
  1056. curl_easy_setopt(curl, CURLOPT_PORT, m_port);
  1057. /* 设置用户名和密码 */
  1058. curl_easy_setopt(curl, CURLOPT_USERNAME, m_username.c_str());
  1059. curl_easy_setopt(curl, CURLOPT_PASSWORD, m_password.c_str());
  1060. /* 设置列出文件命令,只列出文件名称,不携带信息 */
  1061. // curl_easy_setopt(m_curl, CURLOPT_DIRLISTONLY, 1L);
  1062. /* 设置回调函数 */
  1063. curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, writeStringCallback);
  1064. /* 设置需要写入的容器,回调函数的第四个参数 */
  1065. curl_easy_setopt(curl, CURLOPT_WRITEDATA, &strSrc);
  1066. /* 设置超时时间 */
  1067. curl_easy_setopt(curl, CURLOPT_TIMEOUT, 10L);
  1068. curl_easy_setopt(curl, CURLOPT_CONNECTTIMEOUT, 10L);
  1069. // 禁用被动模式(如果需要)
  1070. curl_easy_setopt(curl, CURLOPT_FTP_USE_EPSV, 1L);
  1071. if(m_enableCurlDebug)
  1072. {
  1073. /* 启用调试信息 */
  1074. curl_easy_setopt(curl, CURLOPT_VERBOSE, 1L);
  1075. }
  1076. /* 发送请求 */
  1077. CURLcode res = curl_easy_perform(curl);
  1078. if(res != CURLE_OK)
  1079. {
  1080. SPDLOG_ERROR("Failed to get file list, error code: {} ,{}", (int)res, curl_easy_strerror(res));
  1081. SPDLOG_ERROR("Url = {}", ftpUrl);
  1082. return false;
  1083. }
  1084. /* 解析字符串 */
  1085. parseFileInfo(strSrc, fileInfoList);
  1086. return true;
  1087. }
  1088. /* 检查文件夹路径是否合规,不合规就修改 */
  1089. std::string CurlFtp::checkDirPath(const std::string& dir)
  1090. {
  1091. std::string dirTmp = dir;
  1092. /* 检查是否以“/”开头 */
  1093. std::regex reg(R"(^/[.]*)");
  1094. if(!std::regex_match(dirTmp, reg))
  1095. {
  1096. dirTmp = "/" + dirTmp;
  1097. }
  1098. /* 如果有重复的“/”,替换成一个 “/” */
  1099. std::regex reg1(R"(//)");
  1100. dirTmp = std::regex_replace(dirTmp, reg1, "/");
  1101. /* 检查是否以“/”结束 */
  1102. std::regex reg2(R"([.]*/$)");
  1103. if(!std::regex_match(dirTmp, reg2))
  1104. {
  1105. dirTmp = dirTmp + "/";
  1106. }
  1107. return dirTmp;
  1108. }
  1109. /* 检查文件路径是否合规 */
  1110. std::string CurlFtp::checkFilePath(const std::string& file)
  1111. {
  1112. std::string dirTmp = file;
  1113. /* 检查是否以“/”结束,如果是以“/”结尾,返回空字符串,并报错 */
  1114. std::regex reg2(R"([.]*/$)");
  1115. if(std::regex_match(dirTmp, reg2))
  1116. {
  1117. SPDLOG_ERROR("File path is not correct, end with '/'");
  1118. return std::string();
  1119. }
  1120. /* 检查是否以“/”开头 */
  1121. std::regex reg(R"(^/[.]*)");
  1122. if(!std::regex_match(dirTmp, reg))
  1123. {
  1124. dirTmp = "/" + dirTmp;
  1125. }
  1126. /* 如果有重复的“/”,替换成一个 “/” */
  1127. std::regex reg1(R"(//)");
  1128. dirTmp = std::regex_replace(dirTmp, reg1, "/");
  1129. return dirTmp;
  1130. }
  1131. /**
  1132. * @brief 检查本地文件夹是否存在,不存在则创建
  1133. * 这里默认传入的是文件夹路径,不是文件路径,如果最后有‘/’,会自动去掉
  1134. *
  1135. * @param localDir 文件夹路径
  1136. * @return true
  1137. * @return false
  1138. */
  1139. bool CurlFtp::checkLocalDir(const std::string& localDir)
  1140. {
  1141. /* 去掉最后的‘/’ */
  1142. std::regex reg(R"([.]*/$)");
  1143. std::string localDirTmp = std::regex_replace(localDir, reg, "");
  1144. /* 检查文件夹是否存在 */
  1145. if(std::filesystem::exists(localDirTmp))
  1146. {
  1147. return true;
  1148. }
  1149. /* 创建文件夹 */
  1150. if(!std::filesystem::create_directories(localDirTmp))
  1151. {
  1152. SPDLOG_ERROR("Failed to create local dir: {}", localDirTmp);
  1153. return false;
  1154. }
  1155. return true;
  1156. }
  1157. /* 执行curl,添加重试机制 */
  1158. bool CurlFtp::performCurl(CURL* curl)
  1159. {
  1160. int retry = 3;
  1161. while(retry > 0)
  1162. {
  1163. CURLcode res = curl_easy_perform(curl);
  1164. if(res == CURLE_OK)
  1165. {
  1166. return true;
  1167. }else
  1168. {
  1169. SPDLOG_ERROR("Perform curl failed, error code: {} ,{}", (int)res, curl_easy_strerror(res));
  1170. SPDLOG_ERROR("Retry times: {}", 3 - retry);
  1171. retry--;
  1172. }
  1173. }
  1174. return false;
  1175. }