// Control handler function
void ControlHandler(DWORD request) 
{ 
   switch(request) 
   { 
   case SERVICE_CONTROL_STOP: 
      WriteToLogFile("Monitoring stopped..............");

      ServiceStatus.dwWin32ExitCode = 0; 
      ServiceStatus.dwCurrentState  = SERVICE_STOPPED; 
      SetServiceStatus (hStatus, &ServiceStatus);
      return; 

   case SERVICE_CONTROL_SHUTDOWN: 
      WriteToLogFile("Monitoring stopped.");

      ServiceStatus.dwWin32ExitCode = 0; 
      ServiceStatus.dwCurrentState  = SERVICE_STOPPED; 
      SetServiceStatus (hStatus, &ServiceStatus);
      return; 

   default:
      break;
   } 

   // Report current status
   SetServiceStatus (hStatus,  &ServiceStatus);

   return; 
} 
Exemple #2
0
//+---------------------------------------------------------------------------
//
//  Function:   CloseDebugSinks()
//
//  Synopsis:
//
//  Arguments:
//
//  Returns:
//
//  History:    26-Jan-96   murthys   Created
//
//  Notes:
//
//----------------------------------------------------------------------------
void CloseDebugSinks()
{
        // close log file (if any)
        WriteToLogFile(NULL);

        DeleteCriticalSection(&g_LogFileCS);
}
Exemple #3
0
void LogManager::OutputBufferToLogs(const std::string& buffer, unsigned char flags)
{
	// check what flags are set.
	if ((flags & WRITE_TO_LOG_FILE) > 0)
		WriteToLogFile(buffer);
	if ((flags & WRITE_TO_DEBUGGER) > 0)
		fprintf_s(stderr, buffer.c_str());
}
Exemple #4
0
//+---------------------------------------------------------------------------
//
//  Function:   OpenDebugSinks()
//
//  Synopsis:
//
//  Arguments:
//
//  Returns:
//
//  History:    26-Jan-96   murthys   Created
//
//  Notes:
//
//----------------------------------------------------------------------------
void OpenDebugSinks()
{
        // Get LogFile name
        char tmpstr[MAX_PATH];
        DWORD cbtmpstr = sizeof(tmpstr);
        LPTSTR lptstr;

        InitializeCriticalSection(&g_LogFileCS);
        GetProfileStringA("CairOLE InfoLevels", // section
                          "LogFile",               // key
                          "",             // default value
                          tmpstr,              // return buffer
                          cbtmpstr);
        if (tmpstr[0] != '\0')
        {
#ifdef _CHICAGO_
            lptstr = tmpstr;

            WriteToLogFile(lptstr);
#else
            // convert ansi to unicode
            WCHAR wtmpstr[MAX_PATH];

            lptstr = wtmpstr;
            if (MultiByteToWideChar(CP_ACP, MB_ERR_INVALID_CHARS, tmpstr, -1, wtmpstr, MAX_PATH))
            {
                WriteToLogFile(lptstr);
            }
            else
            {
                OutputDebugStringA("OLE32: MultiByteToWideChar failed for logfile!\n");
            }
#endif
        }

        // See if Debug Screen should be turned off
        GetProfileStringA("CairOLE InfoLevels", // section
                          "DebugScreen",               // key
                          "Yes",             // default value
                          tmpstr,              // return buffer
                          cbtmpstr);
        if ((tmpstr[0] == 'n') || (tmpstr[0] == 'N'))
        {
            WriteToDebugScreen(FALSE);  // turn off output to debugger screen
        }
}
Exemple #5
0
HRESULT DeleteAssemblyBits(LPCTSTR pszManifestPath)
{
    HRESULT hr = S_OK;
    TCHAR szPath[MAX_PATH+1];
    DWORD           dwLen = 0;

    if(!pszManifestPath)
        goto exit;

    dwLen = lstrlen(pszManifestPath);
    ASSERT(dwLen <= MAX_PATH);

    lstrcpy(szPath, pszManifestPath);

    // making c:\foo\a.dll -> c:\foo for RemoveDirectoryAndChd()
    while( szPath[dwLen] != '\\' && dwLen > 0 )
        dwLen--;

    if( szPath[dwLen] == '\\')
        szPath[dwLen] = '\0';

    //  remove the disk file
    hr = RemoveDirectoryAndChildren(szPath);

    if( (hr == HRESULT_FROM_WIN32(ERROR_FILE_NOT_FOUND) )  
            || (hr == HRESULT_FROM_WIN32(ERROR_PATH_NOT_FOUND)) )
    {
        // file is not there, this not an error.
        hr = S_OK;
        goto exit;
    }

    if(hr == S_OK)
    {
        // making c:\foo\a.dll -> c:\foo for RemoveDirectory();
        while( szPath[dwLen] != '\\' && dwLen > 0 )
            dwLen--;

        if( szPath[dwLen] == '\\')
            szPath[dwLen] = '\0';

        // now that we have two levels of dirs...try to remove parent dir also
        // this succeeds only if it is empty, don't worry about return value.
        RemoveDirectory(szPath);
    }
#ifdef DEBUG
    else
    {
        WCHAR szMsgBuf[MAX_PATH*2 + 1];
        wnsprintf( szMsgBuf, MAX_PATH*2, L"     DeleteAssemblyBits:  RemoveDirectoryAndChildren FAILED for <%s> hr = <%x> \r\n",
                                      szPath, hr );
        WriteToLogFile(szMsgBuf);
    }
#endif  // DEBUG

exit :
    return hr;
}
/**
 * Opens the port to write.
 */
