Fix build when using ValyriaTear/luabind (on Ubuntu)
[ryzomcore.git] / ryzom / client / src / login_patch.cpp
blob4233a23c236137677f7909c816c0dd243be03a07
1 // Ryzom - MMORPG Framework <http://dev.ryzom.com/projects/ryzom/>
2 // Copyright (C) 2010-2020 Winch Gate Property Limited
3 //
4 // This source file has been modified by the following contributors:
5 // Copyright (C) 2014 Matthew LAGOE (Botanic) <cyberempires@gmail.com>
6 // Copyright (C) 2014-2020 Jan BOON (Kaetemi) <jan.boon@kaetemi.be>
7 //
8 // This program is free software: you can redistribute it and/or modify
9 // it under the terms of the GNU Affero General Public License as
10 // published by the Free Software Foundation, either version 3 of the
11 // License, or (at your option) any later version.
13 // This program is distributed in the hope that it will be useful,
14 // but WITHOUT ANY WARRANTY; without even the implied warranty of
15 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 // GNU Affero General Public License for more details.
18 // You should have received a copy of the GNU Affero General Public License
19 // along with this program. If not, see <http://www.gnu.org/licenses/>.
22 // Includes
25 #include "stdpch.h"
27 #include <sys/stat.h>
29 #ifndef NL_OS_WINDOWS
30 #include <unistd.h>
31 #endif
33 #ifdef NL_OS_MAC
34 #include "app_bundle_utils.h"
35 #endif
37 #include <memory>
38 #include <errno.h>
40 #define USE_CURL
42 #ifdef USE_CURL
43 #include <curl/curl.h>
44 #endif
46 #include <zlib.h>
48 #include "nel/misc/debug.h"
49 #include "nel/misc/path.h"
50 #include "nel/misc/thread.h"
51 #include "nel/misc/sha1.h"
52 #include "nel/misc/big_file.h"
53 #include "nel/misc/i18n.h"
54 #include "nel/misc/cmd_args.h"
55 #include "nel/misc/seven_zip.h"
56 #include "nel/web/curl_certificates.h"
58 #include "game_share/bg_downloader_msg.h"
60 #include "login_patch.h"
61 #include "login.h"
62 #include "user_agent.h"
65 #ifndef RY_BG_DOWNLOADER
66 #include "client_cfg.h"
67 #else
68 #include "../client_background_downloader/client_background_downloader.h"
69 #define __CLIENT_INSTALL_EXE__
70 #endif
72 #ifdef NL_OS_WINDOWS
73 #include <direct.h>
74 #endif
77 // Namespaces
81 using namespace std;
82 using namespace NLMISC;
85 extern string VersionName;
86 extern string R2ServerVersion;
88 #ifdef __CLIENT_INSTALL_EXE__
89 extern std::string TheTmpInstallDirectory;
90 extern std::string ClientLauncherUrl;
91 #else
92 std::string TheTmpInstallDirectory = "patch/client_install";
93 #endif
95 extern NLMISC::CCmdArgs Args;
97 // ****************************************************************************
98 // ****************************************************************************
99 // ****************************************************************************
100 // CPatchManager
101 // ****************************************************************************
102 // ****************************************************************************
103 // ****************************************************************************
105 struct EPatchDownloadException : public Exception
107 EPatchDownloadException() : Exception( "Download Error" ) {}
108 EPatchDownloadException( const std::string& str ) : Exception( str ) {}
109 virtual ~EPatchDownloadException() throw(){}
113 CPatchManager *CPatchManager::_Instance = NULL;
115 static std::string ClientRootPath;
117 // ****************************************************************************
118 CPatchManager::CPatchManager() : State("t_state"), DataScanState("t_data_scan_state")
120 DescFilename = "ryzom_xxxxx.idx";
122 #ifdef NL_OS_WINDOWS
123 UpdateBatchFilename = "updt_nl.bat";
124 UpgradeBatchFilename = "upgd_nl.bat";
125 #else
126 UpdateBatchFilename = "updt_nl.sh";
127 UpgradeBatchFilename = "upgd_nl.sh";
128 #endif
130 std::string rootPath;
132 if (ClientCfg.getDefaultConfigLocation(rootPath))
134 // use same directory as client_default.cfg
135 rootPath = CFile::getPath(rootPath);
137 else
139 // use current directory
140 rootPath = CPath::getCurrentPath();
143 setClientRootPath(rootPath);
145 VerboseLog = true;
147 PatchThread = NULL;
148 CheckThread = NULL;
149 InstallThread = NULL;
150 ScanDataThread = NULL;
151 DownloadThread = NULL;
152 Thread = NULL;
154 LogSeparator = "\n";
155 ValidDescFile = false;
157 MustLaunchBatFile = false;
159 DownloadInProgress = false;
160 _AsyncDownloader = NULL;
161 _StateListener = NULL;
162 _StartRyzomAtEnd = true;
165 // ****************************************************************************
166 void CPatchManager::setClientRootPath(const std::string& clientRootPath)
168 ClientRootPath = CPath::standardizePath(clientRootPath);
169 ClientPatchPath = CPath::standardizePath(ClientRootPath + "unpack");
171 // Delete the .sh file because it's not useful anymore
172 std::string fullUpdateBatchFilename = ClientRootPath + UpdateBatchFilename;
174 if (NLMISC::CFile::fileExists(fullUpdateBatchFilename))
175 NLMISC::CFile::deleteFile(fullUpdateBatchFilename);
177 WritableClientDataPath = CPath::standardizePath(ClientRootPath + "data");
179 #ifdef NL_OS_MAC
180 ReadableClientDataPath = CPath::standardizePath(getAppBundlePath() + "/Contents/Resources/data");
181 #elif defined(NL_OS_UNIX)
182 ReadableClientDataPath = CPath::standardizePath(getRyzomSharePrefix() + "/data");
183 if (CFile::isDirectory(ReadableClientDataPath)) ReadableClientDataPath.clear();
184 #else
185 ReadableClientDataPath.clear();
186 #endif
188 if (ReadableClientDataPath.empty()) ReadableClientDataPath = WritableClientDataPath;
191 // ****************************************************************************
192 void CPatchManager::setErrorMessage(const std::string &message)
194 _ErrorMessage = message;
197 // ****************************************************************************
198 void CPatchManager::forceStopCheckThread()
200 PatchThread->StopAsked = true;
203 // ****************************************************************************
204 void CPatchManager::forceStopPatchThread()
206 CheckThread->StopAsked = true;
209 // ****************************************************************************
210 void CPatchManager::init(const std::vector<std::string>& patchURIs, const std::string &sServerPath, const std::string &sServerVersion)
212 uint i;
213 PatchServers.clear();
215 for (i=0; i<patchURIs.size(); ++i)
217 PatchServers.push_back(CPatchServer(patchURIs[i]));
220 srand(NLMISC::CTime::getSecondsSince1970());
221 UsedServer = (sint)(((double)rand() / ((double)RAND_MAX+1.0)) * (double)PatchServers.size());
223 ServerPath = CPath::standardizePath (sServerPath);
224 ServerVersion = sServerVersion;
226 string::size_type pos = ServerPath.find ("@");
227 if (pos != string::npos)
228 DisplayedServerPath = "http://" + ServerPath.substr (pos+1);
229 else
230 DisplayedServerPath = ServerPath;
232 NLMISC::CFile::createDirectory(ClientPatchPath);
233 NLMISC::CFile::createDirectory(WritableClientDataPath);
236 // try to read the version file from the server (that will replace the version number)
239 CConfigFile *cf;
241 #ifdef RY_BG_DOWNLOADER
242 cf = &theApp.ConfigFile;
243 #else
244 cf = &ClientCfg.ConfigFile;
245 #endif
247 // App name matches Domain on the SQL server
248 std::string appName = cf->getVarPtr("Application")
249 ? cf->getVar("Application").asString(0)
250 : "default";
252 std::string versionFileName = appName + ".version";
253 getServerFile(versionFileName);
255 // ok, we have the file, extract version number (aka build number) and the
256 // version name if present
258 CIFile versionFile(ClientPatchPath + versionFileName);
259 char buffer[1024];
260 versionFile.getline(buffer, 1024);
261 CSString line(buffer);
263 #ifdef NL_DEBUG
264 CConfigFile::CVar *forceVersion = cf->getVarPtr("ForceVersion");
266 if (forceVersion != NULL)
268 line = forceVersion->asString();
270 #endif
272 // Use the version specified in this file, if the file does not contain an asterisk
273 if (line[0] != '*')
275 ServerVersion = line.firstWord(true);
276 VersionName = line.firstWord(true);
279 // force the R2ServerVersion
280 R2ServerVersion = ServerVersion;
282 #ifdef __CLIENT_INSTALL_EXE__
284 //The install program load a the url of the mini web site in the patch directory
286 std::string clientLauncherUrl = "client_launcher_url.txt";
287 bool ok = true;
290 uint32 nServerVersion;
291 fromString(ServerVersion, nServerVersion);
292 std::string url = toString("%05u/%s", nServerVersion, clientLauncherUrl.c_str());
293 // The client version is different from the server version : download new description file
294 getServerFile(url.c_str(), false); // For the moment description file is not zipped
296 catch (...)
298 // fallback to patch root directory
301 getServerFile(clientLauncherUrl.c_str(), false); // For the moment description file is not zipped
303 catch(...)
305 ok = false;
309 if (ok)
311 CIFile versionFile;
312 if (versionFile.open(ClientPatchPath+clientLauncherUrl) )
314 char buffer[1024];
315 versionFile.getline(buffer, 1024);
316 ClientLauncherUrl = std::string(buffer);
320 #endif
322 catch (...)
324 // no version file
328 // retrieve the current client version, according to .idx
329 readClientVersionAndDescFile();
332 // ***************************************************************************
333 void CPatchManager::readClientVersionAndDescFile()
337 ValidDescFile = false;
338 vector<string> vFiles;
339 CPath::getPathContent(ClientPatchPath, false, false, true, vFiles);
340 uint32 nVersion = 0xFFFFFFFF;
341 uint32 nNewVersion;
342 for (uint32 i = 0; i < vFiles.size(); ++i)
344 string sName = NLMISC::CFile::getFilename(vFiles[i]);
345 string sExt = NLMISC::CFile::getExtension(sName);
346 string sBase = sName.substr(0, sName.rfind('_'));
347 if ((sExt == "idx") && (sBase == "ryzom"))
349 string val = sName.substr(sName.rfind('_')+1, 5);
350 if (fromString(val, nNewVersion) && ((nNewVersion > nVersion) || (nVersion == 0xFFFFFFFF)))
351 nVersion = nNewVersion;
354 if (nVersion != 0xFFFFFFFF)
355 readDescFile(nVersion);
356 else
357 DescFilename = "unknown";
358 ValidDescFile = true;
360 catch(const Exception &)
362 nlwarning("EXCEPTION CATCH: readClientVersionAndDescFile() failed - not important");
363 // Not important that there is no desc file
367 // ****************************************************************************
368 void CPatchManager::startCheckThread(bool includeBackgroundPatch)
370 if (CheckThread != NULL)
372 nlwarning ("check thread is already running");
373 return;
375 if (Thread != NULL)
377 nlwarning ("a thread is already running");
378 return;
381 _ErrorMessage.clear();
383 CheckThread = new CCheckThread(includeBackgroundPatch);
384 nlassert (CheckThread != NULL);
386 Thread = IThread::create (CheckThread);
387 nlassert (Thread != NULL);
388 Thread->start ();
391 // ****************************************************************************
392 bool CPatchManager::isCheckThreadEnded(bool &ok)
394 if (CheckThread == NULL)
396 ok = false;
397 return true;
400 bool end = CheckThread->Ended;
401 if (end)
403 ok = CheckThread->CheckOk;
404 stopCheckThread();
407 return end;
410 // ****************************************************************************
411 void CPatchManager::stopCheckThread()
413 if(CheckThread && Thread)
415 Thread->wait();
416 delete Thread;
417 Thread = NULL;
418 delete CheckThread;
419 CheckThread = NULL;
423 // Return the position of the inserted/found category
424 sint32 updateCat(vector<CPatchManager::SPatchInfo::SCat> &rOutVec, CPatchManager::SPatchInfo::SCat &rInCat)
426 uint32 i;
427 for (i = 0; i < rOutVec.size(); ++i)
429 if (rOutVec[i].Name == rInCat.Name)
430 break;
433 if (i == rOutVec.size())
435 rOutVec.push_back(rInCat);
437 else
439 rOutVec[i].Size += rInCat.Size;
440 rOutVec[i].FinalFileSize += rInCat.FinalFileSize;
441 rOutVec[i].SZipSize += rInCat.SZipSize;
444 return i;
447 // ****************************************************************************
448 void CPatchManager::getInfoToDisp(SPatchInfo &piOut)
450 piOut.NonOptCat.clear();
451 piOut.OptCat.clear();
452 piOut.ReqCat.clear();
454 // Convert FilesToPatch vector that must be initialized into something human readable
455 uint32 i;
456 for (i = 0; i < FilesToPatch.size(); ++i)
458 SFileToPatch &rFTP = FilesToPatch[i];
459 // Find the category of the file
460 sint32 nCat = -1;
461 const CBNPCategorySet &rAllCats = DescFile.getCategories();
462 for (uint32 j = 0; j < rAllCats.categoryCount(); ++j)
464 const CBNPCategory &rCat = rAllCats.getCategory(j);
465 for (uint32 k = 0; k < rCat.fileCount(); ++k)
467 if (rCat.getFile(k) == rFTP.FileName)
469 nCat = j;
470 break;
474 if (nCat != -1)
475 break;
478 if (nCat != -1)
480 // Add the category found, if already there just update the size
481 const CBNPCategory &rCat = rAllCats.getCategory(nCat);
482 string sCatName = rCat.getName();
483 // Size of all patches
484 uint32 nTotalPatchesSize = 0;
485 for (uint32 j = 0; j < rFTP.PatcheSizes.size(); ++j)
486 nTotalPatchesSize += rFTP.PatcheSizes[j];
488 SPatchInfo::SCat c;
489 c.Name = sCatName;
490 c.Size = nTotalPatchesSize;
491 c.SZipSize = rFTP.SZFileSize;
492 c.FinalFileSize = rFTP.FinalFileSize;
493 if (!rCat.getCatRequired().empty())
495 // Ensure the required cat exists
496 SPatchInfo::SCat rc;
497 rc.Name = rCat.getCatRequired();
498 c.Req = updateCat(piOut.ReqCat, rc);
501 // In which category of category should we add it ?
502 if (rCat.isOptional())
504 if (rCat.isHidden())
505 updateCat(piOut.ReqCat, c);
506 else
507 updateCat(piOut.OptCat, c);
509 else
511 updateCat(piOut.NonOptCat, c);
516 for (i = 0; i < OptionalCat.size(); ++i)
518 const CBNPCategory *pCat = DescFile.getCategories().getCategory(OptionalCat[i]);
519 nlassert(pCat != NULL);
521 SPatchInfo::SCat c;
522 c.Name = pCat->getName();
524 if (!pCat->getCatRequired().empty())
526 // Ensure the required cat exists
527 SPatchInfo::SCat rc;
528 rc.Name = pCat->getCatRequired();
529 c.Req = updateCat(piOut.ReqCat, rc);
532 updateCat(piOut.OptCat, c);
536 // ****************************************************************************
537 // TODO : use selected categories to patch a list of files
538 void CPatchManager::startPatchThread(const vector<string> &CategoriesSelected, bool applyPatch)
540 if (PatchThread != NULL)
542 nlwarning ("check thread is already running");
543 return;
545 if (Thread != NULL)
547 nlwarning ("a thread is already running");
548 return;
551 _ErrorMessage.clear();
553 PatchThread = new CPatchThread(applyPatch);
554 nlassert (PatchThread != NULL);
556 // Select all the files we have to patch depending on non-optional categories and selected categories
557 uint32 i, j, k;
558 // Add non-optional categories
559 vector<string> CatsSelected = CategoriesSelected;
560 PatchThread->clear();
561 const CBNPCategorySet &rAllCats = DescFile.getCategories();
562 for (i = 0; i < rAllCats.categoryCount(); ++i)
564 const CBNPCategory &rCat = rAllCats.getCategory(i);
565 if (!rCat.isOptional())
566 CatsSelected.push_back(rCat.getName());
569 // Add all required categories
570 uint32 nSize = (uint32)CatsSelected.size();
573 nSize = (uint32)CatsSelected.size();
575 for (i = 0; i < CatsSelected.size(); ++i)
577 const CBNPCategory *pCat = rAllCats.getCategory(CatsSelected[i]);
578 if (pCat == NULL) continue;
579 if (pCat->getCatRequired().empty()) continue;
580 // Check if the category required is already present
581 for (j = 0; j < CatsSelected.size(); ++j)
583 const CBNPCategory *pCat2 = rAllCats.getCategory(CatsSelected[j]);
584 if (pCat2->getName() == pCat->getCatRequired())
585 break;
587 // Not present ?
588 if (j == CatsSelected.size())
590 CatsSelected.push_back(pCat->getCatRequired());
591 break;
595 while(nSize != CatsSelected.size());
597 // Select files
598 for (i = 0; i < CatsSelected.size(); ++i)
600 // Find the category from the name
601 const CBNPCategory *pCat = rAllCats.getCategory(CatsSelected[i]);
602 if (pCat != NULL)
604 for (j = 0; j < pCat->fileCount(); ++j)
606 const string &rFilename = pCat->getFile(j);
607 const CBNPFileSet &rFileSet = DescFile.getFiles();
608 const CBNPFile *pFile = rFileSet.getFileByName(rFilename);
609 if (pFile != NULL)
611 // Look if it's a file to patch
612 for (k = 0; k < FilesToPatch.size(); ++k)
613 if (FilesToPatch[k].FileName == pFile->getFileName())
614 break;
616 if (k < FilesToPatch.size())
618 FilesToPatch[k].Incremental = pCat->isIncremental();
619 if (!pCat->getUnpackTo().empty())
620 FilesToPatch[k].ExtractPath = CPath::standardizePath(pCat->getUnpackTo());
622 PatchThread->add(FilesToPatch[k]);
624 // Close opened big files
625 CBigFile::getInstance().remove(FilesToPatch[k].FileName);
632 // Launch the thread
633 Thread = IThread::create (PatchThread);
634 nlassert (Thread != NULL);
635 Thread->start ();
638 // ****************************************************************************
639 bool CPatchManager::isPatchThreadEnded (bool &ok)
641 if (PatchThread == NULL)
643 ok = false;
644 return true;
647 bool end = PatchThread->Ended;
648 if (end)
650 ok = PatchThread->PatchOk;
651 stopPatchThread();
654 return end;
657 // ****************************************************************************
658 // Called in main thread
659 bool CPatchManager::getThreadState (std::string &stateOut, vector<string> &stateLogOut)
661 if ((PatchThread == NULL) && (CheckThread == NULL) && (ScanDataThread==NULL))
662 return false;
664 // clear output
665 stateOut.clear();
666 stateLogOut.clear();
668 // Get access to the state
669 bool changed= false;
671 CSynchronized<CState>::CAccessor as(&State);
672 CState &rState= as.value();
673 if (rState.StateChanged)
675 // and retrieve info
676 changed= true;
677 stateOut = rState.State;
678 stateLogOut = rState.StateLog;
679 // clear state
680 rState.StateLog.clear();
681 rState.StateChanged= false;
685 // verbose log
686 if (isVerboseLog() && !stateLogOut.empty())
687 for (uint32 i = 0; i < stateLogOut.size(); ++i)
688 nlinfo("%s", stateLogOut[i].c_str());
690 return changed;
693 // ****************************************************************************
694 void CPatchManager::stopPatchThread()
696 if(PatchThread && Thread)
698 Thread->wait();
699 delete Thread;
700 Thread = NULL;
701 delete PatchThread;
702 PatchThread = NULL;
706 // ****************************************************************************
707 void CPatchManager::deleteBatchFile()
709 deleteFile(ClientRootPath + UpdateBatchFilename, false, false);
712 // ****************************************************************************
713 void CPatchManager::createBatchFile(CProductDescriptionForClient &descFile, bool wantRyzomRestart, bool useBatchFile)
715 uint nblab = 0;
717 std::string content;
719 // Unpack files with category ExtractPath non empty
720 const CBNPCategorySet &rDescCats = descFile.getCategories();
721 OptionalCat.clear();
723 for (uint32 i = 0; i < rDescCats.categoryCount(); ++i)
725 // For all optional categories check if there is a 'file to patch' in it
726 const CBNPCategory &rCat = rDescCats.getCategory(i);
728 nlinfo("Category = %s", rCat.getName().c_str());
730 if (!rCat.getUnpackTo().empty())
731 for (uint32 j = 0; j < rCat.fileCount(); ++j)
733 string rFilename = ClientPatchPath + rCat.getFile(j);
735 nlinfo("\tFileName = %s", rFilename.c_str());
737 // Extract to patch
738 vector<string> vFilenames;
740 bool result = false;
744 result = bnpUnpack(rFilename, ClientPatchPath, vFilenames);
746 catch(...)
748 throw;
751 if (!result)
753 // TODO: handle exception?
754 string err = toString("Error unpacking %s", rFilename.c_str());
756 throw Exception (err);
758 else
760 for (uint32 fff = 0; fff < vFilenames.size (); fff++)
762 // this file must be moved
763 string fullDstPath = CPath::standardizePath(rCat.getUnpackTo()); // to be sure there is a / at the end
764 NLMISC::CFile::createDirectoryTree(fullDstPath);
766 std::string FileName = vFilenames[fff];
768 bool succeeded = false;
770 if (!useBatchFile)
772 // don't check result, because it's possible the olk file doesn't exist
773 CFile::deleteFile(fullDstPath + FileName);
775 // try to move it, if fails move it later in a script
776 if (CFile::moveFile(fullDstPath + FileName, ClientPatchPath + FileName))
777 succeeded = true;
780 // if we didn't succeed to delete or move the file, create a batch file anyway
781 if (!succeeded)
783 string batchRelativeDstPath;
785 // should be always true
786 if (fullDstPath.compare(0, ClientRootPath.length(), ClientRootPath) == 0)
788 batchRelativeDstPath = fullDstPath.substr(ClientRootPath.length()) + FileName;
790 else
792 batchRelativeDstPath = fullDstPath + FileName;
795 #ifdef NL_OS_WINDOWS
796 // only fix backslashes for .bat
797 batchRelativeDstPath = CPath::standardizeDosPath(batchRelativeDstPath);
799 // use DSTPATH and SRCPATH variables and append filenames
800 string realDstPath = toString("\"%%ROOTPATH%%\\%s\"", batchRelativeDstPath.c_str());
801 string realSrcPath = toString("\"%%UNPACKPATH%%\\%s\"", FileName.c_str());
803 content += toString(":loop%u\n", nblab);
804 content += toString("attrib -r -a -s -h %s\n", realDstPath.c_str());
805 content += toString("del %s\n", realDstPath.c_str());
806 content += toString("if exist %s goto loop%u\n", realDstPath.c_str(), nblab);
807 content += toString("move %s %s\n", realSrcPath.c_str(), realDstPath.c_str());
808 #else
809 // use DSTPATH and SRCPATH variables and append filenames
810 string realDstPath = toString("\"$ROOTPATH/%s\"", batchRelativeDstPath.c_str());
811 string realSrcPath = toString("\"$UNPACKPATH/%s\"", FileName.c_str());
813 content += toString("rm -rf %s\n", realDstPath.c_str());
814 content += toString("mv %s %s\n", realSrcPath.c_str(), realDstPath.c_str());
815 #endif
817 content += "\n";
820 nblab++;
826 std::string patchDirectory = CPath::standardizePath(ClientRootPath + "patch");
828 // Finalize batch file
829 if (NLMISC::CFile::isExists(patchDirectory) && NLMISC::CFile::isDirectory(patchDirectory))
831 std::string patchContent;
833 vector<string> vFileList;
834 CPath::getPathContent (patchDirectory, false, false, true, vFileList, NULL, false);
836 for(uint32 i = 0; i < vFileList.size(); ++i)
838 bool succeeded = false;
840 if (!useBatchFile)
842 if (CFile::deleteFile(vFileList[i]))
843 succeeded = true;
846 // if we didn't succeed to delete, create a batch file anyway
847 if (!succeeded)
849 #ifdef NL_OS_WINDOWS
850 patchContent += toString("del \"%%ROOTPATH%%\\patch\\%s\"\n", vFileList[i].c_str());
851 #else
852 patchContent += toString("rm -f \"$ROOTPATH/patch/%s\"\n", vFileList[i].c_str());
853 #endif
857 if (!patchContent.empty())
859 #ifdef NL_OS_WINDOWS
860 content += ":looppatch\n";
862 content += patchContent;
864 content += "rd /Q /S \"%%ROOTPATH%%\\patch\"\n";
865 content += "if exist \"%%ROOTPATH%%\\patch\" goto looppatch\n";
866 #else
867 content += "rm -rf \"$ROOTPATH/patch\"\n";
868 #endif
870 else
872 CFile::deleteDirectory(patchDirectory);
876 if (!content.empty())
878 deleteBatchFile();
880 // batch full path
881 std::string batchFilename = ClientRootPath + UpdateBatchFilename;
883 // write windows .bat format else write sh format
884 FILE *fp = nlfopen (batchFilename, "wt");
886 if (fp == NULL)
888 string err = toString("Can't open file '%s' for writing: code=%d %s (error code 29)", batchFilename.c_str(), errno, strerror(errno));
889 throw Exception (err);
891 else
893 nlinfo("Creating %s...", batchFilename.c_str());
896 string contentPrefix;
898 //use bat if windows if not use sh
899 #ifdef NL_OS_WINDOWS
900 contentPrefix += "@echo off\n";
901 contentPrefix += "set RYZOM_CLIENT=%~1\n";
902 contentPrefix += "set UNPACKPATH=%~2\n";
903 contentPrefix += "set ROOTPATH=%~3\n";
904 contentPrefix += "set STARTUPPATH=%~4\n";
905 contentPrefix += toString("set UPGRADE_FILE=%%ROOTPATH%%\\%s\n", UpgradeBatchFilename.c_str());
906 contentPrefix += "\n";
907 contentPrefix += "set LOGIN=%~5\n";
908 contentPrefix += "set PASSWORD=%~6\n";
909 contentPrefix += "set SHARDID=%~7\n";
910 #else
911 contentPrefix += "#!/bin/sh\n";
912 contentPrefix += "export RYZOM_CLIENT=\"$1\"\n";
913 contentPrefix += "export UNPACKPATH=\"$2\"\n";
914 contentPrefix += "export ROOTPATH=\"$3\"\n";
915 contentPrefix += "export STARTUPPATH=\"$4\"\n";
916 contentPrefix += toString("export UPGRADE_FILE=$ROOTPATH/%s\n", UpgradeBatchFilename.c_str());
917 contentPrefix += "\n";
918 contentPrefix += "LOGIN=\"$5\"\n";
919 contentPrefix += "PASSWORD=\"$6\"\n";
920 contentPrefix += "SHARDID=\"$7\"\n";
921 #endif
923 contentPrefix += "\n";
925 string contentSuffix;
927 // if we need to restart Ryzom, we need to launch it in batch
928 std::string additionalParams;
930 if (Args.haveLongArg("profile"))
932 additionalParams = "--profile " + Args.getLongArg("profile").front();
935 #ifdef NL_OS_WINDOWS
936 // launch upgrade script if present (it'll execute additional steps like moving or deleting files)
937 contentSuffix += "if exist \"%UPGRADE_FILE%\" call \"%UPGRADE_FILE%\"\n";
939 if (wantRyzomRestart)
941 // client shouldn't be in memory anymore else it couldn't be overwritten
942 contentSuffix += toString("start \"\" /D \"%%STARTUPPATH%%\" \"%%RYZOM_CLIENT%%\" %s \"%%LOGIN%%\" \"%%PASSWORD%%\" \"%%SHARDID%%\"\n", additionalParams.c_str());
944 #else
945 if (wantRyzomRestart)
947 // wait until client not in memory anymore
948 contentSuffix += toString("until ! pgrep -x \"%s\" > /dev/null; do sleep 1; done\n", CFile::getFilename(RyzomFilename).c_str());
951 // launch upgrade script if present (it'll execute additional steps like moving or deleting files)
952 contentSuffix += "if [ -e \"$UPGRADE_FILE\" ]; then chmod +x \"$UPGRADE_FILE\" && \"$UPGRADE_FILE\"; fi\n\n";
954 // be sure file is executable
955 contentSuffix += "chmod +x \"$RYZOM_CLIENT\"\n\n";
957 if (wantRyzomRestart)
959 // change to previous client directory
960 contentSuffix += "cd \"$STARTUPPATH\"\n\n";
962 // launch new client
963 #ifdef NL_OS_MAC
964 // use exec command under OS X
965 contentSuffix += toString("exec \"$RYZOM_CLIENT\" %s \"$LOGIN\" \"$PASSWORD\" \"$SHARDID\"\n", additionalParams.c_str());
966 #else
967 contentSuffix += toString("\"$RYZOM_CLIENT\" %s \"$LOGIN\" \"$PASSWORD\" \"$SHARDID\" &\n", additionalParams.c_str());
968 #endif
970 #endif
972 // append content of script
973 fputs(contentPrefix.c_str(), fp);
974 fputs(content.c_str(), fp);
975 fputs(contentSuffix.c_str(), fp);
977 bool writeError = ferror(fp) != 0;
978 bool diskFull = ferror(fp) && errno == 28 /* ENOSPC */;
979 fclose(fp);
980 if (diskFull)
982 throw NLMISC::EDiskFullError(batchFilename.c_str());
984 if (writeError)
986 throw NLMISC::EWriteError(batchFilename.c_str());
991 // ****************************************************************************
992 void CPatchManager::executeBatchFile()
994 // normal quit
995 extern void quitCrashReport ();
996 quitCrashReport ();
998 bool r2Mode = false;
1000 #ifndef RY_BG_DOWNLOADER
1001 r2Mode = ClientCfg.R2Mode;
1002 #endif
1004 std::string batchFilename;
1006 std::vector<std::string> arguments;
1008 std::string startupPath = Args.getStartupPath();
1010 // 3 first parameters are Ryzom client full path, patch directory full path and client root directory full path
1011 #ifdef NL_OS_WINDOWS
1012 batchFilename = CPath::standardizeDosPath(ClientRootPath);
1014 arguments.push_back(CPath::standardizeDosPath(RyzomFilename));
1015 arguments.push_back(CPath::standardizeDosPath(ClientPatchPath));
1016 arguments.push_back(CPath::standardizeDosPath(ClientRootPath));
1017 arguments.push_back(CPath::standardizeDosPath(startupPath));
1018 #else
1019 batchFilename = ClientRootPath;
1021 arguments.push_back(RyzomFilename);
1022 arguments.push_back(ClientPatchPath);
1023 arguments.push_back(ClientRootPath);
1024 arguments.push_back(startupPath);
1025 #endif
1027 // log parameters passed to Ryzom client
1028 nlinfo("Restarting Ryzom...");
1029 nlinfo("RyzomFilename = %s", RyzomFilename.c_str());
1030 nlinfo("ClientPatchPath = %s", ClientPatchPath.c_str());
1031 nlinfo("ClientRootPath = %s", ClientRootPath.c_str());
1032 nlinfo("StartupPath = %s", startupPath.c_str());
1034 batchFilename += UpdateBatchFilename;
1036 // make script executable
1037 CFile::setRWAccess(batchFilename);
1038 CFile::setExecutable(batchFilename);
1040 // append login, password and shard
1041 if (!LoginLogin.empty())
1043 arguments.push_back(LoginLogin);
1045 if (!LoginPassword.empty())
1047 // encode password in hexadecimal to avoid invalid characters on command-line
1048 arguments.push_back("0x" + toHexa(LoginPassword));
1050 if (!r2Mode)
1052 arguments.push_back(toString(LoginShardId));
1057 // launchProgram with array of strings as argument will escape arguments with spaces
1058 if (!launchProgramArray(batchFilename, arguments, false))
1060 // error occurs during the launch
1061 string str = toString("Can't execute '%s': code=%d %s (error code 30)", batchFilename.c_str(), errno, strerror(errno));
1062 throw Exception (str);
1066 // ****************************************************************************
1067 void CPatchManager::reboot()
1069 onFileInstallFinished(); //In install program wait for the player to select in the gui of the install program if we want to Launch Ryzom or not
1070 createBatchFile(DescFile, _StartRyzomAtEnd);
1071 executeBatchFile();
1075 // ****************************************************************************
1076 int CPatchManager::getTotalFilesToGet()
1078 if (CheckThread != NULL)
1079 return CheckThread->TotalFileToCheck;
1081 if (PatchThread != NULL)
1082 return PatchThread->getNbFileToPatch();
1084 if (ScanDataThread != NULL)
1085 return ScanDataThread->TotalFileToScan;
1087 return 1;
1090 // ****************************************************************************
1091 int CPatchManager::getCurrentFilesToGet()
1093 if (CheckThread != NULL)
1094 return CheckThread->CurrentFileChecked;
1096 if (PatchThread != NULL)
1097 return PatchThread->getCurrentFilePatched();
1099 if (ScanDataThread != NULL)
1100 return ScanDataThread->CurrentFileScanned;
1102 return 1;
1105 // ****************************************************************************
1106 int CPatchManager::getPatchingSize()
1108 if (PatchThread != NULL)
1109 return PatchThread->getPatchingSize();
1110 return 0;
1113 // ****************************************************************************
1114 float CPatchManager::getCurrentFileProgress() const
1116 if (PatchThread != NULL)
1117 return PatchThread->getCurrentFileProgress();
1118 return 0.f;
1121 // ****************************************************************************
1122 void CPatchManager::setRWAccess (const string &filename, bool bThrowException)
1124 string s = CI18N::get("uiSetAttrib") + " " + CFile::getFilename(filename);
1125 setState(true, s);
1127 if (!NLMISC::CFile::setRWAccess(filename) && bThrowException)
1129 s = CI18N::get("uiAttribErr") + " " + CFile::getFilename(filename) + " (" + toString(errno) + "," + strerror(errno) + ")";
1130 setState(true, s);
1131 throw Exception (s);
1135 // ****************************************************************************
1136 string CPatchManager::deleteFile (const string &filename, bool bThrowException, bool bWarning)
1138 string s = CI18N::get("uiDelFile") + " " + CFile::getFilename(filename);
1139 setState(true, s);
1141 if (!NLMISC::CFile::fileExists(filename))
1143 s = CI18N::get("uiDelNoFile");
1144 setState(true, s);
1145 return s;
1148 if (!NLMISC::CFile::deleteFile(filename))
1150 s = CI18N::get("uiDelErr") + " " + CFile::getFilename(filename) + " (" + toString(errno) + "," + strerror(errno) + ")";
1151 if(bWarning)
1152 setState(true, s);
1153 if(bThrowException)
1154 throw Exception (s);
1155 return s;
1157 return "";
1160 // ****************************************************************************
1161 void CPatchManager::renameFile (const string &src, const string &dst)
1163 string s = CI18N::get("uiRenameFile") + " " + NLMISC::CFile::getFilename(src);
1164 setState(true, s);
1166 if (!NLMISC::CFile::moveFile(dst, src))
1168 s = CI18N::get("uiRenameErr") + " " + src + " -> " + dst + " (" + toString(errno) + "," + strerror(errno) + ")";
1169 setState(true, s);
1170 throw Exception (s);
1174 // ****************************************************************************
1175 // Take care this function is called by the thread
1176 void CPatchManager::setState (bool bOutputToLog, const string &ucsNewState)
1179 CSynchronized<CState>::CAccessor as(&State);
1180 CState &rState= as.value();
1181 rState.State= ucsNewState;
1182 if(bOutputToLog)
1183 rState.StateLog.push_back(ucsNewState);
1184 rState.StateChanged= true;
1186 if (_StateListener)
1188 _StateListener->setState(bOutputToLog, ucsNewState);
1192 // ****************************************************************************
1193 void CPatchManager::touchState ()
1196 CSynchronized<CState>::CAccessor as(&State);
1197 as.value().StateChanged= true;
1201 // ****************************************************************************
1202 string CPatchManager::getClientVersion()
1204 if (!ValidDescFile)
1205 return "";
1207 return toString(DescFile.getFiles().getVersionNumber());
1210 // ****************************************************************************
1211 void CPatchManager::readDescFile(sint32 nVersion)
1213 DescFilename = toString("ryzom_%05d.idx", nVersion);
1214 string srcName = ClientPatchPath + DescFilename;
1215 DescFile.clear();
1216 if (!DescFile.load(srcName))
1217 throw Exception ("Can't open file '%s'", srcName.c_str ());
1219 uint cat;
1221 if (ClientRootPath != "./")
1223 // fix relative paths
1224 for (cat = 0; cat < DescFile.getCategories().categoryCount(); ++cat)
1226 CBNPCategory &category = const_cast<CBNPCategory &>(DescFile.getCategories().getCategory(cat));
1228 std::string unpackTo = category.getUnpackTo();
1230 if (unpackTo.substr(0, 1) == ".")
1232 unpackTo = CPath::makePathAbsolute(unpackTo, ClientRootPath, true);
1233 category.setUnpackTo(unpackTo);
1238 // patch category for current platform
1239 std::string platformPatchCategory;
1241 #if defined(NL_OS_WIN64)
1242 platformPatchCategory = "main_exedll_win64";
1243 #elif defined(NL_OS_WINDOWS)
1244 platformPatchCategory = "main_exedll_win32";
1245 #elif defined(NL_OS_MAC)
1246 platformPatchCategory = "main_exedll_osx";
1247 #elif defined(NL_OS_UNIX) && defined(_LP64)
1248 platformPatchCategory = "main_exedll_linux64";
1249 #else
1250 platformPatchCategory = "main_exedll_linux32";
1251 #endif
1253 // check if we are using main_exedll or specific main_exedll_* for platform
1254 bool foundPlatformPatchCategory = false;
1256 for (cat = 0; cat < DescFile.getCategories().categoryCount(); ++cat)
1258 CBNPCategory &category = const_cast<CBNPCategory &>(DescFile.getCategories().getCategory(cat));
1260 if (category.getName() == platformPatchCategory)
1262 foundPlatformPatchCategory = true;
1263 break;
1267 if (foundPlatformPatchCategory)
1269 std::set<std::string> forceRemovePatchCategories;
1271 // only download binaries for current platform
1272 forceRemovePatchCategories.insert("main_exedll");
1273 forceRemovePatchCategories.insert("main_exedll_win32");
1274 forceRemovePatchCategories.insert("main_exedll_win64");
1275 forceRemovePatchCategories.insert("main_exedll_linux32");
1276 forceRemovePatchCategories.insert("main_exedll_linux64");
1277 forceRemovePatchCategories.insert("main_exedll_osx");
1279 // remove current platform category from remove list
1280 forceRemovePatchCategories.erase(platformPatchCategory);
1282 CBNPFileSet &bnpFS = const_cast<CBNPFileSet &>(DescFile.getFiles());
1284 for (cat = 0; cat < DescFile.getCategories().categoryCount();)
1286 const CBNPCategory &bnpCat = DescFile.getCategories().getCategory(cat);
1288 if (std::find(forceRemovePatchCategories.begin(), forceRemovePatchCategories.end(),
1289 bnpCat.getName()) != forceRemovePatchCategories.end())
1291 for (uint file = 0; file < bnpCat.fileCount(); ++file)
1293 std::string fileName = bnpCat.getFile(file);
1294 bnpFS.removeFile(fileName);
1296 const_cast<CBNPCategorySet &>(DescFile.getCategories()).deleteCategory(cat);
1298 else
1300 ++cat;
1306 // ****************************************************************************
1307 void CPatchManager::getServerFile (const std::string &name, bool bZipped, const std::string& specifyDestName, NLMISC::IProgressCallback *progress)
1309 string srcName = name;
1310 if (bZipped) srcName += ".ngz";
1312 string dstName;
1313 if (specifyDestName.empty())
1315 dstName = ClientPatchPath + NLMISC::CFile::getFilename(name);
1317 else
1319 dstName = specifyDestName;
1321 if (bZipped) dstName += ".ngz";
1323 bool downloadSuccess = false;
1325 while (!downloadSuccess)
1327 std::string serverPath;
1328 std::string serverDisplayPath;
1330 if (UsedServer >= 0 && !PatchServers.empty())
1332 // first use main patch servers
1333 serverPath = PatchServers[UsedServer].ServerPath;
1334 serverDisplayPath = PatchServers[UsedServer].DisplayedServerPath;
1336 else
1338 // else use alternative emergency patch server
1339 serverPath = ServerPath;
1340 serverDisplayPath = DisplayedServerPath;
1341 UsedServer = -1;
1346 string s = CI18N::get("uiLoginGetFile") + " " + NLMISC::CFile::getFilename(srcName);
1347 setState(true, s);
1349 // get the new file
1350 downloadFile (serverPath+srcName, dstName, progress);
1352 downloadSuccess = true;
1354 catch (const EPatchDownloadException& e)
1356 //nlwarning("EXCEPTION CATCH: getServerFile() failed - try to find an alternative: %i: %s",UsedServer,PatchServers[UsedServer].DisplayedServerPath.c_str());
1358 nlwarning("EXCEPTION CATCH: getServerFile() failed - try to find an alternative :");
1359 nlwarning("%i", UsedServer);
1360 if (UsedServer >= 0 && UsedServer < (int) PatchServers.size())
1362 nlwarning("%s", PatchServers[UsedServer].DisplayedServerPath.c_str());
1365 // if emergency patch server, this is a real issue, rethrow exception
1366 if (UsedServer < 0)
1368 string s = CI18N::get("uiDLFailed");
1369 setState(true, s);
1371 throw Exception(e.what());
1374 string s = CI18N::get("uiDLURIFailed") + " " + serverDisplayPath;
1375 setState(true, s);
1377 // this server is unavailable
1378 PatchServers[UsedServer].Available = false;
1380 sint nextServer = (UsedServer+1) % PatchServers.size();
1382 while (nextServer != UsedServer && !PatchServers[nextServer].Available)
1383 nextServer = (nextServer+1) % PatchServers.size();
1385 // scanned all servers? use alternative
1386 if (nextServer == UsedServer)
1388 string s = CI18N::get("uiNoMoreURI");
1389 setState(true, s);
1390 UsedServer = -1;
1391 nlwarning("EXCEPTION CATCH: getServerFile() failed - no alternative found");
1393 else
1395 UsedServer = nextServer;
1396 nlwarning("EXCEPTION CATCH: getServerFile() failed - trying server: %i: %s",UsedServer,PatchServers[UsedServer].DisplayedServerPath.c_str());
1401 // decompress it
1402 if (bZipped)
1403 decompressFile (dstName);
1406 // ****************************************************************************
1407 void CPatchManager::downloadFileWithCurl (const string &source, const string &dest, NLMISC::IProgressCallback *progress)
1409 DownloadInProgress = true;
1412 #ifdef USE_CURL
1413 string s = CI18N::get("uiDLWithCurl") + " " + CFile::getFilename(dest);
1414 setState(true, s);
1416 // user agent = nel_launcher
1418 CURL *curl;
1419 CURLcode res;
1421 string sTranslate = CI18N::get("uiLoginGetFile") + " " + NLMISC::CFile::getFilename (source);
1422 setState(true, sTranslate);
1423 CurrentFile = NLMISC::CFile::getFilename (source);
1425 curl_global_init(CURL_GLOBAL_ALL);
1426 curl = curl_easy_init();
1427 if(curl == NULL)
1429 // file not found, delete local file
1430 throw Exception ("curl init failed");
1433 curl_easy_setopt(curl, CURLOPT_NOPROGRESS, 0);
1434 curl_easy_setopt(curl, CURLOPT_PROGRESSFUNCTION, downloadProgressFunc);
1435 curl_easy_setopt(curl, CURLOPT_PROGRESSDATA, (void *) progress);
1436 curl_easy_setopt(curl, CURLOPT_URL, source.c_str());
1437 if (source.length() > 8 && (source[4] == 's' || source[4] == 'S')) // 01234 https
1439 NLWEB::CCurlCertificates::addCertificateFile("cacert.pem");
1440 NLWEB::CCurlCertificates::useCertificates(curl);
1441 curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 1L);
1442 curl_easy_setopt(curl, CURLOPT_SSL_VERIFYHOST, 2L);
1445 // create the local file
1446 if (NLMISC::CFile::fileExists(dest))
1448 setRWAccess(dest, false);
1449 NLMISC::CFile::deleteFile(dest.c_str());
1452 FILE *fp = nlfopen (dest, "wb");
1454 if (fp == NULL)
1456 curl_easy_setopt(curl, CURLOPT_PROGRESSDATA, NULL);
1457 throw Exception ("Can't open file '%s' for writing: code=%d %s (error code 37)", dest.c_str (), errno, strerror(errno));
1460 curl_easy_setopt(curl, CURLOPT_WRITEDATA, fp);
1461 curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, fwrite);
1463 //CurrentFilesToGet++;
1465 res = curl_easy_perform(curl);
1467 curl_easy_setopt(curl, CURLOPT_PROGRESSDATA, NULL);
1469 long r;
1470 curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &r);
1472 curl_easy_cleanup(curl);
1474 bool diskFull = ferror(fp) && errno == 28 /*ENOSPC*/;
1476 fclose(fp);
1477 curl_global_cleanup();
1479 CurrentFile.clear();
1481 if (diskFull)
1483 NLMISC::CFile::deleteFile(dest.c_str());
1484 throw NLMISC::EDiskFullError(dest);
1487 if(CURLE_WRITE_ERROR == res)
1489 // file not found, delete local file
1490 NLMISC::CFile::deleteFile(dest.c_str());
1491 throw NLMISC::EWriteError(dest);
1494 if(CURLE_FTP_COULDNT_RETR_FILE == res)
1496 // file not found, delete local file
1497 NLMISC::CFile::deleteFile(dest.c_str());
1498 throw EPatchDownloadException (NLMISC::toString("curl download failed: (ec %d %d)", res, r));
1501 if(CURLE_OK != res)
1503 NLMISC::CFile::deleteFile(dest.c_str());
1504 throw EPatchDownloadException (NLMISC::toString("curl download failed: (ec %d %d)", res, r));
1507 if(r == 404)
1509 // file not found, delete it
1510 NLMISC::CFile::deleteFile(dest.c_str());
1511 throw EPatchDownloadException (NLMISC::toString("curl download failed: (ec %d %d)", res, r));
1514 if(r < 200 || r >= 300)
1516 // file not found, delete it
1517 NLMISC::CFile::deleteFile(dest.c_str());
1518 throw EPatchDownloadException (NLMISC::toString("curl download failed: (ec %d %d)", res, r));
1521 #else
1522 throw Exception("USE_CURL is not defined, no curl method");
1523 #endif
1525 catch(...)
1527 DownloadInProgress = false;
1528 throw;
1530 if (progress)
1532 // set progress to 1
1533 validateProgress((void *) progress, 1, 1, 0, 0);
1535 DownloadInProgress = false;
1538 // ****************************************************************************
1539 void CPatchManager::downloadFile (const string &source, const string &dest, NLMISC::IProgressCallback *progress)
1541 // For the moment use only curl
1542 const string sourceLower = toLowerAscii(source.substr(0, 6));
1544 if (startsWith(sourceLower, "http:")
1545 || startsWith(sourceLower, "https:")
1546 || startsWith(sourceLower, "ftp:")
1547 || startsWith(sourceLower, "file:"))
1549 nldebug("Download patch file %s", source.c_str());
1550 downloadFileWithCurl(source, dest, progress);
1552 else
1554 if (!NLMISC::CFile::copyFile(dest, source, false, progress))
1556 if (errno == 28)
1558 throw NLMISC::EDiskFullError(dest);
1560 throw Exception ("cannot copy file %s to %s", source.c_str(), dest.c_str());
1565 // ****************************************************************************
1566 // TODO : Review this uncompress routine to uncompress in a temp file before overwriting destination file
1568 void CPatchManager::decompressFile (const string &filename)
1570 string sTranslate = CI18N::get("uiDecompressing") + " " + NLMISC::CFile::getFilename(filename);
1571 setState(true, sTranslate);
1573 //if(isVerboseLog()) nlinfo("Calling gzopen('%s','rb')", filename.c_str());
1574 gzFile gz = gzopen (filename.c_str (), "rb");
1575 if (gz == NULL)
1577 string err = toString("Can't open compressed file '%s' : ", filename.c_str());
1578 if(errno == 0)
1580 // gzerror
1581 int gzerrno;
1582 const char *gzerr = gzerror (gz, &gzerrno);
1583 err += toString("code=%d %s", gzerrno, gzerr);
1585 else
1587 err += toString("code=%d %s", errno, strerror (errno));
1589 err += " (error code 31)";
1590 deleteFile (filename);
1591 throw Exception (err);
1594 string dest = filename.substr(0, filename.size ()-4);
1595 setRWAccess(dest, false);
1596 //if(isVerboseLog()) nlinfo("Calling nlfopen('%s','wb')", dest.c_str());
1597 FILE *fp = nlfopen (dest, "wb");
1598 if (fp == NULL)
1600 string err = toString("Can't open file '%s' : code=%d %s, (error code 32)", dest.c_str(), errno, strerror(errno));
1602 gzclose(gz);
1603 deleteFile (filename);
1604 throw Exception (err);
1607 //if(isVerboseLog()) nlinfo("Entering the while loop decompression");
1609 uint32 currentSize = 0;
1610 uint8 buffer[10000];
1611 while (!gzeof(gz))
1613 //if(isVerboseLog()) nlinfo("Calling gzread");
1614 int res = gzread (gz, buffer, 10000);
1615 //if(isVerboseLog()) nlinfo("gzread returns %d", res);
1616 if (res == -1)
1618 int gzerrno;
1619 const char *gzerr = gzerror (gz, &gzerrno);
1620 gzclose(gz);
1621 fclose(fp);
1622 //deleteFile (filename);
1623 throw Exception ("Can't read compressed file '%s' (after %d bytes) : code=%d %s, (error code 33)", filename.c_str(), currentSize, gzerrno, gzerr);
1626 currentSize += res;
1628 //if(isVerboseLog()) nlinfo("Calling fwrite for %d bytes", res);
1629 int res2 = (int)fwrite (buffer, 1, res, fp);
1630 //if(isVerboseLog()) nlinfo("fwrite returns %d", res2);
1631 if (res2 != res)
1633 bool diskFull = (errno == 28 /* ENOSPC */);
1634 string err = toString("Can't write file '%s' : code=%d %s (error code 34)", dest.c_str(), errno, strerror(errno));
1636 gzclose(gz);
1637 fclose(fp);
1638 deleteFile (filename);
1639 if (diskFull)
1641 throw NLMISC::EDiskFullError(err);
1643 else
1645 throw Exception (err);
1650 //if(isVerboseLog()) nlinfo("Exiting the while loop decompression");
1652 //if(isVerboseLog()) nlinfo("Calling gzclose");
1653 gzclose(gz);
1654 //if(isVerboseLog()) nlinfo("Calling fclose");
1655 fclose(fp);
1656 deleteFile(filename);
1658 //if(isVerboseLog()) nlinfo("Exiting the decompressing file");
1661 // ****************************************************************************
1662 void CPatchManager::applyDate (const string &sFilename, uint32 nDate)
1664 // change the file time
1665 if(nDate != 0)
1667 setRWAccess(sFilename, false);
1668 string s = CI18N::get("uiChangeDate") + " " + NLMISC::CFile::getFilename(sFilename) + " " + timestampToHumanReadable(NLMISC::CFile::getFileModificationDate (sFilename)) +
1669 " -> " + timestampToHumanReadable(nDate);
1670 setState(true,s);
1672 if (!NLMISC::CFile::setFileModificationDate(sFilename, nDate))
1674 int err = NLMISC::getLastError();
1675 s = CI18N::get("uiChgDateErr") + " " + CFile::getFilename(sFilename) + " (" + toString(err) + ", " + formatErrorMessage(err) + ")";
1676 setState(true,s);
1678 s = CI18N::get("uiNowDate") + " " + CFile::getFilename(sFilename) + " " + timestampToHumanReadable(NLMISC::CFile::getFileModificationDate (sFilename));
1679 setState(true,s);
1683 // ****************************************************************************
1684 // Get all the patches that need to be applied to a file from the description of this file given by the server
1685 void CPatchManager::getPatchFromDesc(SFileToPatch &ftpOut, const CBNPFile &fIn, bool forceCheckSumTest)
1687 uint32 j;
1688 const CBNPFile rFile = fIn;
1689 const string &rFilename = rFile.getFileName();
1690 string sFilePath;
1691 bool inPatchDir = false;
1692 // first see if there's a version that was downloaded from the background downloader
1693 if (NLMISC::CFile::fileExists(ClientPatchPath + rFilename + ".tmp"))
1695 sFilePath = ClientPatchPath + rFilename + ".tmp";
1696 ftpOut.SrcFileName = sFilePath;
1697 inPatchDir = true;
1700 bool needUnpack = false;
1701 const CBNPCategory *cat = DescFile.getCategories().getCategoryFromFile(rFilename);
1702 if (cat)
1704 needUnpack = !cat->getUnpackTo().empty();
1706 else
1708 nlwarning("Can't find file category for %s:", rFilename.c_str());
1711 // Does the BNP exists ?
1712 // following lines added by Sadge to ensure that the correct file is patched
1713 // Only look in data path if the file should not be unpack (otherwise it should only remains in the "unpack" directory)
1714 if (!needUnpack)
1716 if (sFilePath.empty())
1718 if (NLMISC::CFile::fileExists(WritableClientDataPath + rFilename))
1720 // if file exists in writable directory, use it
1721 sFilePath = WritableClientDataPath + rFilename;
1723 else if (NLMISC::CFile::fileExists(ReadableClientDataPath + rFilename))
1725 // if file exists in readable directory, use it
1726 sFilePath = ReadableClientDataPath + rFilename;
1731 if (sFilePath.empty() && NLMISC::CFile::fileExists(ClientPatchPath + rFilename))
1733 sFilePath = ClientPatchPath + rFilename;
1736 // following lines removed by Sadge to ensure that the correct file is patched
1737 // string sFilePath = CPath::lookup(rFilename, false, false);
1738 // if (sFilePath.empty())
1739 // {
1740 // if (NLMISC::CFile::fileExists(ClientPatchPath + rFilename))
1741 // sFilePath = ClientPatchPath + rFilename;
1742 // }
1744 // if file not found anywhere
1745 if (sFilePath.empty())
1747 ftpOut.FileName = rFilename;
1748 ftpOut.LocalFileToDelete = false;
1749 ftpOut.LocalFileExists = false;
1750 // It happens some time (maybe a bug) that the versionCount is 0... =>
1751 // it happens if the BNP file is empty (8 bytes)
1752 ftpOut.FinalFileSize = EmptyBnpFileSize;
1753 // BNP does not exists : get all the patches version
1754 for (j = 0; j < rFile.versionCount(); ++j)
1756 ftpOut.Patches.push_back(rFile.getVersion(j).getVersionNumber());
1757 ftpOut.PatcheSizes.push_back(rFile.getVersion(j).getPatchSize());
1758 ftpOut.LastFileDate = rFile.getVersion(j).getTimeStamp();
1759 ftpOut.FinalFileSize = rFile.getVersion(j).getFileSize();
1760 ftpOut.SZFileSize = rFile.getVersion(j).get7ZFileSize();
1763 else
1765 // The local BNP file exists : find its version
1766 uint32 nLocalSize = NLMISC::CFile::getFileSize(sFilePath);
1767 uint32 nLocalTime = NLMISC::CFile::getFileModificationDate(sFilePath);
1768 // From the couple time, size look the version of the file
1769 uint32 nVersionFound = 0xFFFFFFFF;
1770 // If forceChecksum is wanted (slow), then don't do the test with filesize/date
1771 if(!forceCheckSumTest)
1773 for (j = 0; j < rFile.versionCount(); ++j)
1775 const CBNPFileVersion &rVersion = rFile.getVersion(j);
1776 uint32 nServerSize = rVersion.getFileSize();
1777 uint32 nServerTime = rVersion.getTimeStamp();
1778 // Does the time and size match a version ?
1779 if ((nServerSize == nLocalSize) && (abs((sint32)(nServerTime - nLocalTime)) <= 2) )
1781 nVersionFound = rVersion.getVersionNumber();
1782 // break; // ace -> get the last good version (if more than one version of the same file exists)
1787 // If the version cannot be found with size and time try with sha1
1788 if (nVersionFound == 0xFFFFFFFF)
1790 string sTranslate = CI18N::get("uiCheckInt") + " " + rFilename;
1791 setState(true, sTranslate);
1792 CHashKey hkLocalSHA1 = getSHA1(sFilePath);
1793 for (j = 0; j < rFile.versionCount(); ++j)
1795 const CBNPFileVersion &rVersion = rFile.getVersion(j);
1796 CHashKey hkServerSHA1 = rVersion.getHashKey();
1797 // Does the sha1 match a version ?
1798 if (hkServerSHA1 == hkLocalSHA1)
1800 nVersionFound = rVersion.getVersionNumber();
1801 applyDate(sFilePath, rVersion.getTimeStamp());
1802 // break; // ace -> same as above
1807 // No version available found
1808 if (nVersionFound == 0xFFFFFFFF)
1810 string sTranslate = CI18N::get("uiNoVersionFound");
1811 setState(true, sTranslate);
1812 // Get all patches from beginning (first patch is reference file)
1813 ftpOut.FileName = rFilename;
1814 ftpOut.LocalFileToDelete = true;
1815 ftpOut.LocalFileExists = !inPatchDir;
1816 // It happens some time (maybe a bug) that the versionCount is 0... =>
1817 // it happens if the BNP file is empty (8 bytes)
1818 ftpOut.FinalFileSize = EmptyBnpFileSize;
1819 // Get all the patches version
1820 for (j = 0; j < rFile.versionCount(); ++j)
1822 ftpOut.Patches.push_back(rFile.getVersion(j).getVersionNumber());
1823 ftpOut.PatcheSizes.push_back(rFile.getVersion(j).getPatchSize());
1824 ftpOut.LastFileDate = rFile.getVersion(j).getTimeStamp();
1825 ftpOut.FinalFileSize = rFile.getVersion(j).getFileSize();
1826 ftpOut.SZFileSize = rFile.getVersion(j).get7ZFileSize();
1829 else // A version of the file has been found
1831 string sTranslate = CI18N::get("uiVersionFound") + " " + toString(nVersionFound);
1832 setState(true, sTranslate);
1833 // Get All patches from this version !
1834 ftpOut.FileName = rFilename;
1835 ftpOut.LocalFileToDelete = false;
1836 ftpOut.LocalFileExists = !inPatchDir;
1837 // Go to the version
1838 for (j = 0; j < rFile.versionCount(); ++j)
1839 if (rFile.getVersion(j).getVersionNumber() == nVersionFound)
1840 break;
1842 nlassert(j != rFile.versionCount()); // Not normal if we cant find the version we found previously
1844 // Point on the next version
1845 j++;
1846 // If there are newer versions
1847 if (j != rFile.versionCount())
1849 // Add all version until the last one
1850 for (; j < rFile.versionCount(); ++j)
1852 ftpOut.Patches.push_back(rFile.getVersion(j).getVersionNumber());
1853 ftpOut.PatcheSizes.push_back(rFile.getVersion(j).getPatchSize());
1854 ftpOut.LastFileDate = rFile.getVersion(j).getTimeStamp();
1855 ftpOut.SZFileSize = rFile.getVersion(j).get7ZFileSize();
1858 // Else this file is up to date !
1860 // For info, get its final file size
1861 ftpOut.FinalFileSize= rFile.getVersion(rFile.versionCount()-1).getFileSize();
1863 } // end of else local BNP file exists
1866 // ****************************************************************************
1867 bool CPatchManager::bnpUnpack(const string &srcBigfile, const string &dstPath, vector<string> &vFilenames)
1869 nldebug("bnpUnpack: srcBigfile=%s", srcBigfile.c_str());
1870 string SourceName, DestPath;
1872 // following lines added by Sadge to ensure that the correct file gets patched
1873 // if (NLMISC::CFile::fileExists(ClientDataPath + srcBigfile)) SourceName = ClientDataPath + srcBigfile;
1874 // else if (NLMISC::CFile::fileExists(srcBigfile)) SourceName = ClientDataPath + srcBigfile;
1875 SourceName= srcBigfile;
1877 // following lines removed by Sadge to ensure that the correct file gets patched
1878 // SourceName = CPath::lookup(srcBigfile, false, false);
1879 // if (SourceName.empty())
1880 // SourceName = ClientPatchPath + srcBigfile;
1882 if (dstPath.empty())
1883 DestPath = ClientRootPath;
1884 else
1885 DestPath = CPath::standardizePath (dstPath);
1887 string s = CI18N::get("uiUnpack") + " " + NLMISC::CFile::getFilename(SourceName);
1888 setState(true,s);
1890 // Read Header of the BNP File
1891 CBigFile::BNP bnpFile;
1892 bnpFile.BigFileName = SourceName;
1894 if (!bnpFile.readHeader())
1896 string s = CI18N::get("uiUnpackErrHead") + " " + CFile::getFilename(SourceName);
1897 setState(true,s);
1898 return false;
1901 // Unpack
1902 if (!bnpFile.unpack(DestPath))
1903 return false;
1905 // Return names
1907 vFilenames.clear();
1908 for (uint32 i = 0; i < bnpFile.SFiles.size(); ++i)
1909 vFilenames.push_back(bnpFile.SFiles[i].Name);
1912 return true;
1916 // ****************************************************************************
1917 int CPatchManager::downloadProgressFunc(void *foo, double t, double d, double ultotal, double ulnow)
1919 if (d != t)
1921 // In the case of progress = 1, don't update because, this will be called in case of error to signal the end of the download, though
1922 // no download actually occurred. Instead, we set progress to 1.f at the end of downloadWithCurl if everything went fine
1923 return validateProgress(foo, t, d, ultotal, ulnow);
1925 return 0;
1928 // ****************************************************************************
1929 int CPatchManager::validateProgress(void *foo, double t, double d, double /* ultotal */, double /* ulnow */)
1931 static std::vector<std::string> units;
1933 if (units.empty())
1935 units.push_back(CI18N::get("uiByte"));
1936 units.push_back(CI18N::get("uiKb"));
1937 units.push_back(CI18N::get("uiMb"));
1940 CPatchManager *pPM = CPatchManager::getInstance();
1941 double pour1 = t!=0.0?d*100.0/t:0.0;
1942 string sTranslate = CI18N::get("uiLoginGetFile") + toString(" %s : %s / %s (%.02f %%)", NLMISC::CFile::getFilename(pPM->CurrentFile).c_str(),
1943 NLMISC::bytesToHumanReadableUnits((uint64)d, units).c_str(), NLMISC::bytesToHumanReadableUnits((uint64)t, units).c_str(), pour1);
1944 pPM->setState(false, sTranslate);
1945 if (foo)
1947 ((NLMISC::IProgressCallback *) foo)->progress((float) (t != 0 ? d / t : 0));
1949 return 0;
1952 // ****************************************************************************
1953 void CPatchManager::MyPatchingCB::progress(float f)
1955 CPatchManager *pPM = CPatchManager::getInstance();
1956 double p = 100.0*f;
1957 string sTranslate = CI18N::get("uiApplyingDelta") + toString(" %s (%.02f %%)", CFile::getFilename(patchFilename).c_str(), p);
1958 pPM->setState(false, sTranslate);
1961 // ***************************************************************************
1962 void CPatchManager::startScanDataThread()
1964 if (ScanDataThread != NULL)
1966 nlwarning ("scan data thread is already running");
1967 return;
1969 if (Thread != NULL)
1971 nlwarning ("a thread is already running");
1972 return;
1975 _ErrorMessage.clear();
1977 // Reset result
1978 clearDataScanLog();
1980 // Read now the client version and Desc File.
1981 readClientVersionAndDescFile();
1983 // start thread
1984 ScanDataThread = new CScanDataThread();
1985 nlassert (ScanDataThread != NULL);
1987 Thread = IThread::create (ScanDataThread);
1988 nlassert (Thread != NULL);
1989 Thread->start ();
1992 // ****************************************************************************
1993 bool CPatchManager::isScanDataThreadEnded(bool &ok)
1995 if (ScanDataThread == NULL)
1997 ok = false;
1998 return true;
2001 bool end = ScanDataThread->Ended;
2002 if (end)
2004 ok = ScanDataThread->CheckOk;
2005 stopScanDataThread();
2008 return end;
2011 // ****************************************************************************
2012 void CPatchManager::stopScanDataThread()
2014 if(ScanDataThread && Thread)
2016 Thread->wait();
2017 delete Thread;
2018 Thread = NULL;
2019 delete ScanDataThread;
2020 ScanDataThread = NULL;
2024 // ***************************************************************************
2025 void CPatchManager::askForStopScanDataThread()
2027 if(!ScanDataThread)
2028 return;
2030 ScanDataThread->AskForCancel= true;
2033 // ***************************************************************************
2034 uint CPatchManager::applyScanDataResult()
2036 // if still running, abort
2037 if(ScanDataThread)
2038 return 0;
2040 uint numError= 0;
2043 TSyncDataScanState::CAccessor ac(&DataScanState);
2044 CDataScanState &val= ac.value();
2045 numError= (uint)val.FilesWithScanDataError.size();
2047 // Touch the files with error (will be reloaded at next patch)
2048 for(uint i=0;i<numError;i++)
2050 SFileToPatch &ftp= val.FilesWithScanDataError[i];
2052 // if the file was not found (just loggued for information)
2053 if(!ftp.LocalFileExists)
2054 continue;
2056 // get file path
2057 // following lines added by Sadge to ensure that the correct file gets patched
2058 string sFilePath;
2059 if (NLMISC::CFile::fileExists(WritableClientDataPath + ftp.FileName)) sFilePath = WritableClientDataPath + ftp.FileName;
2060 if (sFilePath.empty() && NLMISC::CFile::fileExists(ReadableClientDataPath + ftp.FileName)) sFilePath = ReadableClientDataPath + ftp.FileName;
2061 if (sFilePath.empty() && NLMISC::CFile::fileExists(ClientPatchPath + ftp.FileName)) sFilePath = ClientPatchPath + ftp.FileName;
2063 // following lines removed by Sadge to ensure that the correct file gets patched
2064 // string sFilePath = CPath::lookup(ftp.FileName, false, false);
2065 // if (sFilePath.empty())
2066 // {
2067 // if (NLMISC::CFile::fileExists(ClientPatchPath + ftp.FileName))
2068 // sFilePath = ClientPatchPath + ftp.FileName;
2069 // }
2071 // Reset to a dummy date, so the patch will be fully/checked/patched next time
2072 if(!sFilePath.empty())
2073 applyDate(sFilePath, DefaultResetDate);
2074 else
2075 nlwarning("File '%s' Not Found. should exist...", ftp.FileName.c_str());
2079 return numError;
2082 // ***************************************************************************
2083 bool CPatchManager::getDataScanLog(string &text)
2085 text.clear();
2086 bool changed= false;
2088 TSyncDataScanState::CAccessor ac(&DataScanState);
2089 CDataScanState &val= ac.value();
2090 changed= val.Changed;
2091 // if changed, build the log
2092 if(changed)
2094 for(uint i=0;i<val.FilesWithScanDataError.size();i++)
2096 string str;
2097 getCorruptedFileInfo(val.FilesWithScanDataError[i], str);
2098 text+= str + "\n";
2101 // then reset
2102 val.Changed= false;
2105 return changed;
2108 // ***************************************************************************
2109 void CPatchManager::addDataScanLogCorruptedFile(const SFileToPatch &ftp)
2112 TSyncDataScanState::CAccessor ac(&DataScanState);
2113 CDataScanState &val= ac.value();
2114 val.FilesWithScanDataError.push_back(ftp);
2115 val.Changed= true;
2119 // ***************************************************************************
2120 void CPatchManager::clearDataScanLog()
2123 TSyncDataScanState::CAccessor ac(&DataScanState);
2124 CDataScanState &val= ac.value();
2125 val.FilesWithScanDataError.clear();
2126 val.Changed= true;
2130 // ***************************************************************************
2131 void CPatchManager::getCorruptedFileInfo(const SFileToPatch &ftp, string &sTranslate)
2133 sTranslate = CI18N::get("uiCorruptedFile") + " " + ftp.FileName + " (" +
2134 toString("%.1f ", (float)ftp.FinalFileSize/1000000.f) + CI18N::get("uiMb") + ")";
2138 // ****************************************************************************
2139 // ****************************************************************************
2140 // ****************************************************************************
2141 // CCheckThread
2142 // ****************************************************************************
2143 // ****************************************************************************
2144 // ****************************************************************************
2146 // ****************************************************************************
2147 CCheckThread::CCheckThread(bool includeBackgroundPatch)
2149 Ended = false;
2150 CheckOk = false;
2151 TotalFileToCheck = 0;
2152 CurrentFileChecked = 0;
2153 IncludeBackgroundPatch = includeBackgroundPatch;
2154 StopAsked = false;
2157 // ****************************************************************************
2158 void CCheckThread::run ()
2160 nlwarning("CCheckThread::start");
2161 StopAsked = false;
2162 CPatchManager *pPM = CPatchManager::getInstance();
2163 pPM->MustLaunchBatFile = false;
2166 nlwarning("CCheckThread : get version");
2167 uint32 i, j, k;
2168 // Check if the client version is the same as the server version
2169 string sClientVersion = pPM->getClientVersion();
2170 string sServerVersion = pPM->getServerVersion();
2171 string sTranslate = CI18N::get("uiClientVersion") + " (" + sClientVersion + ") ";
2172 sTranslate += CI18N::get("uiServerVersion") + " (" + sServerVersion + ")";
2173 pPM->setState(true, sTranslate);
2175 if (sServerVersion.empty())
2177 // No need to patch
2178 CheckOk = true;
2179 Ended = true;
2180 return;
2183 sint32 nServerVersion, nClientVersion;
2184 fromString(sServerVersion, nServerVersion);
2185 fromString(sClientVersion, nClientVersion);
2187 if (nClientVersion != nServerVersion)
2189 // first, try in the version subdirectory
2192 pPM->DescFilename = toString("%05d/ryzom_%05d.idx", nServerVersion, nServerVersion);
2193 // The client version is different from the server version : download new description file
2194 pPM->getServerFile(pPM->DescFilename, false); // For the moment description file is not zipped
2196 catch (...)
2198 // fallback to patch root directory
2199 pPM->DescFilename = toString("ryzom_%05d.idx", nServerVersion);
2200 // The client version is different from the server version : download new description file
2201 pPM->getServerFile(pPM->DescFilename, false); // For the moment description file is not zipped
2205 nlwarning("CCheckThread : read description files");
2207 // Read the description file
2208 pPM->readDescFile(nServerVersion);
2210 nlwarning("CCheckThread : check files");
2212 // For all bnp in the description file get all patches to apply
2213 // depending on the version of the client bnp files
2214 const CBNPFileSet &rDescFiles = pPM->DescFile.getFiles();
2215 pPM->FilesToPatch.clear();
2216 TotalFileToCheck = rDescFiles.fileCount();
2217 for (i = 0; i < rDescFiles.fileCount(); ++i)
2219 CPatchManager::SFileToPatch ftp;
2220 sTranslate = CI18N::get("uiCheckingFile") + " " + rDescFiles.getFile(i).getFileName();
2221 pPM->setState(true, sTranslate);
2222 // get list of patch to apply to this file. don't to a full checksum test if possible
2223 nlwarning(rDescFiles.getFile(i).getFileName().c_str());
2224 pPM->getPatchFromDesc(ftp, rDescFiles.getFile(i), false);
2225 // add the file if there are some patches to apply, or if an already patched version was found in the unpack directory
2226 if (!ftp.Patches.empty() || (IncludeBackgroundPatch && !ftp.SrcFileName.empty()))
2228 pPM->FilesToPatch.push_back(ftp);
2229 sTranslate = CI18N::get("uiNeededPatches") + " " + toString (ftp.Patches.size());
2230 pPM->setState(true, sTranslate);
2232 CurrentFileChecked = i;
2235 // Here we got all the files to patch in FilesToPatch and all the versions that must be obtained
2236 // Now we have to get the optional categories
2237 const CBNPCategorySet &rDescCats = pPM->DescFile.getCategories();
2238 pPM->OptionalCat.clear();
2239 for (i = 0; i < rDescCats.categoryCount(); ++i)
2241 // For all optional categories check if there is a 'file to patch' in it
2242 const CBNPCategory &rCat = rDescCats.getCategory(i);
2243 if (rCat.isOptional())
2244 for (j = 0; j < rCat.fileCount(); ++j)
2246 const string &rFilename = rCat.getFile(j);
2247 bool bAdded = false;
2248 for (k = 0; k < pPM->FilesToPatch.size(); ++k)
2250 if (stricmp(pPM->FilesToPatch[k].FileName.c_str(), rFilename.c_str()) == 0)
2252 pPM->OptionalCat.push_back(rCat.getName());
2253 bAdded = true;
2254 break;
2257 if (bAdded)
2258 break;
2262 // For all categories that required an optional category if the cat required is present the category that
2263 // reference it must be present
2264 for (i = 0; i < rDescCats.categoryCount(); ++i)
2266 // For all optional categories check if there is a 'file to patch' in it
2267 const CBNPCategory &rCat = rDescCats.getCategory(i);
2268 if (rCat.isOptional() && !rCat.getCatRequired().empty())
2270 // Does the rCat is already present ?
2271 bool bFound = false;
2272 for (j = 0; j < pPM->OptionalCat.size(); ++j)
2274 if (rCat.getName() == pPM->OptionalCat[j])
2276 bFound = true;
2277 break;
2281 if (!bFound)
2283 // rCat is not present but perhaps its required cat is present
2284 const string &sCatReq = rCat.getCatRequired();
2285 for (j = 0; j < pPM->OptionalCat.size(); ++j)
2287 if (sCatReq == pPM->OptionalCat[j])
2289 // Required Cat present -> Add the category rCat
2290 pPM->OptionalCat.push_back(rCat.getName());
2291 break;
2299 // Delete categories optional cat that are hidden
2300 for (i = 0; i < rDescCats.categoryCount(); ++i)
2302 // For all optional categories check if there is a 'file to patch' in it
2303 const CBNPCategory &rCat = rDescCats.getCategory(i);
2304 if (rCat.isOptional() && rCat.isHidden())
2306 // Does the rCat is present ?
2307 for (j = 0; j < pPM->OptionalCat.size(); ++j)
2309 if (rCat.getName() == pPM->OptionalCat[j])
2311 // remove it
2312 /*#ifdef RY_BG_DOWNLOADER
2313 // fixme : strange stlport link error for the background downloader when using erase ...
2314 std::copy(pPM->OptionalCat.begin() + j + 1, pPM->OptionalCat.end(), pPM->OptionalCat.begin()+j);
2315 pPM->OptionalCat.resize(pPM->OptionalCat.size() - 1);
2316 #else*/
2317 pPM->OptionalCat.erase(pPM->OptionalCat.begin()+j);
2318 //#endif
2319 break;
2325 // Get all extract to category and check files inside the bnp with real files
2326 for (i = 0; i < rDescCats.categoryCount(); ++i)
2328 // For all optional categories check if there is a 'file to patch' in it
2329 const CBNPCategory &rCat = rDescCats.getCategory(i);
2330 if (!rCat.getUnpackTo().empty())
2332 for (j = 0; j < rCat.fileCount(); ++j)
2334 string sBNPFilename = pPM->ClientPatchPath + rCat.getFile(j);
2336 sTranslate = CI18N::get("uiCheckInBNP") + " " + rCat.getFile(j);
2337 pPM->setState(true, sTranslate);
2338 CBigFile::BNP bnpFile;
2339 bnpFile.BigFileName = sBNPFilename;
2341 if (bnpFile.readHeader())
2343 // read the file inside the bnp and calculate the sha1
2344 FILE *bnp = nlfopen (sBNPFilename, "rb");
2345 if (bnp != NULL)
2347 for (uint32 k = 0; k < bnpFile.SFiles.size(); ++k)
2349 const CBigFile::SBNPFile &rBNPFile = bnpFile.SFiles[k];
2350 // Is the real file exists ?
2351 string sRealFilename = rCat.getUnpackTo() + rBNPFile.Name;
2352 if (NLMISC::CFile::fileExists(sRealFilename))
2354 // Yes compare the sha1 with the sha1 of the BNP File
2355 CHashKey sha1BNPFile;
2356 nlfseek64 (bnp, rBNPFile.Pos, SEEK_SET);
2357 uint8 *pPtr = new uint8[rBNPFile.Size];
2358 if (fread (pPtr, rBNPFile.Size, 1, bnp) != 1)
2360 delete [] pPtr;
2361 break;
2364 sha1BNPFile = getSHA1(pPtr, rBNPFile.Size);
2365 delete [] pPtr;
2366 CHashKey sha1RealFile = getSHA1(sRealFilename, true);
2367 if ( ! (sha1RealFile == sha1BNPFile))
2369 sTranslate = CI18N::get("uiSHA1Diff") + " " + rBNPFile.Name;
2370 pPM->setState(true, sTranslate);
2371 pPM->MustLaunchBatFile = true;
2374 else
2376 // File dest do not exist
2377 sTranslate = CI18N::get("uiSHA1Diff") + " " + rBNPFile.Name;
2378 pPM->setState(true, sTranslate);
2379 pPM->MustLaunchBatFile = true;
2383 fclose (bnp);
2385 if (StopAsked)
2387 StopAsked = false;
2388 return;
2395 sTranslate = CI18N::get("uiCheckEndNoErr");
2396 pPM->setState(true, sTranslate);
2397 CheckOk = true;
2398 Ended = true;
2400 catch (const NLMISC::EDiskFullError &)
2402 // more explicit message for this common error case
2403 nlwarning("EXCEPTION CATCH: disk full");
2404 pPM->setState(true, CI18N::get("uiCheckEndWithErr"));
2405 pPM->setErrorMessage(CI18N::get("uiPatchDiskFull"));
2406 CheckOk = false;
2407 Ended = true;
2409 catch (const Exception &e)
2411 nlwarning("EXCEPTION CATCH: CCheckThread::run() failed");
2412 string sTranslate = CI18N::get("uiCheckEndWithErr") + " " + e.what();
2413 pPM->setState(true, CI18N::get("uiCheckEndWithErr"));
2414 pPM->setErrorMessage(sTranslate);
2415 CheckOk = false;
2416 Ended = true;
2420 // ****************************************************************************
2421 // ****************************************************************************
2422 // ****************************************************************************
2423 // CPatchThread
2424 // ****************************************************************************
2425 // ****************************************************************************
2426 // ****************************************************************************
2428 // ****************************************************************************
2429 CPatchThread::CPatchThread(bool commitPatch)
2431 Ended = false;
2432 PatchOk = false;
2433 CurrentFilePatched = 0;
2434 PatchSizeProgress = 0;
2435 _CommitPatch = commitPatch;
2436 StopAsked = false;
2439 // ****************************************************************************
2440 void CPatchThread::clear()
2442 AllFilesToPatch.clear();
2445 // ****************************************************************************
2446 // trap : optimize this if needed
2447 void CPatchThread::add(const CPatchManager::SFileToPatch &ftp)
2449 for (uint32 i = 0; i < AllFilesToPatch.size(); ++i)
2451 if (AllFilesToPatch[i].FileName == ftp.FileName)
2452 return;
2454 AllFilesToPatch.push_back(ftp);
2458 // ****************************************************************************
2459 void CPatchThread::run()
2461 StopAsked = false;
2462 CPatchManager *pPM = CPatchManager::getInstance();
2463 bool bErr = false;
2464 uint32 i;
2466 string sServerVersion = pPM->getServerVersion();
2467 PatchSizeProgress = 0;
2469 if (sServerVersion.empty())
2471 // No need to patch
2472 PatchOk = true;
2473 Ended = true;
2474 return;
2477 // Patch all the files
2478 // If at least one file has been patched relaunch the client
2480 CurrentFilePatched = 0.f;
2482 string sTranslate;
2485 // First do all ref files
2486 // ----------------------
2488 for (i = 0; i < AllFilesToPatch.size(); ++i)
2490 CPatchManager::SFileToPatch &rFTP = AllFilesToPatch[i];
2491 string ext = NLMISC::CFile::getExtension(rFTP.FileName);
2492 if (ext == "ref")
2494 float oldCurrentFilePatched = CurrentFilePatched;
2495 processFile (rFTP);
2496 pPM->MustLaunchBatFile = true;
2497 CurrentFilePatched = oldCurrentFilePatched + 1.f;
2499 if (StopAsked)
2501 StopAsked = false;
2502 return;
2506 // Second do all bnp files
2507 // -----------------------
2509 for (i = 0; i < AllFilesToPatch.size(); ++i)
2511 CPatchManager::SFileToPatch &rFTP = AllFilesToPatch[i];
2513 string ext = NLMISC::CFile::getExtension(rFTP.FileName);
2514 if (ext == "bnp" || ext == "snp")
2516 float oldCurrentFilePatched = CurrentFilePatched;
2517 processFile (rFTP);
2518 pPM->MustLaunchBatFile = true;
2519 CurrentFilePatched = oldCurrentFilePatched + 1.f;
2521 if (StopAsked)
2523 StopAsked = false;
2524 return;
2529 catch (const NLMISC::EDiskFullError &)
2531 // more explicit message for this common error case
2532 nlwarning("EXCEPTION CATCH: CPatchThread::run() Disk Full");
2533 pPM->setState(true, CI18N::get("uiPatchEndWithErr"));
2534 sTranslate = CI18N::get("uiPatchDiskFull");
2535 bErr = true;
2537 catch(const Exception &e)
2539 nlwarning("EXCEPTION CATCH: CPatchThread::run() failed");
2540 pPM->setState(true, string(e.what()));
2541 sTranslate = CI18N::get("uiPatchEndWithErr");
2542 bErr = true;
2546 // Unpack all files with the UnpackTo flag
2547 // ---------------------------------------
2548 // To do that we create a batch file that will copy all files (unpacked to patch directory)
2549 // to the directory we want (the UnpackTo string)
2551 // Recreate batch file
2552 if (!pPM->MustLaunchBatFile && !pPM->getAsyncDownloader())
2554 pPM->deleteFile(pPM->UpdateBatchFilename, false, false);
2557 if (!bErr)
2559 sTranslate = CI18N::get("uiPatchEndNoErr");
2561 else
2563 // Set a more explicit error message
2564 pPM->setErrorMessage(sTranslate);
2567 PatchOk = !bErr;
2568 Ended = true;
2572 class CPatchThreadDownloadProgress : public NLMISC::IProgressCallback
2574 public:
2575 CPatchThread *PatchThread;
2576 float Scale;
2577 float Bias;
2578 uint CurrentFilePatched;
2579 CPatchThreadDownloadProgress() : PatchThread(NULL),
2580 Scale(1.f),
2581 Bias(0.f),
2582 CurrentFilePatched(0)
2585 virtual void progress (float progressValue)
2587 clamp(progressValue, 0.f, 1.f);
2588 nlassert(PatchThread);
2589 //PatchThread->CurrentFilePatched = std::max(PatchThread->CurrentFilePatched, (float) this->CurrentFilePatched + Bias + Scale * progressValue);
2590 PatchThread->CurrentFilePatched = this->CurrentFilePatched + Bias + Scale * progressValue;
2591 CPatchManager::getInstance()->touchState();
2597 // ****************************************************************************
2598 void CPatchThread::processFile (CPatchManager::SFileToPatch &rFTP)
2600 CPatchManager *pPM = CPatchManager::getInstance();
2602 // Source File Name (in writable or readable directory)
2603 string SourceName;
2605 // Destination File Name (in writable directory)
2606 string DestinationName;
2608 if (rFTP.ExtractPath.empty())
2610 DestinationName = pPM->WritableClientDataPath + rFTP.FileName;
2612 if (rFTP.LocalFileExists)
2614 // following lines added by Sadge to ensure that the correct file gets patched
2615 SourceName.clear();
2617 if (NLMISC::CFile::fileExists(pPM->WritableClientDataPath + rFTP.FileName))
2619 SourceName = pPM->WritableClientDataPath + rFTP.FileName;
2621 else if (NLMISC::CFile::fileExists(pPM->ReadableClientDataPath + rFTP.FileName))
2623 SourceName = pPM->ReadableClientDataPath + rFTP.FileName;
2626 // version from previous download
2627 if (SourceName.empty()) throw Exception (std::string("ERROR: Failed to find file: ")+rFTP.FileName);
2629 // following lines removed by Sadge to ensure that the correct file gets patched
2630 // SourceName = CPath::lookup(rFTP.FileName); // exception if file do not exists
2632 else
2634 // note : if file was background downloaded, we have :
2635 // rFTP.LocalFileExists = false
2636 // rFTP.SrcFileName = "unpack/filename.bnp.tmp"
2637 SourceName = DestinationName;
2640 else
2642 SourceName = pPM->ClientPatchPath + rFTP.FileName;
2643 DestinationName = SourceName;
2646 if (rFTP.LocalFileToDelete)
2648 // corrupted or invalid file ? ....
2649 NLMISC::CFile::deleteFile(SourceName);
2650 rFTP.LocalFileExists = false;
2653 string sTranslate;
2654 sTranslate = CI18N::get("uiProcessing") + " " + rFTP.FileName;
2655 pPM->setState(true, sTranslate);
2657 if (pPM->getAsyncDownloader())
2659 if (!rFTP.ExtractPath.empty())
2661 std::string info = rFTP.FileName;
2663 string PatchName = toString("%05d/%s%s", rFTP.Patches[rFTP.Patches.size() - 1], rFTP.FileName.c_str(), ".lzma");
2664 pPM->getAsyncDownloader()->addToDownloadList(PatchName, SourceName, rFTP.LastFileDate, rFTP.ExtractPath, rFTP.SZFileSize, rFTP.FinalFileSize );
2665 return;
2669 std::string tmpSourceName = rFTP.SrcFileName.empty() ? SourceName : rFTP.SrcFileName; // source is same than destination, or possibly
2670 // a patch from a previous background downloader session
2671 if (rFTP.LocalFileToDelete)
2673 // corrupted or invalid file ? ....
2674 rFTP.LocalFileExists = false;
2675 NLMISC::CFile::deleteFile(tmpSourceName);
2678 string OutFilename;
2679 bool usePatchFile = true;
2681 // compute the total size of patch to download
2682 uint32 totalPatchSize = 0;
2683 if (rFTP.Incremental)
2685 for (uint i=0; i<rFTP.PatcheSizes.size(); ++i)
2686 totalPatchSize += rFTP.PatcheSizes[i];
2688 else if (!rFTP.PatcheSizes.empty())
2690 totalPatchSize = rFTP.PatcheSizes.back();
2694 CPatchThreadDownloadProgress progress;
2695 progress.PatchThread = this;
2696 progress.CurrentFilePatched = (uint) floorf(CurrentFilePatched);
2698 // look for the source file, if not present or invalid (not matching
2699 // a known version) or if total patch size greater than half the
2700 // uncompressed final size or if total patch size is greater
2701 // than lzma compressed file, then load the lzma file
2702 if ((rFTP.Incremental && !rFTP.LocalFileExists) // incremental and no base file, we need a complete file
2703 || totalPatchSize > rFTP.FinalFileSize / 2 // patch is too big regarding the final file, patch applying time will be slow
2704 || rFTP.SZFileSize < totalPatchSize) // lzma is smaller than patch !
2706 breakable
2708 usePatchFile = false;
2709 // compute the seven zip filename
2710 string lzmaFile = rFTP.FileName+".lzma";
2712 // download the 7zip file
2715 // first, try in the file version subfolfer
2718 progress.Scale = 1.f;
2719 progress.Bias = 0.f;
2720 if (!rFTP.Patches.empty())
2722 pPM->getServerFile(toString("%05u/", rFTP.Patches.back())+lzmaFile, false, "", &progress);
2724 // else -> file comes from a previous download (with .tmp extension, and is up to date)
2725 // the remaining code will just rename it with good name and exit
2727 catch (const NLMISC::EWriteError &)
2729 // this is a local error, rethrow ...
2730 throw;
2732 catch(...)
2734 // failed with version subfolder, try in the root patch directory
2735 pPM->getServerFile(lzmaFile, false, "", &progress);
2738 catch (const NLMISC::EWriteError &)
2740 // this is a local error, rethrow ...
2741 throw;
2743 catch (...)
2745 // can not load the 7zip file, use normal patching
2746 usePatchFile = true;
2747 break;
2750 OutFilename = pPM->ClientPatchPath + NLMISC::CFile::getFilename(rFTP.FileName);
2751 // try to unpack the file
2754 if (!unpackLZMA(pPM->ClientPatchPath+lzmaFile, OutFilename+".tmp"))
2756 // fallback to standard patch method
2757 usePatchFile = true;
2758 break;
2761 catch (const NLMISC::EWriteError&)
2763 throw;
2765 catch (...)
2767 nlwarning("Failed to unpack lzma file %s", (pPM->ClientPatchPath+lzmaFile).c_str());
2768 // fallback to standard patch method
2769 usePatchFile = true;
2770 break;
2773 if (rFTP.LocalFileExists)
2774 pPM->deleteFile(SourceName);
2776 pPM->deleteFile(pPM->ClientPatchPath+lzmaFile); // delete the archive file
2777 pPM->deleteFile(SourceName, false, false); // File can exists if bad BNP loading
2778 if (_CommitPatch)
2780 pPM->renameFile(OutFilename+".tmp", DestinationName);
2784 if (usePatchFile)
2786 uint32 currentPatchedSize = 0;
2787 for (uint32 j = 0; j < rFTP.Patches.size(); ++j)
2789 // Get the patch
2790 // first, try in the patch subdirectory
2791 string PatchName;
2794 PatchName = toString("%05d/", rFTP.Patches[j]) + rFTP.FileName.substr(0, rFTP.FileName.size()-4) + toString("_%05d", rFTP.Patches[j]) + ".patch";
2795 sTranslate = CI18N::get("uiLoginGetFile") + " " + PatchName;
2796 pPM->setState(true, sTranslate);
2797 progress.Scale = 1.f;
2798 progress.Bias = totalPatchSize != 0 ? (float) currentPatchedSize / totalPatchSize : 0.f;
2799 progress.Scale = totalPatchSize != 0 ? (float) rFTP.PatcheSizes[j] / totalPatchSize : 1.f;
2800 pPM->getServerFile(PatchName, false, "", &progress);
2801 // remove the subfolder name
2802 PatchName = NLMISC::CFile::getFilename(PatchName);
2804 catch (const NLMISC::EWriteError &)
2806 throw;
2808 catch (...)
2810 // fallback to patch root directory
2811 PatchName = rFTP.FileName.substr(0, rFTP.FileName.size()-4);
2812 PatchName += toString("_%05d", rFTP.Patches[j]) + ".patch";
2813 sTranslate = CI18N::get("uiLoginGetFile") + " " + PatchName;
2814 pPM->setState(true, sTranslate);
2815 pPM->getServerFile(PatchName, false, "", &progress);
2818 // Apply the patch
2819 // If the patches are not to be applied on the last version
2820 string SourceNameXD = tmpSourceName;
2821 if (!rFTP.Incremental)
2823 // Some note about non incremental patches :
2824 // Usually, files such as '.exe' or '.dll' do not work well with incremental patch, so it is better
2825 // to apply a single patch from a refrence version to them. (so here we necessarily got
2826 // 'rFTP.Patches.size() == 1' !)
2827 // The reference version itself is incrementally patched, however, and may be rebuilt from time to time
2828 // when the delta to the reference has become too big (but is most of the time < to the sum of equivallent delta patchs)
2829 // The non-incremental final patch (from ref file to final bnp), is guaranteed to be done last
2830 // after the reference file has been updated
2832 // Find the reference file to apply the patch
2833 SourceNameXD = rFTP.FileName;
2834 SourceNameXD = SourceNameXD.substr(0, SourceNameXD.rfind('.'));
2835 SourceNameXD += "_.ref";
2837 if (!_CommitPatch)
2839 // works
2840 std::string tmpRefFile = SourceNameXD + ".tmp";
2841 if (!NLMISC::CFile::fileExists(pPM->ClientPatchPath + tmpRefFile))
2843 // Not found in the patch directory -> version in data directory should be good, or would have been
2844 // detected by the check thread else.
2846 else
2848 SourceNameXD = tmpRefFile; // good ref file download by bg downloader
2852 // following lines added by Sadge to ensure that the correct file gets patched
2853 // string SourceNameXDFull;
2854 // if (NLMISC::CFile::fileExists(pPM->ClientDataPath + SourceNameXD)) SourceNameXDFull = pPM->ClientDataPath + SourceNameXD;
2856 // following lines removed by Sadge to ensure that the correct file gets patched
2857 // string SourceNameXDFull = CPath::lookup(SourceNameXD, false, false);
2858 // if (SourceNameXDFull.empty())
2859 // SourceNameXDFull = pPM->ClientDataPath + SourceNameXD;
2860 // SourceNameXD = SourceNameXDFull;
2861 if (CFile::fileExists(pPM->WritableClientDataPath + SourceNameXD))
2863 SourceNameXD = pPM->WritableClientDataPath + SourceNameXD;
2865 else if (CFile::fileExists(pPM->ReadableClientDataPath + SourceNameXD))
2867 SourceNameXD = pPM->ReadableClientDataPath + SourceNameXD;
2871 PatchName = pPM->ClientPatchPath + PatchName;
2873 string OutFilename = pPM->ClientPatchPath + rFTP.FileName + ".tmp__" + toString(j);
2875 sTranslate = CI18N::get("uiApplyingDelta") + " " + CFile::getFilename(PatchName);
2876 pPM->setState(true, sTranslate);
2878 xDeltaPatch(PatchName, SourceNameXD, OutFilename);
2880 if (rFTP.LocalFileExists)
2881 pPM->deleteFile(SourceName);
2882 pPM->deleteFile(PatchName);
2884 if (j > 0)
2886 pPM->deleteFile(SourceNameXD, false, false); // File can exists if bad BNP loading
2888 tmpSourceName = OutFilename;
2889 PatchSizeProgress += rFTP.PatcheSizes[j];
2890 currentPatchedSize += rFTP.PatcheSizes[j];
2893 if (tmpSourceName != DestinationName)
2895 pPM->deleteFile(SourceName, false, false); // File can exists if bad BNP loading
2896 if (!_CommitPatch)
2898 // let the patch in the unpack directory
2899 pPM->renameFile(tmpSourceName, pPM->ClientPatchPath + rFTP.FileName + ".tmp");
2901 else
2903 pPM->renameFile(tmpSourceName, DestinationName);
2907 else
2909 PatchSizeProgress += totalPatchSize;
2912 // If all patches applied with success so file size should be ok
2913 // We just have to change file date to match the last patch applied
2914 pPM->applyDate(DestinationName, rFTP.LastFileDate);
2915 //progress.progress(1.f);
2918 // ****************************************************************************
2919 void CPatchThread::xDeltaPatch(const string &patch, const string &src, const string &out)
2921 // Internal xdelta
2923 CPatchManager::MyPatchingCB patchingCB;
2925 patchingCB.patchFilename = patch;
2926 patchingCB.srcFilename = src;
2928 CPatchManager *pPM = CPatchManager::getInstance();
2929 pPM->deleteFile(out, false, false);
2931 std::string errorMsg;
2932 CXDeltaPatch::TApplyResult ar = CXDeltaPatch::apply(patch, src, out, errorMsg, &patchingCB);
2933 if (ar != CXDeltaPatch::ApplyResult_Ok)
2935 switch(ar)
2937 case CXDeltaPatch::ApplyResult_WriteError:
2938 throw NLMISC::EWriteError(out);
2939 break;
2940 case CXDeltaPatch::ApplyResult_DiskFull:
2941 throw NLMISC::EDiskFullError(out);
2942 break;
2943 default:
2945 std::string str = toString("Error applying %s to %s giving %s", patch.c_str(), src.c_str(), out.c_str());
2946 throw Exception (str);
2948 break;
2953 // Launching xdelta
2955 // Start the child process.
2956 string strCmdLine = "xdelta patch " + patch + " " + src + " " + out;
2961 // ****************************************************************************
2962 // ****************************************************************************
2963 // ****************************************************************************
2964 // CScanDataThread
2965 // ****************************************************************************
2966 // ****************************************************************************
2967 // ****************************************************************************
2969 // ****************************************************************************
2970 CScanDataThread::CScanDataThread()
2972 AskForCancel= false;
2973 Ended = false;
2974 CheckOk = false;
2975 TotalFileToScan = 1;
2976 CurrentFileScanned = 1;
2979 // ****************************************************************************
2980 void CScanDataThread::run ()
2982 CPatchManager *pPM = CPatchManager::getInstance();
2985 uint32 i;
2986 // Check if the client version is the same as the server version
2987 string sClientVersion = pPM->getClientVersion();
2988 string sTranslate = CI18N::get("uiClientVersion") + " (" + sClientVersion + ") ";
2989 pPM->setState(true, sTranslate);
2991 // For all bnp in the description file get all patches to apply
2992 // depending on the version of the client bnp files
2993 const CBNPFileSet &rDescFiles = pPM->DescFile.getFiles();
2994 TotalFileToScan = rDescFiles.fileCount();
2995 for (i = 0; i < rDescFiles.fileCount(); ++i)
2997 sTranslate = CI18N::get("uiCheckingFile") + " " + rDescFiles.getFile(i).getFileName();
2998 pPM->setState(true, sTranslate);
3000 // get list of file to apply to this patch, performing a full checksum test (slow...)
3001 CPatchManager::SFileToPatch ftp;
3002 pPM->getPatchFromDesc(ftp, rDescFiles.getFile(i), false);
3003 // if the file has been found but don't correspond to any local version (SHA1)
3004 // or if the file has not been found (or the .bnp is very very buggy so that addSearchFile() failed)
3005 if( (ftp.LocalFileExists && ftp.LocalFileToDelete) ||
3006 (!ftp.LocalFileExists && !ftp.LocalFileToDelete) )
3008 pPM->addDataScanLogCorruptedFile(ftp);
3009 CPatchManager::getCorruptedFileInfo(ftp, sTranslate);
3010 pPM->setState(true, sTranslate);
3012 CurrentFileScanned = i;
3014 // if the user ask to cancel the thread, stop now
3015 if(AskForCancel)
3016 break;
3019 sTranslate = CI18N::get("uiCheckEndNoErr");
3020 pPM->setState(true, sTranslate);
3021 CheckOk = true;
3022 Ended = true;
3024 catch (const Exception &e)
3026 nlwarning("EXCEPTION CATCH: CScanDataThread::run() failed");
3027 string sTranslate = CI18N::get("uiCheckEndWithErr") + " " + e.what();
3028 pPM->setState(true, sTranslate);
3029 CheckOk = false;
3030 Ended = true;
3035 // ****************************************************************************
3036 uint32 CPatchManager::SPatchInfo::getAvailablePatchsBitfield() const
3038 // About the test (until a patch enum is added, we use the 'optional' flag)
3039 // Non optional -> must patch it (will be for RoS)
3040 // Optional -> Will be for Mainland
3041 // Required : stands for 'bnp' required by the Optional bnps !! so ignore only RoS is wanted
3043 uint32 result = 0;
3044 if (!NonOptCat.empty())
3046 result |= (1 << BGDownloader::DownloadID_RoS);
3048 if (!OptCat.empty() || !ReqCat.empty())
3050 result |= (1 << BGDownloader::DownloadID_MainLand);
3052 return result;
3055 // ***************************************************************************
3056 void CPatchManager::setAsyncDownloader(IAsyncDownloader* asyncDownloader)
3058 _AsyncDownloader = asyncDownloader;
3060 // ***************************************************************************
3061 IAsyncDownloader* CPatchManager::getAsyncDownloader() const
3063 return _AsyncDownloader;
3065 // **************************************************************************
3066 // ****************************************************************************
3067 void CPatchManager::startInstallThread(const std::vector<CInstallThreadEntry>& entries)
3069 InstallThread = new CInstallThread(entries);
3070 Thread = IThread::create (InstallThread);
3071 nlassert (Thread != NULL);
3072 Thread->start ();
3075 void CPatchManager::startDownloadThread(const std::vector<CInstallThreadEntry>& entries)
3077 DownloadThread = new CDownloadThread(entries);
3078 Thread = IThread::create (DownloadThread);
3079 nlassert (Thread != NULL);
3080 Thread->start ();
3084 void CPatchManager::onFileInstallFinished()
3086 if (_AsyncDownloader)
3088 _AsyncDownloader->onFileInstallFinished();
3093 void CPatchManager::onFileDownloadFinished()
3095 if (_AsyncDownloader)
3097 _AsyncDownloader->onFileDownloadFinished();
3102 void CPatchManager::onFileDownloading(const std::string& sourceName, uint32 rate, uint32 fileIndex, uint32 fileCount, uint64 fileSize, uint64 fullSize)
3104 if (_AsyncDownloader)
3106 _AsyncDownloader->onFileDownloading(sourceName, rate, fileIndex, fileCount, fileSize, fullSize);
3110 void CPatchManager::onFileInstalling(const std::string& sourceName, uint32 rate, uint32 fileIndex, uint32 fileCount, uint64 fileSize, uint64 fullSize)
3112 if (_AsyncDownloader)
3114 _AsyncDownloader->onFileInstalling(sourceName, rate, fileIndex, fileCount, fileSize, fullSize);
3118 bool CPatchManager::download(const std::string& patchFullname, const std::string& sourceFullname,
3119 const std::string& tmpDirectory, uint32 timestamp)
3121 CPatchManager *pPM = CPatchManager::getInstance();
3123 static std::string zsStr = ".lzma";
3124 static std::string::size_type zsStrLength = zsStr.size();
3126 // we delete file if present and diferent timestamp
3127 // if the file is the same then indicates its not necessary to download it a second time
3128 if (NLMISC::CFile::fileExists(sourceFullname))
3130 uint32 t = NLMISC::CFile::getFileModificationDate(sourceFullname);
3131 if (t == timestamp)
3132 { //we didn't downl oad
3133 return true;
3135 pPM->deleteFile(sourceFullname);
3137 // file will be save to a .tmp file
3138 std::string extension;
3139 if (patchFullname.size() >= zsStrLength && patchFullname.substr(patchFullname.size() - zsStrLength) == zsStr)
3141 extension = zsStr;
3143 // remove tmp file if exist
3144 std::string patchName = tmpDirectory + NLMISC::CFile::getFilename(sourceFullname) + extension + std::string(".tmp");
3145 if (NLMISC::CFile::fileExists(patchName))
3147 pPM->deleteFile(patchName);
3149 // creates directory tree if necessary
3150 NLMISC::CFile::createDirectoryTree( NLMISC::CFile::getPath(patchName) );
3151 NLMISC::CFile::createDirectoryTree( NLMISC::CFile::getPath(sourceFullname) );
3153 // try to download
3156 pPM->getServerFile(patchFullname, false, patchName);
3158 catch ( const std::exception& e)
3160 nlwarning("%s", e.what());
3161 pPM->setState(true, string(e.what()) );
3162 return false;
3165 // install
3166 if (!NLMISC::CFile::fileExists(patchName))
3168 return false;
3170 // if file is compressed unpack then commit (rename)
3171 if (patchName.size() >= zsStrLength
3172 && patchName.substr(patchName.size() - zsStrLength) == zsStr)
3174 std::string outFilename = patchName.substr(0, patchName.size() - zsStrLength);
3175 unpack7Zip(patchName, outFilename);
3176 pPM->deleteFile(patchName);
3177 pPM->renameFile(outFilename, sourceFullname);
3179 else
3181 // file is not compressed so rename the .tmp file to final name
3182 pPM->renameFile(patchName, sourceFullname);
3184 // apply modification date
3185 pPM->applyDate(sourceFullname, timestamp);
3187 return true;
3191 bool CPatchManager::extract(const std::string& patchPath,
3192 const std::vector<std::string>& sourceFilename,
3193 const std::vector<std::string>& extractPath,
3194 const std::string& updateBatchFilename,
3195 const std::string& execName,
3196 void (*stopFun)() )
3198 nlassert(sourceFilename.size() == extractPath.size());
3199 CPatchManager *pPM = CPatchManager::getInstance();
3201 bool ok = false;
3202 for (uint32 j = 0; j < extractPath.size() && !ok; ++j)
3204 if (!extractPath[j].empty())
3206 ok = true;
3210 if (!ok)
3212 // nothing to extract
3213 return false;
3216 // extract
3217 uint nblab = 0;
3218 pPM->deleteFile(updateBatchFilename, false, false);
3220 FILE *fp = nlfopen (updateBatchFilename, "wt");
3222 if (fp == 0)
3224 string err = toString("Can't open file '%s' for writing: code=%d %s (error code 29)", updateBatchFilename.c_str(), errno, strerror(errno));
3225 throw Exception (err);
3228 #ifdef NL_OS_WINDOWS
3229 fprintf(fp, "@echo off\n");
3230 fprintf(fp, "ping 127.0.0.1 -n 7 -w 1000 > nul\n"); // wait
3231 #else
3232 fprintf(fp, "#!/bin/sh\n");
3233 fprintf(fp, "sleep 7\n"); // wait
3234 #endif
3236 // Unpack files with category ExtractPath non empty
3237 for (uint32 j = 0; j < sourceFilename.size(); ++j)
3239 if (!extractPath[j].empty())
3241 string rFilename = sourceFilename[j];
3242 // Extract to patch
3243 vector<string> vFilenames;
3244 if (!pPM->bnpUnpack(rFilename, patchPath, vFilenames))
3247 string err = toString("Error unpacking %s", rFilename.c_str());
3248 throw Exception (err);
3251 else
3253 std::string sourcePath = NLMISC::CFile::getPath(sourceFilename[j]);
3254 for (uint32 fff = 0; fff < vFilenames.size (); fff++)
3256 string SrcPath = CPath::standardizeDosPath(sourcePath);
3257 string SrcName = SrcPath + vFilenames[fff];
3258 string DstPath = CPath::standardizeDosPath(extractPath[j]);
3259 string DstName = DstPath + vFilenames[fff];
3260 NLMISC::CFile::createDirectoryTree(extractPath[j]);
3262 // this file must be moved
3263 #ifdef NL_OS_WINDOWS
3264 fprintf(fp, ":loop%u\n", nblab);
3265 fprintf(fp, "attrib -r -a -s -h %s\n", DstName.c_str());
3266 fprintf(fp, "del %s\n", DstName.c_str());
3267 fprintf(fp, "if exist %s goto loop%u\n", DstName.c_str(), nblab);
3268 fprintf(fp, "move %s %s\n", SrcName.c_str(), DstPath.c_str());
3269 #else
3270 // TODO: for Linux and OS X
3271 #endif
3273 nblab++;
3281 #ifdef NL_OS_WINDOWS
3282 fprintf(fp, "start %s %%1 %%2 %%3\n", execName.c_str());
3283 #else
3284 // TODO: for Linux and OS X
3285 #endif
3287 fclose(fp);
3289 if (stopFun)
3291 stopFun();
3294 if (!launchProgram(updateBatchFilename, "", false))
3296 // error occurs during the launch
3297 string str = toString("Can't execute '%s': code=%d %s (error code 30)", updateBatchFilename.c_str(), errno, strerror(errno));
3298 throw Exception (str);
3301 return true;
3305 void CPatchManager::setStateListener(IPatchManagerStateListener* stateListener)
3307 _StateListener = stateListener;
3311 void CPatchManager::fatalError(const std::string& errorId, const std::string& param1, const std::string& param2)
3313 if (_AsyncDownloader)
3315 _AsyncDownloader->fatalError(errorId, param1, param2);
3320 // ****************************************************************************
3321 void CDownloadThread::run()
3323 CPatchManager *pPM = CPatchManager::getInstance();
3325 std::string patchPath = CPath::standardizePath (ClientRootPath+TheTmpInstallDirectory)+"patch/";
3328 static bool _FirstTime = true;
3329 static uint64 _FullSize = 0;
3330 static uint64 _CurrentSize = 0;
3331 static uint32 _Start;
3333 // At first launch calculat the amount of data need to download
3334 if (_FirstTime)
3336 for (uint first = 0,last = (uint)_Entries.size() ; first != last; ++first)
3338 _FullSize += _Entries[first].SZipFileSize;
3340 _Start = NLMISC::CTime::getSecondsSince1970();
3341 _FirstTime = false;
3345 for (uint first = 0,last = (uint)_Entries.size() ; first != last; ++first)
3347 std::string patchName = CPath::standardizePath (_Entries[first].PatchName, false);
3348 std::string sourceName = CPath::standardizePath (_Entries[first].SourceName, false);
3350 _CurrentSize += _Entries[first].SZipFileSize;
3352 uint32 rate = 0;
3353 // Calculate the time since last update
3354 uint32 dt = NLMISC::CTime::getSecondsSince1970() - _Start;
3355 if (dt)
3357 rate = uint32(_CurrentSize / dt);
3359 // update Gui
3360 pPM->onFileDownloading(sourceName, rate, first+1, last, _CurrentSize, _FullSize);
3362 std::string finalFile =patchPath+ patchName;
3363 std::string tmpFile = finalFile + std::string(".part");
3366 bool toDownload = true;
3367 static volatile bool simulateDownload = false;
3368 if (simulateDownload)
3370 nlSleep(100);
3372 else
3374 // Do not download if file are identicaly (check size and modification date)
3375 if (NLMISC::CFile::fileExists(finalFile))
3377 uint64 fz = NLMISC::CFile::getFileSize(finalFile);
3378 uint32 timestamp = _Entries[first].Timestamp;
3379 uint32 timestamp2 = NLMISC::CFile::getFileModificationDate(finalFile);
3380 if ( fz == _Entries[first].SZipFileSize && timestamp == timestamp2)
3382 toDownload = false;
3384 else
3386 NLMISC::CFile::deleteFile(finalFile);
3390 // file need to be download
3391 if (toDownload)
3393 // delete tmp file if exist
3394 if (NLMISC::CFile::fileExists(tmpFile))
3396 NLMISC::CFile::deleteFile(tmpFile);
3398 std::string path = NLMISC::CFile::getPath(tmpFile);
3399 // create directory tree
3400 NLMISC::CFile::createDirectoryTree(path);
3401 // Try to download, rename, applyDate and send error msg to gui in case of error
3404 pPM->getServerFile(patchName, false, tmpFile);
3405 NLMISC::CFile::moveFile(finalFile, tmpFile);
3407 pPM->applyDate(finalFile, _Entries[first].Timestamp);
3409 catch ( const std::exception& e)
3411 nlwarning("%s", e.what());
3412 pPM->setState(true, string(e.what()) );
3413 pPM->fatalError("uiCanNotDownload", patchName.c_str(), "");
3415 catch (...)
3417 pPM->fatalError("uiCanNotDownload", patchName.c_str(), "");
3423 // message to gui to indicates that all file are downloaded
3424 pPM->onFileDownloadFinished();
3428 void CInstallThread::run()
3430 std::string patchPath = CPath::standardizePath (ClientRootPath+TheTmpInstallDirectory)+"patch/";
3431 CPatchManager *pPM = CPatchManager::getInstance();
3433 std::set<std::string> allowed;
3435 uint first, last;
3437 for (first = 0,last = (uint)_Entries.size() ; first != last; ++first)
3439 std::string correct = CPath::standardizePath (patchPath + _Entries[first].PatchName, false);
3440 allowed.insert(correct);
3442 // Delete file from tmp directory that are not "allowed" (torrent protocol can download partial file that are not asked)
3443 std::vector<std::string> vFiles;
3444 CPath::getPathContent(patchPath , true, false, true, vFiles);
3445 for (uint32 i = 0; i < vFiles.size(); ++i)
3447 std::string sName2 = CPath::standardizePath (vFiles[i], false);
3448 if (allowed.find(sName2) == allowed.end() )
3450 pPM->deleteFile(sName2 , false, false);
3454 static bool _FirstTime = true;
3455 static uint64 _FullSize = 0;
3456 static uint64 _CurrentSize = 0;
3457 static uint32 _Start;
3459 // calculate size of data to download in order to know the install speed
3460 if (_FirstTime)
3462 for (uint first = 0,last = (uint)_Entries.size() ; first != last; ++first)
3464 _FullSize += _Entries[first].Size;
3466 _Start = NLMISC::CTime::getSecondsSince1970();
3467 _FirstTime = false;
3471 for (first = 0,last = (uint)_Entries.size() ; first != last; ++first)
3473 std::string patchName = CPath::standardizePath (patchPath +_Entries[first].PatchName, false);
3474 std::string sourceName = CPath::standardizePath (_Entries[first].SourceName, false);
3475 uint32 lastFileDate = _Entries[first].Timestamp;
3478 _CurrentSize += _Entries[first].Size;
3479 uint32 rate = 0;
3480 // calcule the install speed
3481 uint32 dt = NLMISC::CTime::getSecondsSince1970() - _Start;
3482 if (dt)
3484 uint64 size = _CurrentSize / dt;
3485 rate = uint32 (size);
3488 // File can exists if bad BNP loading
3489 if (NLMISC::CFile::fileExists(sourceName))
3491 pPM->deleteFile(sourceName, false, false);
3494 if (NLMISC::CFile::fileExists(patchName))
3496 static std::string zsStr = ".lzma";
3497 static std::string::size_type zsStrLength = zsStr.size();
3500 // if file is compressed unpack the file (decompress, rename tempory file, apply modification date)
3501 if (patchName.size() >= zsStrLength
3502 && patchName.substr(patchName.size() - zsStrLength) == zsStr)
3504 std::string outFilename = patchName.substr(0, patchName.size() - zsStrLength);
3505 std::string localOutFilename = CPath::standardizeDosPath(outFilename);
3507 if ( unpackLZMA(patchName, localOutFilename) )
3509 pPM->deleteFile(patchName);
3510 pPM->renameFile(outFilename, sourceName);
3511 pPM->applyDate(sourceName, lastFileDate);
3513 else
3515 throw NLMISC::Exception("Can not unpack");
3519 else
3521 // if file is uncompressed rename tempory file and apply modification date)
3522 pPM->renameFile(patchName, sourceName);
3523 pPM->applyDate(sourceName, lastFileDate);
3526 catch ( const std::exception& e)
3528 nlwarning("%s", e.what());
3529 pPM->setState(true, string(e.what()) );
3530 pPM->fatalError("uiCanNotInstall", patchName.c_str(), "");
3531 return;
3534 catch (...)
3536 pPM->fatalError("uiCanNotInstall", patchName.c_str(), "");
3537 return;
3540 // update gui
3541 pPM->onFileInstalling(sourceName, rate, first+1, last, _CurrentSize, _FullSize);
3544 // extract bnp
3547 // remove date from tmp directory (because install is finished)
3548 std::string install = CPath::standardizePath (ClientRootPath+TheTmpInstallDirectory);
3550 std::vector<std::string> vFiles;
3551 // Delete all classic file from tmp directory
3552 CPath::getPathContent(install, true, false, true, vFiles);
3553 for (uint32 i = 0; i < vFiles.size(); ++i)
3555 NLMISC::CFile::deleteFile(vFiles[i]);
3557 // Delete all directory from tmp directory
3560 vFiles.clear();
3561 CPath::getPathContent(install, true, true, false, vFiles);
3562 for (uint32 i = 0; i < vFiles.size(); ++i)
3564 NLMISC::CFile::deleteDirectory(vFiles[i]);
3567 while ( !vFiles.empty() );
3568 // delete tmp directory
3569 NLMISC::CFile::deleteDirectory(install);
3570 // delete libtorrent_logs directory if exist (not activate)
3571 if (NLMISC::CFile::fileExists("libtorrent_logs"))
3575 vFiles.clear();
3576 CPath::getPathContent("libtorrent_logs", true, true, false, vFiles);
3577 for (uint32 i = 0; i < vFiles.size(); ++i)
3579 NLMISC::CFile::deleteDirectory(vFiles[i]);
3582 while ( !vFiles.empty() );
3583 NLMISC::CFile::deleteDirectory("libtorrent_logs");
3588 pPM->reboot(); // do not reboot just run the extract .bat