CurlFtp.cpp 43 KB

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