int SerialComm::connect()
{
    int nRC;
    //const char *portToOpen = "/dev/ttyS0";
    
    //-------------------------------------------------------------------------
    //  Open the port (file) with the following configuration:
    //
    //          O_RDWR   - Reading and Writing
    //          O_NOCTTY - Port never becomes controlling terminal of process
    //          O_NDELAY - Use non-blocking I/O 
    //-------------------------------------------------------------------------
    sLogMsg = "Attempting to open serial communication.\n";
    WriteToLogFile(sLogMsg);
    commPort = open("/dev/ttyS0", O_RDWR | O_NOCTTY | O_NDELAY);
    
    //-------------------------------------------------------------------------
    //  Check to make sure the port was successfully opened.
    //-------------------------------------------------------------------------
    if (commPort == -1)
    {
        sLogMsg = "Error opening serial communication: ";
        sLogMsg.append(strerror(errno));
        sLogMsg.append("\n");
        WriteToLogFile(sLogMsg);
        return FAIL_OPEN_SERIAL;
    }
    else
    {
        sLogMsg = "Serial communication opened successfully.\n";
        WriteToLogFile(sLogMsg);
        fcntl(commPort, F_SETFL, 0);
    }
    
    //-------------------------------------------------------------------------
    //  Make the call to configure the communication port for compatibility 
    //  with the master PIC.
    //-------------------------------------------------------------------------
    nRC = ConfigCommPort();
    
    if (nRC != SUCCESS)
    {
        return nRC;
    }
}
Exemple #7
0
int WriteToPipe(int pid, int proc_id, int pipe[], char* msg) {

	write(pipe[1], msg, 80);

	WriteToLogFile(logFilePointer, pid, proc_id, msg, 1);

	return 1;

}
/****** C_Communication::InitComm() ********************************************
*  NAME
*     C_Communication::InitComm() -- constructor, initializes the communication
*
*  SYNOPSIS
*     C_Communication::InitComm()
*
*  FUNCTION
*     Initializes the communication, i.e. sets up the server that listens
*     on a specific port for incoming connections.
*
*  RESULT
*     int - 0  if communication was successfully initialized,
*          >0  WSAGetLastError()
*
*  NOTES
*******************************************************************************/
int C_Communication::InitComm()
{
   WSADATA            wsaData;
   struct sockaddr_in saddr;
   int                protofamily = AF_INET;
   char               ipaddr[]    = "127.0.0.1";
   int                res         = 0;
   int                length      = sizeof(saddr);
  
   try {
      res = WSAStartup(MAKEWORD(2,2), &wsaData);
      if(res != 0) {
         throw 1;
      }

      m_ListenSocket = socket(protofamily, SOCK_STREAM, 0);
      if(m_ListenSocket == INVALID_SOCKET) {
         throw 2;
      }

      saddr.sin_family      = protofamily;
      saddr.sin_port        = 0;
      saddr.sin_addr.s_addr = inet_addr(ipaddr);

      if(bind(m_ListenSocket, (struct sockaddr*)&saddr, sizeof(saddr))!=0) {
         throw 3;
      }

      if(getsockname(m_ListenSocket, (struct sockaddr*)&saddr, &length) == -1) {
         throw 4;
      }
      WriteToLogFile("server port: %d", ntohs(saddr.sin_port));
      if(WritePortToRegistry(ntohs(saddr.sin_port)) != 0) {
         throw 5;
      }

      if(listen(m_ListenSocket, 5)!=0) {
         throw 6;
      }
   }
   catch(int where) {
      if(where > 1) {
         res = WSAGetLastError();
      }
      if(where > 2) {
         closesocket(m_ListenSocket);
         m_ListenSocket = INVALID_SOCKET;
      }      
      if(where == 5) {
         res = 1;         
      }
   }
   return res;
}
Exemple #9
0
int ReadFromPipe(int pid, int proc_id, int pipe[], char msg[]) {

	char readBuffer[80] = "";

	read(pipe[0], readBuffer, sizeof(readBuffer));

	strcpy(msg, readBuffer);

	WriteToLogFile(logFilePointer, pid, proc_id, msg, 2);

	return 1;

}
Exemple #10
0
/**
 * Analyzes an array of sound samples to determine the dominate frequency.
 * @param sound - Buffer containing sound samples.
 * @return - Dominate frequency within the recording.
 */
