CurlFtp.cpp 39 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323
  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_easy_cleanup(m_curl);
  383. curl_global_cleanup();
  384. hasInstace = false;
  385. }
  386. /* 设置用户名和密码 */
  387. bool CurlFtp::setUsernameAndPassword(const std::string& username, const std::string& password)
  388. {
  389. m_username = username;
  390. m_password = password;
  391. return true;
  392. }
  393. /* 设置IP和端口 */
  394. bool CurlFtp::setFtpIPAndPort(const std::string& IP, const int port)
  395. {
  396. /*先判断是否有ftp器前缀,通过正则表达式,取出IP地址和端口号,去掉前缀和后面的'/ */
  397. m_IP = IP;
  398. m_port = port;
  399. m_ftpUrl = "ftp://" + m_IP + ":" + std::to_string(m_port);
  400. SPDLOG_INFO("Set ftpUrl = {}", m_ftpUrl);
  401. m_isSftp = false;
  402. return true;
  403. }
  404. /* 设置SFTP的IP和端口 */
  405. bool CurlFtp::setSftpIPAndPort(const std::string& IP, const int port)
  406. {
  407. m_IP = IP;
  408. m_port = port;
  409. m_ftpUrl = "sftp://" + m_IP + ":" + std::to_string(m_port);
  410. SPDLOG_INFO("Set sftpUrl = {}", m_ftpUrl);
  411. m_isSftp = true;
  412. return true;
  413. }
  414. /* 设置是否忽略SSL证书,使用SFTP不建议忽略 */
  415. void CurlFtp::setIgnoreSSLCert(bool isIgnore)
  416. {
  417. m_isIgnoreSSLCert = isIgnore;
  418. }
  419. /* 设置CA证书文件 */
  420. void CurlFtp::setCaCertFile(const std::string& caCertFile)
  421. {
  422. m_caCertFile = caCertFile;
  423. }
  424. /* 设置是否启用CURL的调试信息 */
  425. void CurlFtp::enableCurlDebug(bool isPrint)
  426. {
  427. m_enableCurlDebug = isPrint;
  428. }
  429. /* 列出文件列表 */
  430. bool CurlFtp::getFileList(std::string dir, std::vector<std::string>& fileList)
  431. {
  432. if(m_IP.empty())
  433. {
  434. SPDLOG_WARN("IP or port is empty");
  435. return false;
  436. }
  437. /* 检查dir,添加前缀“/” */
  438. auto dirTmp = checkDirPath(dir);
  439. // CURL *curl = nullptr;
  440. // curl = curl_easy_init();
  441. // if(curl == nullptr)
  442. // {
  443. // SPDLOG_ERROR("curl init failed !");
  444. // return false;
  445. // }
  446. resetCurl(m_curl);
  447. std::vector<CF_FileInfo> listInfo;
  448. /* 获取文件信息 */
  449. listAll(m_curl, dirTmp, listInfo);
  450. for(const CF_FileInfo& fi : listInfo)
  451. {
  452. // SPDLOG_INFO("type = {}, size = {}, name = {}", (int)fi.type, fi.size, fi.name);
  453. if(fi.type == CF_FileType::FILE)
  454. {
  455. fileList.push_back(fi.name);
  456. }
  457. }
  458. // curl_easy_cleanup(curl);
  459. return true;
  460. }
  461. /* 获取文件夹列表 */
  462. bool CurlFtp::getDirList(std::string dir, std::vector<std::string>& dirList)
  463. {
  464. if(m_IP.empty())
  465. {
  466. SPDLOG_WARN("IP or port is empty");
  467. return false;
  468. }
  469. /* 检查dir,添加前缀“/” */
  470. auto dirTmp = checkDirPath(dir);
  471. // CURL *curl = nullptr;
  472. // curl = curl_easy_init();
  473. // if(curl == nullptr)
  474. // {
  475. // SPDLOG_ERROR("curl init failed !");
  476. // return false;
  477. // }
  478. resetCurl(m_curl);
  479. std::vector<CF_FileInfo> listInfo;
  480. /* 获取文件信息 */
  481. listAll(m_curl, dirTmp, listInfo);
  482. for(const CF_FileInfo& fi : listInfo)
  483. {
  484. // SPDLOG_INFO("type = {}, size = {}, name = {}", (int)fi.type, fi.size, fi.name);
  485. if(fi.type == CF_FileType::DIR)
  486. {
  487. dirList.push_back(fi.name);
  488. }
  489. }
  490. // curl_easy_cleanup(curl);
  491. return true;
  492. }
  493. /* 判断文件夹是否存在 */
  494. bool CurlFtp::isDirExist(const std::string& dir)
  495. {
  496. SPDLOG_DEBUG("Check dir: {}", dir);
  497. if(m_ftpUrl.empty())
  498. {
  499. SPDLOG_ERROR("ftpUrl is empty");
  500. return false;
  501. }
  502. /* 检查传入的文件夹 */
  503. auto dirTmp = checkDirPath(dir);
  504. // CURL* curl = nullptr;
  505. resetCurl(m_curl);
  506. std::string ftpUrl = m_ftpUrl + dirTmp;
  507. curl_easy_setopt(m_curl, CURLOPT_URL, ftpUrl.c_str());
  508. curl_easy_setopt(m_curl, CURLOPT_USERNAME, m_username.c_str());
  509. curl_easy_setopt(m_curl, CURLOPT_PASSWORD, m_password.c_str());
  510. /* 获取文件夹是否存在,不需要接收文件 */
  511. curl_easy_setopt(m_curl, CURLOPT_NOBODY, 1L);
  512. /* 设置SFTP */
  513. setSftp(m_curl);
  514. /* 启用调试信息 */
  515. if(m_enableCurlDebug)
  516. {
  517. curl_easy_setopt(m_curl, CURLOPT_VERBOSE, 1L);
  518. }
  519. /* 启用持久连接 */
  520. // curl_easy_setopt(m_curl, CURLOPT_TCP_KEEPALIVE, 1L);
  521. /* 这里只需要执行一次 */
  522. CURLcode res = curl_easy_perform(m_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(m_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. if(m_curl == nullptr)
  564. {
  565. m_curl = curl_easy_init();
  566. if(m_curl == nullptr)
  567. {
  568. SPDLOG_ERROR("curl init failed !");
  569. return false;
  570. }
  571. }else {
  572. curl_easy_reset(m_curl);
  573. }
  574. curl_easy_setopt(m_curl, CURLOPT_URL, m_ftpUrl.c_str());
  575. curl_easy_setopt(m_curl, CURLOPT_USERNAME, m_username.c_str());
  576. curl_easy_setopt(m_curl, CURLOPT_PASSWORD, m_password.c_str());
  577. /* 创建FTP头信息 */
  578. struct curl_slist *headerlist = NULL;
  579. std::string mkdir = "MKD " + dirTmp;
  580. headerlist = curl_slist_append(headerlist, mkdir.c_str());
  581. /* 设置FTP命令行选项 */
  582. curl_easy_setopt(m_curl, CURLOPT_QUOTE, headerlist);
  583. /* 不包含实体 */
  584. curl_easy_setopt(m_curl, CURLOPT_NOBODY, 1L);
  585. /* 启用跟随重定向 */
  586. curl_easy_setopt(m_curl, CURLOPT_FOLLOWLOCATION, 1L);
  587. /* 设置超时时间 */
  588. curl_easy_setopt(m_curl, CURLOPT_TIMEOUT, 30L);
  589. curl_easy_setopt(m_curl, CURLOPT_CONNECTTIMEOUT, 30L);
  590. /* 设置SFTP */
  591. setSftp(m_curl);
  592. if(m_enableCurlDebug)
  593. {
  594. /* 启用调试信息 */
  595. curl_easy_setopt(m_curl, CURLOPT_VERBOSE, 1L);
  596. }
  597. // 启用持久连接
  598. // curl_easy_setopt(m_curl, CURLOPT_TCP_KEEPALIVE, 1L);
  599. SPDLOG_DEBUG("Create dir: {}", dirTmp);
  600. // CURLcode res = curl_easy_perform(curl);
  601. bool ret = performCurl(m_curl);
  602. if(!ret)
  603. {
  604. SPDLOG_ERROR("Failed to create FTP Dir");
  605. }
  606. // curl_easy_cleanup(curl);
  607. curl_slist_free_all(headerlist);
  608. return ret;
  609. }
  610. /* 创建FTP文件夹,递归创建 */
  611. bool CurlFtp::createDirectories(const std::string& ftpDir)
  612. {
  613. /* 检查路径格式,并去掉第一个 / */
  614. std::string ftpDirTmp = checkDirPath(ftpDir);
  615. std::string ftpDir2 = ftpDirTmp.substr(1, ftpDirTmp.size() -1);
  616. /* 将文件夹分开,取出每一个文件夹名称 */
  617. std::vector<std::string> strList;
  618. std::regex reg(R"(/)");
  619. std::sregex_token_iterator it(ftpDir2.begin(), ftpDir2.end(), reg, -1);
  620. for( ; it != std::sregex_token_iterator(); ++it)
  621. {
  622. strList.push_back(it->str());
  623. }
  624. /* 将每一层拼接起来,逐层递归 */
  625. std::vector<std::string> dirList;
  626. for(const std::string& dir : strList)
  627. {
  628. std::string dirTmp = "/";
  629. if(!dirList.empty())
  630. {
  631. dirTmp = dirList.back();
  632. dirTmp += "/";
  633. }
  634. dirTmp += dir;
  635. dirList.push_back(dirTmp);
  636. }
  637. /* 逐层创建 */
  638. for(const std::string& dir : dirList)
  639. {
  640. // SPDLOG_DEBUG("Create dir: {}", dir);
  641. if(!createDirectory(dir))
  642. {
  643. SPDLOG_ERROR("Failed to create dir: {}", dir);
  644. return false;
  645. }
  646. }
  647. return true;
  648. }
  649. /**
  650. * @brief 下载文件
  651. *
  652. * @param remoteFile
  653. * @param localFile
  654. * @param timeout 超时时间,单位秒
  655. * @return true
  656. * @return false
  657. */
  658. bool CurlFtp::downloadFile(const std::string& remoteFile, const std::string& localFile, size_t timeout)
  659. {
  660. if(m_ftpUrl.empty())
  661. {
  662. SPDLOG_ERROR("ftpUrl is empty");
  663. return false;
  664. }
  665. /* 检查传入的文件是否符合规范 */
  666. std::string remoteFileTmp = checkFilePath(remoteFile);
  667. std::string ftpUrl = m_ftpUrl + remoteFileTmp;
  668. /* 检查本地文件夹是否存在,不存在则创建 */
  669. // std::string localDir = localFile.substr(0, localFile.find_last_of("/")); /* 去掉最后的 / */
  670. std::string localDirTmp = localFile.substr(0, localFile.find_last_of("/"));
  671. if(!checkLocalDir(localDirTmp))
  672. {
  673. SPDLOG_ERROR("Failed to create local dir: {}", localDirTmp);
  674. return false;
  675. }
  676. // CURL* curl = nullptr;
  677. // curl = curl_easy_init();
  678. // if(curl == nullptr)
  679. // {
  680. // SPDLOG_ERROR("curl init failed !");
  681. // return false;
  682. // }
  683. resetCurl(m_curl);
  684. /* 打开文件 */
  685. std::ofstream ofs;
  686. ofs.open(localFile, std::ios::out | std::ios::binary | std::ios::trunc);
  687. /* 设置FTP地址 */
  688. curl_easy_setopt(m_curl, CURLOPT_URL, ftpUrl.c_str());
  689. curl_easy_setopt(m_curl, CURLOPT_PORT, m_port);
  690. /* 设置用户名和密码 */
  691. curl_easy_setopt(m_curl, CURLOPT_USERNAME, m_username.c_str());
  692. curl_easy_setopt(m_curl, CURLOPT_PASSWORD, m_password.c_str());
  693. curl_easy_setopt(m_curl, CURLOPT_USERPWD, (m_username + ":" + m_password).c_str());
  694. /* 启用跟随重定向 */
  695. curl_easy_setopt(m_curl, CURLOPT_FOLLOWLOCATION, 1L);
  696. /* 设置回调函数 */
  697. curl_easy_setopt(m_curl, CURLOPT_WRITEFUNCTION, writeFileCallBack);
  698. curl_easy_setopt(m_curl, CURLOPT_WRITEDATA, &ofs);
  699. /* 设置超时时间 */
  700. // curl_easy_setopt(curl, CURLOPT_TIMEOUT, 30L);
  701. curl_easy_setopt(m_curl, CURLOPT_CONNECTTIMEOUT, timeout);
  702. /* 设置进度回调函数 */
  703. curl_easy_setopt(m_curl, CURLOPT_XFERINFOFUNCTION, progress_callback);
  704. curl_easy_setopt(m_curl, CURLOPT_XFERINFODATA, nullptr);
  705. /* 启用下载进度回调函数 */
  706. curl_easy_setopt(m_curl, CURLOPT_NOPROGRESS, 0L);
  707. /* 设置SFTP */
  708. setSftp(m_curl);
  709. if(m_enableCurlDebug)
  710. {
  711. /* 启用调试信息 */
  712. curl_easy_setopt(m_curl, CURLOPT_VERBOSE, 1L);
  713. }
  714. /* 启用持久连接 */
  715. curl_easy_setopt(m_curl, CURLOPT_TCP_KEEPALIVE, 1L);
  716. /* 发送请求 */
  717. bool ret = performCurl(m_curl);
  718. if(!ret)
  719. {
  720. SPDLOG_ERROR("Failed to get file list, Url = {}", ftpUrl);
  721. /* 清理下载失败的文件 */
  722. ofs.close();
  723. std::remove(localFile.c_str());
  724. return false;
  725. }
  726. /* 关闭文件,清理curl */
  727. ofs.close();
  728. // curl_easy_cleanup(curl);
  729. /* 打印一个换行符 */
  730. // printf("\n");
  731. printf("\n");
  732. return true;
  733. }
  734. /* 下载文件到数组 */
  735. bool CurlFtp::downloadToArray(const std::string& remoteFile, std::vector<char>& arrayInfo, size_t timeout)
  736. {
  737. if(m_ftpUrl.empty())
  738. {
  739. SPDLOG_ERROR("ftpUrl is empty");
  740. return false;
  741. }
  742. /* 检查传入的文件是否符合规范 */
  743. std::string remoteFileTmp = checkFilePath(remoteFile);
  744. std::string ftpUrl = m_ftpUrl + remoteFileTmp;
  745. // CURL* curl = nullptr;
  746. // curl = curl_easy_init();
  747. // if(curl == nullptr)
  748. // {
  749. // SPDLOG_ERROR("curl init failed !");
  750. // return false;
  751. // }
  752. resetCurl(m_curl);
  753. /* 设置FTP地址 */
  754. curl_easy_setopt(m_curl, CURLOPT_URL, ftpUrl.c_str());
  755. curl_easy_setopt(m_curl, CURLOPT_PORT, m_port);
  756. /* 设置用户名和密码 */
  757. curl_easy_setopt(m_curl, CURLOPT_USERNAME, m_username.c_str());
  758. curl_easy_setopt(m_curl, CURLOPT_PASSWORD, m_password.c_str());
  759. curl_easy_setopt(m_curl, CURLOPT_USERPWD, (m_username + ":" + m_password).c_str());
  760. /* 启用跟随重定向 */
  761. curl_easy_setopt(m_curl, CURLOPT_FOLLOWLOCATION, 1L);
  762. /* 设置回调函数 */
  763. curl_easy_setopt(m_curl, CURLOPT_WRITEFUNCTION, writeDataCallBack);
  764. curl_easy_setopt(m_curl, CURLOPT_WRITEDATA, &arrayInfo);
  765. /* 设置超时时间 */
  766. // curl_easy_setopt(curl, CURLOPT_TIMEOUT, 30L);
  767. curl_easy_setopt(m_curl, CURLOPT_CONNECTTIMEOUT, timeout);
  768. /* 设置进度回调函数 */
  769. curl_easy_setopt(m_curl, CURLOPT_XFERINFOFUNCTION, progress_callback);
  770. curl_easy_setopt(m_curl, CURLOPT_XFERINFODATA, nullptr);
  771. /* 启用下载进度回调函数 */
  772. curl_easy_setopt(m_curl, CURLOPT_NOPROGRESS, 0L);
  773. /* 设置SFTP */
  774. setSftp(m_curl);
  775. if(m_enableCurlDebug)
  776. {
  777. /* 启用调试信息 */
  778. curl_easy_setopt(m_curl, CURLOPT_VERBOSE, 1L);
  779. }
  780. /* 启用持久连接 */
  781. curl_easy_setopt(m_curl, CURLOPT_TCP_KEEPALIVE, 1L);
  782. /* 发送请求 */
  783. bool ret = performCurl(m_curl);
  784. if(!ret)
  785. {
  786. SPDLOG_ERROR("Failed to get file list, Url = {}", ftpUrl);
  787. }
  788. /* 清理curl */
  789. // curl_easy_cleanup(curl);
  790. /* 打印一个换行符 */
  791. // printf("\n");
  792. printf("\n");
  793. return ret;
  794. }
  795. /**
  796. * @brief 上传文件
  797. *
  798. * @param localFile 本地文件
  799. * @param remoteFile 远程文件
  800. * @param timeout 超时时间,单位秒
  801. * @return true
  802. * @return false
  803. */
  804. bool CurlFtp::uploadFile(const std::string& localFile, const std::string& remoteFile, size_t timeout, bool isCreateDir)
  805. {
  806. if(m_ftpUrl.empty())
  807. {
  808. SPDLOG_ERROR("Url is empty");
  809. return false;
  810. }
  811. /* 检查本地文件是否存在 */
  812. if(!std::filesystem::exists(localFile))
  813. {
  814. SPDLOG_ERROR("Local file is not exist: {}", localFile);
  815. return false;
  816. }
  817. /* 检查FTP文件名是否符合规范 */
  818. std::string remoteFileTmp = checkFilePath(remoteFile);
  819. std::string remoteDirTmp = remoteFileTmp.substr(0, remoteFileTmp.find_last_of("/"));
  820. /* 检查远程FTP上的文件夹是否存在,不存在则创建 */
  821. if(!isDirExist(remoteDirTmp))
  822. {
  823. if(isCreateDir)
  824. {
  825. if(!createDirectories(remoteDirTmp))
  826. {
  827. // SPDLOG_ERROR("Failed to create remote dir: {}", remoteFileTmp);
  828. return false;
  829. }
  830. }else {
  831. SPDLOG_ERROR("Remote dir is not exist: {}", remoteDirTmp);
  832. return false;
  833. }
  834. }
  835. /* 拼接远程文件的url */
  836. std::string ftpUrl = m_ftpUrl + remoteFileTmp;
  837. /* 打开文件 */
  838. std::ifstream ifs;
  839. ifs.open(localFile, std::ios::in | std::ios::binary);
  840. if(!ifs.is_open())
  841. {
  842. SPDLOG_ERROR("Failed to open local file: {}", localFile);
  843. return false;
  844. }
  845. /* 获取文件大小 */
  846. // auto startPos = ifs.tellg();
  847. ifs.seekg(0, std::ios::end);
  848. auto fileSize = ifs.tellg();
  849. /* 恢复指针到文件头 */
  850. ifs.seekg(0, std::ios::beg);
  851. SPDLOG_DEBUG("File size: {}", (long)fileSize);
  852. // CURL* curl = nullptr;
  853. // curl = curl_easy_init();
  854. // if(curl == nullptr)
  855. // {
  856. // SPDLOG_ERROR("curl init failed !");
  857. // ifs.close();
  858. // return false;
  859. // }
  860. if(!resetCurl(m_curl))
  861. {
  862. ifs.close();
  863. return false;
  864. }
  865. /* 设置FTP地址 */
  866. curl_easy_setopt(m_curl, CURLOPT_URL, ftpUrl.c_str());
  867. curl_easy_setopt(m_curl, CURLOPT_PORT, m_port);
  868. /* 设置用户名和密码 */
  869. curl_easy_setopt(m_curl, CURLOPT_USERNAME, m_username.c_str());
  870. curl_easy_setopt(m_curl, CURLOPT_PASSWORD, m_password.c_str());
  871. /* 启用跟随重定向 */
  872. curl_easy_setopt(m_curl, CURLOPT_FOLLOWLOCATION, 1L);
  873. /* 启用上传 */
  874. curl_easy_setopt(m_curl, CURLOPT_UPLOAD, 1L);
  875. /* 设置回调函数 */
  876. curl_easy_setopt(m_curl, CURLOPT_READFUNCTION, readFileCallBack);
  877. curl_easy_setopt(m_curl, CURLOPT_READDATA, &ifs);
  878. /* 设置上传文件的大小 */
  879. curl_easy_setopt(m_curl, CURLOPT_INFILESIZE_LARGE, (curl_off_t)fileSize);
  880. /* 设置超时时间 */
  881. // curl_easy_setopt(curl, CURLOPT_TIMEOUT, 30L);
  882. curl_easy_setopt(m_curl, CURLOPT_CONNECTTIMEOUT, timeout);
  883. /* 设置进度回调函数 */
  884. curl_easy_setopt(m_curl, CURLOPT_XFERINFOFUNCTION, progress_callback);
  885. curl_easy_setopt(m_curl, CURLOPT_XFERINFODATA, nullptr);
  886. /* 启用下载进度回调函数 */
  887. curl_easy_setopt(m_curl, CURLOPT_NOPROGRESS, 0L);
  888. /* 设置SFTP */
  889. setSftp(m_curl);
  890. /* 启用调试信息 */
  891. if(m_enableCurlDebug)
  892. {
  893. curl_easy_setopt(m_curl, CURLOPT_VERBOSE, 1L);
  894. }
  895. /* 启用持久连接 */
  896. curl_easy_setopt(m_curl, CURLOPT_TCP_KEEPALIVE, 1L);
  897. /* 发送请求 */
  898. bool ret = performCurl(m_curl);
  899. if(!ret)
  900. {
  901. SPDLOG_ERROR("Upload file failed, Url = {}", ftpUrl);
  902. }
  903. /* 关闭文件,清理curl */
  904. ifs.close();
  905. // curl_easy_cleanup(curl);
  906. /* 打印一个换行符 */
  907. printf("\n");
  908. return ret;
  909. }
  910. /**
  911. * @brief 上传文件,上传数据
  912. * 注意:函数内不会拷贝数据,因此在上传完成前需要保证该指针的有效性,拷贝完成后也不会销毁源数据
  913. * 默认超时时间是30秒,也无法设置
  914. *
  915. * @param srcData 数据指针
  916. * @param size 数据大小
  917. * @param remoteFile 远程文件名,包括地址
  918. * @param timeout 超时时间,单位秒
  919. * @return true
  920. * @return false
  921. */
  922. bool CurlFtp::uploadData(char* srcData, size_t size, const std::string& remoteFile, size_t timeout, bool isCreateDir)
  923. {
  924. if(m_ftpUrl.empty())
  925. {
  926. SPDLOG_ERROR("Url is empty");
  927. return false;
  928. }
  929. /* 初始化本地数据 */
  930. CF_ArrayInfo arrayInfo;
  931. arrayInfo.data = srcData;
  932. arrayInfo.size = size;
  933. arrayInfo.pos = 0;
  934. /* 检查FTP文件名是否符合规范 */
  935. std::string remoteFileTmp = checkFilePath(remoteFile);
  936. std::string remoteDirTmp = remoteFileTmp.substr(0, remoteFileTmp.find_last_of("/"));
  937. /* 检查远程FTP上的文件夹是否存在,不存在则创建 */
  938. if(!isDirExist(remoteDirTmp))
  939. {
  940. if(isCreateDir)
  941. {
  942. if(!createDirectories(remoteDirTmp))
  943. {
  944. // SPDLOG_ERROR("Failed to create remote dir: {}", remoteFileTmp);
  945. return false;
  946. }
  947. }else {
  948. SPDLOG_ERROR("Remote dir is not exist: {}", remoteDirTmp);
  949. return false;
  950. }
  951. }
  952. /* 拼接远程文件的url */
  953. std::string ftpUrl = m_ftpUrl + remoteFileTmp;
  954. SPDLOG_DEBUG("Data size: {}", arrayInfo.size);
  955. // CURL* curl = nullptr;
  956. // curl = curl_easy_init();
  957. // if(curl == nullptr)
  958. // {
  959. // SPDLOG_ERROR("curl init failed !");
  960. // return false;
  961. // }
  962. if(!resetCurl(m_curl))
  963. {
  964. return false;
  965. }
  966. /* 设置FTP地址 */
  967. curl_easy_setopt(m_curl, CURLOPT_URL, ftpUrl.c_str());
  968. curl_easy_setopt(m_curl, CURLOPT_PORT, m_port);
  969. /* 设置用户名和密码 */
  970. // curl_easy_setopt(curl, CURLOPT_USERNAME, m_username.c_str());
  971. // curl_easy_setopt(curl, CURLOPT_PASSWORD, m_password.c_str());
  972. curl_easy_setopt(m_curl, CURLOPT_USERPWD, (m_username + ":" + m_password).c_str());
  973. /* 启用跟随重定向 */
  974. curl_easy_setopt(m_curl, CURLOPT_FOLLOWLOCATION, 1L);
  975. /* 启用上传 */
  976. curl_easy_setopt(m_curl, CURLOPT_UPLOAD, 1L);
  977. /* 设置回调函数 */
  978. curl_easy_setopt(m_curl, CURLOPT_READFUNCTION, readDataCallBack);
  979. curl_easy_setopt(m_curl, CURLOPT_READDATA, &arrayInfo);
  980. /* 设置上传文件的大小 */
  981. curl_easy_setopt(m_curl, CURLOPT_INFILESIZE_LARGE, (curl_off_t)arrayInfo.size);
  982. /* 设置超时时间 */
  983. // curl_easy_setopt(curl, CURLOPT_TIMEOUT, 30L);
  984. curl_easy_setopt(m_curl, CURLOPT_CONNECTTIMEOUT, timeout);
  985. /* 设置进度回调函数 */
  986. curl_easy_setopt(m_curl, CURLOPT_XFERINFOFUNCTION, progress_callback);
  987. curl_easy_setopt(m_curl, CURLOPT_XFERINFODATA, nullptr);
  988. /* 启用下载进度回调函数 */
  989. curl_easy_setopt(m_curl, CURLOPT_NOPROGRESS, 0L);
  990. // 禁用被动模式(如果需要)
  991. curl_easy_setopt(m_curl, CURLOPT_FTP_USE_EPSV, 1L);
  992. if(m_enableCurlDebug)
  993. {
  994. /* 启用调试信息 */
  995. curl_easy_setopt(m_curl, CURLOPT_VERBOSE, 1L);
  996. }
  997. /* 启用持久连接 */
  998. curl_easy_setopt(m_curl, CURLOPT_TCP_KEEPALIVE, 1L);
  999. /* 发送请求 */
  1000. bool ret = performCurl(m_curl);
  1001. if(!ret)
  1002. {
  1003. SPDLOG_ERROR("Upload file failed, Url = {}", ftpUrl);
  1004. }
  1005. /* 关闭文件,清理curl */
  1006. // curl_easy_cleanup(curl);
  1007. /* 打印一个换行符 */
  1008. printf("\n");
  1009. return ret;
  1010. }
  1011. /**
  1012. * @brief 列出文件列表,这个需要的参数很多,无法设置成静态函数
  1013. *
  1014. * @param curl CURL句柄
  1015. * @param dir 文件夹,相对路径,不带有IP和端口号
  1016. * @param fileList 返回值,文件列表
  1017. * @return true
  1018. * @return false
  1019. */
  1020. bool CurlFtp::listAll(CURL* curl, std::string dir, std::vector<CF_FileInfo>& fileInfoList)
  1021. {
  1022. if(m_IP.empty())
  1023. {
  1024. SPDLOG_ERROR("IP is empty");
  1025. return false;
  1026. }
  1027. bool result = false;
  1028. std::string strSrc;
  1029. /* 先设置FTP地址 */
  1030. std::string ftpUrl = m_ftpUrl + dir;
  1031. curl_easy_setopt(curl, CURLOPT_URL, ftpUrl.c_str());
  1032. curl_easy_setopt(curl, CURLOPT_PORT, m_port);
  1033. /* 设置用户名和密码 */
  1034. curl_easy_setopt(curl, CURLOPT_USERNAME, m_username.c_str());
  1035. curl_easy_setopt(curl, CURLOPT_PASSWORD, m_password.c_str());
  1036. /* 设置列出文件命令,只列出文件名称,不携带信息 */
  1037. // curl_easy_setopt(m_curl, CURLOPT_DIRLISTONLY, 1L);
  1038. /* 设置回调函数 */
  1039. curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, writeStringCallback);
  1040. /* 设置需要写入的容器,回调函数的第四个参数 */
  1041. curl_easy_setopt(curl, CURLOPT_WRITEDATA, &strSrc);
  1042. /* 设置超时时间 */
  1043. curl_easy_setopt(curl, CURLOPT_TIMEOUT, 10L);
  1044. curl_easy_setopt(curl, CURLOPT_CONNECTTIMEOUT, 10L);
  1045. // 禁用被动模式,设置为0是禁用(如果需要)
  1046. // curl_easy_setopt(curl, CURLOPT_FTP_USE_EPSV, 1L);
  1047. if(m_enableCurlDebug)
  1048. {
  1049. /* 启用调试信息 */
  1050. curl_easy_setopt(curl, CURLOPT_VERBOSE, 1L);
  1051. }
  1052. /* 发送请求 */
  1053. // CURLcode res = curl_easy_perform(curl);
  1054. bool ret = performCurl(curl);
  1055. if(!ret)
  1056. {
  1057. SPDLOG_ERROR("Failed to get file listUrl = {}", ftpUrl);
  1058. return false;
  1059. }
  1060. /* 解析字符串 */
  1061. parseFileInfo(strSrc, fileInfoList);
  1062. return true;
  1063. }
  1064. /* 检查文件夹路径是否合规,不合规就修改 */
  1065. std::string CurlFtp::checkDirPath(const std::string& dir)
  1066. {
  1067. std::string dirTmp = dir;
  1068. /* 检查是否以“/”开头 */
  1069. std::regex reg(R"(^/[.]*)");
  1070. if(!std::regex_match(dirTmp, reg))
  1071. {
  1072. dirTmp = "/" + dirTmp;
  1073. }
  1074. /* 如果有重复的“/”,替换成一个 “/” */
  1075. std::regex reg1(R"(//)");
  1076. dirTmp = std::regex_replace(dirTmp, reg1, "/");
  1077. /* 检查是否以“/”结束 */
  1078. std::regex reg2(R"([.]*/$)");
  1079. if(!std::regex_match(dirTmp, reg2))
  1080. {
  1081. dirTmp = dirTmp + "/";
  1082. }
  1083. return dirTmp;
  1084. }
  1085. /* 检查文件路径是否合规 */
  1086. std::string CurlFtp::checkFilePath(const std::string& file)
  1087. {
  1088. std::string dirTmp = file;
  1089. /* 检查是否以“/”结束,如果是以“/”结尾,返回空字符串,并报错 */
  1090. std::regex reg2(R"([.]*/$)");
  1091. if(std::regex_match(dirTmp, reg2))
  1092. {
  1093. SPDLOG_ERROR("File path is not correct, end with '/'");
  1094. return std::string();
  1095. }
  1096. /* 检查是否以“/”开头 */
  1097. std::regex reg(R"(^/[.]*)");
  1098. if(!std::regex_match(dirTmp, reg))
  1099. {
  1100. dirTmp = "/" + dirTmp;
  1101. }
  1102. /* 如果有重复的“/”,替换成一个 “/” */
  1103. std::regex reg1(R"(//)");
  1104. dirTmp = std::regex_replace(dirTmp, reg1, "/");
  1105. return dirTmp;
  1106. }
  1107. /**
  1108. * @brief 检查本地文件夹是否存在,不存在则创建
  1109. * 这里默认传入的是文件夹路径,不是文件路径,如果最后有‘/’,会自动去掉
  1110. *
  1111. * @param localDir 文件夹路径
  1112. * @return true
  1113. * @return false
  1114. */
  1115. bool CurlFtp::checkLocalDir(const std::string& localDir)
  1116. {
  1117. /* 去掉最后的‘/’ */
  1118. std::regex reg(R"([.]*/$)");
  1119. std::string localDirTmp = std::regex_replace(localDir, reg, "");
  1120. /* 检查文件夹是否存在 */
  1121. if(std::filesystem::exists(localDirTmp))
  1122. {
  1123. return true;
  1124. }
  1125. /* 创建文件夹 */
  1126. if(!std::filesystem::create_directories(localDirTmp))
  1127. {
  1128. SPDLOG_ERROR("Failed to create local dir: {}", localDirTmp);
  1129. return false;
  1130. }
  1131. return true;
  1132. }
  1133. /* 执行curl,添加重试机制 */
  1134. bool CurlFtp::performCurl(CURL* curl)
  1135. {
  1136. int retry = 3;
  1137. while(retry > 0)
  1138. {
  1139. CURLcode res = curl_easy_perform(curl);
  1140. if(res == CURLE_OK)
  1141. {
  1142. return true;
  1143. }
  1144. else if (res == CURLE_LOGIN_DENIED)
  1145. {
  1146. SPDLOG_ERROR("Login failed, error code: {} ,{}", (int)res, curl_easy_strerror(res));
  1147. /* 设置用户名和密码 */
  1148. curl_easy_setopt(curl, CURLOPT_USERNAME, m_username.c_str());
  1149. curl_easy_setopt(curl, CURLOPT_PASSWORD, m_password.c_str());
  1150. }
  1151. else
  1152. {
  1153. SPDLOG_ERROR("Perform curl failed, error code: {} ,{}", (int)res, curl_easy_strerror(res));
  1154. SPDLOG_ERROR("Retry times: {}", 4 - retry);
  1155. }
  1156. retry--;
  1157. }
  1158. return false;
  1159. }
  1160. /* 重置curl设置 */
  1161. bool CurlFtp::resetCurl(CURL* curl)
  1162. {
  1163. if(m_curl == nullptr)
  1164. {
  1165. m_curl = curl_easy_init();
  1166. if(m_curl == nullptr)
  1167. {
  1168. SPDLOG_ERROR("curl init failed !");
  1169. return false;
  1170. }
  1171. }else {
  1172. curl_easy_reset(m_curl);
  1173. }
  1174. return true;
  1175. }
  1176. /* 设置sftp,如果是sftp就设置 */
  1177. bool CurlFtp::setSftp(CURL* curl)
  1178. {
  1179. /* 判断是否是SFTP */
  1180. if(m_isSftp)
  1181. {
  1182. /* 判断是否需要设置CA证书 */
  1183. if(m_isIgnoreSSLCert)
  1184. {
  1185. /* 忽略证书验证 */
  1186. curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 0L);
  1187. /* 忽略主机名验证 */
  1188. curl_easy_setopt(curl, CURLOPT_SSL_VERIFYHOST, 0L);
  1189. } else
  1190. {
  1191. /* 设置CA证书 */
  1192. curl_easy_setopt(curl, CURLOPT_CAINFO, m_caCertFile.c_str());
  1193. }
  1194. }
  1195. return true;
  1196. }