CurlFtp.cpp 43 KB

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