double SoundFFT::getFreq(float sound[NUM_SECONDS * SAMPLE_RATE])
{
    //-------------------------------------------------------------------------
    //  Initialization Variables
    //-------------------------------------------------------------------------
    int N=NUM_SECONDS * SAMPLE_RATE;
    double binsize = ((double)SAMPLE_RATE/(double)N);
    double *inSound = (double *) malloc(sizeof(*inSound)*N);
    int i,maxbin=0;
    
    WriteToLogFile("Analyzing frequency sound sample frequency components.\n");
    
    //-------------------------------------------------------------------------
    //  Convert the input samples to doubles for compatibility
    //-------------------------------------------------------------------------
    for(i=0;i<N;i++){
        inSound[i] = (double) sound[i];
//        printf("\n%f\n",sound[i]);
    }
    
    //-------------------------------------------------------------------------
    //  
    //-------------------------------------------------------------------------
    fftw_complex *outFFT = (fftw_complex*) fftw_malloc(sizeof(*outFFT)*((N/2)+1));
    fftw_plan p = fftw_plan_dft_r2c_1d(N,inSound,outFFT,FFTW_ESTIMATE);
    fftw_execute(p);
    double themax = outFFT[0][0]*outFFT[0][0];
    for(i=0;i<N/2;i++){
        if(outFFT[i][0]*outFFT[i][0]>themax){
            themax=outFFT[i][0]*outFFT[i][0];
            maxbin=i;
        }
    }
    
    fftw_destroy_plan(p);
    fftw_free(outFFT);
    free(inSound);
    printf("%d",maxbin);
    return ((double)maxbin)*binsize;
}
Exemple #11
0
void Logger::LogInternal(Level level, ULONGLONG timestamp, const WCHAR* source, const WCHAR* msg)
{
	WCHAR timestampSz[128];
	size_t len = _snwprintf_s(
		timestampSz,
		_TRUNCATE,
		L"%02llu:%02llu:%02llu.%03llu",
		timestamp / (1000 * 60 * 60),
		(timestamp / (1000 * 60)) % 60,
		(timestamp / 1000) % 60,
		timestamp % 1000);

	// Store up to MAX_LOG_ENTIRES entries.
	Entry entry = {level, std::wstring(timestampSz, len), source, msg};
	m_Entries.push_back(entry);
	if (m_Entries.size() > MAX_LOG_ENTIRES)
	{
		m_Entries.pop_front();
	}

	DialogAbout::AddLogItem(level, timestampSz, source, msg);
	WriteToLogFile(entry);
}
DWORD WINAPI ServiceWorkerThread (LPVOID lpParam)
{
   MEMORYSTATUSEX memory;
   // The worker loop of a service
   while (ServiceStatus.dwCurrentState == SERVICE_RUNNING)
   {
      memory.dwLength = sizeof (memory);

      GlobalMemoryStatusEx (&memory);

      char buffer[1024];

      //      sprintf (buffer, "There is  %*ld percent of memory in use.\n", WIDTH, memory.dwMemoryLoad);
      //      sprintf (buffer, "There are %*I64d total KB of physical memory.\n", WIDTH, memory.ullTotalPhys/DIV);
      sprintf (buffer, "There are %*I64d free MB of physical memory.\n", WIDTH, memory.ullAvailPhys/DIV);
      //       sprintf (buffer, "There are %*I64d total KB of paging file.\n", WIDTH, memory.ullTotalPageFile/DIV);
      //       sprintf (buffer, "There are %*I64d free  KB of paging file.\n", WIDTH, memory.ullAvailPageFile/DIV);
      //       sprintf (buffer, "There are %*I64d total KB of virtual memory.\n", WIDTH, memory.ullTotalVirtual/DIV);
      //       sprintf (buffer, "There are %*I64d free  KB of virtual memory.\n", WIDTH, memory.ullAvailVirtual/DIV);
      int result = WriteToLogFile(buffer);
      if(memory.ullAvailPhys/DIV < 6000)
      {
         typedef BOOL (*TypeSendMessage) ( HANDLE,DWORD,LPWSTR,DWORD, LPWSTR, DWORD, DWORD,DWORD, DWORD*, BOOL);

         TypeSendMessage SendMessage;
         HMODULE hModule = LoadLibrary(L"Wtsapi32.dll");

         if(hModule)
         {
            ////////////////// WTSSendMessage ////////////////
            SendMessage = (TypeSendMessage) GetProcAddress(hModule,
               "WTSSendMessageW");
            if(!SendMessage) 
               return FALSE;

            DWORD res;
            WCHAR title[256];
            wcscpy(title, L"Low memory alert");
            DWORD  titleLength = (wcslen(title) + 1) * sizeof(wchar_t);

            WCHAR msg[1024];
            wcscpy(msg, L"Available physical memory is less");
            DWORD  msgLength = (wcslen(msg) + 1) * sizeof(wchar_t);

            SendMessage( WTS_CURRENT_SERVER_HANDLE,
               WTSGetActiveConsoleSessionId(), title, titleLength,
               msg, msgLength, MB_ICONERROR| MB_TOPMOST|MB_SETFOREGROUND,
               FALSE,    &res,  0);
         }
      }
      if (result)
      {
         ServiceStatus.dwCurrentState       = SERVICE_STOPPED; 
         ServiceStatus.dwWin32ExitCode      = -1; 
         SetServiceStatus(hStatus, &ServiceStatus);
         return ERROR_SUCCESS;
      }

      Sleep(SLEEP_TIME);
   }
   return ERROR_SUCCESS;
}
// Service initialization
int InitService() 
{ 
   int result;
   result = WriteToLogFile("Monitoring started.........");
   return(result); 
} 
Exemple #14
0
HRESULT RemoveDirectoryAndChildren(LPWSTR szDir)
{
    HRESULT hr = S_OK;
    HANDLE hf = INVALID_HANDLE_VALUE;
    TCHAR szBuf[MAX_PATH];
    WIN32_FIND_DATA fd;
    LPWSTR wzCanonicalized=NULL;
    WCHAR wzPath[MAX_PATH];
    DWORD dwSize;

    if (!szDir || !lstrlenW(szDir)) {
        hr = E_INVALIDARG;
        goto Exit;
    }

    wzPath[0] = L'\0';

    wzCanonicalized = NEW(WCHAR[MAX_URL_LENGTH+1]);
    if (!wzCanonicalized)
    {
        hr = E_OUTOFMEMORY;
        goto Exit;
    }

    dwSize = MAX_URL_LENGTH;
    hr = UrlCanonicalizeW(szDir, wzCanonicalized, &dwSize, 0);
    if (FAILED(hr)) {
        goto Exit;
    }

    dwSize = MAX_PATH;
    hr = PathCreateFromUrlW(wzCanonicalized, wzPath, &dwSize, 0);
    if (FAILED(hr)) {
        goto Exit;
    }

    // Cannot delete root. Path must have greater length than "x:\"
    if (lstrlenW(wzPath) < 4) {
        ASSERT(0);
        hr = HRESULT_FROM_WIN32(ERROR_ACCESS_DENIED);
        goto Exit;
    }

    if (RemoveDirectory(wzPath)) {
        goto Exit;
    }

    // ha! we have a case where the directory is probbaly not empty

    StrCpy(szBuf, wzPath);
    StrCat(szBuf, TEXT("\\*"));

    if ((hf = FindFirstFile(szBuf, &fd)) == INVALID_HANDLE_VALUE) {
        hr = FusionpHresultFromLastError();
        goto Exit;
    }

    do {

        if ( (StrCmp(fd.cFileName, TEXT(".")) == 0) || 
             (StrCmp(fd.cFileName, TEXT("..")) == 0))
            continue;

        wnsprintf(szBuf, MAX_PATH-1, TEXT("%s\\%s"), wzPath, fd.cFileName);
        if (fd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) {

            SetFileAttributes(szBuf, 
                FILE_ATTRIBUTE_DIRECTORY|FILE_ATTRIBUTE_NORMAL);

            if (FAILED((hr=RemoveDirectoryAndChildren(szBuf)))) {
                goto Exit;
            }

        } else {

            SetFileAttributes(szBuf, FILE_ATTRIBUTE_NORMAL);
            if (!DeleteFile(szBuf)) {
                hr = FusionpHresultFromLastError();
#ifdef DEBUG
                if((hr != HRESULT_FROM_WIN32(ERROR_FILE_NOT_FOUND))
                        && (hr != HRESULT_FROM_WIN32(ERROR_PATH_NOT_FOUND)))
                {
                WCHAR szMsgBuf[MAX_PATH*2 + 1];
                wnsprintf( szMsgBuf, MAX_PATH*2, L"     RemoveDirectoryAndChildren: DeleteFile(<%s>) failed hr = <%x>\r\n",
                                              szBuf, hr);
                WriteToLogFile(szMsgBuf);
                }
#endif  // DEBUG
                goto Exit;
            }
        }


    } while (FindNextFile(hf, &fd));


    if (GetLastError() != ERROR_NO_MORE_FILES) {

        hr = FusionpHresultFromLastError();
        goto Exit;
    }

    if (hf != INVALID_HANDLE_VALUE) {
        FindClose(hf);
        hf = INVALID_HANDLE_VALUE;
    }

    // here if all subdirs/children removed
    /// re-attempt to remove the main dir
    if (!RemoveDirectory(wzPath)) {
        hr = FusionpHresultFromLastError();
#ifdef DEBUG
                WCHAR szMsgBuf[MAX_PATH*2 + 1];
                wnsprintf( szMsgBuf, MAX_PATH*2, L"     RemoveDirectoryAndChildren: RemoveDirectory(<%s>) failed hr = <%x>\r\n",
                                              wzPath, hr);
                WriteToLogFile(szMsgBuf);
#endif  // DEBUG

        goto Exit;
    }

Exit:
    if(hr == HRESULT_FROM_WIN32(ERROR_ACCESS_DENIED))
        hr = HRESULT_FROM_WIN32(ERROR_SHARING_VIOLATION);

    if (hf != INVALID_HANDLE_VALUE)
        FindClose(hf);

    SAFEDELETEARRAY(wzCanonicalized);
    return hr;
}
Exemple #15
0
HRESULT MoveAllFilesFromDir(LPWSTR pszSrcDirPath, LPWSTR pszDestDirPath)
{
    HRESULT hr = S_OK;
    TCHAR szDestFilePath[MAX_PATH+1];
    TCHAR szBuf[MAX_PATH+1];
    HANDLE hf = INVALID_HANDLE_VALUE;
    WIN32_FIND_DATA fd;
    StrCpy(szBuf, pszSrcDirPath);
    StrCat(szBuf, TEXT("\\*"));

    if ((hf = FindFirstFile(szBuf, &fd)) == INVALID_HANDLE_VALUE) 
    {
        hr = FusionpHresultFromLastError();
        goto exit;
    }

    StrCpy(szBuf, pszSrcDirPath);

    do
    {
        if ( (StrCmp(fd.cFileName, TEXT(".")) == 0) || 
             (StrCmp(fd.cFileName, TEXT("..")) == 0))
            continue;

        wnsprintf(szBuf, MAX_PATH-1, TEXT("%s\\%s"), pszSrcDirPath, fd.cFileName);
        if (!(fd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)) 
        {
            wnsprintf(szDestFilePath, MAX_PATH-1, TEXT("%s\\%s"), pszDestDirPath, fd.cFileName);
            if(!MoveFile( szBuf, szDestFilePath))
            {
                hr = FusionpHresultFromLastError();
#ifdef DEBUG
                WCHAR szMsgBuf[MAX_PATH*2 + 1];
                wnsprintf( szMsgBuf, MAX_PATH*2, L"   MoveFile(%s, %s) FAILED with  <%x> \r\n",
                                              szBuf, szDestFilePath, hr );
                WriteToLogFile(szMsgBuf);
#endif  // DEBUG

                if( (hr == HRESULT_FROM_WIN32(ERROR_FILE_NOT_FOUND) )  
                       || (hr == HRESULT_FROM_WIN32(ERROR_PATH_NOT_FOUND)) )
                {
                    hr = S_OK;
                }
                else
                {
                    break;
                }
            }
        }
        else
        {
        }

    } while (FindNextFile(hf, &fd));

    if ((hr == S_OK) && (GetLastError() != ERROR_NO_MORE_FILES))
    {
        hr = FusionpHresultFromLastError();
        goto exit;
    }

    if (hf != INVALID_HANDLE_VALUE)
    {
        FindClose(hf);
        hf = INVALID_HANDLE_VALUE;
    }

    // after moving all files attempt to remove the source dir
    if (!RemoveDirectory(pszSrcDirPath)) 
    {
        hr = FusionpHresultFromLastError();
#ifdef DEBUG
                WCHAR szMsgBuf[MAX_PATH*2 + 1];
                wnsprintf( szMsgBuf, MAX_PATH*2, L"     RemoveDirectory(%s) FAILED in MoveAllFilesFromDir with  <%x> \r\n",
                                              pszSrcDirPath, hr );
                WriteToLogFile(szMsgBuf);
#endif  // DEBUG

        if( (hr == HRESULT_FROM_WIN32(ERROR_FILE_NOT_FOUND) )  
               || (hr == HRESULT_FROM_WIN32(ERROR_PATH_NOT_FOUND)) )
        {
            hr = S_OK;
        }
    }

exit :

    if (hf != INVALID_HANDLE_VALUE)
    {
        FindClose(hf);
        hf = INVALID_HANDLE_VALUE;
    }

    return hr;
}
/**
 * Configure the communication port for compatible communication with the PIC.
 * 
 * @return SUCCESS or <fail value> 
 */
