CurlFtp.cpp 44 KB

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