CurlFtp.cpp 41 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401
  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. /* 检查FTP文件夹是否存在 */
  1197. bool CurlFtp::checkFtpDirExist(const std::string& dir)
  1198. {
  1199. /* 检查传入的文件夹 */
  1200. auto dirTmp = checkDirPath(dir);
  1201. resetCurl(m_curl);
  1202. std::string ftpUrl = m_ftpUrl + dir;
  1203. curl_easy_setopt(m_curl, CURLOPT_URL, ftpUrl.c_str());
  1204. curl_easy_setopt(m_curl, CURLOPT_USERNAME, m_username.c_str());
  1205. curl_easy_setopt(m_curl, CURLOPT_PASSWORD, m_password.c_str());
  1206. /* 获取文件夹是否存在,不需要接收文件 */
  1207. curl_easy_setopt(m_curl, CURLOPT_NOBODY, 1L);
  1208. curl_easy_setopt(m_curl, CURLOPT_HEADER, 1L);
  1209. /* 设置SFTP */
  1210. setSftp(m_curl);
  1211. /* 启用调试信息 */
  1212. if(m_enableCurlDebug)
  1213. {
  1214. curl_easy_setopt(m_curl, CURLOPT_VERBOSE, 1L);
  1215. }
  1216. /* 启用持久连接 */
  1217. // curl_easy_setopt(m_curl, CURLOPT_TCP_KEEPALIVE, 1L);
  1218. /* 这里只需要执行一次 */
  1219. CURLcode res = curl_easy_perform(m_curl);
  1220. bool result = true;
  1221. if(res == CURLE_REMOTE_FILE_NOT_FOUND)
  1222. {
  1223. result = false;
  1224. }
  1225. else if(res != CURLE_OK)
  1226. {
  1227. // SPDLOG_ERROR("Check remote dir error, error code: {} ,{}", (int)res, curl_easy_strerror(res));
  1228. result = false;
  1229. }
  1230. else
  1231. {
  1232. /* sftp即使远程文件夹不存在也会返回OK,这里使用http进行检查 */
  1233. // long response_code = -1;
  1234. // res = curl_easy_getinfo(m_curl, CURLINFO_HTTP_CONNECTCODE, &response_code);
  1235. // if((res == CURLE_OK) && (response_code == 0))
  1236. // {
  1237. // SPDLOG_ERROR("Remote directory not found: {}", dir);
  1238. // result = false;
  1239. // }
  1240. // SPDLOG_DEBUG("response_code: {}", response_code);
  1241. }
  1242. return result;
  1243. }
  1244. /* 检查SFTP文件夹是否存在,这里通过列出上一层的文件夹中的内容,然后进行对比判断的 */
  1245. bool CurlFtp::checkSftpDirExist(const std::string& dir)
  1246. {
  1247. /* 取出上一层文件夹路径 */
  1248. std::string parentDir = std::filesystem::path(dir).parent_path().string();
  1249. // SPDLOG_DEBUG("Parent dir: {}", parentDir);
  1250. std::vector<std::string> vecDir;
  1251. bool ret = getDirList(parentDir, vecDir);
  1252. if(!ret)
  1253. {
  1254. SPDLOG_ERROR("Failed to check sftp dir: {}", dir);
  1255. return false;
  1256. }
  1257. /* 取出本层文件夹名称 */
  1258. std::string dirName = std::filesystem::path(dir).filename().string();
  1259. // SPDLOG_DEBUG("Dir name: {}", dirName);
  1260. /* 判断是否存在 */
  1261. bool result = false;
  1262. for(const std::string& str : vecDir)
  1263. {
  1264. if(str == dirName)
  1265. {
  1266. result = true;
  1267. break;
  1268. }
  1269. }
  1270. return result;
  1271. }