Improve current executable path computing.

Fixes #960 (hopefully).
This commit is contained in:
John Preston 2017-08-15 20:12:57 +03:00
parent f2801d4775
commit 8e433971c9
13 changed files with 406 additions and 375 deletions

View File

@ -39,16 +39,16 @@ using std::deque;
using std::cout; using std::cout;
bool do_mkdir(const char *path) { // from http://stackoverflow.com/questions/675039/how-can-i-create-directory-tree-in-c-linux bool do_mkdir(const char *path) { // from http://stackoverflow.com/questions/675039/how-can-i-create-directory-tree-in-c-linux
struct stat statbuf; struct stat statbuf;
if (stat(path, &statbuf) != 0) { if (stat(path, &statbuf) != 0) {
/* Directory does not exist. EEXIST for race condition */ /* Directory does not exist. EEXIST for race condition */
if (mkdir(path, S_IRWXU) != 0 && errno != EEXIST) return false; if (mkdir(path, S_IRWXU) != 0 && errno != EEXIST) return false;
} else if (!S_ISDIR(statbuf.st_mode)) { } else if (!S_ISDIR(statbuf.st_mode)) {
errno = ENOTDIR; errno = ENOTDIR;
return false; return false;
} }
return true; return true;
} }
bool _debug = false; bool _debug = false;
@ -56,161 +56,164 @@ string updaterDir;
string updaterName; string updaterName;
string workDir; string workDir;
string exeName; string exeName;
string exePath;
FILE *_logFile = 0; FILE *_logFile = 0;
void openLog() { void openLog() {
if (!_debug || _logFile) return; if (!_debug || _logFile) return;
if (!do_mkdir((workDir + "DebugLogs").c_str())) { if (!do_mkdir((workDir + "DebugLogs").c_str())) {
return; return;
} }
time_t timer; time_t timer;
time(&timer); time(&timer);
struct tm *t = localtime(&timer); struct tm *t = localtime(&timer);
static const int maxFileLen = 65536; static const int maxFileLen = 65536;
char logName[maxFileLen]; char logName[maxFileLen];
sprintf(logName, "%sDebugLogs/%04d%02d%02d_%02d%02d%02d_upd.txt", workDir.c_str(), sprintf(logName, "%sDebugLogs/%04d%02d%02d_%02d%02d%02d_upd.txt", workDir.c_str(),
t->tm_year + 1900, t->tm_mon + 1, t->tm_mday, t->tm_hour, t->tm_min, t->tm_sec); t->tm_year + 1900, t->tm_mon + 1, t->tm_mday, t->tm_hour, t->tm_min, t->tm_sec);
_logFile = fopen(logName, "w"); _logFile = fopen(logName, "w");
} }
void closeLog() { void closeLog() {
if (!_logFile) return; if (!_logFile) return;
fclose(_logFile); fclose(_logFile);
_logFile = 0; _logFile = 0;
} }
void writeLog(const char *format, ...) { void writeLog(const char *format, ...) {
if (!_logFile) return; if (!_logFile) {
return;
}
va_list args; va_list args;
va_start(args, format); va_start(args, format);
vfprintf(_logFile, format, args); vfprintf(_logFile, format, args);
fprintf(_logFile, "\n"); fprintf(_logFile, "\n");
fflush(_logFile); fflush(_logFile);
va_end(args); va_end(args);
} }
bool copyFile(const char *from, const char *to) { bool copyFile(const char *from, const char *to) {
FILE *ffrom = fopen(from, "rb"), *fto = fopen(to, "wb"); FILE *ffrom = fopen(from, "rb"), *fto = fopen(to, "wb");
if (!ffrom) { if (!ffrom) {
if (fto) fclose(fto); if (fto) fclose(fto);
return false; return false;
} }
if (!fto) { if (!fto) {
fclose(ffrom); fclose(ffrom);
return false; return false;
} }
static const int BufSize = 65536; static const int BufSize = 65536;
char buf[BufSize]; char buf[BufSize];
while (size_t size = fread(buf, 1, BufSize, ffrom)) { while (size_t size = fread(buf, 1, BufSize, ffrom)) {
fwrite(buf, 1, size, fto); fwrite(buf, 1, size, fto);
} }
struct stat fst; // from http://stackoverflow.com/questions/5486774/keeping-fileowner-and-permissions-after-copying-file-in-c struct stat fst; // from http://stackoverflow.com/questions/5486774/keeping-fileowner-and-permissions-after-copying-file-in-c
//let's say this wont fail since you already worked OK on that fp //let's say this wont fail since you already worked OK on that fp
if (fstat(fileno(ffrom), &fst) != 0) { if (fstat(fileno(ffrom), &fst) != 0) {
fclose(ffrom); fclose(ffrom);
fclose(fto); fclose(fto);
return false; return false;
} }
//update to the same uid/gid //update to the same uid/gid
if (fchown(fileno(fto), fst.st_uid, fst.st_gid) != 0) { if (fchown(fileno(fto), fst.st_uid, fst.st_gid) != 0) {
fclose(ffrom); fclose(ffrom);
fclose(fto); fclose(fto);
return false; return false;
} }
//update the permissions //update the permissions
if (fchmod(fileno(fto), fst.st_mode) != 0) { if (fchmod(fileno(fto), fst.st_mode) != 0) {
fclose(ffrom); fclose(ffrom);
fclose(fto); fclose(fto);
return false; return false;
} }
fclose(ffrom); fclose(ffrom);
fclose(fto); fclose(fto);
return true; return true;
} }
bool remove_directory(const string &path) { // from http://stackoverflow.com/questions/2256945/removing-a-non-empty-directory-programmatically-in-c-or-c bool remove_directory(const string &path) { // from http://stackoverflow.com/questions/2256945/removing-a-non-empty-directory-programmatically-in-c-or-c
DIR *d = opendir(path.c_str()); DIR *d = opendir(path.c_str());
writeLog("Removing dir '%s'", path.c_str()); writeLog("Removing dir '%s'", path.c_str());
if (!d) { if (!d) {
writeLog("Could not open dir '%s'", path.c_str()); writeLog("Could not open dir '%s'", path.c_str());
return (errno == ENOENT); return (errno == ENOENT);
} }
while (struct dirent *p = readdir(d)) { while (struct dirent *p = readdir(d)) {
/* Skip the names "." and ".." as we don't want to recurse on them. */ /* Skip the names "." and ".." as we don't want to recurse on them. */
if (!strcmp(p->d_name, ".") || !strcmp(p->d_name, "..")) continue; if (!strcmp(p->d_name, ".") || !strcmp(p->d_name, "..")) continue;
string fname = path + '/' + p->d_name; string fname = path + '/' + p->d_name;
struct stat statbuf; struct stat statbuf;
writeLog("Trying to get stat() for '%s'", fname.c_str()); writeLog("Trying to get stat() for '%s'", fname.c_str());
if (!stat(fname.c_str(), &statbuf)) { if (!stat(fname.c_str(), &statbuf)) {
if (S_ISDIR(statbuf.st_mode)) { if (S_ISDIR(statbuf.st_mode)) {
if (!remove_directory(fname.c_str())) { if (!remove_directory(fname.c_str())) {
closedir(d); closedir(d);
return false; return false;
} }
} else { } else {
writeLog("Unlinking file '%s'", fname.c_str()); writeLog("Unlinking file '%s'", fname.c_str());
if (unlink(fname.c_str())) { if (unlink(fname.c_str())) {
writeLog("Failed to unlink '%s'", fname.c_str()); writeLog("Failed to unlink '%s'", fname.c_str());
closedir(d); closedir(d);
return false; return false;
} }
} }
} else { } else {
writeLog("Failed to call stat() on '%s'", fname.c_str()); writeLog("Failed to call stat() on '%s'", fname.c_str());
} }
} }
closedir(d); closedir(d);
writeLog("Finally removing dir '%s'", path.c_str()); writeLog("Finally removing dir '%s'", path.c_str());
return !rmdir(path.c_str()); return !rmdir(path.c_str());
} }
bool mkpath(const char *path) { bool mkpath(const char *path) {
int status = 0, pathsize = strlen(path) + 1; int status = 0, pathsize = strlen(path) + 1;
char *copypath = new char[pathsize]; char *copypath = new char[pathsize];
memcpy(copypath, path, pathsize); memcpy(copypath, path, pathsize);
char *pp = copypath, *sp; char *pp = copypath, *sp;
while (status == 0 && (sp = strchr(pp, '/')) != 0) { while (status == 0 && (sp = strchr(pp, '/')) != 0) {
if (sp != pp) { if (sp != pp) {
/* Neither root nor double slash in path */ /* Neither root nor double slash in path */
*sp = '\0'; *sp = '\0';
if (!do_mkdir(copypath)) { if (!do_mkdir(copypath)) {
delete[] copypath; delete[] copypath;
return false; return false;
} }
*sp = '/'; *sp = '/';
} }
pp = sp + 1; pp = sp + 1;
} }
delete[] copypath; delete[] copypath;
return do_mkdir(path); return do_mkdir(path);
} }
bool equal(string a, string b) { bool equal(string a, string b) {
std::transform(a.begin(), a.end(), a.begin(), ::tolower); std::transform(a.begin(), a.end(), a.begin(), ::tolower);
std::transform(b.begin(), b.end(), b.begin(), ::tolower); std::transform(b.begin(), b.end(), b.begin(), ::tolower);
return a == b; return a == b;
} }
void delFolder() { void delFolder() {
string delPathOld = workDir + "tupdates/ready", delPath = workDir + "tupdates/temp", delFolder = workDir + "tupdates"; string delPathOld = workDir + "tupdates/ready", delPath = workDir + "tupdates/temp", delFolder = workDir + "tupdates";
writeLog("Fully clearing old path '%s'..", delPathOld.c_str()); writeLog("Fully clearing old path '%s'..", delPathOld.c_str());
if (!remove_directory(delPathOld)) { if (!remove_directory(delPathOld)) {
writeLog("Failed to clear old path! :( New path was used?.."); writeLog("Failed to clear old path! :( New path was used?..");
} }
writeLog("Fully clearing path '%s'..", delPath.c_str()); writeLog("Fully clearing path '%s'..", delPath.c_str());
if (!remove_directory(delPath)) { if (!remove_directory(delPath)) {
writeLog("Error: failed to clear path! :("); writeLog("Error: failed to clear path! :(");
@ -219,210 +222,233 @@ void delFolder() {
} }
bool update() { bool update() {
writeLog("Update started.."); writeLog("Update started..");
string updDir = workDir + "tupdates/temp", readyFilePath = workDir + "tupdates/temp/ready", tdataDir = workDir + "tupdates/temp/tdata"; string updDir = workDir + "tupdates/temp", readyFilePath = workDir + "tupdates/temp/ready", tdataDir = workDir + "tupdates/temp/tdata";
{ {
FILE *readyFile = fopen(readyFilePath.c_str(), "rb"); FILE *readyFile = fopen(readyFilePath.c_str(), "rb");
if (readyFile) { if (readyFile) {
fclose(readyFile); fclose(readyFile);
writeLog("Ready file found! Using new path '%s'..", updDir.c_str()); writeLog("Ready file found! Using new path '%s'..", updDir.c_str());
} else { } else {
updDir = workDir + "tupdates/ready"; // old updDir = workDir + "tupdates/ready"; // old
tdataDir = workDir + "tupdates/ready/tdata"; tdataDir = workDir + "tupdates/ready/tdata";
writeLog("Ready file not found! Using old path '%s'..", updDir.c_str()); writeLog("Ready file not found! Using old path '%s'..", updDir.c_str());
} }
} }
deque<string> dirs; deque<string> dirs;
dirs.push_back(updDir); dirs.push_back(updDir);
deque<string> from, to, forcedirs; deque<string> from, to, forcedirs;
do { do {
string dir = dirs.front(); string dir = dirs.front();
dirs.pop_front(); dirs.pop_front();
string toDir = updaterDir; string toDir = exePath;
if (dir.size() > updDir.size() + 1) { if (dir.size() > updDir.size() + 1) {
toDir += (dir.substr(updDir.size() + 1) + '/'); toDir += (dir.substr(updDir.size() + 1) + '/');
forcedirs.push_back(toDir); forcedirs.push_back(toDir);
writeLog("Parsing dir '%s' in update tree..", toDir.c_str()); writeLog("Parsing dir '%s' in update tree..", toDir.c_str());
} }
DIR *d = opendir(dir.c_str()); DIR *d = opendir(dir.c_str());
if (!d) { if (!d) {
writeLog("Failed to open dir %s", dir.c_str()); writeLog("Failed to open dir %s", dir.c_str());
return false; return false;
} }
while (struct dirent *p = readdir(d)) { while (struct dirent *p = readdir(d)) {
/* Skip the names "." and ".." as we don't want to recurse on them. */ /* Skip the names "." and ".." as we don't want to recurse on them. */
if (!strcmp(p->d_name, ".") || !strcmp(p->d_name, "..")) continue; if (!strcmp(p->d_name, ".") || !strcmp(p->d_name, "..")) continue;
string fname = dir + '/' + p->d_name; string fname = dir + '/' + p->d_name;
struct stat statbuf; struct stat statbuf;
if (fname.substr(0, tdataDir.size()) == tdataDir && (fname.size() <= tdataDir.size() || fname.at(tdataDir.size()) == '/')) { if (fname.substr(0, tdataDir.size()) == tdataDir && (fname.size() <= tdataDir.size() || fname.at(tdataDir.size()) == '/')) {
writeLog("Skipping 'tdata' path '%s'", fname.c_str()); writeLog("Skipping 'tdata' path '%s'", fname.c_str());
} else if (!stat(fname.c_str(), &statbuf)) { } else if (!stat(fname.c_str(), &statbuf)) {
if (S_ISDIR(statbuf.st_mode)) { if (S_ISDIR(statbuf.st_mode)) {
dirs.push_back(fname); dirs.push_back(fname);
writeLog("Added dir '%s' in update tree..", fname.c_str()); writeLog("Added dir '%s' in update tree..", fname.c_str());
} else { } else {
string tofname = updaterDir + fname.substr(updDir.size() + 1); string tofname = exePath + fname.substr(updDir.size() + 1);
if (equal(tofname, updaterName)) { // bad update - has Updater - delete all dir if (equal(tofname, updaterName)) { // bad update - has Updater - delete all dir
writeLog("Error: bad update, has Updater! '%s' equal '%s'", tofname.c_str(), updaterName.c_str()); writeLog("Error: bad update, has Updater! '%s' equal '%s'", tofname.c_str(), updaterName.c_str());
delFolder(); delFolder();
return false; return false;
} else if (equal(tofname, updaterDir + "Telegram") && exeName != "Telegram") { } else if (equal(tofname, exePath + "Telegram") && exeName != "Telegram") {
string fullBinaryPath = updaterDir + exeName; string fullBinaryPath = exePath + exeName;
writeLog("Target binary found: '%s', changing to '%s'", tofname.c_str(), fullBinaryPath.c_str()); writeLog("Target binary found: '%s', changing to '%s'", tofname.c_str(), fullBinaryPath.c_str());
tofname = fullBinaryPath; tofname = fullBinaryPath;
} }
if (fname == readyFilePath) { if (fname == readyFilePath) {
writeLog("Skipped ready file '%s'", fname.c_str()); writeLog("Skipped ready file '%s'", fname.c_str());
} else { } else {
from.push_back(fname); from.push_back(fname);
to.push_back(tofname); to.push_back(tofname);
writeLog("Added file '%s' to be copied to '%s'", fname.c_str(), tofname.c_str()); writeLog("Added file '%s' to be copied to '%s'", fname.c_str(), tofname.c_str());
} }
} }
} else { } else {
writeLog("Could not get stat() for file %s", fname.c_str()); writeLog("Could not get stat() for file %s", fname.c_str());
} }
} }
closedir(d); closedir(d);
} while (!dirs.empty()); } while (!dirs.empty());
for (size_t i = 0; i < forcedirs.size(); ++i) { for (size_t i = 0; i < forcedirs.size(); ++i) {
string forcedir = forcedirs[i]; string forcedir = forcedirs[i];
writeLog("Forcing dir '%s'..", forcedir.c_str()); writeLog("Forcing dir '%s'..", forcedir.c_str());
if (!forcedir.empty() && !mkpath(forcedir.c_str())) { if (!forcedir.empty() && !mkpath(forcedir.c_str())) {
writeLog("Error: failed to create dir '%s'..", forcedir.c_str()); writeLog("Error: failed to create dir '%s'..", forcedir.c_str());
delFolder(); delFolder();
return false; return false;
} }
} }
for (size_t i = 0; i < from.size(); ++i) { for (size_t i = 0; i < from.size(); ++i) {
string fname = from[i], tofname = to[i]; string fname = from[i], tofname = to[i];
writeLog("Copying file '%s' to '%s'..", fname.c_str(), tofname.c_str()); writeLog("Copying file '%s' to '%s'..", fname.c_str(), tofname.c_str());
int copyTries = 0, triesLimit = 30; int copyTries = 0, triesLimit = 30;
do { do {
if (!copyFile(fname.c_str(), tofname.c_str())) { if (!copyFile(fname.c_str(), tofname.c_str())) {
++copyTries; ++copyTries;
usleep(100000); usleep(100000);
} else { } else {
break; break;
} }
} while (copyTries < triesLimit); } while (copyTries < triesLimit);
if (copyTries == triesLimit) { if (copyTries == triesLimit) {
writeLog("Error: failed to copy, asking to retry.."); writeLog("Error: failed to copy, asking to retry..");
delFolder(); delFolder();
return false; return false;
} }
} }
writeLog("Update succeed! Clearing folder.."); writeLog("Update succeed! Clearing folder..");
delFolder(); delFolder();
return true; return true;
} }
int main(int argc, char *argv[]) { string CurrentExecutablePath(int argc, char *argv[]) {
bool needupdate = true, autostart = false, debug = false, tosettings = false, startintray = false, testmode = false; constexpr auto kMaxPath = 1024;
char result[kMaxPath] = { 0 };
auto count = readlink("/proc/self/exe", result, kMaxPath);
if (count > 0) {
return string(result);
}
char *key = 0, *crashreport = 0; // Fallback to the first command line argument.
for (int i = 1; i < argc; ++i) { return argc ? string(argv[0]) : string();
if (equal(argv[i], "-noupdate")) { }
needupdate = false;
} else if (equal(argv[i], "-autostart")) { int main(int argc, char *argv[]) {
autostart = true; bool needupdate = true, autostart = false, debug = false, tosettings = false, startintray = false, testmode = false;
char *key = 0, *crashreport = 0;
for (int i = 1; i < argc; ++i) {
if (equal(argv[i], "-noupdate")) {
needupdate = false;
} else if (equal(argv[i], "-autostart")) {
autostart = true;
} else if (equal(argv[i], "-debug")) { } else if (equal(argv[i], "-debug")) {
debug = _debug = true; debug = _debug = true;
} else if (equal(argv[i], "-startintray")) { } else if (equal(argv[i], "-startintray")) {
startintray = true; startintray = true;
} else if (equal(argv[i], "-testmode")) { } else if (equal(argv[i], "-testmode")) {
testmode = true; testmode = true;
} else if (equal(argv[i], "-tosettings")) { } else if (equal(argv[i], "-tosettings")) {
tosettings = true; tosettings = true;
} else if (equal(argv[i], "-key") && ++i < argc) { } else if (equal(argv[i], "-key") && ++i < argc) {
key = argv[i]; key = argv[i];
} else if (equal(argv[i], "-workpath") && ++i < argc) { } else if (equal(argv[i], "-workpath") && ++i < argc) {
workDir = argv[i]; workDir = argv[i];
} else if (equal(argv[i], "-crashreport") && ++i < argc) { } else if (equal(argv[i], "-crashreport") && ++i < argc) {
crashreport = argv[i]; crashreport = argv[i];
} else if (equal(argv[i], "-exename") && ++i < argc) { } else if (equal(argv[i], "-exename") && ++i < argc) {
exeName = argv[i]; exeName = argv[i];
} else if (equal(argv[i], "-exepath") && ++i < argc) {
exePath = argv[i];
} }
} }
if (exeName.empty() || exeName.find('/') != string::npos) { if (exeName.empty() || exeName.find('/') != string::npos) {
exeName = "Telegram"; exeName = "Telegram";
} }
openLog(); openLog();
writeLog("Updater started.."); writeLog("Updater started..");
for (int i = 0; i < argc; ++i) { for (int i = 0; i < argc; ++i) {
writeLog("Argument: '%s'", argv[i]); writeLog("Argument: '%s'", argv[i]);
} }
if (needupdate) writeLog("Need to update!"); if (needupdate) writeLog("Need to update!");
if (autostart) writeLog("From autostart!"); if (autostart) writeLog("From autostart!");
updaterName = argv[0]; updaterName = CurrentExecutablePath(argc, argv);
writeLog("Updater binary name is: %s", updaterName.c_str()); writeLog("Updater binary full path is: %s", updaterName.c_str());
if (updaterName.size() >= 7) { if (exePath.empty()) {
if (equal(updaterName.substr(updaterName.size() - 7), "Updater")) { writeLog("Executable path is not specified :(");
} else {
writeLog("Executable path: %s", exePath.c_str());
}
if (updaterName.size() >= 7) {
if (equal(updaterName.substr(updaterName.size() - 7), "Updater")) {
updaterDir = updaterName.substr(0, updaterName.size() - 7); updaterDir = updaterName.substr(0, updaterName.size() - 7);
writeLog("Updater binary dir is: %s", updaterDir.c_str()); writeLog("Updater binary dir is: %s", updaterDir.c_str());
if (needupdate) { if (exePath.empty()) {
if (workDir.empty()) { // old app launched, update prepared in tupdates/ready (not in tupdates/temp) exePath = updaterDir;
writeLog("No workdir, trying to figure it out"); writeLog("Using updater binary dir.", exePath.c_str());
struct passwd *pw = getpwuid(getuid()); }
if (pw && pw->pw_dir && strlen(pw->pw_dir)) { if (needupdate) {
string tryDir = pw->pw_dir + string("/.TelegramDesktop/"); if (workDir.empty()) { // old app launched, update prepared in tupdates/ready (not in tupdates/temp)
struct stat statbuf; writeLog("No workdir, trying to figure it out");
writeLog("Trying to use '%s' as workDir, getting stat() for tupdates/ready", tryDir.c_str()); struct passwd *pw = getpwuid(getuid());
if (!stat((tryDir + "tupdates/ready").c_str(), &statbuf)) { if (pw && pw->pw_dir && strlen(pw->pw_dir)) {
writeLog("Stat got"); string tryDir = pw->pw_dir + string("/.TelegramDesktop/");
if (S_ISDIR(statbuf.st_mode)) { struct stat statbuf;
writeLog("It is directory, using home work dir"); writeLog("Trying to use '%s' as workDir, getting stat() for tupdates/ready", tryDir.c_str());
workDir = tryDir; if (!stat((tryDir + "tupdates/ready").c_str(), &statbuf)) {
} writeLog("Stat got");
} if (S_ISDIR(statbuf.st_mode)) {
} writeLog("It is directory, using home work dir");
if (workDir.empty()) { workDir = tryDir;
workDir = updaterDir; }
}
}
if (workDir.empty()) {
workDir = exePath;
struct stat statbuf; struct stat statbuf;
writeLog("Trying to use current as workDir, getting stat() for tupdates/ready"); writeLog("Trying to use current as workDir, getting stat() for tupdates/ready");
if (!stat("tupdates/ready", &statbuf)) { if (!stat("tupdates/ready", &statbuf)) {
writeLog("Stat got"); writeLog("Stat got");
if (S_ISDIR(statbuf.st_mode)) { if (S_ISDIR(statbuf.st_mode)) {
writeLog("It is directory, using current dir"); writeLog("It is directory, using current dir");
workDir = string(); workDir = string();
} }
} }
} }
} else { } else {
writeLog("Passed workpath is '%s'", workDir.c_str()); writeLog("Passed workpath is '%s'", workDir.c_str());
} }
update(); update();
} }
} else { } else {
writeLog("Error: bad exe name!"); writeLog("Error: bad exe name!");
} }
} else { } else {
writeLog("Error: short exe name!"); writeLog("Error: short exe name!");
} }
static const int MaxLen = 65536, MaxArgsCount = 128; static const int MaxLen = 65536, MaxArgsCount = 128;
char path[MaxLen] = {0}; char path[MaxLen] = {0};
string fullBinaryPath = updaterDir + exeName; string fullBinaryPath = exePath + exeName;
strcpy(path, fullBinaryPath.c_str()); strcpy(path, fullBinaryPath.c_str());
char *args[MaxArgsCount] = {0}, p_noupdate[] = "-noupdate", p_autostart[] = "-autostart", p_debug[] = "-debug", p_tosettings[] = "-tosettings", p_key[] = "-key", p_startintray[] = "-startintray", p_testmode[] = "-testmode"; char *args[MaxArgsCount] = {0}, p_noupdate[] = "-noupdate", p_autostart[] = "-autostart", p_debug[] = "-debug", p_tosettings[] = "-tosettings", p_key[] = "-key", p_startintray[] = "-startintray", p_testmode[] = "-testmode";
int argIndex = 0; int argIndex = 0;
args[argIndex++] = path; args[argIndex++] = path;
if (crashreport) { if (crashreport) {
args[argIndex++] = crashreport; args[argIndex++] = crashreport;
} else { } else {
@ -437,13 +463,13 @@ int main(int argc, char *argv[]) {
args[argIndex++] = key; args[argIndex++] = key;
} }
} }
pid_t pid = fork(); pid_t pid = fork();
switch (pid) { switch (pid) {
case -1: writeLog("fork() failed!"); return 1; case -1: writeLog("fork() failed!"); return 1;
case 0: execv(path, args); return 1; case 0: execv(path, args); return 1;
} }
writeLog("Executed Telegram, closing log and quitting.."); writeLog("Executed Telegram, closing log and quitting..");
closeLog(); closeLog();
return 0; return 0;

View File

@ -454,7 +454,7 @@ void Application::startUpdateCheck(bool forceWait) {
if (!Sandbox::started()) return; if (!Sandbox::started()) return;
_updateCheckTimer->stop(); _updateCheckTimer->stop();
if (_updateThread || _updateReply || !cAutoUpdate()) return; if (_updateThread || _updateReply || !cAutoUpdate() || cExeName().isEmpty()) return;
int32 constDelay = cBetaVersion() ? 600 : UpdateDelayConstPart, randDelay = cBetaVersion() ? 300 : UpdateDelayRandPart; int32 constDelay = cBetaVersion() ? 600 : UpdateDelayConstPart, randDelay = cBetaVersion() ? 300 : UpdateDelayRandPart;
int32 updateInSecs = cLastUpdateCheck() + constDelay + int32(rand() % randDelay) - unixtime(); int32 updateInSecs = cLastUpdateCheck() + constDelay + int32(rand() % randDelay) - unixtime();

View File

@ -486,7 +486,7 @@ UpdateChecker::~UpdateChecker() {
bool checkReadyUpdate() { bool checkReadyUpdate() {
QString readyFilePath = cWorkingDir() + qsl("tupdates/temp/ready"), readyPath = cWorkingDir() + qsl("tupdates/temp"); QString readyFilePath = cWorkingDir() + qsl("tupdates/temp/ready"), readyPath = cWorkingDir() + qsl("tupdates/temp");
if (!QFile(readyFilePath).exists()) { if (!QFile(readyFilePath).exists() || cExeName().isEmpty()) {
if (QDir(cWorkingDir() + qsl("tupdates/ready")).exists() || QDir(cWorkingDir() + qsl("tupdates/temp")).exists()) { if (QDir(cWorkingDir() + qsl("tupdates/ready")).exists() || QDir(cWorkingDir() + qsl("tupdates/temp")).exists()) {
UpdateChecker::clearAll(); UpdateChecker::clearAll();
} }

View File

@ -369,7 +369,7 @@ namespace Logs {
LOG(("Executable dir: %1, name: %2").arg(cExeDir()).arg(cExeName())); LOG(("Executable dir: %1, name: %2").arg(cExeDir()).arg(cExeName()));
LOG(("Initial working dir: %1").arg(initialWorkingDir)); LOG(("Initial working dir: %1").arg(initialWorkingDir));
LOG(("Working dir: %1").arg(cWorkingDir())); LOG(("Working dir: %1").arg(cWorkingDir()));
LOG(("Arguments: %1").arg(cArguments())); LOG(("Command line: %1").arg(cArguments()));
if (!LogsData) { if (!LogsData) {
LOG(("FATAL: Could not open '%1' for writing log!").arg(_logsFilePath(LogDataMain, qsl("_startXX")))); LOG(("FATAL: Could not open '%1' for writing log!").arg(_logsFilePath(LogDataMain, qsl("_startXX"))));
@ -391,7 +391,6 @@ namespace Logs {
for (LogsInMemoryList::const_iterator i = list.cbegin(), e = list.cend(); i != e; ++i) { for (LogsInMemoryList::const_iterator i = list.cbegin(), e = list.cend(); i != e; ++i) {
if (i->first == LogDataMain) { if (i->first == LogDataMain) {
_logsWrite(i->first, i->second); _logsWrite(i->first, i->second);
LOG(("First: %1, %2").arg(i->first).arg(i->second));
} }
} }
} }

View File

@ -40,6 +40,27 @@ Copyright (c) 2014-2017 John Preston, https://desktop.telegram.org
using namespace Platform; using namespace Platform;
using Platform::File::internal::EscapeShell; using Platform::File::internal::EscapeShell;
namespace Platform {
QString CurrentExecutablePath(int argc, char *argv[]) {
constexpr auto kMaxPath = 1024;
char result[kMaxPath] = { 0 };
auto count = readlink("/proc/self/exe", result, kMaxPath);
if (count > 0) {
auto filename = QFile::decodeName(result);
auto deletedPostfix = qstr(" (deleted)");
if (filename.endsWith(deletedPostfix) && !QFileInfo(filename).exists()) {
filename.chop(deletedPostfix.size());
}
return filename;
}
// Fallback to the first command line argument.
return argc ? QFile::decodeName(argv[0]) : QString();
}
} // namespace Platform
namespace { namespace {
class _PsEventFilter : public QAbstractNativeEventFilter { class _PsEventFilter : public QAbstractNativeEventFilter {
@ -104,7 +125,7 @@ QString demanglestr(const QString &mangled) {
QStringList addr2linestr(uint64 *addresses, int count) { QStringList addr2linestr(uint64 *addresses, int count) {
QStringList result; QStringList result;
if (!count) return result; if (!count || cExeName().isEmpty()) return result;
result.reserve(count); result.reserve(count);
QByteArray cmd = "addr2line -e " + EscapeShell(QFile::encodeName(cExeDir() + cExeName())); QByteArray cmd = "addr2line -e " + EscapeShell(QFile::encodeName(cExeDir() + cExeName()));
@ -306,34 +327,6 @@ QString psDownloadPath() {
return QStandardPaths::writableLocation(QStandardPaths::DownloadLocation) + '/' + str_const_toString(AppName) + '/'; return QStandardPaths::writableLocation(QStandardPaths::DownloadLocation) + '/' + str_const_toString(AppName) + '/';
} }
QString psCurrentExeDirectory(int argc, char *argv[]) {
QString first = argc ? QFile::decodeName(argv[0]) : QString();
if (!first.isEmpty()) {
QFileInfo info(first);
if (info.isSymLink()) {
info = info.symLinkTarget();
}
if (info.exists()) {
return QDir(info.absolutePath()).absolutePath() + '/';
}
}
return QString();
}
QString psCurrentExeName(int argc, char *argv[]) {
QString first = argc ? QFile::decodeName(argv[0]) : QString();
if (!first.isEmpty()) {
QFileInfo info(first);
if (info.isSymLink()) {
info = info.symLinkTarget();
}
if (info.exists()) {
return info.fileName();
}
}
return QString();
}
void psDoCleanup() { void psDoCleanup() {
try { try {
psAutoStart(false, true); psAutoStart(false, true);
@ -431,7 +424,7 @@ bool _psRunCommand(const QByteArray &command) {
void psRegisterCustomScheme() { void psRegisterCustomScheme() {
#ifndef TDESKTOP_DISABLE_REGISTER_CUSTOM_SCHEME #ifndef TDESKTOP_DISABLE_REGISTER_CUSTOM_SCHEME
auto home = getHomeDir(); auto home = getHomeDir();
if (home.isEmpty() || cBetaVersion()) return; // don't update desktop file for beta version if (home.isEmpty() || cBetaVersion() || cExeName().isEmpty()) return; // don't update desktop file for beta version
#ifndef TDESKTOP_DISABLE_DESKTOP_FILE_GENERATION #ifndef TDESKTOP_DISABLE_DESKTOP_FILE_GENERATION
DEBUG_LOG(("App Info: placing .desktop file")); DEBUG_LOG(("App Info: placing .desktop file"));
@ -533,10 +526,13 @@ void psNewVersion() {
} }
bool _execUpdater(bool update = true, const QString &crashreport = QString()) { bool _execUpdater(bool update = true, const QString &crashreport = QString()) {
if (cExeName().isEmpty()) {
return false;
}
static const int MaxLen = 65536, MaxArgsCount = 128; static const int MaxLen = 65536, MaxArgsCount = 128;
char path[MaxLen] = {0}; char path[MaxLen] = {0};
QByteArray data(QFile::encodeName(cExeDir() + (update ? "Updater" : gExeName))); QByteArray data(QFile::encodeName(cExeDir() + (update ? "Updater" : cExeName())));
memcpy(path, data.constData(), data.size()); memcpy(path, data.constData(), data.size());
char *args[MaxArgsCount] = { 0 }; char *args[MaxArgsCount] = { 0 };
@ -554,6 +550,8 @@ bool _execUpdater(bool update = true, const QString &crashreport = QString()) {
char p_crashreportbuf[MaxLen] = { 0 }; char p_crashreportbuf[MaxLen] = { 0 };
char p_exe[] = "-exename"; char p_exe[] = "-exename";
char p_exebuf[MaxLen] = { 0 }; char p_exebuf[MaxLen] = { 0 };
char p_exepath[] = "-exepath";
char p_exepathbuf[MaxLen] = { 0 };
int argIndex = 0; int argIndex = 0;
args[argIndex++] = path; args[argIndex++] = path;
if (!update) { if (!update) {
@ -592,6 +590,12 @@ bool _execUpdater(bool update = true, const QString &crashreport = QString()) {
args[argIndex++] = p_exe; args[argIndex++] = p_exe;
args[argIndex++] = p_exebuf; args[argIndex++] = p_exebuf;
} }
QByteArray exepathf = QFile::encodeName(cExeDir());
if (exepathf.size() > 0 && exepathf.size() < MaxLen) {
memcpy(p_exepathbuf, exepathf.constData(), exepathf.size());
args[argIndex++] = p_exepath;
args[argIndex++] = p_exepathbuf;
}
Logs::closeMain(); Logs::closeMain();
SignalHandlers::finish(); SignalHandlers::finish();

View File

@ -37,6 +37,8 @@ inline void DeInitOnTopPanel(QWidget *panel) {
inline void ReInitOnTopPanel(QWidget *panel) { inline void ReInitOnTopPanel(QWidget *panel) {
} }
QString CurrentExecutablePath(int argc, char *argv[]);
} // namespace Platform } // namespace Platform
inline QString psServerPrefix() { inline QString psServerPrefix() {
@ -65,8 +67,6 @@ void psActivateProcess(uint64 pid = 0);
QString psLocalServerPrefix(); QString psLocalServerPrefix();
QString psAppDataPath(); QString psAppDataPath();
QString psDownloadPath(); QString psDownloadPath();
QString psCurrentExeDirectory(int argc, char *argv[]);
QString psCurrentExeName(int argc, char *argv[]);
void psAutoStart(bool start, bool silent = false); void psAutoStart(bool start, bool silent = false);
void psSendToMenu(bool send, bool silent = false); void psSendToMenu(bool send, bool silent = false);

View File

@ -25,6 +25,8 @@ inline bool TranslucentWindowsSupported(QPoint globalPosition) {
return true; return true;
} }
QString CurrentExecutablePath(int argc, char *argv[]);
namespace ThirdParty { namespace ThirdParty {
inline void start() { inline void start() {
@ -66,8 +68,6 @@ void psActivateProcess(uint64 pid = 0);
QString psLocalServerPrefix(); QString psLocalServerPrefix();
QString psAppDataPath(); QString psAppDataPath();
QString psDownloadPath(); QString psDownloadPath();
QString psCurrentExeDirectory(int argc, char *argv[]);
QString psCurrentExeName(int argc, char *argv[]);
void psAutoStart(bool start, bool silent = false); void psAutoStart(bool start, bool silent = false);
void psSendToMenu(bool send, bool silent = false); void psSendToMenu(bool send, bool silent = false);

View File

@ -35,6 +35,7 @@ Copyright (c) 2014-2017 John Preston, https://desktop.telegram.org
#include <IOKit/IOKitLib.h> #include <IOKit/IOKitLib.h>
#include <IOKit/hidsystem/ev_keymap.h> #include <IOKit/hidsystem/ev_keymap.h>
#include <SPMediaKeyTap.h> #include <SPMediaKeyTap.h>
#include <mach-o/dyld.h>
namespace { namespace {
@ -82,7 +83,7 @@ void psBringToBack(QWidget *w) {
} }
QAbstractNativeEventFilter *psNativeEventFilter() { QAbstractNativeEventFilter *psNativeEventFilter() {
delete _psEventFilter; delete _psEventFilter;
_psEventFilter = new _PsEventFilter(); _psEventFilter = new _PsEventFilter();
return _psEventFilter; return _psEventFilter;
} }
@ -133,7 +134,7 @@ QString escapeShell(const QString &str) {
QStringList atosstr(uint64 *addresses, int count, uint64 base) { QStringList atosstr(uint64 *addresses, int count, uint64 base) {
QStringList result; QStringList result;
if (!count) return result; if (!count || cExeName().isEmpty()) return result;
result.reserve(count); result.reserve(count);
QString cmdstr = "atos -o " + escapeShell(cExeDir() + cExeName()) + qsl("/Contents/MacOS/Telegram -l 0x%1").arg(base, 0, 16); QString cmdstr = "atos -o " + escapeShell(cExeDir() + cExeName()) + qsl("/Contents/MacOS/Telegram -l 0x%1").arg(base, 0, 16);
@ -316,11 +317,11 @@ TimeMs psIdleTime() {
} }
QStringList psInitLogs() { QStringList psInitLogs() {
return _initLogs; return _initLogs;
} }
void psClearInitLogs() { void psClearInitLogs() {
_initLogs = QStringList(); _initLogs = QStringList();
} }
void psActivateProcess(uint64 pid) { void psActivateProcess(uint64 pid) {
@ -337,28 +338,6 @@ QString psDownloadPath() {
return objc_downloadPath(); return objc_downloadPath();
} }
QString psCurrentExeDirectory(int argc, char *argv[]) {
QString first = argc ? fromUtf8Safe(argv[0]) : QString();
if (!first.isEmpty()) {
QFileInfo info(first);
if (info.exists()) {
return QDir(info.absolutePath() + qsl("/../../..")).absolutePath() + '/';
}
}
return QString();
}
QString psCurrentExeName(int argc, char *argv[]) {
QString first = argc ? fromUtf8Safe(argv[0]) : QString();
if (!first.isEmpty()) {
QFileInfo info(first);
if (info.exists()) {
return QDir(QDir(info.absolutePath() + qsl("/../..")).absolutePath()).dirName();
}
}
return QString();
}
void psDoCleanup() { void psDoCleanup() {
try { try {
psAutoStart(false, true); psAutoStart(false, true);
@ -422,6 +401,10 @@ QString SystemLanguage() {
return QString(); return QString();
} }
QString CurrentExecutablePath(int argc, char *argv[]) {
return NS2QString([[NSBundle mainBundle] bundlePath]);
}
} // namespace Platform } // namespace Platform
void psNewVersion() { void psNewVersion() {

View File

@ -463,6 +463,9 @@ bool objc_execUpdater() {
} }
void objc_execTelegram(const QString &crashreport) { void objc_execTelegram(const QString &crashreport) {
if (cExeName().isEmpty()) {
return;
}
#ifndef OS_MAC_STORE #ifndef OS_MAC_STORE
_execUpdater(NO, crashreport); _execUpdater(NO, crashreport);
#else // OS_MAC_STORE #else // OS_MAC_STORE

View File

@ -211,34 +211,6 @@ QString psDownloadPath() {
return QStandardPaths::writableLocation(QStandardPaths::DownloadLocation) + '/' + str_const_toString(AppName) + '/'; return QStandardPaths::writableLocation(QStandardPaths::DownloadLocation) + '/' + str_const_toString(AppName) + '/';
} }
QString psCurrentExeDirectory(int argc, char *argv[]) {
LPWSTR *args;
int argsCount;
args = CommandLineToArgvW(GetCommandLine(), &argsCount);
if (args) {
QFileInfo info(QDir::fromNativeSeparators(QString::fromWCharArray(args[0])));
if (info.isFile()) {
return info.absoluteDir().absolutePath() + '/';
}
LocalFree(args);
}
return QString();
}
QString psCurrentExeName(int argc, char *argv[]) {
LPWSTR *args;
int argsCount;
args = CommandLineToArgvW(GetCommandLine(), &argsCount);
if (args) {
QFileInfo info(QDir::fromNativeSeparators(QString::fromWCharArray(args[0])));
if (info.isFile()) {
return info.fileName();
}
LocalFree(args);
}
return QString();
}
void psDoCleanup() { void psDoCleanup() {
try { try {
psAutoStart(false, true); psAutoStart(false, true);
@ -374,6 +346,24 @@ QString SystemCountry() {
return QString(); return QString();
} }
QString CurrentExecutablePath(int argc, char *argv[]) {
WCHAR result[MAX_PATH + 1] = { 0 };
auto count = GetModuleFileName(nullptr, result, MAX_PATH + 1);
if (count < MAX_PATH + 1) {
auto info = QFileInfo(QDir::fromNativeSeparators(QString::fromWCharArray(result)));
return info.absoluteFilePath();
}
// Fallback to the first command line argument.
auto argsCount = 0;
if (auto args = CommandLineToArgvW(GetCommandLine(), &argsCount)) {
auto info = QFileInfo(QDir::fromNativeSeparators(QString::fromWCharArray(args[0])));
LocalFree(args);
return info.absoluteFilePath();
}
return QString();
}
namespace { namespace {
QString GetLangCodeById(unsigned lngId) { QString GetLangCodeById(unsigned lngId) {
@ -592,6 +582,9 @@ namespace {
} }
void RegisterCustomScheme() { void RegisterCustomScheme() {
if (cExeName().isEmpty()) {
return;
}
#ifndef TDESKTOP_DISABLE_REGISTER_CUSTOM_SCHEME #ifndef TDESKTOP_DISABLE_REGISTER_CUSTOM_SCHEME
DEBUG_LOG(("App Info: Checking custom scheme 'tg'...")); DEBUG_LOG(("App Info: Checking custom scheme 'tg'..."));
@ -647,6 +640,10 @@ void psNewVersion() {
} }
void psExecUpdater() { void psExecUpdater() {
if (cExeName().isEmpty()) {
return;
}
QString targs = qsl("-update -exename \"") + cExeName() + '"'; QString targs = qsl("-update -exename \"") + cExeName() + '"';
if (cLaunchMode() == LaunchModeAutoStart) targs += qsl(" -autostart"); if (cLaunchMode() == LaunchModeAutoStart) targs += qsl(" -autostart");
if (cDebug()) targs += qsl(" -debug"); if (cDebug()) targs += qsl(" -debug");
@ -666,6 +663,9 @@ void psExecUpdater() {
} }
void psExecTelegram(const QString &crashreport) { void psExecTelegram(const QString &crashreport) {
if (cExeName().isEmpty()) {
return;
}
QString targs = crashreport.isEmpty() ? qsl("-noupdate") : ('"' + crashreport + '"'); QString targs = crashreport.isEmpty() ? qsl("-noupdate") : ('"' + crashreport + '"');
if (crashreport.isEmpty()) { if (crashreport.isEmpty()) {
if (cRestartingToSettings()) targs += qsl(" -tosettings"); if (cRestartingToSettings()) targs += qsl(" -tosettings");
@ -687,6 +687,9 @@ void psExecTelegram(const QString &crashreport) {
} }
void _manageAppLnk(bool create, bool silent, int path_csidl, const wchar_t *args, const wchar_t *description) { void _manageAppLnk(bool create, bool silent, int path_csidl, const wchar_t *args, const wchar_t *description) {
if (cExeName().isEmpty()) {
return;
}
WCHAR startupFolder[MAX_PATH]; WCHAR startupFolder[MAX_PATH];
HRESULT hr = SHGetFolderPath(0, path_csidl, 0, SHGFP_TYPE_CURRENT, startupFolder); HRESULT hr = SHGetFolderPath(0, path_csidl, 0, SHGFP_TYPE_CURRENT, startupFolder);
if (SUCCEEDED(hr)) { if (SUCCEEDED(hr)) {
@ -1113,7 +1116,7 @@ void psWriteDump() {
char ImageHlpSymbol64[sizeof(IMAGEHLP_SYMBOL64) + StackEntryMaxNameLength]; char ImageHlpSymbol64[sizeof(IMAGEHLP_SYMBOL64) + StackEntryMaxNameLength];
QString psPrepareCrashDump(const QByteArray &crashdump, QString dumpfile) { QString psPrepareCrashDump(const QByteArray &crashdump, QString dumpfile) {
if (!LoadDbgHelp(true)) { if (!LoadDbgHelp(true) || cExeName().isEmpty()) {
return qsl("ERROR: could not init dbghelp.dll!"); return qsl("ERROR: could not init dbghelp.dll!");
} }

View File

@ -43,6 +43,8 @@ inline void DeInitOnTopPanel(QWidget *panel) {
inline void ReInitOnTopPanel(QWidget *panel) { inline void ReInitOnTopPanel(QWidget *panel) {
} }
QString CurrentExecutablePath(int argc, char *argv[]);
namespace ThirdParty { namespace ThirdParty {
inline void start() { inline void start() {
@ -78,8 +80,6 @@ QString psLocalServerPrefix();
QString psAppDataPath(); QString psAppDataPath();
QString psAppDataPathOld(); QString psAppDataPathOld();
QString psDownloadPath(); QString psDownloadPath();
QString psCurrentExeDirectory(int argc, char *argv[]);
QString psCurrentExeName(int argc, char *argv[]);
void psAutoStart(bool start, bool silent = false); void psAutoStart(bool start, bool silent = false);
void psSendToMenu(bool send, bool silent = false); void psSendToMenu(bool send, bool silent = false);

View File

@ -263,7 +263,7 @@ bool validateShortcutAt(const QString &path) {
bool validateShortcut() { bool validateShortcut() {
QString path = systemShortcutPath(); QString path = systemShortcutPath();
if (path.isEmpty()) return false; if (path.isEmpty() || cExeName().isEmpty()) return false;
if (cBetaVersion()) { if (cBetaVersion()) {
path += qsl("TelegramBeta.lnk"); path += qsl("TelegramBeta.lnk");

View File

@ -163,13 +163,26 @@ void settingsParseArgs(int argc, char *argv[]) {
QStringList args; QStringList args;
for (int32 i = 0; i < argc; ++i) { for (int32 i = 0; i < argc; ++i) {
args.push_back('"' + fromUtf8Safe(argv[i]) + '"'); args.push_back(fromUtf8Safe(argv[i]));
} }
gArguments = args.join(' '); gArguments = args.join(' ');
gExeDir = psCurrentExeDirectory(argc, argv); auto path = Platform::CurrentExecutablePath(argc, argv);
gExeName = psCurrentExeName(argc, argv); LOG(("Executable path before check: %1").arg(path));
for (int32 i = 0; i < argc; ++i) { if (!path.isEmpty()) {
auto info = QFileInfo(path);
if (info.isSymLink()) {
info = info.symLinkTarget();
}
if (info.exists()) {
gExeDir = info.absoluteDir().absolutePath() + '/';
gExeName = info.fileName();
}
}
if (cExeName().isEmpty()) {
LOG(("WARNING: Could not compute executable path, some features will be disabled."));
}
for (auto i = 0; i != argc; ++i) {
if (qstr("-testmode") == argv[i]) { if (qstr("-testmode") == argv[i]) {
gTestMode = true; gTestMode = true;
} else if (qstr("-debug") == argv[i]) { } else if (qstr("-debug") == argv[i]) {