updater_linux.cpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519
  1. /*
  2. This file is part of Telegram Desktop,
  3. the official desktop application for the Telegram messaging service.
  4. For license and copyright information please follow this link:
  5. https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL
  6. */
  7. #include <cstdio>
  8. #include <sys/stat.h>
  9. #include <sys/types.h>
  10. #include <cstdlib>
  11. #include <unistd.h>
  12. #include <dirent.h>
  13. #include <pwd.h>
  14. #include <string>
  15. #include <deque>
  16. #include <vector>
  17. #include <cstring>
  18. #include <cerrno>
  19. #include <algorithm>
  20. #include <cstdarg>
  21. #include <ctime>
  22. #include <iostream>
  23. using std::string;
  24. using std::deque;
  25. using std::vector;
  26. using std::cout;
  27. bool do_mkdir(const char *path) { // from http://stackoverflow.com/questions/675039/how-can-i-create-directory-tree-in-c-linux
  28. struct stat statbuf;
  29. if (stat(path, &statbuf) != 0) {
  30. /* Directory does not exist. EEXIST for race condition */
  31. if (mkdir(path, S_IRWXU) != 0 && errno != EEXIST) return false;
  32. } else if (!S_ISDIR(statbuf.st_mode)) {
  33. errno = ENOTDIR;
  34. return false;
  35. }
  36. return true;
  37. }
  38. bool _debug = false;
  39. bool writeprotected = false;
  40. string updaterDir;
  41. string updaterName;
  42. string workDir;
  43. string exeName;
  44. string exePath;
  45. string argv0;
  46. FILE *_logFile = 0;
  47. void openLog() {
  48. if (!_debug || _logFile) return;
  49. if (!do_mkdir((workDir + "DebugLogs").c_str())) {
  50. return;
  51. }
  52. time_t timer;
  53. time(&timer);
  54. struct tm *t = localtime(&timer);
  55. static const int maxFileLen = 65536;
  56. char logName[maxFileLen];
  57. sprintf(logName, "%sDebugLogs/%04d%02d%02d_%02d%02d%02d_upd.txt", workDir.c_str(),
  58. t->tm_year + 1900, t->tm_mon + 1, t->tm_mday, t->tm_hour, t->tm_min, t->tm_sec);
  59. _logFile = fopen(logName, "w");
  60. }
  61. void closeLog() {
  62. if (!_logFile) return;
  63. fclose(_logFile);
  64. _logFile = 0;
  65. }
  66. void writeLog(const char *format, ...) {
  67. if (!_logFile) {
  68. return;
  69. }
  70. va_list args;
  71. va_start(args, format);
  72. vfprintf(_logFile, format, args);
  73. fprintf(_logFile, "\n");
  74. fflush(_logFile);
  75. va_end(args);
  76. }
  77. bool copyFile(const char *from, const char *to) {
  78. FILE *ffrom = fopen(from, "rb"), *fto = fopen(to, "wb");
  79. if (!ffrom) {
  80. if (fto) fclose(fto);
  81. return false;
  82. }
  83. if (!fto) {
  84. fclose(ffrom);
  85. return false;
  86. }
  87. static const int BufSize = 65536;
  88. char buf[BufSize];
  89. while (size_t size = fread(buf, 1, BufSize, ffrom)) {
  90. fwrite(buf, 1, size, fto);
  91. }
  92. struct stat fst; // from http://stackoverflow.com/questions/5486774/keeping-fileowner-and-permissions-after-copying-file-in-c
  93. //let's say this wont fail since you already worked OK on that fp
  94. if (fstat(fileno(ffrom), &fst) != 0) {
  95. fclose(ffrom);
  96. fclose(fto);
  97. return false;
  98. }
  99. //update to the same uid/gid
  100. if (!writeprotected && fchown(fileno(fto), fst.st_uid, fst.st_gid) != 0) {
  101. fclose(ffrom);
  102. fclose(fto);
  103. return false;
  104. }
  105. //update the permissions
  106. if (fchmod(fileno(fto), fst.st_mode) != 0) {
  107. fclose(ffrom);
  108. fclose(fto);
  109. return false;
  110. }
  111. fclose(ffrom);
  112. fclose(fto);
  113. return true;
  114. }
  115. bool remove_directory(const string &path) { // from http://stackoverflow.com/questions/2256945/removing-a-non-empty-directory-programmatically-in-c-or-c
  116. DIR *d = opendir(path.c_str());
  117. writeLog("Removing dir '%s'", path.c_str());
  118. if (!d) {
  119. writeLog("Could not open dir '%s'", path.c_str());
  120. return (errno == ENOENT);
  121. }
  122. while (struct dirent *p = readdir(d)) {
  123. /* Skip the names "." and ".." as we don't want to recurse on them. */
  124. if (!strcmp(p->d_name, ".") || !strcmp(p->d_name, "..")) continue;
  125. string fname = path + '/' + p->d_name;
  126. struct stat statbuf;
  127. writeLog("Trying to get stat() for '%s'", fname.c_str());
  128. if (!stat(fname.c_str(), &statbuf)) {
  129. if (S_ISDIR(statbuf.st_mode)) {
  130. if (!remove_directory(fname.c_str())) {
  131. closedir(d);
  132. return false;
  133. }
  134. } else {
  135. writeLog("Unlinking file '%s'", fname.c_str());
  136. if (unlink(fname.c_str())) {
  137. writeLog("Failed to unlink '%s'", fname.c_str());
  138. closedir(d);
  139. return false;
  140. }
  141. }
  142. } else {
  143. writeLog("Failed to call stat() on '%s'", fname.c_str());
  144. }
  145. }
  146. closedir(d);
  147. writeLog("Finally removing dir '%s'", path.c_str());
  148. return !rmdir(path.c_str());
  149. }
  150. bool mkpath(const char *path) {
  151. int status = 0, pathsize = strlen(path) + 1;
  152. char *copypath = new char[pathsize];
  153. memcpy(copypath, path, pathsize);
  154. char *pp = copypath, *sp;
  155. while (status == 0 && (sp = strchr(pp, '/')) != 0) {
  156. if (sp != pp) {
  157. /* Neither root nor double slash in path */
  158. *sp = '\0';
  159. if (!do_mkdir(copypath)) {
  160. delete[] copypath;
  161. return false;
  162. }
  163. *sp = '/';
  164. }
  165. pp = sp + 1;
  166. }
  167. delete[] copypath;
  168. return do_mkdir(path);
  169. }
  170. bool equal(string a, string b) {
  171. std::transform(a.begin(), a.end(), a.begin(), ::tolower);
  172. std::transform(b.begin(), b.end(), b.begin(), ::tolower);
  173. return a == b;
  174. }
  175. void delFolder() {
  176. string delPathOld = workDir + "tupdates/ready", delPath = workDir + "tupdates/temp", delFolder = workDir + "tupdates";
  177. writeLog("Fully clearing old path '%s'..", delPathOld.c_str());
  178. if (!remove_directory(delPathOld)) {
  179. writeLog("Failed to clear old path! :( New path was used?..");
  180. }
  181. writeLog("Fully clearing path '%s'..", delPath.c_str());
  182. if (!remove_directory(delPath)) {
  183. writeLog("Error: failed to clear path! :(");
  184. }
  185. rmdir(delFolder.c_str());
  186. }
  187. bool update() {
  188. writeLog("Update started..");
  189. string updDir = workDir + "tupdates/temp", readyFilePath = workDir + "tupdates/temp/ready", tdataDir = workDir + "tupdates/temp/tdata";
  190. {
  191. FILE *readyFile = fopen(readyFilePath.c_str(), "rb");
  192. if (readyFile) {
  193. fclose(readyFile);
  194. writeLog("Ready file found! Using new path '%s'..", updDir.c_str());
  195. } else {
  196. updDir = workDir + "tupdates/ready"; // old
  197. tdataDir = workDir + "tupdates/ready/tdata";
  198. writeLog("Ready file not found! Using old path '%s'..", updDir.c_str());
  199. }
  200. }
  201. deque<string> dirs;
  202. dirs.push_back(updDir);
  203. deque<string> from, to, forcedirs;
  204. do {
  205. string dir = dirs.front();
  206. dirs.pop_front();
  207. string toDir = exePath;
  208. if (dir.size() > updDir.size() + 1) {
  209. toDir += (dir.substr(updDir.size() + 1) + '/');
  210. forcedirs.push_back(toDir);
  211. writeLog("Parsing dir '%s' in update tree..", toDir.c_str());
  212. }
  213. DIR *d = opendir(dir.c_str());
  214. if (!d) {
  215. writeLog("Failed to open dir %s", dir.c_str());
  216. return false;
  217. }
  218. while (struct dirent *p = readdir(d)) {
  219. /* Skip the names "." and ".." as we don't want to recurse on them. */
  220. if (!strcmp(p->d_name, ".") || !strcmp(p->d_name, "..")) continue;
  221. string fname = dir + '/' + p->d_name;
  222. struct stat statbuf;
  223. if (fname.substr(0, tdataDir.size()) == tdataDir && (fname.size() <= tdataDir.size() || fname.at(tdataDir.size()) == '/')) {
  224. writeLog("Skipping 'tdata' path '%s'", fname.c_str());
  225. } else if (!stat(fname.c_str(), &statbuf)) {
  226. if (S_ISDIR(statbuf.st_mode)) {
  227. dirs.push_back(fname);
  228. writeLog("Added dir '%s' in update tree..", fname.c_str());
  229. } else {
  230. string tofname = exePath + fname.substr(updDir.size() + 1);
  231. if (equal(tofname, updaterName)) { // bad update - has Updater - delete all dir
  232. writeLog("Error: bad update, has Updater! '%s' equal '%s'", tofname.c_str(), updaterName.c_str());
  233. delFolder();
  234. return false;
  235. } else if (equal(tofname, exePath + "Telegram") && exeName != "Telegram") {
  236. string fullBinaryPath = exePath + exeName;
  237. writeLog("Target binary found: '%s', changing to '%s'", tofname.c_str(), fullBinaryPath.c_str());
  238. tofname = fullBinaryPath;
  239. }
  240. if (fname == readyFilePath) {
  241. writeLog("Skipped ready file '%s'", fname.c_str());
  242. } else {
  243. from.push_back(fname);
  244. to.push_back(tofname);
  245. writeLog("Added file '%s' to be copied to '%s'", fname.c_str(), tofname.c_str());
  246. }
  247. }
  248. } else {
  249. writeLog("Could not get stat() for file %s", fname.c_str());
  250. }
  251. }
  252. closedir(d);
  253. } while (!dirs.empty());
  254. for (size_t i = 0; i < forcedirs.size(); ++i) {
  255. string forcedir = forcedirs[i];
  256. writeLog("Forcing dir '%s'..", forcedir.c_str());
  257. if (!forcedir.empty() && !mkpath(forcedir.c_str())) {
  258. writeLog("Error: failed to create dir '%s'..", forcedir.c_str());
  259. delFolder();
  260. return false;
  261. }
  262. }
  263. for (size_t i = 0; i < from.size(); ++i) {
  264. string fname = from[i], tofname = to[i];
  265. // it is necessary to remove the old file to not to get an error if appimage file is used by fuse
  266. struct stat statbuf;
  267. writeLog("Trying to get stat() for '%s'", tofname.c_str());
  268. if (!stat(tofname.c_str(), &statbuf)) {
  269. if (S_ISDIR(statbuf.st_mode)) {
  270. writeLog("Fully clearing path '%s'..", tofname.c_str());
  271. if (!remove_directory(tofname.c_str())) {
  272. writeLog("Error: failed to clear path '%s'", tofname.c_str());
  273. delFolder();
  274. return false;
  275. }
  276. } else {
  277. writeLog("Unlinking file '%s'", tofname.c_str());
  278. if (unlink(tofname.c_str())) {
  279. writeLog("Error: failed to unlink '%s'", tofname.c_str());
  280. delFolder();
  281. return false;
  282. }
  283. }
  284. }
  285. writeLog("Copying file '%s' to '%s'..", fname.c_str(), tofname.c_str());
  286. int copyTries = 0, triesLimit = 30;
  287. do {
  288. if (!copyFile(fname.c_str(), tofname.c_str())) {
  289. ++copyTries;
  290. usleep(100000);
  291. } else {
  292. break;
  293. }
  294. } while (copyTries < triesLimit);
  295. if (copyTries == triesLimit) {
  296. writeLog("Error: failed to copy, asking to retry..");
  297. delFolder();
  298. return false;
  299. }
  300. }
  301. writeLog("Update succeed! Clearing folder..");
  302. delFolder();
  303. return true;
  304. }
  305. string CurrentExecutablePath(int argc, char *argv[]) {
  306. constexpr auto kMaxPath = 1024;
  307. char result[kMaxPath] = { 0 };
  308. auto count = readlink("/proc/self/exe", result, kMaxPath);
  309. if (count > 0) {
  310. return string(result);
  311. }
  312. // Fallback to the first command line argument.
  313. return argc ? string(argv[0]) : string();
  314. }
  315. int main(int argc, char *argv[]) {
  316. bool needupdate = true;
  317. bool autostart = false;
  318. bool debug = false;
  319. bool tosettings = false;
  320. bool startintray = false;
  321. bool customWorkingDir = false;
  322. bool justUpdate = false;
  323. char *key = 0;
  324. char *workdir = 0;
  325. for (int i = 1; i < argc; ++i) {
  326. if (equal(argv[i], "-noupdate")) {
  327. needupdate = false;
  328. } else if (equal(argv[i], "-autostart")) {
  329. autostart = true;
  330. } else if (equal(argv[i], "-debug")) {
  331. debug = _debug = true;
  332. } else if (equal(argv[i], "-startintray")) {
  333. startintray = true;
  334. } else if (equal(argv[i], "-tosettings")) {
  335. tosettings = true;
  336. } else if (equal(argv[i], "-workdir_custom")) {
  337. customWorkingDir = true;
  338. } else if (equal(argv[i], "-writeprotected")) {
  339. writeprotected = true;
  340. justUpdate = true;
  341. } else if (equal(argv[i], "-justupdate")) {
  342. justUpdate = true;
  343. } else if (equal(argv[i], "-key") && ++i < argc) {
  344. key = argv[i];
  345. } else if (equal(argv[i], "-workpath") && ++i < argc) {
  346. workDir = workdir = argv[i];
  347. } else if (equal(argv[i], "-exename") && ++i < argc) {
  348. exeName = argv[i];
  349. } else if (equal(argv[i], "-exepath") && ++i < argc) {
  350. exePath = argv[i];
  351. } else if (equal(argv[i], "-argv0") && ++i < argc) {
  352. argv0 = argv[i];
  353. }
  354. }
  355. if (exeName.empty() || exeName.find('/') != string::npos) {
  356. exeName = "Telegram";
  357. }
  358. openLog();
  359. writeLog("Updater started, new argments formatting..");
  360. for (int i = 0; i < argc; ++i) {
  361. writeLog("Argument: '%s'", argv[i]);
  362. }
  363. if (needupdate) writeLog("Need to update!");
  364. if (autostart) writeLog("From autostart!");
  365. if (writeprotected) writeLog("Write Protected folder!");
  366. updaterName = CurrentExecutablePath(argc, argv);
  367. writeLog("Updater binary full path is: %s", updaterName.c_str());
  368. if (exePath.empty()) {
  369. writeLog("Executable path is not specified :(");
  370. } else {
  371. writeLog("Executable path: %s", exePath.c_str());
  372. }
  373. if (updaterName.size() >= 7) {
  374. if (equal(updaterName.substr(updaterName.size() - 7), "Updater")) {
  375. updaterDir = updaterName.substr(0, updaterName.size() - 7);
  376. writeLog("Updater binary dir is: %s", updaterDir.c_str());
  377. if (exePath.empty()) {
  378. exePath = updaterDir;
  379. writeLog("Using updater binary dir.", exePath.c_str());
  380. }
  381. if (needupdate) {
  382. if (workDir.empty()) { // old app launched, update prepared in tupdates/ready (not in tupdates/temp)
  383. customWorkingDir = false;
  384. writeLog("No workdir, trying to figure it out");
  385. struct passwd *pw = getpwuid(getuid());
  386. if (pw && pw->pw_dir && strlen(pw->pw_dir)) {
  387. string tryDir = pw->pw_dir + string("/.TelegramDesktop/");
  388. struct stat statbuf;
  389. writeLog("Trying to use '%s' as workDir, getting stat() for tupdates/ready", tryDir.c_str());
  390. if (!stat((tryDir + "tupdates/ready").c_str(), &statbuf)) {
  391. writeLog("Stat got");
  392. if (S_ISDIR(statbuf.st_mode)) {
  393. writeLog("It is directory, using home work dir");
  394. workDir = tryDir;
  395. }
  396. }
  397. }
  398. if (workDir.empty()) {
  399. workDir = exePath;
  400. struct stat statbuf;
  401. writeLog("Trying to use current as workDir, getting stat() for tupdates/ready");
  402. if (!stat("tupdates/ready", &statbuf)) {
  403. writeLog("Stat got");
  404. if (S_ISDIR(statbuf.st_mode)) {
  405. writeLog("It is directory, using current dir");
  406. workDir = string();
  407. }
  408. }
  409. }
  410. } else {
  411. writeLog("Passed workpath is '%s'", workDir.c_str());
  412. }
  413. update();
  414. }
  415. } else {
  416. writeLog("Error: bad exe name!");
  417. }
  418. } else {
  419. writeLog("Error: short exe name!");
  420. }
  421. // let the parent launch instead
  422. if (justUpdate) {
  423. writeLog("Closing log and quitting..");
  424. } else {
  425. const auto fullBinaryPath = exePath + exeName;
  426. auto values = vector<string>();
  427. const auto push = [&](string arg) {
  428. // Force null-terminated .data() call result.
  429. values.push_back(arg + char(0));
  430. };
  431. push(!argv0.empty() ? argv0 : fullBinaryPath);
  432. push("-noupdate");
  433. if (autostart) push("-autostart");
  434. if (debug) push("-debug");
  435. if (startintray) push("-startintray");
  436. if (tosettings) push("-tosettings");
  437. if (key) {
  438. push("-key");
  439. push(key);
  440. }
  441. if (customWorkingDir && workdir) {
  442. push("-workdir");
  443. push(workdir);
  444. }
  445. auto args = vector<char*>();
  446. for (auto &arg : values) {
  447. args.push_back(arg.data());
  448. }
  449. args.push_back(nullptr);
  450. pid_t pid = fork();
  451. switch (pid) {
  452. case -1:
  453. writeLog("fork() failed!");
  454. return 1;
  455. case 0:
  456. execv(fullBinaryPath.c_str(), args.data());
  457. return 1;
  458. }
  459. writeLog("Executed Telegram, closing log and quitting..");
  460. }
  461. closeLog();
  462. return 0;
  463. }