This article focuses on only one aspect of Target Eye, which is the Auto Update mechanism. This mechanism is used for silently updating the Target Eye Secret Agent whenever there is a newer version available on the server.
Introduction
Auto Update mechanism doesn't have to be based on the actual version number (kept in the Version String), but can also base on the Last Modified Date Stamp of the newer version compared to the old one. Target Eye Monitoring System, developed from 2000 until 2010, had such mechanism. The next article in this series is about Target Eye's screen capturing and the third one is about the Shopping List mechanism. The fourth article is about Keyboard Capturing. The fifth article is about the Cover Story mechanism. The sixth article is about hiding files the Target Eye way.
Background
Target Eye Monitoring System, which I have developed 12 years ago, was one of the first surveillance and monitoring tools for capturing activity of remote computers. The following description is taken from the original Business Plan of this venture:
Target Eye Monitoring System
Target Eye is a start-up company whose mission is to develop integrated software solutions for real-time monitoring of remote PCs, which are based on the company’s patent pending technologies (60/204,084 and 60/203,832). Our major product, Target Eye Monitoring System, is a software product that can continuously track, record, playback, analyze and report any activity performed on one or multiple remote PCs, in a way which is undetectable by their users. The software relies on a stream of rapidly captured, compressed full-screen images and continuous keystroke capturing to provide a comprehensive and accurate account of user activities, including local activities which do not generate any network traffic. In this way, the software can track and record activities, which are undetectable by systems relying on network traffic analysis. A smart agent module running on the monitored PCs uses a rule base to send alerts to the monitoring location(s) or perform pre-defined local operations. Monitoring can be performed from multiple locations. Major markets are law-enforcement.
Target Eye Monitoring System was developed with an auto update mechanism. This mechanism allows smooth and silent (un-attendant) execution of the new version instead of the current one.
An historical image: The first version of Target Eye (April 2000)
A more recent version (Target Eye 2007)
Target Eye's Building Blocks
There are several terms and building blocks that sums up to the Target Eye Monitoring System:
- Target Eye Secret Agent - the covert part of the product that runs on the monitored computer
- Target Eye Operator - the authority that operates the Secret Agent (for example: a Law Enforcement agency).
- A Mission - a request to perform an action. There are many possible actions (for example, capturing the screen, as described in another article of mine or searching and finding files, as described in this article).
- Target Eye Compiler - The tool that is used by the Target Eye Operator to customize a Secret Agent for performing specific tasks.
About this Article
This article focuses on only one aspect of this product, which is the Auto Update mechanism. This mechanism is used for silently updating the Target Eye Secret Agent whenever there is a newer version available on the server.
Creating and Marking Incremental Versions
In order to be able to determine a newer version over the current one, there must be a mechanism to mark the various versions, to increment the version number, and to examine the version of a given executable.
The most common way of doing so is using the "Version String" resource, and to use a prebuild automated tool to promote this string each time the application is built.
I used another method which is based on the list modification date of the executable file. This method has its pros and cons, but can be useful for most cases, since it will allow your end users to get any version of your application that was built after the one that is currently installed.
Before I explain, it is important to mention two global variables which are used to build at start:
strRegularLocation
The location and full path of the application when it runs normally (i.e., c:\program files\your app name\your app.exe),
and…
strTemporaryLocation
Another full path to be used for the temporary version downloaded when there is an update.
The reason for doing so is because since the application downloads its new version, the new version can't be downloaded to its current location, and can't replace itself because while a file is used (or an application is running), the file is locked and can't be moved, deleted or renamed.
char strRegularLocation[256];
char strTemporaryLocation[256];
Filling strRegularLocation
and strTemporaryLocation
with real values.
strRegularLocation
is taken simply from __argv[0]
, provided that we are sure that we aren't running already from the temporary location. We ensure that by using a parameter named "INSTALL
" which will be explained later.
strTemporaryLocation
is built using a common folder and a temporary name combined. We use GetSpecialFolder()
to find the path name of this folder in any computer running the application.
Getting the Date Stamp of Current Version
To do so, TEGetVersion()
, the first building block, is used and returns a CString
containing the last modification date of a given file.
TEGetVersion returns the last modification date / time of a given file
CString
TEGetVersion (CString FileName)
{
CFileStatus status1;
CTime Time1;
if( CFile::GetStatus( FileName, status1) )
{
Time1 = status1.m_mtime;
return (Time1.Format("%d%m%M%S"));
}
return ((CString)"");
}
When my application starts, I store the date / time stamp of it somewhere.
TE_Options.Version=TEGetVersion((CString)__argv[0]);
Now we need to get the date / time stamp of the file online, preferably, without having to download it first, so we only download when we need to update to a newer version.
HINTERNET FileHandle=NULL;
WIN32_FIND_DATA ftpFileData;
FileHandle= FtpFindFirstFile( m_ftpHandle, FTP_NEWVERSION, &ftpFileData,
INTERNET_FLAG_RELOAD, 0 );
if( NULL != FileHandle )
{
SYSTEMTIME ftpFileWriteTime, stUTC1;
FILETIME ftp;
FileTimeToSystemTime( &ftpFileData.ftLastWriteTime, &stUTC1 );
SystemTimeToTzSpecificLocalTime( NULL, &stUTC1, &ftpFileWriteTime );
}
We need to define how old the current versionshould be in order to update it. Again, this approach can be very useful in some cases and less useful in other cases. For example, if your application involves a database, you might be interested to ensure that the database is always most recent and never older than 3 days.
#define UPDATEEVERY 60*24*7 // 7 days
#define APP_EXE_NAME "TargetEyeTest.exe"
#define FTP_NEWVERSION "NewVersion.exe"
#define APP_REGULAR_FOLDER "\\TargetEye\\"
The next step is to compare the date / time stamp of each file.
CFileStatus
statusOld;
CTime TimeOld;
if( CFile::GetStatus( FileHandle, statusOld ) )
{
CTime ct,OldTime;
OldTime=statusOld.m_mtime;
hFindFile.GetLastWriteTime(ct);
LONG Diff;
ver=ct.FormatGmt("%d %m %Y %H:%M %Z");
oldver=OldTime.FormatGmt("%d %m %Y %H:%M %Z");
Diff = ((CTimeSpan)(ct-OldTime)).GetTotalMinutes();
hFindFile.Close();
if (Diff>UPDATEEVERY || resultSpecific)
{
}
}
Downloading the New Version
Downloading the newer version is performed using TE_DownladLoad()
which is listed here. We make several attempts in case there is a temporary block or communication problem.
#define FTPRETRIES 5 // number of retries
BOOL TE_DownloadLoad(char *FtpFileName,char *LocalFileName)
{
int DoTry=FTPRETRIES;
int result;
TryAgain:;
try
{
result = MyConnection.m_FtpConn->GetFile(FtpFileName, LocalFileName, FALSE);
}
catch (CInternetException* pEx)
{
TCHAR sz[1024];
pEx->GetErrorMessage(sz,1024);
WriteToLog("Error %s\n", sz);
if(TE_DEBUG) MessageBox(NULL,sz,"Error 6 - TE_Load",MB_OK);
pEx->Delete();
}
if (!result)
{
if(DoTry-- >0) goto TryAgain;
return(FALSE);
}
else
{
return (TRUE);
}
}
Now we are ready to switch between the currently running version (the old one) with the newer one.
Executing the Newer Version
BOOL ExecuteNewVersion(char *ExeName,char *Param)
{
STARTUPINFO sinfo;
PROCESS_INFORMATION pinfo;
ZeroMemory(&sinfo, sizeof(sinfo));
sinfo.cb = sizeof(sinfo);
sinfo.lpDesktop= "WinSta0\\Default";
sinfo.dwFlags=STARTF_USESHOWWINDOW ;
sinfo.wShowWindow=SW_SHOW;
if(!CreateProcess(NULL,(char*)(LPCTSTR)((CString)(ExeName)+(CString)"
"+(CString)(Param)), NULL, NULL,FALSE,NORMAL_PRIORITY_CLASS |
CREATE_NEW_CONSOLE, NULL, NULL, &sinfo, &pinfo))
{
char s[256];
sprintf(s,"Can't execute program: %s params %s",ExeName,Param);
TELog.LogError("Execute New Version",s,0);
return FALSE;
}
else
{
return TRUE;
}
}
So if we put all the code together, we get:
CFileStatus statusOld;
CTime TimeOld;
if(CFile::GetStatus( FileHandle, statusOld ) )
{
CTime ct,OldTime;
OldTime=statusOld.m_mtime;
hFindFile.GetLastWriteTime(ct);
LONG Diff;
ver=ct.FormatGmt("%d %m %Y %H:%M %Z");
oldver=OldTime.FormatGmt("%d %m %Y %H:%M %Z");
Diff = ((CTimeSpan)(ct-OldTime)).GetTotalMinutes();
hFindFile.Close();
if (Diff>UPDATEEVERY || resultSpecific)
{
if(TE_DownLoad((resultGeneric)?NEWEXESTR:NEWEXE,TEMPPLACE))
{
if(ExecuteNewVersion(TEMPPLACE,"INSTALL"))
{
}
else
}
else
{
TELog.LogError("New Ftp version found","Can't download",0);
}
}
}
The TE_Init() Function
TE_Init()
is used to determine the parameters used when application was executed (unlike the full version of Target Eye Monitoring System, which is much more complex, in our example, there is one optional parameter – "INSTALL
").
if(__argc>1)
{
if(strcmp(__argv[1],"INSTALL")==0)
{
}
}
else
{
}
Replacing Old With New
In order to quit in a normal fashion, without missing anything we wish to do before quitting, the main even loop contains a check for the value of NeedToQuit
, which would normally be FALSE
.
BOOL NeedToQuit=FALSE;
When NeedToQuit
becomes TRUE
, the application will perform any routine required before quitting (for example, saving unsaved work). For example:
if(NeedToQuit)
{
if(TE_DEBUG)
MessageBox(NULL,"Terminating Targe Eye",
"Target Eye Monitoring System",NULL);
return FALSE;
}
Further, the application expects to be executed either with the "INSTALL
" parameter as part of the command line, or without it. The following scheme illustrates the flow of an installation of a newer version to a temporary location (the Desktop folder, in our example), up to the moment the temporary file used for it is deleted. This requires several stages:
The Target Eye Cycle
Stage | Ran with Parameter | Ran from location | Description |
1 | None | Regular | The current (old) version is running before the newer version is available |
2 | | | The newer version checks if there is a temporary copy of itself at the temporary location, but there isn't any |
3 | | | A newer version is found |
4 | | | Newer version is downloaded to a temporary location |
5 | | | Newer version runs from the temporary location with the "INSTALL " parameter. |
6 | | | Current version quits |
7 | INSTALL | Temporary | The newer application ran from the temporary location copies itself to the regular location, replacing the old version which quitted (5) |
8 | | | The newer version runs the copy located in the regular location and quits. |
9 | None | Regular | The newer version checks if there is a temporary copy of itself at the temporary location, and deletes it. |
Choosing an FTP Server for this Demo
In order to use the source code that is attached to this article, there are predefined settings of a public Secured FTP server available to the public by Chilkat Software, Inc.
The details of this server are:
Secure FTP Server Details
Type | FileZilla |
Address | ftp.secureftp-test.com |
Login | Test |
Password | Test |
There is a file there named hamlet.xml which can be used for testing a remote file date stamp.
Internationalization
To comply with scenarios in which there are users worldwide, and yet we wish to release a version to be available at the same moment to all of them regardless of their local time, we use:
FormatGmt
GMT is an absolute time reference and doesn't change regardless of the season or the location. FormatGmt
is used like that:
CTime t( 1999, 3, 19, 22, 15, 0 );
CString s = t.Format( "%A, %B %d, %Y" );
ATLASSERT( s == "Friday, March 19, 1999" );
Limiting to a Single Instance
The mechanism described in this article can only work if we limit our application to run only once at any given moment. To do so, several methods can be used, such as CreateMutex()
.
See http://support.microsoft.com/kb/243953
Target Eye Monitoring System uses a different and a bit "brutal" approach, which will be explained in detail over another article. Basically, Target Eye Monitoring System searches for other instances currently running in memory, and when found, does one of the two following options:
- If the instance found is newer, the current running instance quits.
- If the instance found is older, the current running instance kills it.
To explain, let's consider the following scenario. An end user had his current copy of software updated to a newer one. A day after, this end user runs the original CD of the software. The version that resides on the original CD, will search for new updates at the FTP server, which is unnecessary. Further, if the application runs constantly (like a monitoring application should), then probably when the CD version is run, there is also another newer version already running. To address such scenario and other scenarios, we should take the necessary measures to ensure that an application will always be up to date.
Further Reading
History
- 4th January, 2012: Initial version
©2000-2010 Target Eye LTD (UK)
All materials contained on this article are protected by International copyright law and may not be used, reproduced, distributed, transmitted, displayed, published or broadcast without the prior written permission given by Target Eye LTD (UK). You may not alter or remove any trademark, copyright or other notice from copies of the content.
Michael Haephrati , CodeProject MVP 2013