UploadFSM.cpp 70 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030
  1. #include "stdafx.h"
  2. #include "UploadFSM.h"
  3. #include <regex>
  4. #include <fileutil.h>
  5. #include <array.h>
  6. #ifdef RVC_OS_WIN
  7. #include <cstdlib>
  8. #include <ctime>
  9. #include "EventCode.h"
  10. #include "filecryption.h"
  11. #else
  12. #include <thread>
  13. #include "upload.h"
  14. #include "libtoolkit/path.h"
  15. #include <sys/stat.h>
  16. #include <sys/types.h>
  17. #include <fcntl.h>
  18. #include <time.h>
  19. #include <stdio.h>
  20. #include <cstdio>
  21. #include <iostream>
  22. #include <errno.h>
  23. #include "EventCode.h"
  24. #endif
  25. #define UPLOAD_CONTENT_EACH_LEN 2*1024*1024
  26. UploadFSM::UploadFSM() : m_currUploadFile(NULL)
  27. {
  28. m_uploadList = new list<UploadFileInfo*>();
  29. m_uploadPlanList = new list<UploadPlan *>();
  30. m_overLenFileList = new list<string>();
  31. m_eachUploadLen=UPLOAD_CONTENT_EACH_LEN;
  32. m_uploadMaxNum = 1000;
  33. m_isOffLine=true;//初始离线状态为true
  34. m_printPlan = true;//初始化为打印
  35. }
  36. UploadFSM::~UploadFSM()
  37. {
  38. }
  39. namespace Task
  40. {
  41. struct SendFileTask : public ITaskSp
  42. {
  43. UploadFSM* m_fsm;
  44. explicit SendFileTask(UploadFSM* e) : m_fsm(e) {}
  45. void Process(){
  46. //判断是分行url请求还是总行url请求
  47. //判断是临时文件还是永久文件
  48. //循环上传
  49. //登记上传流水或者失败流水
  50. //根据最终上传结果返回成功还是失败
  51. CSystemStaticInfo info;
  52. auto rc = m_fsm->GetEntityBase()->GetFunction()->GetSystemStaticInfo(info);
  53. if (rc != Error_Succeed)
  54. {
  55. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("SendFileTask")("get CSystemStaticInfo fail,file = %s",m_fsm->m_currUploadFile->filePath.c_str());
  56. m_fsm->PostEventFIFO(new FSMEvent(USER_EVT_UPLOAD_FAIL));//失败发送
  57. return;
  58. }
  59. bool isLanTerminal=true;//行内行外标志
  60. //if(info.strSite.Compare("CMB.LIB",true)==0||info.strSite.Compare("CMB.SSB",true)==0){
  61. // isLanTerminal=true;
  62. //}else{
  63. // isLanTerminal=false;
  64. //}
  65. if(strcmp(m_fsm->m_currUploadFile->upload_address_env.c_str(),"BIZ")==0){
  66. isLanTerminal=true;
  67. }else{
  68. isLanTerminal=false;
  69. }
  70. IHttpFunc* client;
  71. client = create_http(m_fsm->HttpsLogCallBack);
  72. bool hasSend=false;
  73. if(m_fsm->m_currUploadFile->plan_type=="T"){
  74. //查询失败统一需要上传
  75. if(queryTempFile(client,info)){
  76. hasSend=true;
  77. }
  78. }
  79. //是否需要上传文件
  80. bool sendOk = false;
  81. if(!hasSend){
  82. string errmsg ="";
  83. if(isLanTerminal){
  84. //DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("SendFileTask")("上传文件到分行:%s",m_fsm->m_currUploadFile->filePath.c_str());
  85. }else{
  86. //DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("SendFileTask")("上传文件到总行:%s",m_fsm->m_currUploadFile->filePath.c_str());
  87. }
  88. string MD5str = ""; //返回的MD5值
  89. string branchFilePath = ""; //返回的分行保存路径值
  90. //修改为重试上传机制,防止上传当中网络抖动,避免等待下次上传
  91. bool isUploadSucc=false;
  92. for (int i =0 ; i<2;i++ )
  93. {
  94. errmsg="";//每次上传前清空错误信息,只记录最后一次的
  95. if(uploadFile(client,info,MD5str,branchFilePath,errmsg)){
  96. isUploadSucc = true;
  97. break;
  98. }
  99. Sleep(3000);//等待3秒下次传送
  100. }
  101. if(isUploadSucc){
  102. if(updateState(client,info,isLanTerminal,MD5str,branchFilePath,errmsg)){
  103. if(operateFile(errmsg)){
  104. sendOk = true;//成功
  105. }else{
  106. m_fsm->m_uploadReport.operateFileFail++;//添加操作失败计数
  107. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("SendFileTask")("operateFile fail,file = %s",m_fsm->m_currUploadFile->filePath.c_str());
  108. addUploadFail(client,info,isLanTerminal,"2",errmsg);//操作失败
  109. }
  110. }else{
  111. m_fsm->m_uploadReport.updateState++;//添加登记失败计数
  112. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("SendFileTask")("updateState fail,file = %s",m_fsm->m_currUploadFile->filePath.c_str());
  113. addUploadFail(client,info,isLanTerminal,"1",errmsg);//登记失败
  114. }
  115. }else{
  116. m_fsm->m_uploadReport.uploadFail++;//添加上传失败计数
  117. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("SendFileTask")("uploadFile fail,file = %s",m_fsm->m_currUploadFile->filePath.c_str());
  118. addUploadFail(client,info,isLanTerminal,"1",errmsg);//上传失败
  119. }
  120. }else{
  121. sendOk=true;
  122. }
  123. client->Destory();
  124. if(sendOk){
  125. m_fsm->PostEventFIFO(new FSMEvent(USER_EVT_UPLOAD_SUCC));//成功发送
  126. }else{
  127. m_fsm->PostEventFIFO(new FSMEvent(USER_EVT_UPLOAD_FAIL));//失败发送
  128. }
  129. }
  130. //上传文件:断点续传,多次调用
  131. bool uploadFile(IHttpFunc* client,CSystemStaticInfo info,string &MD5str,string &branchFilePath, string &errmsg){
  132. string reqUrl;
  133. unsigned seed;
  134. seed = time(0);
  135. srand(seed);
  136. if(m_fsm->m_branchIpList.size()>0){
  137. int branchSeq = (rand() % m_fsm->m_branchIpList.size()) + 1;
  138. map<int,string>::iterator it = m_fsm->m_branchIpList.find(branchSeq);
  139. if(it != m_fsm->m_branchIpList.end())
  140. {
  141. reqUrl = it->second;
  142. }else{
  143. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("uploadFile")("uploadFile is fail ,branchIp[%d] is null",branchSeq);
  144. errmsg = CSimpleStringA::Format("uploadFile is fail ,branchIp[%d] is null",branchSeq).GetData();
  145. return false;
  146. }
  147. }else{
  148. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("uploadFile")("uploadFile is fail ,branchIp is null");
  149. errmsg = "uploadFile is fail ,branchIp is null";
  150. return false;
  151. }
  152. //解密文件
  153. unsigned char* pdecdata = NULL;//记得释放内存
  154. size_t udecheadlen = 0;
  155. int decOffSet = 0;//文件明文头和密文头的偏移量:可能是负数、零、正数
  156. char* pHeadJson = NULL;//记得释放内存
  157. size_t uheadJsonLen = 0;
  158. #ifdef RVC_OS_WIN
  159. filecryption_callback_t cb = {0};
  160. cb.dbg = &Dbg;
  161. int decRet = rvc_file_decrypt(&pdecdata,&udecheadlen,&decOffSet,&pHeadJson,&uheadJsonLen,m_fsm->m_currUploadFile->filePath.c_str(),&cb);
  162. #else
  163. int decRet = 0;
  164. #endif
  165. if(decRet!=0){
  166. //解密报错
  167. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("uploadFile")("uploadFile is fail, decode file fail=%d",decRet);
  168. errmsg=CSimpleStringA::Format("uploadFile is fail, decode file fail=%d",decRet).GetData();
  169. #ifdef RVC_OS_WIN
  170. rvc_free_data((void**)&pdecdata);
  171. rvc_free_data((void**)&pHeadJson);
  172. #endif
  173. m_fsm->m_uploadReport.decodeFail++;//添加解密失败计数
  174. return false;
  175. }
  176. //计算出解密后总长度:
  177. m_fsm->m_currUploadFile->decFileLen = m_fsm->m_currUploadFile->fileLen-decOffSet;//重新赋值
  178. //DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("uploadFile")("decode file len=%d, decOffSet=%d, decHeadLen=%d, uheadJsonLen=%d",m_fsm->m_currUploadFile->decFileLen,decOffSet,(int)udecheadlen,(int)uheadJsonLen);
  179. //解密自定义头赋值
  180. if(pHeadJson!=NULL){
  181. m_fsm->m_currUploadFile->decHeadJson = pHeadJson;
  182. }else{
  183. m_fsm->m_currUploadFile->decHeadJson = "";
  184. }
  185. //获取服务器文件长度
  186. unsigned char* contentFirst = new unsigned char[1];
  187. memset(contentFirst,0,1);
  188. UploadDataRet respFirst ={0};
  189. bool is_finish =false; //是否续传
  190. if(!uploadFileImpl(client,info,reqUrl,contentFirst,0,"",respFirst)){
  191. delete[] contentFirst;
  192. errmsg=CSimpleStringA::Format("url=%s, uploadFileImpl first is fail",reqUrl.c_str()).GetData();
  193. #ifdef RVC_OS_WIN
  194. rvc_free_data((void**)&pdecdata);
  195. rvc_free_data((void**)&pHeadJson);
  196. #endif
  197. return false;//返回失败
  198. }else{
  199. delete[] contentFirst;
  200. }
  201. long uploadedLen = respFirst.uploaded_length;//服务器返回已上传的长度
  202. if(uploadedLen>m_fsm->m_currUploadFile->decFileLen){
  203. //服务器返回长度大于终端文件长度
  204. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("uploadFile")("uploadFile is fail, server filelen [%d] is over terminal decfilelen [%d]",uploadedLen,m_fsm->m_currUploadFile->decFileLen);
  205. errmsg=CSimpleStringA::Format("uploadFile is fail, server filelen [%d] is over terminal decfilelen [%d]",uploadedLen,m_fsm->m_currUploadFile->decFileLen).GetData();
  206. #ifdef RVC_OS_WIN
  207. rvc_free_data((void**)&pdecdata);
  208. rvc_free_data((void**)&pHeadJson);
  209. #endif
  210. return false;
  211. }
  212. //密文解密
  213. if(uploadedLen==0){
  214. //文件头传输
  215. if(udecheadlen>0){
  216. //密文数据,传送首块,传解密字节块
  217. UploadDataRet firstResp ={0};
  218. if(!uploadFileImpl(client,info,reqUrl,pdecdata,(long)udecheadlen,"",firstResp)){
  219. #ifdef RVC_OS_WIN
  220. rvc_free_data((void**)&pdecdata);
  221. rvc_free_data((void**)&pHeadJson);
  222. #endif
  223. errmsg="uploadFileImpl first data upload is fail";
  224. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("uploadFile")("uploadFileImpl first data upload is fail, url=%s",reqUrl.c_str());
  225. return false;//返回错误
  226. }
  227. }
  228. uploadedLen += (long)udecheadlen+decOffSet;//改变文件游标偏移量
  229. }else{
  230. //数据传输
  231. uploadedLen += decOffSet; //改变文件游标偏移量
  232. }
  233. #ifdef RVC_OS_WIN
  234. rvc_free_data((void**)&pdecdata);//释放解密内存
  235. rvc_free_data((void**)&pHeadJson);
  236. #endif
  237. if(uploadedLen>m_fsm->m_currUploadFile->fileLen){
  238. //续传起始位置大于终端文件长度
  239. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("uploadFile")("uploadFile is fail, begin read filelen [%d] is over terminal filelen [%d]",uploadedLen,m_fsm->m_currUploadFile->fileLen);
  240. errmsg=CSimpleStringA::Format("uploadFile is fail, begin read filelen [%d] is over terminal filelen [%d]",uploadedLen,m_fsm->m_currUploadFile->fileLen).GetData();
  241. return false;
  242. }
  243. if(uploadedLen<0){
  244. //服务器报错的头文件内容加上偏移量后,极端情况可能会出现负数,设置为零,最后服务端做长度比较不相同,会清空临时文件重传
  245. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("uploadFile")("uploadFile decode uploadedLen beginPos < 0");
  246. uploadedLen =0;
  247. }
  248. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("uploadFile")("文件[%s] 开始传送位置 uploadedLen = %d, decode file len=%d, decOffSet=%d, decHeadLen=%d, uheadJsonLen=%d",m_fsm->m_currUploadFile->filePath.c_str(), uploadedLen, m_fsm->m_currUploadFile->decFileLen,decOffSet,(int)udecheadlen,(int)uheadJsonLen);
  249. //循环传送数据块
  250. FILE* pFile =fopen(m_fsm->m_currUploadFile->filePath.c_str(),"rb");
  251. if(pFile==NULL){
  252. //读取文件失败;
  253. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("uploadFile")("uploadFile is fail, file open fail");
  254. errmsg="uploadFile is fail, file open fail";
  255. return false;
  256. }
  257. bool uploadSucc= false;
  258. while(true){
  259. //续传
  260. if((m_fsm->m_currUploadFile->fileLen-uploadedLen)>m_fsm->m_eachUploadLen){
  261. int uploadLen = m_fsm->m_eachUploadLen;//传送数据长度
  262. unsigned char* content = new unsigned char[uploadLen];
  263. memset(content,0,uploadLen);
  264. //从文件拷贝字节
  265. if(m_fsm->getFileContent(pFile,content,uploadedLen,uploadLen)){
  266. UploadDataRet resp ={0};
  267. if(uploadFileImpl(client,info,reqUrl,content,uploadLen,"",resp)){
  268. delete[] content;
  269. uploadedLen +=uploadLen;//改变已上传长度
  270. }else{
  271. delete[] content;
  272. errmsg=CSimpleStringA::Format("url=%s, uploadFileImpl continue is fail",reqUrl.c_str()).GetData();
  273. break;//上传失败
  274. }
  275. }else{
  276. delete[] content;
  277. errmsg="uploadFile is fail , getFileContent fail";
  278. break;//获取文件内存失败
  279. }
  280. }else{
  281. //获取最后一次传送时文件长度
  282. CSimpleStringA filepath = m_fsm->m_currUploadFile->filePath.c_str();
  283. long fileLastLen = 0;
  284. if(!m_fsm->GetFileLength(filepath.GetData(),fileLastLen)){
  285. errmsg="uploadFile is fail , end get file len fail";
  286. break;//计算sm3出错
  287. }
  288. string fileLastLenStr= CSimpleStringA::Format("%d",fileLastLen-decOffSet).GetData();//计算出解密后总长度
  289. //最后一块
  290. int uploadLen = m_fsm->m_currUploadFile->fileLen-uploadedLen;
  291. unsigned char* contentEnd;
  292. if(uploadLen==0){
  293. //对零的长度特殊处理
  294. contentEnd = new unsigned char[1];
  295. memset(contentEnd,0,1);
  296. }else{
  297. contentEnd = new unsigned char[uploadLen];
  298. memset(contentEnd,0,uploadLen);
  299. }
  300. if(m_fsm->getFileContent(pFile,contentEnd,uploadedLen,uploadLen)){
  301. UploadDataRet respEnd ={0};
  302. if(uploadFileImpl(client,info,reqUrl,contentEnd,uploadLen,fileLastLenStr,respEnd)){
  303. delete[] contentEnd;
  304. if(respEnd.upload_finish){
  305. uploadSucc =true;//成功
  306. branchFilePath = respEnd.branchFilePath;//分行保存地址
  307. }else{
  308. uploadSucc =false;//失败
  309. }
  310. break;
  311. }else{
  312. delete[] contentEnd;
  313. errmsg=CSimpleStringA::Format("url=%s, uploadFileImpl end is fail",reqUrl.c_str()).GetData();
  314. break;//上传失败
  315. }
  316. }else{
  317. delete[] contentEnd;
  318. errmsg="uploadFile is fail , end getFileContent fail";
  319. break;//获取文件内存失败
  320. }
  321. }
  322. }
  323. if(uploadSucc){
  324. //DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("uploadFile")("uploadFile succ");
  325. }else{
  326. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("uploadFile")("uploadFile fail url=%s",reqUrl.c_str());
  327. }
  328. if(pFile){
  329. if(fclose(pFile)!=0){
  330. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("uploadFile")("uploadFile fail, close file fail ,url=%s",reqUrl.c_str());
  331. errmsg="uploadFile fail, close file fail";
  332. return false;
  333. }
  334. }
  335. return uploadSucc;
  336. }
  337. //上传文件:具体实现
  338. bool uploadFileImpl(IHttpFunc* client,CSystemStaticInfo info,string httpUrl,unsigned char* fileContent,long fileContentSize,string lastFileLength,UploadDataRet& uploadData){
  339. UploadFileReq qTempReq;
  340. UploadFileRet qTempRet;
  341. qTempRet.m_userCode ="";
  342. qTempRet.m_errMsg="";
  343. Json::Value rootReq;
  344. Json::FastWriter writer;
  345. rootReq["terminal_no"] = info.strTerminalID.GetData();
  346. rootReq["branch_no"] = m_fsm->m_currUploadFile->branch_no.c_str();
  347. rootReq["file_name"] = m_fsm->m_currUploadFile->fileName.c_str();
  348. rootReq["file_path"] = m_fsm->m_currUploadFile->fileUploadPath.c_str();
  349. rootReq["plan_id"] = m_fsm->m_currUploadFile->plan_id.c_str();
  350. rootReq["file_type"] = m_fsm->m_currUploadFile->file_type.c_str();
  351. //rootReq["origin_file_length"] = CSimpleStringA::Format("%d",m_fsm->m_currUploadFile->fileLen).GetData();
  352. rootReq["first_file_length"] = CSimpleStringA::Format("%d",m_fsm->m_currUploadFile->decFileLen).GetData();//加密后需要修改,服务端根据此长度做判断
  353. rootReq["last_file_length"] = lastFileLength.c_str();//加密后需要修改,最后一次长度跟服务端保存长度做对比
  354. rootReq["upload_length"] = CSimpleStringA::Format("%d",fileContentSize).GetData();
  355. //rootReq["first_sm3"] = firstMD5Str.c_str();
  356. //rootReq["last_sm3"] = lastMD5Str.c_str();
  357. rootReq["file_head_custom"] = m_fsm->m_currUploadFile->decHeadJson.c_str();//自定义解密的头json格式,可为空
  358. #ifdef RVC_OS_WIN
  359. rootReq["system_type"] = "W";//系统标记,代表路径分隔符
  360. #else
  361. rootReq["system_type"] = "L";//系统标记,代表路径分隔符
  362. #endif
  363. string jsonReq = writer.write(rootReq);
  364. qTempReq.url = httpUrl;
  365. qTempReq.paramContent = jsonReq;
  366. qTempReq.fileName = m_fsm->m_currUploadFile->fileName;
  367. qTempReq.fileContent = fileContent;
  368. qTempReq.fileContentSize= fileContentSize;
  369. qTempReq.m_timeOut = 5*60;//设置超时时间
  370. //qTempReq.m_printDbg=true;
  371. //调用上传接口
  372. if(!client->UploadFileBlock(qTempReq,qTempRet)){
  373. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("uploadFileImpl")("uploadFile http req fail ,url =%s ,fileName = %s",httpUrl.c_str(), m_fsm->m_currUploadFile->fileName.c_str());
  374. return false;
  375. }
  376. if(qTempRet.httpCode!=200){
  377. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("uploadFileImpl")("uploadFile http req fail ,url =%s ,retHttpCode=%d, fileName = %s",httpUrl.c_str(), qTempRet.httpCode, m_fsm->m_currUploadFile->fileName.c_str());
  378. return false;
  379. }
  380. //解析回应报文
  381. Json::Reader reader;
  382. Json::Value rootRet;
  383. if (!reader.parse(qTempRet.strBody, rootRet, false))
  384. {
  385. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("uploadFileImpl")("uploadFile http parse resp is fail,fileName = %s",m_fsm->m_currUploadFile->fileName.c_str());
  386. return false;//解析失败
  387. }
  388. uploadData.strBody = qTempRet.strBody;
  389. bool isSucc = rootRet["success"].asBool();
  390. if(isSucc){
  391. if(rootRet.isMember("data")){
  392. uploadData.uploaded_length= rootRet["data"]["uploaded_length"].asInt();
  393. uploadData.upload_finish = rootRet["data"]["upload_finish"].asBool();
  394. uploadData.branchFilePath = rootRet["data"]["branch_file_path"].asCString();
  395. return true;//返回值
  396. }else{
  397. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("uploadFileImpl")("uploadFile http [success][data] is invaild ,url =%s, fileName = %s",httpUrl.c_str(),m_fsm->m_currUploadFile->fileName.c_str());
  398. return false;//无data字段
  399. }
  400. }else{
  401. //失败
  402. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("uploadFileImpl")("uploadFile http [success] is false, url[%s],userCode[%s],errmsg[%s],fileName = %s",httpUrl.c_str(),qTempRet.m_userCode.c_str(),qTempRet.m_errMsg.c_str(),m_fsm->m_currUploadFile->fileName.c_str());
  403. return false;
  404. }
  405. }
  406. //查询临时文件 post
  407. bool queryTempFile(IHttpFunc* client,CSystemStaticInfo info){
  408. UploadQueryTempFileReq qTempReq;
  409. UploadQueryTempFileRet qTempRet;
  410. qTempRet.m_userCode ="";
  411. qTempRet.m_errMsg="";
  412. Json::Value rootReq;
  413. Json::FastWriter writer;
  414. rootReq["terminal_no"] = info.strTerminalID.GetData();
  415. rootReq["plan_id"] = m_fsm->m_currUploadFile->plan_id.c_str();
  416. rootReq["file_path"] = m_fsm->m_currUploadFile->fileUploadPath.c_str();
  417. rootReq["file_type"] = m_fsm->m_currUploadFile->file_type.c_str();
  418. string jsonReq = writer.write(rootReq);
  419. qTempReq.m_reqStr = jsonReq;//请求参数
  420. //qTempReq.m_printDbg = true;
  421. qTempReq.m_url=m_fsm->m_centerUrl.queryTempFileUrl;//访问地址
  422. if(!client->Post(qTempReq, qTempRet)){
  423. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("queryTempFile")("queryTempFile http req fail ,fileName = %s, err=%s",m_fsm->m_currUploadFile->filePath.c_str(),qTempRet.m_errMsg.c_str());
  424. return false;
  425. }
  426. //解析报文
  427. //解析回应报文
  428. Json::Reader reader;
  429. Json::Value rootRet;
  430. if (!reader.parse(qTempRet.m_retStr, rootRet, false))
  431. {
  432. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("queryTempFile")("queryTempFile parse resp is fail,fileName = %s",m_fsm->m_currUploadFile->filePath.c_str());
  433. m_fsm->m_uploadReport.queryTempFail++;//添加查询临时失败计数
  434. return false;//解析失败
  435. }
  436. bool isSucc = rootRet["success"].asBool();
  437. if(isSucc){
  438. if(rootRet.isMember("data")){
  439. if(rootRet["data"]["upload_flag"].asBool()){
  440. return true;//查询有
  441. }else{
  442. return false;//查询没有
  443. }
  444. }else{
  445. m_fsm->m_uploadReport.queryTempFail++;//添加查询临时失败计数
  446. return false;//无data字段
  447. }
  448. }else{
  449. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("queryTempFile")("queryTempFile [success] is false, fileName = %s",m_fsm->m_currUploadFile->filePath.c_str());
  450. m_fsm->m_uploadReport.queryTempFail++;//添加查询临时失败计数
  451. return false;
  452. }
  453. }
  454. //登记文件流水状态 post
  455. bool updateState(IHttpFunc* client,CSystemStaticInfo info,bool isLanTerminal, string MD5str,string branchFilePath, string &errmsg){
  456. if(!isLanTerminal){
  457. return true;//行外默认是总行那边登记交易流水,终端不再发送交易流水登记,直接返回成功
  458. }
  459. UploadUpdateStateReq updateStateReq;
  460. UploadUpdateStateRet updateStateRet;
  461. updateStateRet.m_userCode="";
  462. updateStateRet.m_errMsg="";
  463. Json::Value rootReq;
  464. Json::FastWriter writer;
  465. rootReq["plan_id"] = m_fsm->m_currUploadFile->plan_id.c_str();
  466. rootReq["branch_no"] = m_fsm->m_currUploadFile->branch_no.c_str();
  467. rootReq["terminal_no"] = info.strTerminalID.GetData();
  468. rootReq["file_type"] = m_fsm->m_currUploadFile->file_type.c_str();
  469. rootReq["file_name"] = m_fsm->m_currUploadFile->fileName.c_str();
  470. rootReq["file_path"] = m_fsm->m_currUploadFile->fileUploadPath.c_str();
  471. rootReq["branch_file_path"] = branchFilePath.c_str();
  472. rootReq["file_length"] = CSimpleStringA::Format("%d",m_fsm->m_currUploadFile->fileLen).GetData();
  473. if(isLanTerminal){
  474. rootReq["status"] = "1";//分行
  475. }else{
  476. rootReq["status"] = "2";//总行
  477. }
  478. rootReq["upload_time"] = CSmallDateTime::GetNow().ToTimeString().GetData();
  479. rootReq["remark"] = "";
  480. rootReq["sm3"] = MD5str.c_str();
  481. string jsonReq = writer.write(rootReq);
  482. updateStateReq.m_reqStr = jsonReq;//请求参数
  483. updateStateReq.m_url=m_fsm->m_centerUrl.updateStateUrl;//访问地址
  484. if(!client->Post(updateStateReq, updateStateRet)){
  485. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("updateState")("updateState is fail, userCode = %s, errmsg = %s",updateStateRet.m_userCode.c_str(), updateStateRet.m_errMsg.c_str());
  486. errmsg = CSimpleStringA::Format("updateState is fail, userCode = %s, errmsg = %s",updateStateRet.m_userCode.c_str(), updateStateRet.m_errMsg.c_str());
  487. return false;
  488. }
  489. //解析报文
  490. //解析回应报文
  491. Json::Reader reader;
  492. Json::Value rootRet;
  493. if (!reader.parse(updateStateRet.m_retStr, rootRet, false))
  494. {
  495. errmsg="return pack parse is fail";
  496. return false;//解析失败
  497. }
  498. bool isSucc = rootRet["success"].asBool();
  499. if(isSucc){
  500. if(rootRet.isMember("data")){
  501. if(rootRet["data"]["update_flag"].asBool()){
  502. return true;//登记成功
  503. }else{
  504. errmsg="return pack [data][update_flag] is not bool";
  505. return false;//登记失败
  506. }
  507. }else{
  508. errmsg="return pack [data] is null";
  509. return false;//无data字段
  510. }
  511. }else{
  512. errmsg="return pack [success] is false";
  513. return false;
  514. }
  515. }
  516. //登记失败文件流水 post
  517. bool addUploadFail(IHttpFunc* client,CSystemStaticInfo info,bool isLanTerminal,string operation,string errmsg){
  518. UploadUploadFailReq updateFailReq;
  519. UploadUploadFailRet updateFailRet;
  520. updateFailRet.m_userCode="";
  521. updateFailRet.m_errMsg="";
  522. Json::Value rootReq;
  523. Json::FastWriter writer;
  524. rootReq["plan_id"] = m_fsm->m_currUploadFile->plan_id.c_str();
  525. rootReq["branch_no"] = m_fsm->m_currUploadFile->branch_no.c_str();
  526. rootReq["terminal_no"] = info.strTerminalID.GetData();
  527. rootReq["file_name"] = m_fsm->m_currUploadFile->fileName.c_str();
  528. rootReq["file_path"] = m_fsm->m_currUploadFile->fileUploadPath.c_str();
  529. if(isLanTerminal){
  530. rootReq["stage"] = "1";//分行
  531. }else{
  532. rootReq["stage"] = "2";//总行
  533. }
  534. rootReq["operation"] = operation;
  535. rootReq["upload_time"] = CSmallDateTime::GetNow().ToTimeString().GetData();//2021-03-11 10:20:02
  536. rootReq["reason"] = errmsg.c_str();
  537. rootReq["remark"] = "";
  538. string jsonReq = writer.write(rootReq);
  539. updateFailReq.m_reqStr = jsonReq;//请求参数
  540. updateFailReq.m_url = m_fsm->m_centerUrl.addUploadFailUrl;//访问地址
  541. if(!client->Post(updateFailReq, updateFailRet)){
  542. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("addUploadFail")("addUploadFail is fail,userCode = %s",updateFailRet.m_userCode.c_str());
  543. return false;
  544. }
  545. //解析报文
  546. //解析回应报文
  547. Json::Reader reader;
  548. Json::Value rootRet;
  549. if (!reader.parse(updateFailRet.m_retStr, rootRet, false))
  550. {
  551. return false;//解析失败
  552. }
  553. bool isSucc = rootRet["success"].asBool();
  554. if(isSucc){
  555. if(rootRet.isMember("data")){
  556. if(rootRet["data"]["update_flag"].asBool()){
  557. return true;//登记成功
  558. }else{
  559. return false;//登记失败
  560. }
  561. }else{
  562. return false;//无data字段
  563. }
  564. }else{
  565. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("addUploadFail")("addUploadFail [success] is false");
  566. return false;
  567. }
  568. }
  569. //上传后文件处理
  570. bool operateFile(string &errmsg){
  571. if(m_fsm->m_currUploadFile->after_deal_type=="D"){
  572. #ifdef RVC_OS_WIN
  573. if(remove(m_fsm->m_currUploadFile->filePath.c_str())==0){
  574. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("operateFile")("delete file is ok, file =%s",m_fsm->m_currUploadFile->filePath.c_str());
  575. return true;
  576. }else{
  577. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("operateFile")("delete file is error, file =%s, errno=%d",m_fsm->m_currUploadFile->filePath.c_str(),(int)GetLastError());
  578. errmsg = CSimpleStringA::Format("delete file is error, file =%s, errno=%d",m_fsm->m_currUploadFile->filePath.c_str(),(int)GetLastError());
  579. return false;
  580. }
  581. #else
  582. if (changeFileAtt(m_fsm->m_currUploadFile->filePath.c_str()) == 0) {
  583. if (remove(m_fsm->m_currUploadFile->filePath.c_str()) == 0) {
  584. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("operateFile")("delete file is ok, file =%s",m_fsm->m_currUploadFile->filePath.c_str());
  585. return true;
  586. }
  587. else {
  588. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("operateFile")("delete file is error,file =%s, errno=%d",m_fsm->m_currUploadFile->filePath.c_str(), errno);
  589. errmsg = CSimpleStringA::Format("delete file is error, file =%s, errno=%d",m_fsm->m_currUploadFile->filePath.c_str(), errno);
  590. return false;
  591. }
  592. }
  593. else {
  594. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("operateFile")("delete file is error,changefileAtt fail,file =%s, errno=%d",m_fsm->m_currUploadFile->filePath.c_str(), errno);
  595. errmsg = CSimpleStringA::Format("delete file is error,changefileAtt fail,file =%s, errno=%d",m_fsm->m_currUploadFile->filePath.c_str(), errno);
  596. return false;
  597. }
  598. #endif
  599. }else if(m_fsm->m_currUploadFile->after_deal_type=="M"){
  600. string destPath="";
  601. string destDir="";
  602. //根据路径类型组成最后移动路径
  603. if(m_fsm->m_currUploadFile->path_type=="R"){
  604. #ifdef RVC_OS_WIN
  605. destPath = m_fsm->m_rootPath+"\\"+m_fsm->m_currUploadFile->after_deal_text+"\\"+m_fsm->m_currUploadFile->fileName;
  606. destDir = m_fsm->m_rootPath+"\\"+m_fsm->m_currUploadFile->after_deal_text;
  607. #else
  608. destPath = m_fsm->m_rootPath + SPLIT_SLASH_STR + m_fsm->m_currUploadFile->after_deal_text + SPLIT_SLASH_STR + m_fsm->m_currUploadFile->fileName;
  609. destDir = m_fsm->m_rootPath + SPLIT_SLASH_STR + m_fsm->m_currUploadFile->after_deal_text;
  610. #endif
  611. }else{
  612. #ifdef RVC_OS_WIN
  613. destPath = m_fsm->m_currUploadFile->after_deal_text+"\\"+m_fsm->m_currUploadFile->fileName;
  614. #else
  615. destPath = m_fsm->m_currUploadFile->after_deal_text + SPLIT_SLASH_STR + m_fsm->m_currUploadFile->fileName;
  616. #endif
  617. destDir = m_fsm->m_currUploadFile->after_deal_text;
  618. }
  619. string srcPath = m_fsm->m_currUploadFile->filePath;
  620. //DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("operateFile")("move file %s to %s",srcPath.c_str(),destPath.c_str());
  621. //判断是否存在目标文件,如存在,则先删除
  622. #ifdef RVC_OS_WIN
  623. if(ExistsFileA(destPath.c_str())){
  624. if(remove(destPath.c_str())==0){
  625. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("operateFile")("delete dest file is ok [%s]",destPath.c_str());
  626. }else{
  627. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("operateFile")("delete dest file is error, errno=%d, [%s]",(int)GetLastError(),destPath.c_str());
  628. errmsg = CSimpleStringA::Format("delete dest file is error, errno=%d, [%s]",(int)GetLastError(),destPath.c_str());
  629. return false;
  630. }
  631. }
  632. //判断移动目标文件夹是否存在,不存在,则创建
  633. if(!ExistsDirA(destDir.c_str())){
  634. if(!CreateDirRecursiveA(destDir.c_str())){
  635. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("operateFile")("create dest dir [%s] is error, errno=%d",destDir.c_str(),GetLastError());
  636. errmsg = CSimpleStringA::Format("create dest dir [%s] is error, errno=%d",destDir.c_str(),GetLastError());
  637. return false;
  638. }
  639. }
  640. //移动文件
  641. int i;
  642. int tries = 10;
  643. bool isSucc = false;
  644. for (i = 0; i < tries; ++i) {
  645. if(rename(srcPath.c_str(),destPath.c_str())==0){
  646. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("operateFile")("move file ok! tries:%d, [%s] to [%s] ", i, srcPath.c_str(),destPath.c_str());
  647. isSucc = true;
  648. break;
  649. } else {
  650. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("operateFile")("move file failed! errno:%d, [%s] to [%s] ", (int)GetLastError(), srcPath.c_str(),destPath.c_str());
  651. errmsg = CSimpleStringA::Format("move file failed! errno:%d, [%s] to [%s] ", (int)GetLastError(), srcPath.c_str(),destPath.c_str());
  652. Sleep(1000);
  653. }
  654. }
  655. return isSucc;
  656. #else
  657. if (ExistsFileA(destPath.c_str())) {
  658. if (changeFileAtt(destPath.c_str()) == 0) {
  659. if (remove(destPath.c_str()) == 0) {
  660. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("operateFile")("delete dest file is ok [%s]",destPath.c_str());
  661. }
  662. else {
  663. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("operateFile")("delete dest file is error, errno=%d, [%s]", errno, destPath.c_str());
  664. errmsg = CSimpleStringA::Format("delete src file is error, errno=%d, [%s]", errno, destPath.c_str());
  665. return false;
  666. }
  667. }
  668. else {
  669. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("operateFile")("delete dest file is error,changefileAtt fail ,errno=%d , file=%s ", errno, destPath.c_str());
  670. errmsg = CSimpleStringA::Format("delete src file is error, changefileAtt fail, errno=%d, file=%s", errno, destPath.c_str());
  671. return false;
  672. }
  673. }
  674. //判断移动目标文件夹是否存在,不存在,则创建
  675. if (!ExistsDirA(destDir.c_str())) {
  676. if (!CreateDirRecursiveA(destDir.c_str())) {
  677. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("operateFile")("create dest dir [%s] is error, errno=%d", destDir.c_str(), errno);
  678. errmsg = CSimpleStringA::Format("create dest dir [%s] is error, errno=%d", destDir.c_str(), errno);
  679. return false;
  680. }
  681. }
  682. //移动文件
  683. if (changeFileAtt(srcPath.c_str()) == 0)
  684. {
  685. int i;
  686. int tries = 10;
  687. bool isSucc = false;
  688. for (i = 0; i < tries; ++i) {
  689. //rename函数对于跨分支的目录存在拷贝不成功的情况,故采用先拷贝后删除的操作修复此bug
  690. if (fileutil_copy_file(destPath.c_str(), srcPath.c_str()) == 0) {
  691. if (remove(srcPath.c_str()) == 0) {
  692. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("operateFile")("move file ok! tries:%d, [%s] to [%s] ", i, srcPath.c_str(),destPath.c_str());
  693. isSucc = true;
  694. break;
  695. }
  696. else {
  697. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("operateFile")("move file failed! errno:%d, [%s] to [%s] ", errno, srcPath.c_str(),destPath.c_str());
  698. errmsg = CSimpleStringA::Format("move file failed! errno:%d, [%s] to [%s] ", errno, srcPath.c_str(),destPath.c_str());
  699. Sleep(1000);
  700. }
  701. }
  702. else {
  703. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("operateFile")("move file failed! copy src file fail, errno:%d, [%s] to [%s] ", errno, srcPath.c_str(),destPath.c_str());
  704. errmsg = CSimpleStringA::Format("move file failed! copy src file fail, errno:%d, [%s] to [%s] ", errno, srcPath.c_str(),destPath.c_str());
  705. Sleep(1000);
  706. }
  707. }
  708. return isSucc;
  709. }
  710. else {
  711. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("operateFile")("move file failed! changefileAtt fail, errno:%d, [%s] to [%s] ", errno, srcPath.c_str(),destPath.c_str());
  712. errmsg = CSimpleStringA::Format("move file failed! changefileAtt fail, errno:%d, [%s] to [%s] ", errno, srcPath.c_str(),destPath.c_str());
  713. return false;
  714. }
  715. #endif
  716. }else if(m_fsm->m_currUploadFile->after_deal_type=="N"){
  717. return true;
  718. }else{
  719. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("operateFile")("file [%s] invalid after_deal_type=%s",m_fsm->m_currUploadFile->fileName.c_str(),m_fsm->m_currUploadFile->after_deal_type.c_str());
  720. errmsg = CSimpleStringA::Format("invalid after_deal_type=%s",m_fsm->m_currUploadFile->after_deal_type.c_str());
  721. return false;
  722. }
  723. }
  724. };
  725. //struct SaveDirPathTask : public ITaskSp {
  726. // UploadFSM* m_fsm;
  727. // explicit SaveDirPathTask(UploadFSM* e) : m_fsm(e) {}
  728. // void Process() {
  729. // IHttpFunc* client;
  730. // client = create_http(m_fsm->HttpsLogCallBack);
  731. // if (SaveDirPathImpl(client)) {
  732. // DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI("SaveDirPathImpl")("SaveDirPath http req succ");
  733. // }
  734. // else {
  735. // DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI("SaveDirPathImpl")("SaveDirPath http req fail");
  736. // }
  737. // client->Destory();
  738. // }
  739. // bool SaveDirPathImpl(IHttpFunc* client) {
  740. // SaveDirPathReq qTempReq;
  741. // SaveDirPathRet qTempRet;
  742. // qTempRet.m_userCode = "";
  743. // qTempRet.m_errMsg = "";
  744. // //组装请求报文
  745. // string jsonReq = "";
  746. // if (!GetPathInfo(jsonReq)) {
  747. // DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI("SaveDirPathImpl")("GetPathInfo is fail");
  748. // return false;//组装报文失败
  749. // }
  750. // qTempReq.m_reqStr = jsonReq;//请求参数
  751. // //qTempReq.m_printDbg = true;
  752. // qTempReq.m_url = m_fsm->m_centerUrl.queryTempFileUrl;//访问地址
  753. // if (!client->Post(qTempReq, qTempRet)) {
  754. // DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI("SaveDirPathImpl")("SaveDirPathImpl http req fail, err=%s", qTempRet.m_errMsg.c_str());
  755. // return false;
  756. // }
  757. // //解析报文
  758. // //解析回应报文
  759. // Json::Reader reader;
  760. // Json::Value rootRet;
  761. // if (!reader.parse(qTempRet.m_retStr, rootRet, false))
  762. // {
  763. // DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI("SaveDirPathImpl")("SaveDirPathImpl parse resp is fail");
  764. // return false;//解析失败
  765. // }
  766. // bool isSucc = rootRet["success"].asBool();
  767. // if (isSucc) {
  768. // return true;
  769. // }
  770. // else {
  771. // DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI("SaveDirPathImpl")("SaveDirPathImpl [success] is fail,errmsg=%s",qTempRet.m_errMsg.c_str());
  772. // return false;
  773. // }
  774. // }
  775. // bool GetPathInfo(string &jsonStr) {
  776. // string jsonReq = "";
  777. // Json::Value rootReq;
  778. // Json::Value pathValue;
  779. // Json::FastWriter writer;
  780. // CSystemStaticInfo info;
  781. // ErrorCodeEnum rc = m_fsm->GetEntityBase()->GetFunction()->GetSystemStaticInfo(info);
  782. // if (rc != Error_Succeed)
  783. // {
  784. // DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI("GetPathInfo")("GetPathInfo get CSystemStaticInfo fail");
  785. // return false;
  786. // }
  787. // rootReq["terminal_no"] = info.strTerminalID.GetData();
  788. //
  789. // addPathInfo("Root", rootReq);
  790. // addPathInfo("rvc", rootReq);
  791. // addPathInfo("UploadVideo", rootReq);
  792. // addPathInfo("UploadPhoto", rootReq);
  793. // addPathInfo("Ad", rootReq);
  794. // addPathInfo("Upgraded", rootReq);
  795. // addPathInfo("Download", rootReq);
  796. // addPathInfo("Photo", rootReq);
  797. // addPathInfo("SysRoot", rootReq);
  798. // addPathInfo("InterLog", rootReq);
  799. // addPathInfo("SysLog", rootReq);
  800. // addPathInfo("Temp", rootReq);
  801. // addPathInfo("Rec", rootReq);
  802. // jsonStr = writer.write(rootReq);
  803. // return true;
  804. // }
  805. // bool addPathInfo(string pathNameKey, Json::Value rootReq) {
  806. // Json::Value pathValue;
  807. // CSimpleStringA tempPath;
  808. // ErrorCodeEnum err;
  809. // err = m_fsm->GetEntityBase()->GetFunction()->GetPath(pathNameKey.c_str(), tempPath);
  810. // if (Error_Succeed == err) {
  811. // pathValue["path_name"] = pathNameKey.c_str();
  812. // pathValue["path"] = tempPath.GetData();
  813. // rootReq["path_list"].append(pathValue);
  814. // DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI("addPathInfo")("getPath [%s] path is success, path=%d", pathNameKey.c_str(), tempPath.GetData());
  815. // return true;
  816. // }
  817. // else {
  818. // DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI("addPathInfo")("getPath [%s] path is fail, err=%d", pathNameKey.c_str(), (int)err);
  819. // return false;
  820. // }
  821. // }
  822. //};
  823. }
  824. void UploadFSM::OnStateTrans( int iSrcState, int iDstState )
  825. {
  826. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("OnStateTrans")("trans from %s to %s", GetStateName(iSrcState), GetStateName(iDstState));
  827. }
  828. void UploadFSM::OnSysVarEvent( const char *pszKey, const char *pszValue,const char *pszOldValue,const char *pszEntityName )
  829. {
  830. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("OnSysVarEvent")("rx sysvar %s from %s, %s to %s", pszKey, pszEntityName, pszOldValue, pszValue);
  831. if (pszValue[0] == 'O') {
  832. m_isOffLine = true;
  833. PostEventFIFO(new FSMEvent(USER_EVT_JMP_ENABLE));
  834. } else {
  835. m_isOffLine = false;
  836. PostEventFIFO(new FSMEvent(USER_EVT_JMP_DISABLE));
  837. }
  838. }
  839. ErrorCodeEnum UploadFSM::OnInit()
  840. {
  841. ErrorCodeEnum Error;
  842. CSimpleStringA checkStr="";
  843. CSmartPointer<IConfigInfo> spConfig;
  844. Error = m_pEntity->GetFunction()->OpenConfig(Config_CenterSetting, spConfig);
  845. if(Error==Error_Succeed){
  846. //获取模式控制参数
  847. m_centerModel = (int)centerModel;//强制总行模式
  848. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI("OnInit")("model is centerModel, CenterModel = %d", m_centerModel);
  849. //增加总行接口Url参数
  850. CSimpleStringA str="";
  851. Error = spConfig->ReadConfigValue("upload", "QueryPlanUrl", str);
  852. if (Error == Error_Succeed)
  853. {
  854. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("OnInit")("[CenterUrl] QueryPlanUrl =%s",str.GetData());
  855. m_centerUrl.queryPlanUrl = str.GetData();
  856. }
  857. else
  858. {
  859. return Error;
  860. }
  861. Error = spConfig->ReadConfigValue("upload", "QueryTempFileUrl", str);
  862. if (Error == Error_Succeed)
  863. {
  864. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("OnInit")("[CenterUrl] QueryTempFileUrl =%s",str.GetData());
  865. m_centerUrl.queryTempFileUrl = str.GetData();
  866. }
  867. else
  868. {
  869. return Error;
  870. }
  871. Error = spConfig->ReadConfigValue("upload", "UpdateStateUrl", str);
  872. if (Error == Error_Succeed)
  873. {
  874. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("OnInit")("[CenterUrl] UpdateStateUrl =%s",str.GetData());
  875. m_centerUrl.updateStateUrl = str.GetData();
  876. }
  877. else
  878. {
  879. return Error;
  880. }
  881. Error = spConfig->ReadConfigValue("upload", "AddUploadFailUrl", str);
  882. if (Error == Error_Succeed)
  883. {
  884. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("OnInit")("[CenterUrl] AddUploadFailUrl =%s",str.GetData());
  885. m_centerUrl.addUploadFailUrl = str.GetData();
  886. }
  887. else
  888. {
  889. return Error;
  890. }
  891. Error = spConfig->ReadConfigValue("upload", "EachUploadLen", str);
  892. if (Error == Error_Succeed)
  893. {
  894. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("OnInit")("[CenterUrl] EachUploadLen =%s",str.GetData());
  895. if(str.IsNullOrEmpty()){
  896. m_eachUploadLen = UPLOAD_CONTENT_EACH_LEN;
  897. }else{
  898. m_eachUploadLen = atoi(str.GetData())*1024;
  899. }
  900. }
  901. else
  902. {
  903. return Error;
  904. }
  905. int uploadMaxNum = 0;
  906. Error = spConfig->ReadConfigValueInt("upload", "UploadMaxNum", uploadMaxNum);
  907. if (Error == Error_Succeed)
  908. {
  909. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("OnInit")("[CenterUrl] UploadMaxNum =%d",uploadMaxNum);
  910. if(uploadMaxNum<=10){
  911. m_uploadMaxNum = 1000;
  912. }else{
  913. m_uploadMaxNum = uploadMaxNum;
  914. }
  915. }
  916. else
  917. {
  918. return Error;
  919. }
  920. //获取系统文件根路径
  921. CSimpleStringA runPath ;
  922. Error =this->GetEntityBase()->GetFunction()->GetPath("rvc",runPath);//例如:C:\\Run /opt/Run
  923. if(Error_Succeed == Error){
  924. if(!runPath.IsNullOrEmpty()){
  925. string runPathStr = runPath.GetData();
  926. #ifdef RVC_OS_WIN
  927. int pos = runPathStr.find_last_of('\\');
  928. #else
  929. int pos = runPathStr.find_last_of(SPLIT_SLASH);//修改为路径分隔符
  930. #endif
  931. m_rootPath = runPathStr.substr(0,pos);
  932. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("OnInit")("get rvc path is %s",m_rootPath.c_str());
  933. }else{
  934. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("OnInit")("get rvc path is null");
  935. return Error_Unexpect;
  936. }
  937. }else{
  938. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("OnInit")("get rvc path is error");
  939. return Error_Unexpect;
  940. }
  941. }else{
  942. return Error;
  943. }
  944. Error = m_pEntity->GetFunction()->RegistSysVarEvent("CallState", this);
  945. if (Error == Error_Succeed) {
  946. AddStateHooker(this);
  947. }
  948. //......
  949. return Error;
  950. }
  951. ErrorCodeEnum UploadFSM::OnExit()
  952. {
  953. m_pEntity->GetFunction()->UnregistSysVarEvent("CallState");
  954. return Error_Succeed;
  955. }
  956. void UploadFSM::s0_on_entry()
  957. {
  958. //Task::SaveDirPathTask* task = new Task::SaveDirPathTask(this);//注意保持此线程实体只启动一次
  959. //ErrorCodeEnum rc = this->GetEntityBase()->GetFunction()->PostThreadPoolTask(task);
  960. //if (rc != Error_Succeed)
  961. //{
  962. // LogWarn(Severity_Middle, Error_Unexpect, LOG_WARN_UPLOAD_QUERY_PLAN_ERROR, CSimpleStringA::Format("SaveDirPathTask task create thread fail, err=%d", (int)rc).GetData());
  963. //}
  964. CSimpleStringA strValue;
  965. ErrorCodeEnum Error = m_pEntity->GetFunction()->GetSysVar("CallState", strValue);
  966. if (Error == Error_Succeed) {
  967. if (strValue[0] == 'O') { // only upload when CallState in offline state
  968. PostEventLIFO(new FSMEvent(USER_EVT_JMP_ENABLE));
  969. } else {
  970. PostEventLIFO(new FSMEvent(USER_EVT_JMP_DISABLE));
  971. }
  972. }
  973. }
  974. void UploadFSM::s0_on_exit()
  975. {
  976. }
  977. unsigned int UploadFSM::s0_on_event( FSMEvent* event )
  978. {
  979. return 0;
  980. }
  981. void UploadFSM::s1_on_entry()
  982. {
  983. ScheduleTimer(8, 30000);
  984. }
  985. void UploadFSM::s1_on_exit()
  986. {
  987. CancelTimer(8);
  988. }
  989. unsigned int UploadFSM::s1_on_event(FSMEvent* event)
  990. {
  991. if (event->iEvt == EVT_TIMER) {
  992. if(m_isOffLine){
  993. PostEventLIFO(new FSMEvent(USER_EVT_JMP_ENABLE));
  994. }else{
  995. ScheduleTimer(8, 30000);//继续等待
  996. }
  997. }
  998. return 0;
  999. }
  1000. void UploadFSM::s2_on_entry()
  1001. {
  1002. m_uploadModel = true;//默认总行上传模式
  1003. //清理上次扫描文件列表,扫描计划,分行ip列表
  1004. if(m_uploadList!=NULL){
  1005. list<UploadFileInfo*>::iterator iter ;
  1006. for(iter=m_uploadList->begin();iter!=m_uploadList->end();++iter){
  1007. delete *iter;
  1008. }
  1009. m_uploadList->clear();
  1010. }
  1011. if(m_uploadPlanList!=NULL){
  1012. list<UploadPlan*>::iterator iter ;
  1013. for(iter=m_uploadPlanList->begin();iter!=m_uploadPlanList->end();++iter){
  1014. delete *iter;
  1015. }
  1016. m_uploadPlanList->clear();
  1017. }
  1018. m_branchIpList.clear();
  1019. if(m_centerModel == (int)centerModel){
  1020. //DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("centerModel");
  1021. //防止url无效,新模式直接停止上传 等待下一次
  1022. if(m_centerUrl.addUploadFailUrl.empty()||m_centerUrl.queryPlanUrl.empty()||
  1023. m_centerUrl.queryTempFileUrl.empty()||m_centerUrl.updateStateUrl.empty()){
  1024. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("centerModel mode ,centerUrl is null , wait for next time");
  1025. ScheduleTimer(1, 120000);
  1026. return ;
  1027. }
  1028. //新模式,查询策略
  1029. if(queryPlan()){
  1030. m_uploadModel = true;
  1031. }else{
  1032. //查询策略失败,等待下一次
  1033. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("queryPlan is fail , wait for next time");
  1034. ScheduleTimer(1, 120000);
  1035. return ;
  1036. }
  1037. }else{
  1038. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("m_centerModel is invalid");
  1039. ScheduleTimer(1, 120000);
  1040. return;
  1041. }
  1042. if(m_uploadModel){
  1043. //新模式扫描
  1044. PostEventLIFO(new FSMEvent(USER_EVT_JMP_NEW_SCAN));
  1045. }else{
  1046. //旧模式扫描
  1047. PostEventLIFO(new FSMEvent(USER_EVT_JMP_OLD_SCAN));
  1048. }
  1049. }
  1050. void UploadFSM::s2_on_exit()
  1051. {
  1052. CancelTimer(1);
  1053. }
  1054. unsigned int UploadFSM::s2_on_event(FSMEvent* event)
  1055. {
  1056. if (event->iEvt == EVT_TIMER) {
  1057. m_uploadModel = true;//默认是分行上传模式
  1058. //清理上次扫描文件列表,扫描计划,分行ip列表
  1059. if(m_uploadList!=NULL){
  1060. list<UploadFileInfo*>::iterator iter ;
  1061. for(iter=m_uploadList->begin();iter!=m_uploadList->end();++iter){
  1062. delete *iter;
  1063. }
  1064. m_uploadList->clear();
  1065. }
  1066. if(m_uploadPlanList!=NULL){
  1067. list<UploadPlan*>::iterator iter ;
  1068. for(iter=m_uploadPlanList->begin();iter!=m_uploadPlanList->end();++iter){
  1069. delete *iter;
  1070. }
  1071. m_uploadPlanList->clear();
  1072. }
  1073. m_branchIpList.clear();
  1074. //上传模式确定
  1075. if(m_centerModel == (int)centerModel){
  1076. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("centerModel");
  1077. //防止url无效,新模式直接停止上传,等待下一次
  1078. if(m_centerUrl.addUploadFailUrl.empty()||m_centerUrl.queryPlanUrl.empty()||
  1079. m_centerUrl.queryTempFileUrl.empty()||m_centerUrl.updateStateUrl.empty()){
  1080. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("centerModel mode ,centerUrl is null , wait for next time");
  1081. ScheduleTimer(1, 240000);
  1082. return 0;
  1083. }
  1084. //新模式,查询策略
  1085. if(queryPlan()){
  1086. m_uploadModel = true;
  1087. }else{
  1088. //查询策略失败,等待下一次
  1089. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("queryPlan is fail , wait for next time");
  1090. ScheduleTimer(1, 240000);
  1091. return 0;
  1092. }
  1093. }else{
  1094. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("m_centerModel is invalid");
  1095. ScheduleTimer(1, 240000);
  1096. return 0;
  1097. }
  1098. if(m_uploadModel){
  1099. //新模式扫描
  1100. PostEventLIFO(new FSMEvent(USER_EVT_JMP_NEW_SCAN));
  1101. }else{
  1102. //旧模式扫描
  1103. PostEventLIFO(new FSMEvent(USER_EVT_JMP_OLD_SCAN));
  1104. }
  1105. }else if (event->iEvt == USER_EVT_JMP_NEW_SCAN) {
  1106. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("enter new model upload");
  1107. //新模式
  1108. if (m_uploadList->size() == 0) {
  1109. //重新扫描文件
  1110. scanFile();
  1111. }
  1112. if (m_uploadList->size() == 0) {
  1113. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("m_uploadList is 0,wait for 8 min retry scan");
  1114. ScheduleTimer(1, 480000);
  1115. } else {
  1116. PostEventLIFO(new FSMEvent(USER_EVT_JMP_NEW_UPLOAD));//跳到新的上传状态
  1117. }
  1118. }
  1119. return 0;
  1120. }
  1121. void UploadFSM::s3_on_entry()
  1122. {
  1123. }
  1124. void UploadFSM::s3_on_exit()
  1125. {
  1126. }
  1127. unsigned int UploadFSM::s3_on_event(FSMEvent* event)
  1128. {
  1129. return 0;
  1130. }
  1131. void UploadFSM::s4_on_entry()
  1132. {
  1133. }
  1134. void UploadFSM::s4_on_exit()
  1135. {
  1136. }
  1137. unsigned int UploadFSM::s4_on_event(FSMEvent* event)
  1138. {
  1139. return 0;
  1140. }
  1141. void UploadFSM::s5_on_entry()
  1142. {
  1143. }
  1144. void UploadFSM::s5_on_exit()
  1145. {
  1146. }
  1147. unsigned int UploadFSM::s5_on_event(FSMEvent* event)
  1148. {
  1149. return 0;
  1150. }
  1151. void UploadFSM::s6_on_entry()
  1152. {
  1153. }
  1154. void UploadFSM::s6_on_exit()
  1155. {
  1156. }
  1157. unsigned int UploadFSM::s6_on_event(FSMEvent* event)
  1158. {
  1159. return 0;
  1160. }
  1161. void UploadFSM::s7_on_entry()
  1162. {
  1163. //新上传模式
  1164. m_uploadReport.sum = m_uploadList->size();
  1165. m_uploadReport.succ = 0;
  1166. m_uploadReport.fail = 0;
  1167. m_uploadReport.uploadFail = 0;
  1168. m_uploadReport.updateState = 0;
  1169. m_uploadReport.decodeFail = 0;
  1170. m_uploadReport.operateFileFail= 0;
  1171. m_uploadReport.queryTempFail =0;
  1172. m_uploadReport.isBreak =false;
  1173. //获取一个新文件,发送上传请求线程
  1174. if(m_uploadList->size()>0){
  1175. m_currUploadFile = *(m_uploadList->begin());//首元素赋值给全局变量
  1176. m_uploadList->pop_front();//去除首元素
  1177. Task::SendFileTask* task = new Task::SendFileTask(this);
  1178. ErrorCodeEnum rc = this->GetEntityBase()->GetFunction()->PostThreadPoolTask(task);
  1179. if (rc != Error_Succeed)
  1180. {
  1181. if(m_currUploadFile!=NULL){
  1182. delete m_currUploadFile;
  1183. m_currUploadFile=NULL;
  1184. }
  1185. LogError(Severity_Middle, rc, 0, "Post SendFileTask task to Thread is fail,wait 30s retry");
  1186. ScheduleTimer(7, 30000);
  1187. }
  1188. }
  1189. }
  1190. void UploadFSM::s7_on_exit()
  1191. {
  1192. if(m_currUploadFile!=NULL){
  1193. delete m_currUploadFile;
  1194. m_currUploadFile=NULL;
  1195. }
  1196. CancelTimer(7);
  1197. }
  1198. unsigned int UploadFSM::s7_on_event(FSMEvent* event)
  1199. {
  1200. if (event->iEvt == USER_EVT_UPLOAD_SUCC) {
  1201. m_uploadReport.succ++;//成功计数
  1202. //获取新的上传文件,发送上传请求线程
  1203. //判断是否已经需要退出
  1204. //无文件,跳出此状态
  1205. if(m_isOffLine){
  1206. if(m_uploadList->size()>0){
  1207. if(m_currUploadFile!=NULL){
  1208. delete m_currUploadFile;
  1209. m_currUploadFile=NULL;
  1210. }
  1211. m_currUploadFile = *(m_uploadList->begin());//首元素赋值给全局变量
  1212. m_uploadList->pop_front();//去除首元素
  1213. Task::SendFileTask* task = new Task::SendFileTask(this);
  1214. ErrorCodeEnum rc = this->GetEntityBase()->GetFunction()->PostThreadPoolTask(task);
  1215. if (rc != Error_Succeed)
  1216. {
  1217. if(m_currUploadFile!=NULL){
  1218. delete m_currUploadFile;
  1219. m_currUploadFile=NULL;
  1220. }
  1221. m_uploadReport.isBreak =true;
  1222. reportBatchMsg();
  1223. LogError(Severity_Middle, rc, 0, "Post SendFileTask task to Thread is fail,wait 240s retry scan");
  1224. ScheduleTimer(7, 240000);
  1225. }
  1226. }else{
  1227. m_uploadReport.isBreak =false;
  1228. reportBatchMsg();
  1229. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("NewUpload m_uploadList is empty,wait 240s retry scan");
  1230. ScheduleTimer(7, 240000);// goto s2
  1231. }
  1232. }else{
  1233. m_uploadReport.isBreak =true;
  1234. reportBatchMsg();
  1235. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("NewUpload m_isOffLine is false,jump s1");
  1236. PostEventLIFO(new FSMEvent(USER_EVT_JMP_NEW_DISABLE));// goto s1
  1237. }
  1238. }else if (event->iEvt == USER_EVT_UPLOAD_FAIL) {
  1239. m_uploadReport.fail++;//失败计数
  1240. //获取新的上传文件,发送上传请求线程
  1241. //判断是否已经需要退出
  1242. //无文件,跳出此状态
  1243. if(m_isOffLine){
  1244. Sleep(3000);//上传失败,等待3秒再下一个
  1245. if(m_uploadList->size()>0){
  1246. if(m_currUploadFile!=NULL){
  1247. delete m_currUploadFile;
  1248. m_currUploadFile=NULL;
  1249. }
  1250. m_currUploadFile = *(m_uploadList->begin());//首元素赋值给全局变量
  1251. m_uploadList->pop_front();//去除首元素
  1252. Task::SendFileTask* task = new Task::SendFileTask(this);
  1253. ErrorCodeEnum rc = this->GetEntityBase()->GetFunction()->PostThreadPoolTask(task);
  1254. if (rc != Error_Succeed)
  1255. {
  1256. if(m_currUploadFile!=NULL){
  1257. delete m_currUploadFile;
  1258. m_currUploadFile=NULL;
  1259. }
  1260. m_uploadReport.isBreak =true;
  1261. reportBatchMsg();
  1262. LogError(Severity_Middle, rc, 0, "Post SendFileTask task to Thread is fail,wait 240s retry scan");
  1263. ScheduleTimer(7, 240000);
  1264. }
  1265. }else{
  1266. m_uploadReport.isBreak =false;
  1267. reportBatchMsg();
  1268. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("NewUpload m_uploadList is empty,wait 240s retry scan");
  1269. ScheduleTimer(7, 240000);// goto s2
  1270. }
  1271. }else{
  1272. m_uploadReport.isBreak =true;
  1273. reportBatchMsg();
  1274. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("NewUpload m_isOffLine is false,jump s1");
  1275. PostEventLIFO(new FSMEvent(USER_EVT_JMP_NEW_DISABLE));// goto s1
  1276. }
  1277. }else if (event->iEvt == EVT_TIMER) {
  1278. // goto s2
  1279. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("NewUpload ,jump to s2");
  1280. }
  1281. return 0;
  1282. }
  1283. //通过
  1284. bool UploadFSM::queryPlan()
  1285. {
  1286. // DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("queryPlan")("queryPlan begin");
  1287. IHttpFunc* client;
  1288. client = create_http(HttpsLogCallBack);
  1289. CSystemStaticInfo si;
  1290. ErrorCodeEnum error = this->GetEntityBase()->GetFunction()->GetSystemStaticInfo(si);
  1291. if(error!=Error_Succeed){
  1292. return false;//获取失败,走旧模式
  1293. }
  1294. UploadQueryPlanReq planReq;
  1295. UploadQueryPlanRet planRet;
  1296. Json::Value rootReq;
  1297. Json::FastWriter writer;
  1298. rootReq["terminal_no"] = si.strTerminalID.GetData();
  1299. #ifdef RVC_OS_WIN
  1300. rootReq["os_type"] = "WIN";
  1301. #else
  1302. rootReq["os_type"] = "UOS";
  1303. #endif
  1304. string jsonReq = writer.write(rootReq);
  1305. planReq.m_reqStr = jsonReq;
  1306. //planReq.m_printDbg = true;
  1307. planReq.m_url = m_centerUrl.queryPlanUrl.c_str();
  1308. if(!client->Post(planReq, planRet)){
  1309. LogWarn(Severity_Middle, Error_Unexpect, LOG_WARN_UPLOAD_QUERY_PLAN_ERROR, CSimpleStringA::Format("queryPlan http req fail,url is %s, err=%s",m_centerUrl.queryPlanUrl.c_str(),planRet.m_errMsg.c_str()).GetData());
  1310. client->Destory();
  1311. return false;//http错误,走旧模式
  1312. }
  1313. client->Destory();
  1314. //解析回应报文
  1315. Json::Reader reader;
  1316. Json::Value rootRet;
  1317. if (!reader.parse(planRet.m_retStr, rootRet, false))
  1318. {
  1319. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("queryPlan")("queryPlan parse resp is fail");
  1320. return false;//解析失败,走旧模式
  1321. }
  1322. bool isSucc = rootRet["success"].asBool();
  1323. if(isSucc){
  1324. if(rootRet.isMember("data")){
  1325. if(rootRet["data"]["mode"].asBool()){
  1326. //新模式
  1327. string branchNO = rootRet["data"]["branch_no"].asString();
  1328. //分行服务器列表:可能为空
  1329. if(rootRet["data"]["upload_address"].isMember("upload_url")){
  1330. for(int i =0;i<rootRet["data"]["upload_address"]["upload_url"].size();i++){
  1331. string bUploadUrl = rootRet["data"]["upload_address"]["upload_url"][i].asString();
  1332. m_branchIpList[i+1]=bUploadUrl;
  1333. if(!bUploadUrl.empty()){
  1334. // DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("queryPlan")("queryPlan return upload_url=%s",bUploadUrl.c_str());
  1335. }else{
  1336. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("queryPlan")("queryPlan return upload_url=");
  1337. }
  1338. }
  1339. }else{
  1340. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("queryPlan")("[data][upload_address][upload_url] is null");
  1341. }
  1342. string env = "";//上传服务器地址属于行内还是行外
  1343. if(rootRet["data"]["upload_address"].isMember("env")){
  1344. env = rootRet["data"]["upload_address"]["env"].asString();
  1345. if(strcmp(env.c_str(),"DMZ")==0||strcmp(env.c_str(),"BIZ")==0){
  1346. }else{
  1347. LogWarn(Severity_Middle, Error_Unexpect, LOG_WARN_UPLOAD_QUERY_PLAN_DATA_ERROR, CSimpleStringA::Format("queryPlan http req fail, return [data][upload_address][env] is invaild [%s]",env.c_str()).GetData());
  1348. return false;//上传服务ip环境不正确,走旧模式
  1349. }
  1350. }else{
  1351. LogWarn(Severity_Middle, Error_Unexpect, LOG_WARN_UPLOAD_QUERY_PLAN_DATA_ERROR, CSimpleStringA::Format("queryPlan http req fail, return [data][upload_address][env] is null").GetData());
  1352. return false;//上传服务ip环境为空,走旧模式
  1353. }
  1354. //扫描策略:可能为空
  1355. for (int i =0;i <rootRet["data"]["plan_list"].size();i++){
  1356. UploadPlan* p = new UploadPlan();
  1357. p->plan_id = rootRet["data"]["plan_list"][i]["plan_id"].asString();
  1358. p->branch_no = branchNO;//分行号
  1359. p->plan_type = rootRet["data"]["plan_list"][i]["plan_type"].asString();
  1360. p->file_type = rootRet["data"]["plan_list"][i]["file_type"].asString();
  1361. p->path_type = rootRet["data"]["plan_list"][i]["path_type"].asString();
  1362. #ifdef RVC_OS_WIN
  1363. p->path_name = rootRet["data"]["plan_list"][i]["path_name"].asString();
  1364. #else
  1365. //转义路径里面windows反斜杠'\'为'/'
  1366. //p->path_name = rootRet["data"]["plan_list"][i]["path_name"].asString();
  1367. string pathName = rootRet["data"]["plan_list"][i]["path_name"].asString();
  1368. std::replace(pathName.begin(), pathName.end(), '\\', SPLIT_SLASH);
  1369. p->path_name = pathName.c_str();
  1370. #endif
  1371. p->file_name = rootRet["data"]["plan_list"][i]["file_name"].asString();
  1372. p->file_regex = rootRet["data"]["plan_list"][i]["file_regex"].asString();
  1373. p->before_deal_type = rootRet["data"]["plan_list"][i]["before_deal_type"].asString();
  1374. p->after_deal_type = rootRet["data"]["plan_list"][i]["after_deal_type"].asString();
  1375. #ifdef RVC_OS_WIN
  1376. p->after_deal_text = rootRet["data"]["plan_list"][i]["after_deal_text"].asString();
  1377. #else
  1378. //转义路径里面windows反斜杠'\'为'/'
  1379. //p->after_deal_text = rootRet["data"]["plan_list"][i]["after_deal_text"].asString();
  1380. string afterDealText = rootRet["data"]["plan_list"][i]["after_deal_text"].asString();
  1381. std::replace(afterDealText.begin(), afterDealText.end(), '\\', SPLIT_SLASH);
  1382. p->after_deal_text = afterDealText.c_str();
  1383. #endif
  1384. p->file_limit = rootRet["data"]["plan_list"][i]["file_limit"].asInt();
  1385. if (p->file_limit <= 0) {
  1386. //默认文件最大扫描个数为1000
  1387. p->file_length_limit = 1000;
  1388. }
  1389. p->file_length_limit = rootRet["data"]["plan_list"][i]["file_length_limit"].asInt();//增加扫描文件最大长度限制
  1390. if(p->file_length_limit==0){
  1391. //默认扫描文件最大长度设置为200m
  1392. p->file_length_limit = 200;
  1393. }
  1394. p->max_silent = rootRet["data"]["plan_list"][i]["max_silent"].asInt();
  1395. if (p->max_silent <= 0) {
  1396. //默认文件流逝时间间隔为900s
  1397. p->file_length_limit = 900;
  1398. }
  1399. p->upload_address_env = env;
  1400. m_uploadPlanList->push_back(p);
  1401. }
  1402. //行内需要判断分行服务url地址(废弃用终端场所判断,统一由后台服务返回文件上传地址)
  1403. //if(si.strSite.Compare("CMB.LIB",true)==0||si.strSite.Compare("CMB.SSB",true)==0){
  1404. // if(m_branchIpList.size()==0){
  1405. // return false;//告警分行服务ip为空,走旧模式
  1406. // }
  1407. //}
  1408. if(m_branchIpList.size()==0){
  1409. LogWarn(Severity_Middle, Error_Unexpect, LOG_WARN_UPLOAD_QUERY_PLAN_DATA_ERROR, CSimpleStringA::Format("queryPlan http req fail, return upload_url count is 0, url is %s",m_centerUrl.queryPlanUrl.c_str()).GetData());
  1410. return false;//上传服务ip为空,走旧模式
  1411. }
  1412. if(m_uploadPlanList->size()==0){
  1413. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("queryPlan")("queryPlan return %d plan ",m_uploadPlanList->size());
  1414. return true;//等待下一次请求,走新模式
  1415. }
  1416. return true;//明确走新模式
  1417. }else{
  1418. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("queryPlan")("queryPlan return [data].[mode] is false");
  1419. return false;//明确走旧模式
  1420. }
  1421. }else{
  1422. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("queryPlan")("queryPlan return data is null");
  1423. return false;//无data字段,走旧模式
  1424. }
  1425. }else{
  1426. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("queryPlan")("queryPlan return success is false");
  1427. return false;//服务返回错误,走旧模式
  1428. }
  1429. }
  1430. //通过
  1431. void UploadFSM::scanFile()
  1432. {
  1433. list<UploadPlan*>::iterator iter;
  1434. for(iter = m_uploadPlanList->begin();iter!=m_uploadPlanList->end();++iter){
  1435. UploadPlan* up = *iter;
  1436. //构建初始的扫描根路径
  1437. string path="";
  1438. if(up->path_type=="R"){
  1439. #ifdef RVC_OS_WIN
  1440. path = m_rootPath + "\\" + up->path_name;
  1441. #else
  1442. path = m_rootPath + SPLIT_SLASH_STR + up->path_name;
  1443. #endif
  1444. }else if(up->path_type=="A"){
  1445. path=up->path_name;
  1446. }else{
  1447. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("scanFile")("plan path_type is invalid path_type=%s",up->path_type.c_str());
  1448. continue;
  1449. }
  1450. if(m_printPlan){
  1451. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("scanFile")("planID=[%s], scanDir=[%s], filter=[%s], file_limit=[%d], max_silent=[%d]",up->plan_id.c_str(),path.c_str(),up->file_name.c_str(),up->file_limit,up->max_silent);
  1452. }
  1453. scanDirfresh(up,path.c_str());
  1454. }
  1455. m_printPlan=false;//只打印一次,设置为不打印
  1456. //加入文件超过阈值后告警
  1457. if(m_uploadList->size()>m_uploadMaxNum){
  1458. LogWarn(Severity_Middle, Error_Unexpect, LOG_WARN_UPLOAD_MAX_ERROR, CSimpleStringA::Format("upload list num(%d) is over max num",m_uploadList->size()).GetData());
  1459. }
  1460. }
  1461. //通过
  1462. void UploadFSM::scanDirfresh(UploadPlan* plan,const char *path)
  1463. {
  1464. array_header_t *arr_files = fileutil_get_sub_files2_a(path, plan->file_limit);
  1465. if (arr_files) {
  1466. int i;
  1467. for (i = 0; i < arr_files->nelts; ++i){
  1468. char *file_path = ARRAY_IDX(arr_files, i, char*);
  1469. //得到文件名
  1470. string fileName = _GetFileName(file_path);
  1471. //文件名通配符过滤
  1472. CSimpleStringA strFileFilter = _GetFileName(plan->file_name.c_str());
  1473. if(!IsFileMatch(strFileFilter.GetData(),fileName.c_str())){
  1474. continue;//继续下一个文件
  1475. }
  1476. //正则表达式过滤
  1477. if(!plan->file_regex.empty()){
  1478. regex e(plan->file_regex.c_str());
  1479. if(!regex_match(fileName.c_str(),e,regex_constants::match_default)){
  1480. continue;//继续下一个文件
  1481. }
  1482. }
  1483. #ifdef RVC_OS_WIN
  1484. //最后修改时间间隔过滤
  1485. WIN32_FILE_ATTRIBUTE_DATA attr;
  1486. if (!GetFileAttributesExA(file_path, GetFileExInfoStandard, &attr)) {
  1487. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("scanDirfresh")("get local file attrr fail! file_path=%s",file_path);
  1488. continue;//继续下一个文件
  1489. }
  1490. //判断文件是否超过最大扫描文件长度
  1491. unsigned long limit = plan->file_length_limit*1024*1024;
  1492. if(attr.nFileSizeLow>limit){
  1493. if (!findOverLenWarn(file_path)) {
  1494. //未找到则告警
  1495. CSimpleStringA warnStr = CSimpleStringA::Format("local file len (%u), over file_length_limit (%d)m, file_path=%s", attr.nFileSizeLow, plan->file_length_limit, file_path);
  1496. LogWarn(Severity_Low, Error_Unexpect, LOG_WARN_UPLOAD_QUERY_FILE_OVER_LIMIT, warnStr.GetData());
  1497. }
  1498. continue;//继续下一个文件
  1499. }
  1500. FILETIME fttmp;
  1501. SYSTEMTIME filest;
  1502. SYSTEMTIME st;
  1503. if(!FileTimeToLocalFileTime(&attr.ftLastWriteTime,&fttmp)){
  1504. continue;//继续下一个文件
  1505. }
  1506. if(!FileTimeToSystemTime(&fttmp,&filest)){
  1507. continue;//继续下一个文件
  1508. }
  1509. GetLocalTime(&st);
  1510. int nsecondsInterval = (st.wYear-filest.wYear)*32140800+(st.wMonth-filest.wMonth)*2678400+(st.wDay-filest.wDay)*86400+(st.wHour-filest.wHour)*3600+(st.wMinute-filest.wMinute)*60+(st.wSecond-filest.wSecond);
  1511. if(nsecondsInterval<plan->max_silent){
  1512. continue;//继续下一个文件,时间不够
  1513. }else{
  1514. //时间已够,判断文件是否能独占锁
  1515. if(!test_zero_ref(file_path)){
  1516. continue;//继续下一个文件
  1517. }
  1518. }
  1519. //得到文件长度
  1520. unsigned long filelen = attr.nFileSizeLow;
  1521. #else
  1522. struct stat attr_of_src;
  1523. if (lstat(file_path, &attr_of_src) != 0) {
  1524. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("scanDirfresh")("get local file attrr fail! file_path=%s", file_path);
  1525. continue;//继续下一个文件
  1526. }
  1527. //判断文件是否超过最大扫描文件长度
  1528. unsigned long limit = plan->file_length_limit * 1024 * 1024;
  1529. if (attr_of_src.st_size > limit) {
  1530. CSimpleStringA warnStr = CSimpleStringA::Format("local file len (%u), over file_length_limit (%d)m, file_path=%s", attr_of_src.st_size, plan->file_length_limit, file_path);
  1531. LogWarn(Severity_Low, Error_Unexpect, LOG_WARN_UPLOAD_QUERY_FILE_OVER_LIMIT, warnStr.GetData());
  1532. continue;//继续下一个文件
  1533. }
  1534. time_t nowTime = time((time_t*)NULL);//当前时间
  1535. if (nowTime > attr_of_src.st_mtime)
  1536. {
  1537. long diff = nowTime - attr_of_src.st_mtime;
  1538. if (diff < plan->max_silent)
  1539. {
  1540. continue;//继续下一个文件,时间不够
  1541. }else{
  1542. //时间已够,判断文件是否能独占锁
  1543. if (!test_zero_ref(file_path)) {
  1544. continue;//继续下一个文件
  1545. }
  1546. }
  1547. }else {
  1548. continue;//继续下一个文件,时间不够
  1549. }
  1550. //得到文件长度
  1551. unsigned long filelen = attr_of_src.st_size;
  1552. #endif
  1553. //添加扫描文件
  1554. UploadFileInfo* upFile = new UploadFileInfo();
  1555. upFile->fileName = fileName;
  1556. upFile->filePath = file_path;
  1557. if(upFile->filePath.length()>900){
  1558. //路径太长,ECS存储有问题,截取路径,并加入模拟路径前缀:window S:\\ , linux /S/
  1559. #ifdef RVC_OS_WIN
  1560. upFile->fileUploadPath.append("S:\\");
  1561. #else
  1562. upFile->fileUploadPath.append("/S/");
  1563. #endif
  1564. upFile->fileUploadPath.append(fileName.c_str());
  1565. //upFile->fileUploadRelativePath = "S:\\";
  1566. }else{
  1567. //直接赋值
  1568. upFile->fileUploadPath = file_path;
  1569. //upFile->fileUploadRelativePath = upFile->fileUploadPath.substr(0,upFile->fileUploadPath.length()-fileName.length());//截取文件名称的路径
  1570. }
  1571. upFile->BranchFilePath = file_path;
  1572. upFile->fileLen = filelen;
  1573. #ifdef RVC_OS_WIN
  1574. upFile->editTime = CSimpleStringA::Format("%d-%d-%d %d:%d:%d",filest.wYear, filest.wMonth, filest.wDay, filest.wHour, filest.wMinute, filest.wSecond);
  1575. #else
  1576. tm fileTimeTm = { 0 };
  1577. localtime_r(&attr_of_src.st_mtime, &fileTimeTm);
  1578. upFile->editTime = CSimpleStringA::Format("%d-%d-%d %d:%d:%d", fileTimeTm.tm_year+1900, fileTimeTm.tm_mon+1, fileTimeTm.tm_mday, fileTimeTm.tm_hour, fileTimeTm.tm_min, fileTimeTm.tm_sec);
  1579. #endif
  1580. upFile->plan_id = plan->plan_id;
  1581. upFile->branch_no = plan->branch_no;
  1582. upFile->plan_type = plan->plan_type;
  1583. upFile->file_type = plan->file_type;
  1584. upFile->path_type = plan->path_type;
  1585. upFile->path_name = plan->path_name;//因传回路径可能是windows路径斜杠,转义为linux斜杠
  1586. upFile->file_name = plan->file_name;
  1587. upFile->file_regex = plan->file_regex;
  1588. upFile->before_deal_type = plan->before_deal_type;
  1589. upFile->after_deal_type = plan->after_deal_type;
  1590. upFile->after_deal_text = plan->after_deal_text;
  1591. upFile->file_limit = plan->file_limit;
  1592. upFile->file_length_limit = plan->file_length_limit;
  1593. upFile->max_silent = plan->max_silent;
  1594. upFile->upload_address_env = plan->upload_address_env;
  1595. m_uploadList->push_back(upFile);
  1596. //DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("scanDirfresh")("file %s lenth(%d) added!",file_path,filelen);
  1597. }
  1598. toolkit_array_free2(arr_files);
  1599. }
  1600. array_header_t *arr_dir = fileutil_get_sub_dirs_a(path);
  1601. if (arr_dir) {
  1602. int i;
  1603. for (i = 0; i < arr_dir->nelts; ++i) {
  1604. char *dir_path = ARRAY_IDX(arr_dir, i, char*);
  1605. scanDirfresh(plan, dir_path);
  1606. }
  1607. }
  1608. }
  1609. void UploadFSM::HttpsLogCallBack(const char* logtxt)
  1610. {
  1611. if(logtxt!=NULL){
  1612. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("HttpsLogCallBack")("http dbg: %s",logtxt);
  1613. }
  1614. }
  1615. bool UploadFSM::IsFileMatch(const char *pszFilter, const char *pszFileName)
  1616. {
  1617. const char *p1 = pszFilter;
  1618. const char *p2 = pszFileName;
  1619. if (p1 == NULL)
  1620. return true;
  1621. if (p2 == NULL)
  1622. return false;
  1623. if (*p1 ==NULL && *p2 ==NULL)
  1624. return true;
  1625. else if (*p1 == NULL)
  1626. return false;
  1627. else if (*p2 == NULL)
  1628. {
  1629. // 查找*p1是否全是*
  1630. while(*p1 == '*')
  1631. p1++;
  1632. if (*p1 == NULL)
  1633. return true;
  1634. else
  1635. return false;
  1636. }
  1637. if (*p1 != '*')
  1638. {
  1639. if (tolower(*p1) != tolower(*p2))
  1640. return false;
  1641. else
  1642. return IsFileMatch(p1+1, p2+1);
  1643. }
  1644. else
  1645. {
  1646. while(*++p1 == '*');
  1647. if (*p1 == NULL)
  1648. return true;
  1649. while (*p2)
  1650. {
  1651. while(tolower(*p1) != tolower(*p2) && *++p2);
  1652. if (*p2 == NULL)
  1653. return false;
  1654. if(IsFileMatch(p1+1, p2+1))
  1655. return true;
  1656. p2++;
  1657. }
  1658. return false;
  1659. }
  1660. }
  1661. ErrorCodeEnum UploadFSM::SM3FileToStr(CSimpleStringA strFilePath, CSimpleStringA &strSM3,bool isSub)
  1662. {
  1663. if(strFilePath.IsNullOrEmpty()){
  1664. return Error_Null;
  1665. }
  1666. int nlen = strlen(strFilePath.GetData());
  1667. char* pchar = new char[nlen+1];
  1668. strcpy(pchar,strFilePath.GetData());
  1669. BYTE md5[32]={0};
  1670. try
  1671. {
  1672. if(SM3File(pchar,md5)){
  1673. delete pchar;
  1674. //获取16进制的字符串
  1675. if(Error_Succeed!=SM3_Str(strSM3,md5,isSub)){
  1676. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("SM3FileToStr")("sm3国密转16进制字符串失败,file=%s",strFilePath.GetData());
  1677. return Error_Unexpect;
  1678. }
  1679. return Error_Succeed;
  1680. }else{
  1681. delete pchar;
  1682. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("SM3FileToStr")("sm3国密加密失败,file=%s",strFilePath.GetData());
  1683. return Error_Unexpect;
  1684. }
  1685. }
  1686. catch (...)
  1687. {
  1688. delete pchar;
  1689. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("SM3FileToStr")("sm3国密加密异常失败,file=%s",strFilePath.GetData());
  1690. return Error_Exception;
  1691. }
  1692. }
  1693. ErrorCodeEnum UploadFSM::SM3_Str(CSimpleStringA &strSM3,BYTE * SM3Byte,bool isSub)
  1694. {
  1695. if(SM3Byte == NULL){
  1696. return Error_Exception;
  1697. }
  1698. int SM3_len=64;
  1699. if(isSub){
  1700. SM3_len=32;
  1701. }
  1702. int i;
  1703. char* file_SM3 = (char*)malloc((SM3_len + 1) * sizeof(char));
  1704. if(file_SM3 == NULL)
  1705. {
  1706. fprintf(stderr, "SM3 malloc failed.\n");
  1707. return Error_Exception;
  1708. }
  1709. memset(file_SM3, 0, (SM3_len + 1));
  1710. if(SM3_len == 32)
  1711. {
  1712. for(i=0; i<16; i++)
  1713. { //SM3截取中间16位字节,8-24位字节数,小写
  1714. sprintf(&file_SM3[i*2], "%02x", SM3Byte[i+8]);
  1715. }
  1716. }
  1717. else if(SM3_len == 64)
  1718. {
  1719. for(i=0; i<32; i++)
  1720. {
  1721. sprintf(&file_SM3[i*2], "%02x", SM3Byte[i]);
  1722. }
  1723. }
  1724. strSM3=file_SM3;
  1725. free(file_SM3);
  1726. return Error_Succeed;
  1727. }
  1728. bool UploadFSM::getFileContent(FILE* pFile,unsigned char* content,int beginPos, int contentLen)
  1729. {
  1730. if(pFile==NULL||content==NULL){
  1731. return false;
  1732. }
  1733. #ifdef RVC_OS_WIN
  1734. clearerr(pFile);//尝试先复位错误指针
  1735. #endif
  1736. if(fseek(pFile,beginPos,SEEK_SET)!=0){
  1737. #ifdef RVC_OS_WIN
  1738. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("getFileContent")("getFileContent fail,fseek beginPos =%d is error =%d",beginPos,(int)GetLastError());
  1739. #else
  1740. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("getFileContent")("getFileContent fail,fseek beginPos =%d is error =%d",beginPos, errno);
  1741. #endif
  1742. return false;
  1743. }
  1744. unsigned char* pRead = content;//移动的指针
  1745. int pRemaind = contentLen; //剩余字节数
  1746. int numBytes = 0;
  1747. while(!feof(pFile)&&!ferror(pFile)){
  1748. if(pRemaind<=0){
  1749. break;
  1750. }
  1751. numBytes=(int)fread(pRead,1,pRemaind,pFile);
  1752. if(numBytes>0){
  1753. pRemaind -=numBytes;
  1754. pRead +=numBytes;
  1755. }
  1756. }
  1757. if(pRemaind==0){
  1758. return true;
  1759. }else{
  1760. #ifdef RVC_OS_WIN
  1761. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("getFileContent")("getFileContent fail,pRemaind =%d, error=%d",pRemaind,(int)GetLastError());
  1762. #else
  1763. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("getFileContent")("getFileContent fail,pRemaind =%d, error=%d",pRemaind, errno);
  1764. #endif
  1765. return false;
  1766. }
  1767. }
  1768. bool UploadFSM::test_zero_ref(const char *path)
  1769. {
  1770. #ifdef RVC_OS_WIN
  1771. HANDLE hFile = CreateFileA(path,
  1772. GENERIC_READ, 0, NULL, OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL); // try open
  1773. if (hFile != INVALID_HANDLE_VALUE) {
  1774. CloseHandle(hFile);
  1775. return TRUE;
  1776. } else {
  1777. //添加获取句柄失败情况
  1778. LogWarn(Severity_Low, Error_Unexpect, LOG_WARN_UPLOAD_SCANFILE_LOCK_ERROR, CSimpleStringA::Format("test_zero_ref is fail:%s",path).GetData());
  1779. DWORD dwRet = GetLastError();
  1780. return FALSE;
  1781. }
  1782. #else
  1783. //后期改为linux真正的文件锁,现在来看,暂时用不着
  1784. FILE* fp = fopen(path, "rb");
  1785. if (fp != NULL) {
  1786. fclose(fp);
  1787. return true;
  1788. }
  1789. else
  1790. {
  1791. LogWarn(Severity_Low, Error_Unexpect, LOG_WARN_UPLOAD_SCANFILE_LOCK_ERROR, CSimpleStringA::Format("check_zero_ref is fail:%s", path).GetData());
  1792. return false;
  1793. }
  1794. #endif // RVC_OS_WIN
  1795. }
  1796. bool UploadFSM::GetFileLength(const char* filePath,long &fileLen)
  1797. {
  1798. FILE* file = fopen(filePath, "rb");
  1799. if (file!=NULL)
  1800. {
  1801. #ifdef RVC_OS_WIN
  1802. fileLen = filelength(fileno(file));
  1803. fclose(file);
  1804. return true;
  1805. #else
  1806. //取得当前文件流的读取位置
  1807. int cur_pos = ftell(file);
  1808. //将文件流的读取位置设为文件末尾
  1809. if (fseek(file, SEEK_SET, SEEK_END)==0) {
  1810. //获取文件末尾的读取位置,即文件大小
  1811. fileLen = ftell(file);
  1812. //将文件流的读取位置还原为原先的值
  1813. fseek(file, cur_pos, SEEK_SET);
  1814. fclose(file);
  1815. return true;
  1816. }
  1817. else {
  1818. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("GetFileLength")("fseek file=%s is fail, err=%d", filePath,errno);
  1819. fclose(file);
  1820. return false;
  1821. }
  1822. #endif
  1823. } else{
  1824. fileLen = 0;
  1825. return false;
  1826. }
  1827. }
  1828. void UploadFSM::reportBatchMsg()
  1829. {
  1830. CSimpleStringA strReport;
  1831. if(m_uploadReport.fail==0){
  1832. strReport =CSimpleStringA::Format("batch=succ isbreak=%d sum=%d succ=%d fail=%d detail fail: uploadFail=%d updateState=%d operateFileFail=%d (decodeFail=%d queryTempFail=%d)",
  1833. m_uploadReport.isBreak, m_uploadReport.sum, m_uploadReport.succ, m_uploadReport.fail, m_uploadReport.uploadFail, m_uploadReport.updateState,
  1834. m_uploadReport.operateFileFail, m_uploadReport.decodeFail, m_uploadReport.queryTempFail);
  1835. LogWarn(Severity_Low, Error_Unexpect, LOG_WARN_UPLOAD_FILE_REPORT, strReport.GetData());
  1836. }else{
  1837. strReport =CSimpleStringA::Format("batch=fail isbreak=%d sum=%d succ=%d fail=%d detail fail: uploadFail=%d updateState=%d operateFileFail=%d (decodeFail=%d queryTempFail=%d)",
  1838. m_uploadReport.isBreak, m_uploadReport.sum, m_uploadReport.succ, m_uploadReport.fail, m_uploadReport.uploadFail, m_uploadReport.updateState,
  1839. m_uploadReport.operateFileFail, m_uploadReport.decodeFail, m_uploadReport.queryTempFail);
  1840. LogWarn(Severity_Middle, Error_Unexpect, LOG_WARN_UPLOAD_FILE_REPORT, strReport.GetData());
  1841. }
  1842. //LogWarn(Severity_Middle, Error_Unexpect, LOG_WARN_UPLOAD_FILE_REPORT, strReport.GetData());
  1843. }
  1844. bool UploadFSM::findOverLenWarn(const char* fileName) {
  1845. if (m_overLenFileList != NULL) {
  1846. bool isfind = false;
  1847. list<string>::iterator iter;
  1848. for (iter = m_overLenFileList->begin(); iter != m_overLenFileList->end(); ++iter) {
  1849. string fileStr = *iter;
  1850. if (strcmp(fileName, fileStr.c_str()) == 0) {
  1851. isfind = true;
  1852. break;
  1853. }
  1854. }
  1855. if (!isfind) {
  1856. //未找到,加入队列
  1857. m_overLenFileList->push_back(fileName);
  1858. }
  1859. return isfind;
  1860. }
  1861. return false;
  1862. }