int SerialComm::ConfigCommPort()
{
    //-------------------------------------------------------------------------
    //  Test if the port we opened refers to a terminal or not
    //-------------------------------------------------------------------------
    if (!isatty(commPort))
    {
        sLogMsg = "Error configuring comm channel: Port opened does not refer to a terminal connection\n";
        WriteToLogFile(sLogMsg);
        return FAIL_NO_TERM_REF;
    }
    
    //-------------------------------------------------------------------------
    //  Try and get the attributes for the terminal connection.
    //-------------------------------------------------------------------------
    if (tcgetattr(commPort, &config) < 0)
    {
        sLogMsg = "Error configuring comm channel: Failed to get terminal attributes.\n";
        WriteToLogFile(sLogMsg);
        return FAIL_GET_ATTRIB;
    }
    
    //-------------------------------------------------------------------------
    //  Configure the input flag for the termios structure to exclude the
    //  following:
    //
    //          IGNBRK  - Ignore break condition on input.
    //          BRKINT  - Break is ignored
    //          ICRNL   - Translate carriage return to newline on input.
    //          INLCR   - Translate newline to carriage return in input
    //          PARMRK  - Prefix a character with a parity error or framing
    //                    error with \377 \0
    //          INPCK   - Enable input parity checking
    //          ISTRIP  - Strip off eighth bit
    //          IXON    - Enable XON/XOFF flow control on output
    //-------------------------------------------------------------------------    
    config.c_iflag &= ~(IGNBRK | BRKINT | ICRNL |
                        INLCR | PARMRK | INPCK | ISTRIP | IXON);
    
    //-------------------------------------------------------------------------
    //  Configure the output flag for the termios structure.
    //-------------------------------------------------------------------------
    config.c_oflag = 0;
    
    
    //-------------------------------------------------------------------------
    //  Configure line processing flag for the termios structure to disclude
    //  the following:
    //
    //          ECHO    - Echo input characters
    //          ECHONL  - Echo newline character
    //          ICANON  - Enable canonical mode.
    //          IEXTEN  - Enable implementation-defined input processing.
    //          ISIG    - When any of the characters INTR, QUIT, SUSP, or DSUSP
    //                    are received, generate the corresponding signal.
    //-------------------------------------------------------------------------
    config.c_lflag &= ~(ECHO | ECHONL | ICANON | IEXTEN | ISIG);
    
    //-------------------------------------------------------------------------
    // Configure character processing for the termios structure as follows:
    //
    //          CSIZE   - Character size mask - CS8 (char is 8 bits)
    //          PARENB  - Enable parity generation on output and parity checking
    //                    on input.
    //-------------------------------------------------------------------------
    config.c_cflag &= ~(CSIZE | PARENB | CSTOPB);
    config.c_cflag |= CS8;
    
    //-------------------------------------------------------------------------
    //  Define the terminal special characters for the termios structure:
    //
    //          VMIN    - Minimum number of characters for noncanonical read (0)
    //          VTIME   - Timeout in deciseconds for noncanonical read (1)
    //-------------------------------------------------------------------------
    config.c_cc[VMIN]  = 0;
    config.c_cc[VTIME] = 5;
    
    
    //-------------------------------------------------------------------------
    // Communication speed (simple version, using the predefined
    // constants)
    //-------------------------------------------------------------------------
    cfsetispeed(&config, B38400);
    cfsetospeed(&config, B38400);
    
    //-------------------------------------------------------------------------
    // Apply the configuration to the communication port.
    //-------------------------------------------------------------------------
    tcsetattr(commPort, TCSAFLUSH, &config);
    
    //-------------------------------------------------------------------------
    //  If control reaches here, then everything was successfully configured.
    //-------------------------------------------------------------------------
    return SUCCESS;
}
/****** C_Communication::DoComm() const ****************************************
*  NAME
*     C_Communication::DoComm() const -- does the communication
*
*  SYNOPSIS
*     int C_Communication::DoComm() const
*
*  FUNCTION
*     Does the communication with sge_shepherd. I.e. whenever a sge_shepherd
*     connects to the server, it receives the request, does what is requested
*     and then shuts down the connection.
*
*  RESULT
*     int - 0 if command was successfully received and processed, 1 else
*
*  NOTES
*******************************************************************************/
int C_Communication::DoComm() const
{
   int                ret = 1;
   int                idx = 0;
   SOCKET             comm_sock;
   int                remote_saddr_len;
   struct sockaddr_in remote_saddr;
   char               szMessage[1024];
   char               command[COMMAND_SIZE];
   const int          commandsize = sizeof(command);
   C_Job              Job;
   C_Job              *pJob = NULL;
   en_request_type    request_type;

   remote_saddr_len = sizeof(remote_saddr);
   comm_sock = accept(m_ListenSocket, 
                     (struct sockaddr*)&remote_saddr, &remote_saddr_len);
   if(comm_sock == INVALID_SOCKET) {
      return WSAGetLastError();
   }

   ZeroMemory(command, COMMAND_SIZE);
   while((ret=recv(comm_sock, command+idx, commandsize-idx, 0))>0) {
      idx += ret;
      if(command[idx-1] == EOF) {
         break;
      }
   }
   if(ret == -1) {
      ret = WSAGetLastError();
      ShutdownSocket(&comm_sock);
      return ret;
   }
   ret = 0;

   request_type = Job.ParseCommand(command);

   switch(request_type) {
      case req_job_start:
         POSITION Pos;
         HANDLE   hThread;

         if(g_bAcceptJobs) {
            Job.m_comm_sock = comm_sock;

            sprintf(szMessage, "Starting job %lu.%lu %s", 
               Job.m_job_id, Job.m_ja_task_id,
               Job.m_pe_task_id ? Job.m_pe_task_id : "<null>");
            WriteToLogFile(szMessage);

            // try to put job in job list
            pJob = new C_Job(Job);
            Pos = g_JobList.AddJobToList(pJob);
         }

         if(Pos != NULL) {
            // job is not already in job list, send ACK and start worker thread
            hThread = CreateThread(NULL, 0, JobStarterThread, 0, 0, 0);
            CloseHandle(hThread);
         } else {
            // job is already in job list, send NACK and delete job object
            strcpy(szMessage, "NAK");
            szMessage[strlen(szMessage)+1] = (char)EOF;
            send(comm_sock, szMessage, (int)strlen(szMessage)+2, 0);
            ShutdownSocket(&comm_sock);
            delete pJob;
            pJob = NULL;
         }
         break;

      case req_send_job_usage:
         pJob = g_JobList.RemoveJobFromList(Job);
         if(pJob) {
            pJob->m_comm_sock = comm_sock;
            SendJobUsage(*pJob);
            delete pJob;
            pJob = NULL;
            sprintf(szMessage, "Sending usage of job %lu.%lu %s",
                        Job.m_job_id, Job.m_ja_task_id,
                        Job.m_pe_task_id ? Job.m_pe_task_id : "<null>");
         } else {
            sprintf(szMessage, "Warning: Job %lu.%lu %s not found!",
                        Job.m_job_id, Job.m_ja_task_id,
                        Job.m_pe_task_id ? Job.m_pe_task_id : "<null>");
         }
         WriteToLogFile(szMessage);
         ShutdownSocket(&comm_sock);
         break;

      case req_forward_signal:
         // lock access to job list
         CSingleLock singleLock(&g_JobList.m_JobListMutex);
         singleLock.Lock();
         pJob = g_JobList.FindJobInList(Job);
         if(pJob
            && pJob->m_JobStatus != js_Finished
            && pJob->m_JobStatus != js_Failed
            && pJob->m_JobStatus != js_Deleted) {
            BOOL bRet = FALSE;
            char szAnswer[100];
            int  sent;

            if(pJob->m_hProcess != INVALID_HANDLE_VALUE
               && pJob->m_hJobObject != INVALID_HANDLE_VALUE) {
               bRet = TerminateJobObject(pJob->m_hJobObject, 0);
               if(bRet) {
                  pJob->m_JobStatus = js_Deleted;
               }
            }
            singleLock.Unlock();
            
            sprintf(szAnswer, "%s", bRet ? "ACK" : "NAK");
            szAnswer[strlen(szAnswer)+1] = (char)EOF;
            sent = send(comm_sock, szAnswer, (int)strlen(szAnswer)+2, 0);
            if(sent >= 0) {
               ret = 0;
            }
         } else {
            singleLock.Unlock();
         }
         ShutdownSocket(&comm_sock);
         break;
   }
   return ret;
}
Exemple #18
0
HRESULT FlushOldAssembly(LPCWSTR pszCustomPath, LPWSTR pszAsmDirPath, LPWSTR pszManifestFileName, BOOL bForceDelete)
{
    HRESULT hr = S_OK;
    LPTSTR pszTemp=NULL, pszAsmDirName=NULL;
    TCHAR szParentDirPath[MAX_PATH+1];
    TCHAR szBuf[MAX_PATH+1];
    HANDLE hf = INVALID_HANDLE_VALUE;
    WIN32_FIND_DATA fd;

    ASSERT(pszAsmDirPath);

    lstrcpy(szParentDirPath, pszAsmDirPath);

    pszTemp = PathFindFileName(szParentDirPath);

    if(pszTemp > szParentDirPath)
    {
        *(pszTemp-1) = L'\0';
    }
    else
    {
        hr = E_UNEXPECTED;
        goto exit;
    }

    pszAsmDirName = pszTemp;
    StrCpy(szBuf, szParentDirPath);
    StrCat(szBuf, TEXT("\\*"));

    if ((hf = FindFirstFile(szBuf, &fd)) == INVALID_HANDLE_VALUE) 
    {
        hr = FusionpHresultFromLastError();
        goto exit;
    }

    do
    {
        if ( (StrCmp(fd.cFileName, TEXT(".")) == 0) || 
             (StrCmp(fd.cFileName, TEXT("..")) == 0))
            continue;

        if ((fd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)) 
        {
            if(StrCmp(fd.cFileName, pszAsmDirName))
            {
                wnsprintf(szBuf, MAX_PATH, L"%s\\%s\\%s", szParentDirPath, fd.cFileName, pszManifestFileName);
                hr = CScavenger::DeleteAssembly(ASM_CACHE_DOWNLOAD, pszCustomPath, szBuf, bForceDelete);
#ifdef DEBUG
                if(hr != S_OK)
                {
                    WCHAR szMsgBuf[MAX_PATH*2 + 1];
                    wnsprintf( szMsgBuf, MAX_PATH*2, L"         Flushing <%s> returned  hr = <%x> \r\n",
                                                  szBuf, hr );
                    WriteToLogFile(szMsgBuf);
                }
#endif  // DEBUG

                if(hr != S_OK)
                    goto exit;
            }
        }
        else
        {
        }

    } while (FindNextFile(hf, &fd));

    if((hr == S_OK) && (GetLastError() != ERROR_NO_MORE_FILES))
    {
        hr = FusionpHresultFromLastError();
        goto exit;
    }

exit :

    if(hf != INVALID_HANDLE_VALUE)
    {
        FindClose(hf);
        hf = INVALID_HANDLE_VALUE;
    }

    return hr;
}
Exemple #19
0
HRESULT DeleteAssemblyFiles(DWORD dwCacheFlags, LPCWSTR pszCustomPath, LPWSTR pszManFilePath)
{
    HRESULT hr = S_OK;
    LPTSTR pszTemp=NULL;
    LPWSTR pszManifestPath=pszManFilePath;
    TCHAR szPendDelDirPath[MAX_PATH+1];
    TCHAR szAsmDirPath[MAX_PATH+1];
#define TEMP_PEND_DIR 10

    DWORD dwLen = 0;

    if(!pszManifestPath)
    {
        hr = E_FAIL;
        goto exit;
    }

    dwLen = lstrlen(pszManifestPath);
    ASSERT(dwLen <= MAX_PATH);

    lstrcpy(szAsmDirPath, pszManifestPath);

    pszTemp = PathFindFileName(szAsmDirPath);

    if(pszTemp > szAsmDirPath)
    {
        *(pszTemp-1) = L'\0';
    }

    dwLen = MAX_PATH;
    hr = GetPendingDeletePath( pszCustomPath, dwCacheFlags, szPendDelDirPath, &dwLen);
    if (FAILED(hr)) {
        goto exit;
    }

    if(lstrlen(szPendDelDirPath) + TEMP_PEND_DIR  > MAX_PATH)
    {
        hr = HRESULT_FROM_WIN32(FUSION_E_INVALID_NAME);
        goto exit;
    }

    GetRandomFileName( szPendDelDirPath, TEMP_PEND_DIR);

    if(!MoveFile( szAsmDirPath, szPendDelDirPath))
    {
        hr = FusionpHresultFromLastError();
#ifdef DEBUG
                WCHAR szMsgBuf[MAX_PATH*2 + 1];
                wnsprintf( szMsgBuf, MAX_PATH*2, L"     MoveFile((%s, %s)) FAILED in DeleteAssemblyFiles with  <%x> \r\n",
                                              szAsmDirPath, szPendDelDirPath, hr );
                WriteToLogFile(szMsgBuf);
#endif  // DEBUG

        if( (hr == HRESULT_FROM_WIN32(ERROR_FILE_NOT_FOUND) )  
               || (hr == HRESULT_FROM_WIN32(ERROR_PATH_NOT_FOUND)) )
        {
            hr = S_OK;
            goto exit;
        }
    }
    else
    {
        hr = RemoveDirectoryAndChildren(szPendDelDirPath);
        hr = S_OK; // don't worry about passing back error here. its already in pend-del dir.
        goto exit;
    }

    // looks like there are some in-use files here.
    // move all the asm files to pend del dir.
    if(!CreateDirectory(szPendDelDirPath, NULL))
    {
        hr = FusionpHresultFromLastError();
        goto exit;
    }

    hr = MoveAllFilesFromDir(szAsmDirPath, szPendDelDirPath);

    if(hr == S_OK)
    {
        // assembly deleted successfully delete/pend all temp files.
        hr = RemoveDirectoryAndChildren(szPendDelDirPath);
        hr = S_OK; // don't worry about passing back error here. its already in pend-del dir.
    }
    else
    {
        // could not delete assembly; restore all files back to original state.
#ifdef DEBUG
        HRESULT hrTemp =
#endif
        MoveAllFilesFromDir(szPendDelDirPath, szAsmDirPath);
#ifdef DEBUG
                WCHAR szMsgBuf[MAX_PATH*2 + 1];
                wnsprintf( szMsgBuf, MAX_PATH*2, L"     Restored all files back to <%s> hr = <%x> hrTemp = <%x> \r\n",
                                              szAsmDirPath, hr, hrTemp );
                WriteToLogFile(szMsgBuf);
#endif  // DEBUG

        hr = HRESULT_FROM_WIN32(ERROR_SHARING_VIOLATION);
    }

exit :

    if(hr == S_OK)
    {
        pszTemp = PathFindFileName(szAsmDirPath);

        if(pszTemp > szAsmDirPath)
        {
            *(pszTemp-1) = L'\0';
        }

        // now that we have two levels of dirs...try to remove parent dir also
        // this succeeds only if it is empty, don't worry about return value.
        RemoveDirectory(szAsmDirPath);
    }

    return hr;
}