CurlFtp.cpp 41 KB

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