CurlFtp.cpp 39 KB

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