UploadFSM.cpp 71 KB

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