Esempio n. 1
0
int CConnectionSettingsAdvanced::DoModal(CConnectionSettings *pConnSettings)
   {
      int      nRetVal;

      ASSERT(pConnSettings);
      if(pConnSettings == NULL)
         return IDCANCEL;

      m_pConnSettings = pConnSettings;
      SetAppTitle(m_pConnSettings->GetName());
      SetAppFileName(m_pConnSettings->GetAppFileName());
      SetTimeOut(m_pConnSettings->GetTimeOut());
      SetFirstCheck(m_pConnSettings->GetFirstCheck());
      m_bUsesDialup = m_pConnSettings->WatchForDialup();
      m_bRestoreAutodial = m_pConnSettings->RestoreAutodial();

      nRetVal = CDialog::DoModal();

      if(nRetVal == IDOK)
         {
            m_pConnSettings->SetTimeOut(GetTimeOut());
            m_pConnSettings->SetFirstCheck(GetFirstCheck());
            m_pConnSettings->SetName(GetAppTitle());
            m_pConnSettings->SetAppFileName(GetAppFileName());
            m_pConnSettings->SetWatchForDialup(m_bUsesDialup);
            m_pConnSettings->SetRestoreAutodial(m_bRestoreAutodial);
            m_pConnSettings->SaveSettings();
         }
      return nRetVal;
   }
Esempio n. 2
0
bool CPeerCacheUpSocket::ProcessHttpRequest()
{
	if (GetClient() == NULL)
		throw CString(__FUNCTION__ " - No client attached to HTTP socket");

	UINT uHttpRes = GetClient()->ProcessPeerCacheUpHttpRequest(m_astrHttpHeaders);
	if (uHttpRes != HTTP_STATUS_OK){
		CStringA strResponse;
		strResponse.AppendFormat("HTTP/1.0 %u\r\n", uHttpRes);
		strResponse.AppendFormat("Content-Length: 0\r\n");
		strResponse.AppendFormat("\r\n");

		if (thePrefs.GetDebugClientTCPLevel() > 0)
			Debug(_T("Sending PeerCache HTTP respone:\n%hs"), strResponse);
		CRawPacket* pHttpPacket = new CRawPacket(strResponse);
		theStats.AddUpDataOverheadFileRequest(pHttpPacket->size);
		SendPacket(pHttpPacket);
		SetHttpState(HttpStateUnknown);

		// PC-TODO: Problem, the packet which was queued for sending will not be sent, if we immediatly
		// close that socket. Currently I just let it timeout.
		//return false;
		SetTimeOut(SEC2MS(30));
		return true;
	}
	GetClient()->SetHttpSendState(0);

	SetHttpState(HttpStateRecvExpected);
	GetClient()->SetUploadState(US_UPLOADING);
	
	return true;
}
Esempio n. 3
0
static uint_fast8_t ICACHE_FLASH_ATTR
ISO14443_read(uint_fast8_t block, uint8_t *rd_buf)
{
    phcsBfl_Status_t     status = PH_ERR_BFL_SUCCESS;
    /* Buffer serial number                     */
//    uint8_t serial[12];
    /* Counter variable */
    uint_fast8_t i;
    /* Response shall now be sent within 5ms */
    SetTimeOut(&rc_reg_ctl, &rc_op_ctl, 5000, 0);
    /* Prepare data for Mifare Read */
    mfr_p.cmd           = PHCS_BFLMFRD_READ;          // set Read command
    mfr_p.addr          = block;                 // Block 5, must be authenticated before
    mfr_p.buffer        = rd_buf;               // set return buffer to buffer
    mfr_p.buffer_length = 0;                    // nothing is handed over in the buffer
    /* Start Mifare Read */
    status = mfrd.Transaction(&mfr_p);
    /* Check return code and display error number if an error occured, else display data */
    if(status != PH_ERR_BFL_SUCCESS)
    {
        PDEBUG("*** ERROR! MifareRead: Block=%02X, Status = %04X \r\n", mfr_p.addr, status);
    }
    else
    {
        PDEBUG("Mifare Read OK: Blk=%02X, Dat: ", mfr_p.addr);
        for(i=0; i<mfr_p.buffer_length; i++)
        {
            PDEBUG("%02X", mfr_p.buffer[i]);
        }
        PDEBUG("\r\n");
    }
    return status;
}
int ClientSocket::Send(const void* lpBuf, int nBufLen, int nFlags = 0/* = 0 */)
{
	SetTimeOut(3000);
	int nSend = CSocket::Send(lpBuf, nBufLen, nFlags);
	KillTimeOut();
	return nSend;
}
Esempio n. 5
0
static uint_fast8_t ICACHE_FLASH_ATTR
ISO14443_write(uint_fast8_t block, uint8_t *wr_buf)
{
//    phcsBflMfRd_CommandParam_t          mfr_p;
    phcsBfl_Status_t     status = PH_ERR_BFL_SUCCESS;
    /* Response shall now be sent within 5ms */
    SetTimeOut(&rc_reg_ctl, &rc_op_ctl, 5000, 0);
    /* Prepare data for Mifare Write */
    mfr_p.cmd           = PHCS_BFLMFRD_WRITE ;          // set Write command
    mfr_p.addr          = block;
    mfr_p.buffer        = wr_buf;
    mfr_p.buffer_length = PHCS_BFLMFRD_STD_BLOCK_SIZE;  // nothing is handed over in the buffer
    /* Start Mifare write */
    status = mfrd.Transaction(&mfr_p);
    /* Check return code and display error number if an error occured, else display data */
    if(status != PH_ERR_BFL_SUCCESS)
    {
        PDEBUG("*** ERROR! MifareWrite: Block=%02X, Status = %04x \r\n", mfr_p.addr, status);
    }
    else
    {
        uint_fast8_t i = 0;
        PDEBUG("Mifare write OK: Blk=%02X Dat:", mfr_p.addr);
        for(i=0; i<PHCS_BFLMFRD_STD_BLOCK_SIZE; i++)
        {
            PDEBUG("%02X", mfr_p.buffer[i]);
        }
        PDEBUG("\r\n");
    }
    return status;
}
Esempio n. 6
0
int MSocket::Receive(CString& str, UINT uTimeOut, int nFlags)
{

	//static char szBuf[5000];
	AutoBuf szBuf(5000);
	memset(szBuf.p, 0, 5000);

	// If a timeout value was specified, set it
	if (uTimeOut > 0)
		SetTimeOut(uTimeOut);

	// Call base class function
	int nRet = CSocket::Receive(szBuf.p, 5000, nFlags);

	// If we previously set a timeout
	if (uTimeOut > 0)
	{
		KillTimeOut();
		// If the operation timedout, set a more
		// natural error message
		if (nRet == SOCKET_ERROR)
		{
			if (GetLastError() == WSAEINTR)
				SetLastError(WSAETIMEDOUT);
		}
	}

	// Fill in the CString reference
	str = szBuf.p;
	return nRet;
}
Esempio n. 7
0
CurlEasy::CurlEasy(CurlOption ops): m_ops(ops)
{
	if ((m_curl = curl_easy_init()) == NULL)
		throw CurlException(EC_CURL_FAILED_INIT);
	curl_easy_setopt(m_curl, CURLOPT_NOSIGNAL, 1);
	// Default time-out values
	SetConnectionTimeOut(60);
	SetTimeOut(120);
}
Esempio n. 8
0
/*
 * This example shows how to act as Mifare reader
 */
int ICACHE_FLASH_ATTR
MifareReader_requestA(int argc, char *argv[])
{
    /* Status variable */
    phcsBfl_Status_t     status = PH_ERR_BFL_SUCCESS;
    /* Buffer for data transfer (send/receive) */
//    uint8_t buffer[EXAMPLE_TRX_BUFFER_SIZE];
    /* Buffer serial number                     */
    /* Counter variable */
    get_pre_timer_tick();
    if (argc & COIN_OPT_INIT_PRE_FLOW)
    {
        MifareReader_init();
        ISO14443_active(0, NULL);
    }
    /* Set timeout for REQA, ANTICOLL, SELECT to 200us */
    SetTimeOut(&rc_reg_ctl, &rc_op_ctl, 500, 0);
    /*
     * Do activation according to ISO14443A Part3
     * Prepare the Request command
     */
    buffer[0] = 0;
    buffer[1] = 0;
    /* Set Request command code (or Wakeup: ISO14443_3_REQALL) */
    //req_p.req_code = PHCS_BFLI3P3A_REQIDL;
    req_p.req_code = PHCS_BFLI3P3A_REQALL;
    req_p.atq      = buffer;                /* Let Request use the defined return buffer */
    status = iso14443_3.RequestA(&req_p);   /* Start Request command */
    /*
     * In normal operation this command returns one of the following three return codes:
     * - PH_ERR_BFL_SUCCESS             At least one card has responded
     * - PH_ERR_BFL_COLLISION_ERROR     At least two cards have responded
     * - PH_ERR_BFL_IO_TIMEOUT          No response at all
     */
    if(status == PH_ERR_BFL_SUCCESS || (status & PH_ERR_BFL_ERR_MASK) == PH_ERR_BFL_COLLISION_ERROR)
    {
        /* There was at least one response */
        if((status & PH_ERR_BFL_ERR_MASK) == PH_ERR_BFL_COLLISION_ERROR)
        {
            PDEBUG("[W] Multiple Cards detected!! Collision occured during Request!\r\n");
        }
        else
        {
        }
//        if (status = PH_ERR_BFL_SUCCESS)
        //os_printf("ATQA=%02X %02X,sta:%X\r\n", req_p.atq[0],req_p.atq[1], status);
        status = PH_ERR_BFL_SUCCESS;
    }
    else
    {
        /* No response at all */
        PDEBUG("*** ERROR! RequestA: RequestCode=%02X, ATQA=%02X %02X, Status = %04X \r\n",
               req_p.req_code, req_p.atq[0],req_p.atq[1], status);
    }
    return status;
}
Esempio n. 9
0
/*=================================================================
* Function ID :  Open
* Input       :  void
* Output      :  void
* Author      :  
* Date        :  2006  2
* Return	  :  TRUE/FALSE
* Description :  打开串口
* Notice	  :  
*			  :	 
*					
*=================================================================*/
bool CComSmart::Open()
{
	char  szFileName[MAX_PATH];	
	BYTE  str[60];
	
	memset(str,0x00,sizeof str);
	memset(szFileName,0x00,sizeof szFileName);
	
	m_IpPar.bConnect=false;
	
	sprintf(szFileName, "%s", m_IpPar.cIPAddress);
	m_handle = CreateFile(
		szFileName, 
		GENERIC_READ|GENERIC_WRITE,
		0,
		0,
		OPEN_EXISTING,
		FILE_FLAG_OVERLAPPED,
		0);
	if( m_handle == INVALID_HANDLE_VALUE )
	{
		sprintf(m_szErrorText,"打开COM口失败!", GetLastError());
		m_IpPar.bConnect=false;	
		return false;
	}	
	if(!SetState(m_IpPar.nPortNo, 'N', 8, 1))	
	{
		Close();
		m_IpPar.bConnect=false;	
		return false;
	}		
	
	SetTimeOut(10, 0);	
	m_ReadOver.hEvent  = CreateEvent(NULL, TRUE, FALSE, NULL);
	m_WriteOver.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
	
	m_nReadBytes			= 0 ;
	m_nWriteBytes			= 0 ;	
	m_ReadOver.Internal		= 0 ;
	m_ReadOver.InternalHigh = 0 ;
	m_ReadOver.Offset		= 0 ;
	m_ReadOver.OffsetHigh	= 0 ;
	
	ResetEvent(m_ReadOver.hEvent);
	
	m_WriteOver.Internal	= 0 ;
	m_WriteOver.InternalHigh = 0 ;
	m_WriteOver.Offset		= 0 ;
	m_WriteOver.OffsetHigh = 0 ;
	ResetEvent(m_WriteOver.hEvent);
	
	m_IpPar.bConnect=true;	
	sprintf(m_szErrorText,"服务设备[ %s ]打开成功! 串口:%s, 波特率:%ld\n", m_Data.BcdToAsc((BYTE*)m_regno,4,str), m_IpPar.cIPAddress, m_IpPar.nPortNo);
	m_pDialog->AddString(m_szErrorText);
	return true;
}
Esempio n. 10
0
SCom::SCom()
{
	m_bOpened = false;
	m_hCom = 0;
	SetTimeOut(5000,5000);//默认5秒超时
#ifdef WIN32
	memset( &m_OverlappedRead, 0, sizeof( OVERLAPPED ) );
 	memset( &m_OverlappedWrite, 0, sizeof( OVERLAPPED ) );
#endif
}
Esempio n. 11
0
void ClientSocket::OnReceive(int nErrorCode)
{
	// TODO:  在此添加专用代码和/或调用基类
	char *pData = NULL;
	
	//pData = new char[10240];
	//memset(pData, 0, sizeof(char)*10240);
	External_Mag_Head msgHead;
	int msgLen = sizeof(External_Mag_Head);
	UINT leng = 0;
	CString strDoc;
	pData = new char[msgLen];
	memset(pData, 0, sizeof(char)*msgLen);
	SetTimeOut(3000);
	leng = Receive(pData, msgLen, 0);
	KillTimeOut();
	AsyncSelect(FD_READ);
	memcpy(&msgHead, pData, msgLen);
	free(pData);
	pData = new char[msgHead.load_len + 1];
	
	memset(pData, 0, sizeof(char)*msgHead.load_len + 1);
	SetTimeOut(3000);
	leng = Receive(pData, msgHead.load_len, 0);
	KillTimeOut();
	AsyncSelect(FD_READ);
	//char *p_msgBody = (char*)malloc(sizeof(char)*msgHead.load_len);
	//memset(p_msgBody, 0, sizeof(char)*msgHead.load_len);
	//memcpy(p_msgBody, pData + msgLen, sizeof(char)*msgHead.load_len);
	strDoc = StringConvertor::Utf8ToWide(pData);
	m_xml.SetDoc(strDoc);
	ParseXml(m_xml);
	/*DWORD *pParams = new DWORD[2];
	pParams[0] = (DWORD)this;
	pParams[1] = (DWORD)pData;
	m_hThread = ::CreateThread(NULL, NULL, ParseXml, (LPVOID*)(pParams), NULL, NULL);*/
	
	delete pData;
	CSocket::OnReceive(nErrorCode);
}
Esempio n. 12
0
void CATDtmfVts::ConstructL()
	{
	LOGTEXT(_L8("[Ltsy CallControl] Starting CATDtmfVts::ConstructL()"));
	
	//Invoke base class function
	CAtCommandBase::ConstructL();
	
	//Create Timer
	iCallbackTimer = CCallbackTimer::NewL(*this);
	
	//Set read and write timeout
	SetTimeOut(KLtsyDefaultWriteTimeOut, KLtsyVTSReadTimeout);
	}
Esempio n. 13
0
static ICACHE_FLASH_ATTR
uint_fast8_t ISO14443_halt(void)
{
    phcsBfl_Status_t     status = PH_ERR_BFL_SUCCESS;
    /* Set timeouts */
    SetTimeOut(&rc_reg_ctl, &rc_op_ctl, 1000, 0);
    status = iso14443_3.HaltA(&hlt_p);
    /* Check return code: If timeout occures, PH_ERR_BFL_SUCCESS is returned */
    if(status == PH_ERR_BFL_SUCCESS)
    {
        PDEBUG("Halt probably successful, timeout occured\r\n");
    }
    else
    {
        PDEBUG("*** ERROR! HaltA: Status = %04X \r\n", status);
    }
    return status;
}
/// 数据通道连通之后,命令通道就可以开始发“数据传输”相关命令了..
void CFtpClientDataSocket::OnConnect(int nErrorCode)
{
	CFtpClientReqSocket* reqSocket = (DYNAMIC_DOWNCAST(CFtpClient,GetClient()))->GetClientReqSocket();
	if( reqSocket==NULL )
		return;

	if (nErrorCode == 0)
	{
		reqSocket->SetFtpState(ftpRETR_REST); //< 通知命令通道可以开始找断点续传的位置了,但还要看服务器是否支持		
	}
	else
	{
		reqSocket->SetFtpState(ftpABOR);		
	}

	reqSocket->SendCommand();

	SetTimeOut( 4*CONNECTION_TIMEOUT );
}
Esempio n. 15
0
int MSocket::Send(LPCTSTR lpszStr, UINT uTimeOut, int nFlags)
{
	// If a timeout value was specified, set it
	if (uTimeOut > 0)
		SetTimeOut(uTimeOut);

	// Call base class function
	int nRet = CSocket::Send(lpszStr, strlen(lpszStr), nFlags);

	// If we previously set a timeout
	if (uTimeOut > 0)
	{
		KillTimeOut();
		// If the operation timedout, set a more
		// natural error message
		if (GetLastError() == WSAEINTR)
			SetLastError(WSAETIMEDOUT);
	}
	return nRet;
}
Esempio n. 16
0
void NetChannel::Reset()
{
	m_keep_alive = true;
	m_crashed = false;
	m_connected = false;

	m_connect_time = m_System->GetTime();

	SetTimeOut(30);
	SetRate(10000);
	SetUpdateRate(20);

	m_incoming_sequence = 0;
	m_incoming_acknowledged = 0;
	m_incoming_reliable_acknowledged = 0;
	m_incoming_reliable_sequence = 0;
	m_outgoing_sequence = 1;
	m_reliable_sequence = 0;
	m_last_reliable_sequence = 0;
}
Esempio n. 17
0
// Hook process of mouse hook
// Process cases of mouse-button to determine when to send mouse button 3,4,5
// Everything goes here
__declspec(dllexport) LRESULT CALLBACK MouseHookProc(int nCode, WPARAM wParam, LPARAM lParam)
{
	

	if (nCode < HC_ACTION)
		return CallNextHookEx(mousehHook, nCode, wParam, lParam);
	if (passNextClick)
	{
		passNextClick = FALSE;
		return CallNextHookEx(mousehHook, nCode, wParam, lParam);
	}

	switch (wParam)
	{
		// Three finger Swipe
		case WM_RBUTTONDOWN:
			OutputDebugStringA(LPCSTR("WM_RBUTTONDOWN : "));
			RButtonDown = TRUE;
			if (timerOn) StopTimeOut();
			SetTimeOut();
			OutputDebugStringA(LPCSTR("kill\n"));
			return 1; // kiLl the key (retaure if timeout eg real right click)
			break;
		
		case WM_RBUTTONUP:
			OutputDebugStringA(LPCSTR("WM_RBUTTONUP : "));
			if (timerOn && RButtonDown)
			{
				StopTimeOut(); // stop LWIN being fired on timer
				OutputDebugStringA(LPCSTR("kill\n"));
				sendMMiddle();
				RButtonDown = FALSE;				
				return 1; //kill the key
			}
			OutputDebugStringA(LPCSTR("pass\n"));
			break;
	}
	//OutputDebugStringA(LPCSTR("Mouse pass\n"));
	return CallNextHookEx(mousehHook, nCode, wParam, lParam);
}
Esempio n. 18
0
//----------------------------------------------------------------------------------
// Initialize Humidity Sensor driver
int OpenHMSdrv(void)
//----------------------------------------------------------------------------------
{
		if(hms_pin_scl > 15 || hms_pin_sda > 15 || hms_pin_scl == hms_pin_sda) { // return 1;
			hms_pin_scl = 4;
			hms_pin_sda = 5;
		}
		if(i2c_init(hms_pin_scl, hms_pin_sda, 54)) {	// 4,5,54); // 354
			hms_errflg = -3; // драйвер не инициализирован - ошибки параметров инициализации
			return 1;
		}
		hmerrcnt = 0;
        hmioerr = 0;
        hmfuncs = 0;
        hms_errflg = 1; // драйвер запущен
        SetTimeOut(50); // зададим таймаут в 50 ms
		ets_timer_disarm(&test_timer);
		ets_timer_setfn(&test_timer, (os_timer_func_t *)ReadHMS, NULL);
		ets_timer_arm_new(&test_timer, 10, 1, 1); // 100 раз в сек
	    hms_init_flg = 1;
		return 0;
}
Esempio n. 19
0
static uint_fast8_t ICACHE_FLASH_ATTR
ISO14443_auth(uint_fast8_t block, uint8_t *uid, uint8_t *keyA, uint8_t *keyB)
{
    /* Buffer for data transfer (send/receive) */
    uint8_t tmp_buffer[EXAMPLE_TRX_BUFFER_SIZE];
    phcsBfl_Status_t     status = PH_ERR_BFL_SUCCESS;
    /* Prepare data for Mifare Authentication */
    if (NULL != keyA)
    {
        fill_auth_buf_by_key(tmp_buffer, uid, keyA);
        mfr_p.cmd           = PHCS_BFLMFRD_AUTHENT_A;     // Set Authenticate with KeyA
    }
    else if (NULL != keyB)
    {
        fill_auth_buf_by_key(tmp_buffer, uid, keyB);
        mfr_p.cmd           = PHCS_BFLMFRD_AUTHENT_B;     // Set Authenticate with KeyB
    }
    else
    {
        fill_auth_buf_by_key_0xFF(tmp_buffer, uid);
        mfr_p.cmd           = PHCS_BFLMFRD_AUTHENT_A;
    }
    /* Initialize all the variables of authentication structure */
    mfr_p.addr          = block;                 // Block 7
    mfr_p.buffer        = tmp_buffer;               // Set the mifare buffer to the one initialised
    mfr_p.buffer_length = 10;                   // 6 bytes of key and 4 bytes SNR in buffer
    /* Set timeout for Authentication */
    SetTimeOut(&rc_reg_ctl, &rc_op_ctl, 10000, 0);
    /* Start the Mifare authentication */
    status = mfrd.Transaction(&mfr_p);
    /* Check return code and display error number if an error occured */
    if(status != PH_ERR_BFL_SUCCESS)
    {
        PDEBUG("*** ERROR! Mifare Authentication: Command=%01X, Block=%02X, Status = %04X\r\n",
               mfr_p.cmd, mfr_p.addr, status);
    }
    return status;
}
Esempio n. 20
0
void MountAll()
{
    char line[CF_BUFSIZE];
    FILE *pp;

    if (DONTDO)
    {
        CfOut(cf_verbose, "", "Promised to mount filesystem, but not on this trial run\n");
        return;
    }
    else
    {
        CfOut(cf_verbose, "", " -> Attempting to mount all filesystems.\n");
    }

#if defined(__CYGWIN__)
    /* This is a shell script. Make sure it hasn't been compromised. */

    struct stat sb;

    if (cfstat("/etc/fstab", &sb) == -1)
    {
        int fd;
        if ((fd = creat("/etc/fstab", 0755)) > 0)
        {
            if (write(fd, "#!/bin/sh\n\n", 10) != 10)
            {
                UnexpectedError("Failed to write to file '/etc/fstab'");
            }
            close(fd);
        }
        else
        {
            if (sb.st_mode & (S_IWOTH | S_IWGRP))
            {
                CfOut(cf_error, "", "File /etc/fstab was insecure. Cannot mount filesystems.\n");
                return;
            }
        }
    }
#endif

    SetTimeOut(RPCTIMEOUT);

    if ((pp = cf_popen(VMOUNTCOMM[VSYSTEMHARDCLASS], "r")) == NULL)
    {
        CfOut(cf_error, "cf_popen", "Failed to open pipe from %s\n", VMOUNTCOMM[VSYSTEMHARDCLASS]);
        return;
    }

    while (!feof(pp))
    {
        if (ferror(pp))         /* abortable */
        {
            CfOut(cf_inform, "ferror", "Error mounting filesystems\n");
            break;
        }

        if (CfReadLine(line, CF_BUFSIZE, pp) == -1)
        {
            FatalError("Error in CfReadLine");
        }

        if (ferror(pp))         /* abortable */
        {
            CfOut(cf_inform, "ferror", "Error mounting filesystems\n");
            break;
        }

        if ((strstr(line, "already mounted")) || (strstr(line, "exceeded")) || (strstr(line, "determined")))
        {
            continue;
        }

        if (strstr(line, "not supported"))
        {
            continue;
        }

        if ((strstr(line, "denied")) || (strstr(line, "RPC")))
        {
            CfOut(cf_error, "", "There was a mount error, trying to mount one of the filesystems on this host.\n");
            break;
        }

        if ((strstr(line, "trying")) && (!strstr(line, "NFS version 2")) && (!strstr(line, "vers 3")))
        {
            CfOut(cf_error, "", "Attempting abort because mount went into a retry loop.\n");
            break;
        }
    }

    alarm(0);
    signal(SIGALRM, SIG_DFL);
    cf_pclose(pp);
}
Esempio n. 21
0
int LoadMountInfo(Rlist **list)
/* This is, in fact, the most portable way to read the mount info! */
/* Depressing, isn't it? */
{
    FILE *pp;
    char buf1[CF_BUFSIZE], buf2[CF_BUFSIZE], buf3[CF_BUFSIZE];
    char host[CF_MAXVARSIZE], source[CF_BUFSIZE], mounton[CF_BUFSIZE], vbuff[CF_BUFSIZE];
    int i, nfs = false;

    for (i = 0; VMOUNTCOMM[VSYSTEMHARDCLASS][i] != ' '; i++)
    {
        buf1[i] = VMOUNTCOMM[VSYSTEMHARDCLASS][i];
    }

    buf1[i] = '\0';

    SetTimeOut(RPCTIMEOUT);

    if ((pp = cf_popen(buf1, "r")) == NULL)
    {
        CfOut(cf_error, "cf_popen", "Can't open %s\n", buf1);
        return false;
    }

    do
    {
        vbuff[0] = buf1[0] = buf2[0] = buf3[0] = source[0] = '\0';

        if (ferror(pp))         /* abortable */
        {
            CfOut(cf_error, "ferror", "Error getting mount info\n");
            break;
        }

        if (CfReadLine(vbuff, CF_BUFSIZE, pp) == -1)
        {
            FatalError("Error in CfReadLine");
        }

        if (ferror(pp))         /* abortable */
        {
            CfOut(cf_error, "ferror", "Error getting mount info\n");
            break;
        }

        if (strstr(vbuff, "nfs"))
        {
            nfs = true;
        }

        sscanf(vbuff, "%s%s%s", buf1, buf2, buf3);

        if ((vbuff[0] == '\0') || (vbuff[0] == '\n'))
        {
            break;
        }

        if (strstr(vbuff, "not responding"))
        {
            CfOut(cf_error, "", "%s\n", vbuff);
        }

        if (strstr(vbuff, "be root"))
        {
            CfOut(cf_error, "", "Mount access is denied. You must be root.\n");
            CfOut(cf_error, "", "Use the -n option to run safely.");
        }

        if ((strstr(vbuff, "retrying")) || (strstr(vbuff, "denied")) || (strstr(vbuff, "backgrounding")))
        {
            continue;
        }

        if ((strstr(vbuff, "exceeded")) || (strstr(vbuff, "busy")))
        {
            continue;
        }

        if (strstr(vbuff, "RPC"))
        {
            CfOut(cf_inform, "", "There was an RPC timeout. Aborting mount operations.\n");
            CfOut(cf_inform, "", "Session failed while trying to talk to remote host\n");
            CfOut(cf_inform, "", "%s\n", vbuff);
            cf_pclose(pp);
            return false;
        }

#if defined(__sun) || defined(__hpux)
        if (IsAbsoluteFileName(buf3))
        {
            strcpy(host, "localhost");
            strcpy(mounton, buf1);
        }
        else
        {
            sscanf(buf1, "%[^:]:%s", host, source);
            strcpy(mounton, buf1);
        }
#elif defined(_AIX)
        /* skip header */

        if (IsAbsoluteFileName(buf1))
        {
            strcpy(host, "localhost");
            strcpy(mounton, buf2);
        }
        else
        {
            strcpy(host, buf1);
            strcpy(source, buf1);
            strcpy(mounton, buf3);
        }
#elif defined(__CYGWIN__)
        strcpy(mounton, buf2);
        strcpy(host, buf1);
#elif defined(sco) || defined(__SCO_DS)
        CfOut(cf_error, "", "Don't understand SCO mount format, no data");
#else
        if (IsAbsoluteFileName(buf1))
        {
            strcpy(host, "localhost");
            strcpy(mounton, buf3);
        }
        else
        {
            sscanf(buf1, "%[^:]:%s", host, source);
            strcpy(mounton, buf3);
        }
#endif

        CfDebug("GOT: host=%s, source=%s, mounton=%s\n", host, source, mounton);

        if (nfs)
        {
            AugmentMountInfo(list, host, source, mounton, "nfs");
        }
        else
        {
            AugmentMountInfo(list, host, source, mounton, NULL);
        }
    }
    while (!feof(pp));

    alarm(0);
    signal(SIGALRM, SIG_DFL);
    cf_pclose(pp);
    return true;
}
Esempio n. 22
0
int LoadMountInfo(Rlist **list)
/* This is, in fact, the most portable way to read the mount info! */
/* Depressing, isn't it? */
{
    FILE *pp;
    char buf1[CF_BUFSIZE], buf2[CF_BUFSIZE], buf3[CF_BUFSIZE];
    char host[CF_MAXVARSIZE], source[CF_BUFSIZE], mounton[CF_BUFSIZE], vbuff[CF_BUFSIZE];
    int i, nfs = false;

    for (i = 0; VMOUNTCOMM[VSYSTEMHARDCLASS][i] != ' '; i++)
    {
        buf1[i] = VMOUNTCOMM[VSYSTEMHARDCLASS][i];
    }

    buf1[i] = '\0';

    SetTimeOut(RPCTIMEOUT);

    if ((pp = cf_popen(buf1, "r")) == NULL)
    {
        CfOut(cf_error, "cf_popen", "Can't open %s\n", buf1);
        return false;
    }

    do
    {
        vbuff[0] = buf1[0] = buf2[0] = buf3[0] = source[0] = '\0';

        if (ferror(pp))         /* abortable */
        {
            CfOut(cf_error, "ferror", "Error getting mount info\n");
            break;
        }

        CfReadLine(vbuff, CF_BUFSIZE, pp);

        if (ferror(pp))         /* abortable */
        {
            CfOut(cf_error, "ferror", "Error getting mount info\n");
            break;
        }

        if (strstr(vbuff, "nfs"))
        {
            nfs = true;
        }

        sscanf(vbuff, "%s%s%s", buf1, buf2, buf3);

        if ((vbuff[0] == '\0') || (vbuff[0] == '\n'))
        {
            break;
        }

        if (strstr(vbuff, "not responding"))
        {
            CfOut(cf_error, "", "%s\n", vbuff);
        }

        if (strstr(vbuff, "be root"))
        {
            CfOut(cf_error, "", "Mount access is denied. You must be root.\n");
            CfOut(cf_error, "", "Use the -n option to run safely.");
        }

        if ((strstr(vbuff, "retrying")) || (strstr(vbuff, "denied")) || (strstr(vbuff, "backgrounding")))
        {
            continue;
        }

        if ((strstr(vbuff, "exceeded")) || (strstr(vbuff, "busy")))
        {
            continue;
        }

        if (strstr(vbuff, "RPC"))
        {
            CfOut(cf_inform, "", "There was an RPC timeout. Aborting mount operations.\n");
            CfOut(cf_inform, "", "Session failed while trying to talk to remote host\n");
            CfOut(cf_inform, "", "%s\n", vbuff);
            cf_pclose(pp);
            return false;
        }

        switch (VSYSTEMHARDCLASS)
        {
        case darwin:
        case linuxx:
        case unix_sv:
        case freebsd:
        case netbsd:
        case openbsd:
        case qnx:
        case crayos:
        case dragonfly:
            if (IsAbsoluteFileName(buf1))
            {
                strcpy(host, "localhost");
                strcpy(mounton, buf3);
            }
            else
            {
                sscanf(buf1, "%[^:]:%s", host, source);
                strcpy(mounton, buf3);
            }

            break;
        case solaris:

        case hp:
            if (IsAbsoluteFileName(buf3))
            {
                strcpy(host, "localhost");
                strcpy(mounton, buf1);
            }
            else
            {
                sscanf(buf1, "%[^:]:%s", host, source);
                strcpy(mounton, buf1);
            }

            break;
        case aix:
            /* skip header */

            if (IsAbsoluteFileName(buf1))
            {
                strcpy(host, "localhost");
                strcpy(mounton, buf2);
            }
            else
            {
                strcpy(host, buf1);
                strcpy(source, buf1);
                strcpy(mounton, buf3);
            }
            break;

        case cfnt:
            strcpy(mounton, buf2);
            strcpy(host, buf1);
            break;

        case cfsco:
            CfOut(cf_error, "", "Don't understand SCO mount format, no data");

        default:
            printf("cfengine software error: case %d = %s\n", VSYSTEMHARDCLASS, CLASSTEXT[VSYSTEMHARDCLASS]);
            FatalError("System error in GetMountInfo - no such class!");
        }

        CfDebug("GOT: host=%s, source=%s, mounton=%s\n", host, source, mounton);

        if (nfs)
        {
            AugmentMountInfo(list, host, source, mounton, "nfs");
        }
        else
        {
            AugmentMountInfo(list, host, source, mounton, NULL);
        }
    }
    while (!feof(pp));

    alarm(0);
    signal(SIGALRM, SIG_DFL);
    cf_pclose(pp);
    return true;
}
Esempio n. 23
0
bool LoadMountInfo(Seq *list)
/* This is, in fact, the most portable way to read the mount info! */
/* Depressing, isn't it? */
{
    FILE *pp;
    char buf1[CF_BUFSIZE], buf2[CF_BUFSIZE], buf3[CF_BUFSIZE];
    int i, nfs = false;

    for (i = 0; VMOUNTCOMM[VSYSTEMHARDCLASS][i] != ' '; i++)
    {
        buf1[i] = VMOUNTCOMM[VSYSTEMHARDCLASS][i];
    }

    buf1[i] = '\0';

    SetTimeOut(RPCTIMEOUT);

    if ((pp = cf_popen(buf1, "r", true)) == NULL)
    {
        Log(LOG_LEVEL_ERR, "Can't open '%s'. (cf_popen: %s)", buf1, GetErrorStr());
        return false;
    }

    size_t vbuff_size = CF_BUFSIZE;
    char *vbuff = xmalloc(vbuff_size);

    for (;;)
    {
        buf1[0] = buf2[0] = buf3[0] = '\0';
        nfs = false;

        ssize_t res = CfReadLine(&vbuff, &vbuff_size, pp);
        if (res == -1)
        {
            if (!feof(pp))
            {
                Log(LOG_LEVEL_ERR, "Unable to read list of mounted filesystems. (fread: %s)", GetErrorStr());
                cf_pclose(pp);
                free(vbuff);
                return false;
            }
            else
            {
                break;
            }
        }

        if (strstr(vbuff, "nfs"))
        {
            nfs = true;
        }

        // security note: buff is CF_BUFSIZE, so that is the max that can be written to buf1, buf2 or buf3
        sscanf(vbuff, "%s%s%s", buf1, buf2, buf3);

        if ((vbuff[0] == '\0') || (vbuff[0] == '\n'))
        {
            break;
        }

        if (strstr(vbuff, "not responding"))
        {
            Log(LOG_LEVEL_ERR, "%s", vbuff);
        }

        if (strstr(vbuff, "be root"))
        {
            Log(LOG_LEVEL_ERR, "Mount access is denied. You must be root. Use the -n option to run safely");
        }

        if ((strstr(vbuff, "retrying")) || (strstr(vbuff, "denied")) || (strstr(vbuff, "backgrounding")))
        {
            continue;
        }

        if ((strstr(vbuff, "exceeded")) || (strstr(vbuff, "busy")))
        {
            continue;
        }

        if (strstr(vbuff, "RPC"))
        {
            Log(LOG_LEVEL_INFO, "There was an RPC timeout. Aborting mount operations.");
            Log(LOG_LEVEL_INFO, "Session failed while trying to talk to remote host");
            Log(LOG_LEVEL_INFO, "%s", vbuff);
            cf_pclose(pp);
            free(vbuff);
            return false;
        }

        // host: max FQDN is 255 chars (max IPv6 with IPv4 tunneling is 45 chars)
        // source, mounton: hardcoding max path length to 1023; longer is very unlikely
        char host[256], source[1024], mounton[1024];
        host[0] = source[0] = mounton[0] = '\0';


#if defined(__sun) || defined(__hpux)
        if (IsAbsoluteFileName(buf3))
        {
            strlcpy(host, "localhost", sizeof(host));
            strlcpy(mounton, buf1, sizeof(mounton));
        }
        else
        {
            sscanf(buf1, "%255[^:]:%1023s", host, source);
            strlcpy(mounton, buf1, sizeof(mounton));
        }
#elif defined(_AIX)
        /* skip header */

        if (IsAbsoluteFileName(buf1))
        {
            strlcpy(host, "localhost", sizeof(host));
            strlcpy(mounton, buf2, sizeof(mounton));
        }
        else
        {
            strlcpy(host, buf1, sizeof(host));
            strlcpy(source, buf1, sizeof(source));
            strlcpy(mounton, buf3, sizeof(mounton));
        }
#elif defined(__CYGWIN__)
        strlcpy(mounton, buf2, sizeof(mounton));
        strlcpy(host, buf1, sizeof(host));
#elif defined(sco) || defined(__SCO_DS)
        Log(LOG_LEVEL_ERR, "Don't understand SCO mount format, no data");
#else
        if (IsAbsoluteFileName(buf1))
        {
            strlcpy(host, "localhost", sizeof(host));
            strlcpy(mounton, buf3, sizeof(mounton));
        }
        else
        {
            sscanf(buf1, "%255[^:]:%1023s", host, source);
            strlcpy(mounton, buf3, sizeof(mounton));
        }
#endif

        Log(LOG_LEVEL_DEBUG, "LoadMountInfo: host '%s', source '%s', mounton '%s'", host, source, mounton);

        if (nfs)
        {
            AugmentMountInfo(list, host, source, mounton, "nfs");
        }
        else
        {
            AugmentMountInfo(list, host, source, mounton, NULL);
        }
    }

    free(vbuff);
    alarm(0);
    signal(SIGALRM, SIG_DFL);
    cf_pclose(pp);
    return true;
}
Esempio n. 24
0
void MountAll()
{
    FILE *pp;

    if (DONTDO)
    {
        Log(LOG_LEVEL_VERBOSE, "Promised to mount filesystem, but not on this trial run");
        return;
    }
    else
    {
        Log(LOG_LEVEL_VERBOSE, "Attempting to mount all filesystems.");
    }

#if defined(__CYGWIN__)
    /* This is a shell script. Make sure it hasn't been compromised. */

    struct stat sb;

    if (stat("/etc/fstab", &sb) == -1)
    {
        int fd;
        if ((fd = creat("/etc/fstab", 0755)) > 0)
        {
            if (write(fd, "#!/bin/sh\n\n", 10) != 10)
            {
                UnexpectedError("Failed to write to file '/etc/fstab'");
            }
            close(fd);
        }
        else
        {
            if (sb.st_mode & (S_IWOTH | S_IWGRP))
            {
                Log(LOG_LEVEL_ERR, "File /etc/fstab was insecure. Cannot mount filesystems.");
                return;
            }
        }
    }
#endif

    SetTimeOut(RPCTIMEOUT);

    const char *cmd = VMOUNTCOMM[VSYSTEMHARDCLASS];

    if ((pp = cf_popen(cmd, "r", true)) == NULL)
    {
        Log(LOG_LEVEL_ERR, "Failed to open pipe from '%s'. (cf_popen: %s)",
            cmd, GetErrorStr());
        return;
    }

    size_t line_size = CF_BUFSIZE;
    char *line = xmalloc(line_size);

    for (;;)
    {
        ssize_t res = CfReadLine(&line, &line_size, pp);
        if (res == -1)
        {
            if (!feof(pp))
            {
                Log(LOG_LEVEL_ERR,
                    "Error reading output of command '%s' (ferror: %s)",
                    cmd, GetErrorStr());
            }
            break;
        }

        if ((strstr(line, "already mounted")) || (strstr(line, "exceeded")) || (strstr(line, "determined")))
        {
            continue;
        }

        if (strstr(line, "not supported"))
        {
            continue;
        }

        if ((strstr(line, "denied")) || (strstr(line, "RPC")))
        {
            Log(LOG_LEVEL_ERR,
                "There was a mount error while trying to mount the filesystems"
                " (command '%s')", cmd);
            break;
        }

        if ((strstr(line, "trying")) && (!strstr(line, "NFS version 2")) && (!strstr(line, "vers 3")))
        {
            Log(LOG_LEVEL_ERR,
                "Attempting filesystems mount aborted because command"
                " '%s' went into a retry loop", cmd);
            break;
        }
    }

    free(line);
    alarm(0);
    signal(SIGALRM, SIG_DFL);
    cf_pclose(pp);
}
Esempio n. 25
0
int ICACHE_FLASH_ATTR 
ISO14443_active(int argc, char *argv[])
{
    /* Counter variable */
    uint_fast16_t loop_cnt;
    phcsBfl_Status_t     status = PH_ERR_BFL_SUCCESS;
    /* Set the timer to auto mode, 5ms using operation control commands before HF is switched on to
     * guarantee Iso14443-3 compliance of Polling procedure
     */
    SetTimeOut(&rc_reg_ctl, &rc_op_ctl, 5000, 1);
    /* Activate the field (automatically if there is no external field detected) */
    mrp.address = PHCS_BFL_JREG_TXAUTO;
    mrp.mask    = PHCS_BFL_JBIT_INITIALRFON | PHCS_BFL_JBIT_TX2RFAUTOEN | PHCS_BFL_JBIT_TX1RFAUTOEN;
    mrp.set     = 1;
    status = rc_reg_ctl.ModifyRegister(&mrp);
    /*
     * After switching on the drivers wait until the timer interrupt occures, so that
     * the field is on and the 5ms delay have been passed.
     */
    loop_cnt = 5000;
    grp.address = PHCS_BFL_JREG_COMMIRQ;
    do
    {
        status = rc_reg_ctl.GetRegister(&grp);
    }
    while(!(grp.reg_data & PHCS_BFL_JBIT_TIMERI) && (status == PH_ERR_BFL_SUCCESS) && (--loop_cnt));
    /* Check status and diplay error if something went wrong */
    if ((status != PH_ERR_BFL_SUCCESS) || (loop_cnt == 0))
    {
        PDEBUG("*** ERROR! GetReg%02X,Dat=%02X,Sta=%X,loop=%u\r\n",
               grp.address, grp.reg_data, status, loop_cnt);
    }

    /* Clear the status flag afterwards */
    srp.address  = PHCS_BFL_JREG_COMMIRQ;
    srp.reg_data = PHCS_BFL_JBIT_TIMERI;
    status = rc_reg_ctl.SetRegister(&srp);

    SetTimeOut(&rc_reg_ctl, &rc_op_ctl, 5000, 0);
    /*
     * Following two register accesses are only needed if the interrupt pin is used
     * It doesn't hurt if polling is used instead.
     */
    /* Set IRQInv to zero -> interrupt signal won't be inverted */
    mrp.address = PHCS_BFL_JREG_COMMIEN;
    mrp.mask    = 0x80;
    mrp.set     = 0x00;
    status = rc_reg_ctl.ModifyRegister(&mrp);

    /* Enable IRQPushPull so that the PN51x actively drives the signal */
    mrp.address = PHCS_BFL_JREG_DIVIEN;
    mrp.mask    = 0x80;
    mrp.set     = 0xFF;
    status = rc_reg_ctl.ModifyRegister(&mrp);

    /* Activate receiver for communication
       The RcvOff bit and the PowerDown bit are cleared, the command is not changed. */
    srp.address  = PHCS_BFL_JREG_COMMAND;
    srp.reg_data = PHCS_BFL_JCMD_NOCMDCHANGE;
    status = rc_reg_ctl.SetRegister(&srp);
    return 0;
}
int Time_Window(int xtime, int ytime, int timerayon)
{

//background window
Rect TimeWindow(Vec2D (xtime, ytime ), Vec2D ( 370,300));
TimeWindow.SetRoundness(15);
TimeWindow.SetLineWidth(triple_epaisseur_ligne_fader);
TimeWindow.Draw(CouleurFond);
if(window_focus_id==908)
{
TimeWindow.DrawOutline(CouleurFader);
}
else
{
TimeWindow.DrawOutline(CouleurLigne);
}
/////////////////////////////////////////////////////////////////////////////////
Circle monTrajetTime0( Vec2D(xtime+150, ytime+150), 115);
 monTrajetTime0.SetLineWidth(epaisseur_ligne_fader);
 monTrajetTime0.DrawOutline( CouleurBleuProcedure);

Circle monTrajetTime2( Vec2D(xtime+150, ytime+150), 85);
 monTrajetTime2.SetLineWidth(epaisseur_ligne_fader);
 monTrajetTime2.Draw(CouleurBleuProcedure.WithAlpha(0.5));

 //AFFECTATION MIDI Fader

if( Midi_Faders_Affectation_Type!=0 && window_focus_id==W_TIME)
{
 if(mouse_x>xtime+150  && mouse_x< xtime+250 && mouse_y>ytime+150 && mouse_y<ytime+250 )
 {
 monTrajetTime0.DrawOutline(CouleurBlind);
 }
}

 if(show_im_recording_a_time==1)
 {
 monTrajetTime2.Draw(CouleurFader);
 }

 //affichage du pointeur de temps
 Circle monCurseurTime( Vec2D(position_curseur_time_x-4, position_curseur_time_y-4), 8 );
 monCurseurTime.SetLineWidth(epaisseur_ligne_fader);
 monCurseurTime.DrawOutline( CouleurBlind );


neuro.Print(ol::ToString(time_minutes), xtime+85, ytime+150);
neuro.Print("..",xtime+120,ytime+150);
neuro.Print(ol::ToString(time_secondes), xtime+130, ytime+150);
neuro.Print(".",xtime+170,ytime+150);
petitchiffre.Print(ol::ToString(time_centiemes), xtime+180, ytime+150);
petitchiffre.Print("1/100",xtime+190,ytime+135);

print_time_reperes(time_wheel_datatype_is);//affichage des chiffres sur le tableau de bord

///////////////////////CHOIX DE SELECTION ROUE= SECONDES ou MINUTES ou HEURES
Rect SetTimeWheelMode(Vec2D(xtime+120,ytime+80),Vec2D(60,20));
SetTimeWheelMode.SetRoundness(7.5);
SetTimeWheelMode.SetLineWidth(epaisseur_ligne_fader);

SetTimeWheelMode.DrawOutline(CouleurLigne);

if(  window_focus_id==W_TIME && mouse_x>xtime+120 && mouse_x<xtime+180 && mouse_y>ytime+80 && mouse_y<ytime+100)
{
if( Midi_Faders_Affectation_Type!=0)
{SetTimeWheelMode.DrawOutline(CouleurBlind); }
else {SetTimeWheelMode.Draw(CouleurSurvol);   }
}

Line(Vec2D(xtime+150,ytime+100),Vec2D(Vec2D(xtime+150,ytime+115))).Draw(CouleurLigne);
if(time_wheel_datatype_is==0)//minutes
{
Line(Vec2D(xtime+150,ytime+115),Vec2D(Vec2D(xtime+100,ytime+115))).Draw(CouleurLigne);
Line(Vec2D(xtime+100,ytime+115),Vec2D(Vec2D(xtime+100,ytime+120))).Draw(CouleurLigne);
petitchiffrerouge.Print("min",xtime+100,ytime+135);
petitchiffre.Print("MIN.",xtime+135,ytime+95);
}
if(time_wheel_datatype_is==1)//secondes
{
Line(Vec2D(xtime+150,ytime+115),Vec2D(Vec2D(xtime+160,ytime+115))).Draw(CouleurLigne);
Line(Vec2D(xtime+160,ytime+115),Vec2D(Vec2D(xtime+160,ytime+120))).Draw(CouleurLigne);
petitchiffrerouge.Print("sec",xtime+150,ytime+135);
petitchiffre.Print("SEC.",xtime+135,ytime+95);
}
if(time_wheel_datatype_is==2)//1/10
{
Line(Vec2D(xtime+150,ytime+115),Vec2D(Vec2D(xtime+200,ytime+115))).Draw(CouleurLigne);
Line(Vec2D(xtime+200,ytime+115),Vec2D(Vec2D(xtime+200,ytime+120))).Draw(CouleurLigne);
petitchiffrerouge.Print("1/100",xtime+190,ytime+135);
petitchiffre.Print("1/100",xtime+135,ytime+95);
}



//////////////////////////CHRONO//////////////////////////////////////////////////
Circle DoChrono( Vec2D(xtime+140, ytime+190), 15);
DoChrono.SetLineWidth(epaisseur_ligne_fader);
DoChrono.Draw(CouleurBleuProcedure.WithAlpha(0.4));

Circle ResetChrono( Vec2D(xtime+180, ytime+200), 8);
ResetChrono.SetLineWidth(epaisseur_ligne_fader);
ResetChrono.Draw(CouleurBleuProcedure.WithAlpha(0.4));

DoChrono.DrawOutline(CouleurBleuProcedure);
ResetChrono.DrawOutline(CouleurBleuProcedure);

if (index_play_chrono==1){DoChrono.Draw(CouleurFader); }
if(window_focus_id==W_TIME && mouse_x>xtime+125 && mouse_x<xtime+155 && mouse_y>ytime+175 && mouse_y<ytime+205)
{
if(Midi_Faders_Affectation_Type!=0)
{
DoChrono.DrawOutline(CouleurBlind);
}
else
{
DoChrono.Draw(CouleurSurvol);
}
}

if(window_focus_id==W_TIME && mouse_x>xtime+172 && mouse_x<xtime+188 && mouse_y>ytime+192 && mouse_y<ytime+208)
{
if(Midi_Faders_Affectation_Type!=0)
{
ResetChrono.DrawOutline(CouleurBlind);
}
else
{
ResetChrono.Draw(CouleurSurvol);
}
}

petitpetitchiffre.Print("CHRONO",xtime+90,ytime+190);
petitpetitchiffre.Print("clear",xtime+150,ytime+210);


///time
if (index_play_chrono==1)
{
DoChrono.DrawOutline(CouleurFader);
}
/////////////////////////CASES D' AFFECTATION AUX DOCK ET MEMOIRES
Rect SetTimeIn(Vec2D(xtime+300,ytime+20),Vec2D(50,30));
SetTimeIn.SetRoundness(7.5);
SetTimeIn.SetLineWidth(epaisseur_ligne_fader);

Rect SetTimeOut(Vec2D(xtime+300,ytime+70),Vec2D(50,30));
SetTimeOut.SetRoundness(7.5);
SetTimeOut.SetLineWidth(epaisseur_ligne_fader);

Rect SetTimeDIn(Vec2D(xtime+300,ytime+120),Vec2D(50,30));
SetTimeDIn.SetRoundness(7.5);
SetTimeDIn.SetLineWidth(epaisseur_ligne_fader);

Rect SetTimeDOut(Vec2D(xtime+300,ytime+170),Vec2D(50,30));
SetTimeDOut.SetRoundness(7.5);
SetTimeDOut.SetLineWidth(epaisseur_ligne_fader);


SetTimeIn.DrawOutline(CouleurLigne);
SetTimeOut.DrawOutline(CouleurLigne);
SetTimeDIn.DrawOutline(CouleurLigne);
SetTimeDOut.DrawOutline(CouleurLigne);


if(index_type_of_time_to_affect[0]==1)
{SetTimeDIn.Draw(CouleurFader);
SetTimeDIn.DrawOutline(CouleurFader);}
if(index_type_of_time_to_affect[1]==1)
{SetTimeIn.Draw(CouleurFader);
SetTimeIn.DrawOutline(CouleurFader);}
if(index_type_of_time_to_affect[2]==1)
{SetTimeDOut.Draw(CouleurFader);
SetTimeDOut.DrawOutline(CouleurFader);}
if(index_type_of_time_to_affect[3]==1)
{SetTimeOut.Draw(CouleurFader);
SetTimeOut.DrawOutline(CouleurFader);}


if( Midi_Faders_Affectation_Type!=0 && window_focus_id==W_TIME )
{
if(mouse_x>xtime+300 && mouse_x<xtime+350)
{
//DIN
if(mouse_y>ytime+120 && mouse_y<ytime+150)
{
SetTimeDIn.DrawOutline(CouleurBlind);
}
//IN
if(mouse_y>ytime+20 && mouse_y<ytime+50)
{
SetTimeIn.DrawOutline(CouleurBlind);
}
//DOUT
if(mouse_y>ytime+170 && mouse_y<ytime+200)
{
SetTimeDOut.DrawOutline(CouleurBlind);
}
//OUT
if(mouse_y>ytime+70 && mouse_y<ytime+100)
{
SetTimeOut.DrawOutline(CouleurBlind);
}
}
}


petitchiffre.Print("IN",xtime+320,ytime+40);
petitchiffre.Print("OUT",xtime+315,ytime+90);
petitchiffre.Print("D.IN",xtime+313,ytime+140);
petitchiffre.Print("D.OUT",xtime+305,ytime+190);

////////////TAP TEMPO/////////////////////////////////////////////////////////
Rect TapTempo(Vec2D(xtime+310,ytime+210),Vec2D(40,30));
TapTempo.SetRoundness(7.5);
TapTempo.SetLineWidth(demi_epaisseur_ligne_fader);
if(do_light_tap_tempo==1)
{
TapTempo.Draw(CouleurFader);
do_light_tap_tempo=0;
}
TapTempo.DrawOutline(CouleurLigne);
if(window_focus_id==W_TIME && mouse_x>xtime+310 && mouse_x<xtime+350 && mouse_y>ytime+210 && mouse_y<ytime+240)
{
TapTempo.DrawOutline(CouleurBlind);
}

Rect RecTempo(Vec2D(xtime+285,ytime+210),Vec2D(15,15));
RecTempo.SetRoundness(4);
if(index_recording_tap_tempo==1)
{RecTempo.Draw(CouleurBlind);}
RecTempo.DrawOutline(CouleurLigne);
if(window_focus_id==W_TIME && mouse_x>xtime+285 && mouse_x<xtime+300 && mouse_y>ytime+210 && mouse_y<ytime+225)
{
RecTempo.DrawOutline(CouleurBlind);
}
petitpetitchiffre.Print("R",xtime+288,ytime+220);
petitpetitchiffre.Print("Tempo",xtime+310,ytime+225);
petitpetitchiffre.Print(string_tap_tempo_average,xtime+260,ytime+252);
petitpetitchiffrerouge.Print(string_actual_tap_tempo,xtime+260,ytime+240);

Rect TapSend(Vec2D(xtime+265,ytime+210),Vec2D(15,15));
TapSend.SetRoundness(4);
if(do_light_send_tap==1)
{TapSend.Draw(CouleurFader);do_light_send_tap=0;}
TapSend.DrawOutline(CouleurLigne);
if(window_focus_id==W_TIME && mouse_x>xtime+265 && mouse_x<xtime+280 && mouse_y>ytime+210 && mouse_y<ytime+225  )
{
TapSend.DrawOutline(CouleurBlind);
}
petitpetitchiffre.Print("S",xtime+268,ytime+220);

///////////AFFECT TIME////////////////////////////////////////////////////////
Rect TimeAffect(Vec2D(xtime+280,ytime+260),Vec2D(70,30));
TimeAffect.SetRoundness(7.5);
TimeAffect.SetLineWidth(epaisseur_ligne_fader);

if(index_affect_time==1)
{
TimeAffect.Draw(CouleurFader);
TimeAffect.DrawOutline(CouleurFader);
}


if(window_focus_id==W_TIME && Midi_Faders_Affectation_Type!=0)
{
if(mouse_x>xtime+280 && mouse_x<xtime+350 && mouse_y>ytime+260 && mouse_y<ytime+290)
{
TimeAffect.DrawOutline(CouleurBlind);
}
}
petitchiffre.Print("AFFECT",xtime+290,ytime+280);
TimeAffect.DrawOutline(CouleurLigne);



///midi out
button_midi_out_visu( xtime+250, ytime+250,758);
//liaison visuelle au fader du cercle midi out
Line (Vec2D( xtime+231,ytime+231),Vec2D( xtime+245,ytime+245)).Draw(CouleurLigne);

return(0);
}
Esempio n. 27
0
//----------------------------------------------------------------------------------
void ReadHMS(void)
//----------------------------------------------------------------------------------
{
	if(timeout) timeout--;
        if(hmioerr)
        {
          if(++hmerrcnt>3) // больше трех ошибок подряд?
          {
            hmerrcnt=0; // сбросить счетчик ошибок
            hms_errflg = -2; // неисправность сенсора влажности
//            ets_printf("*");
          };
          hmioerr = 0; // сбросить флаг ошибки
          hmfuncs = 0;  // далее сбросить датчик
          SetTimeOut(50); // зададим таймаут в 50 ms
        };
        switch(hmfuncs)
        {
          default:
           if(!TestTimeOut()) break; // ожидание паузы
           s_connectionreset(); // 26t
//           s_transstart();      // 8t transmission start
           if(hmioerr) break;
           s_write_byte(HTD_WS);// 18t Status Register Write  [0x06]
           if(hmioerr) break;
           s_write_byte(0x00);  // 18t
           if(hmioerr) break;
           hmioerr=0; // сбросить флаг ошибки (см. InitHMS())
           hmfuncs=1; // далее на запрос температуры датчика
           break; // 26+8+16+18 = 68t -> 68*1.25=85 us

          case 2:  // чтение данных температуры с датчика и запрос данных о влажности
          case 5:  // чтение данных температуры с датчика и запрос данных о влажности
           if(i2c_test_sda())
           {
             if(TestTimeOut()) hmioerr++;
             break;
           }
           reg_tmp = s_read_byte() << 8; // 19t
           reg_tmp |= s_read_byte(); // 19t
           if (s_read_crc()) // 19t
           {
             hmioerr++;
             break;
           };
           s_transstart(); // 8t transmission start
           s_write_byte(HTD_MH); // 18t Read Measure Humidity [0x05] ... 0.06133 s
           hmfuncs++; // след. функция
           SetTimeOut(120); // зададим таймаут в 120 ms
           break; // 19*3+8+18=83t  83*1.25=103.75us=0.00010375 sec

          case 3: // чтение данных о влажности
          case 6: // чтение данных о влажности
           if(i2c_test_sda())
           {
            if(TestTimeOut()) hmioerr++;
            break;
           }
           reg_rh = s_read_byte()<<8; // 19t
           reg_rh |= s_read_byte();
           if (s_read_crc()) // 19t  // ~75us
           {
             hmioerr++;
             break;
           };
          case 1: // запрос температуры датчика       (цикл опроса 0.2744s)
           s_transstart(); // 8t transmission start
           s_write_byte(HTD_MT); // 18t Read Measure Temperature  [0x03] ... 0.2128 s
           hmfuncs++; // далее на чтение данных температуры с датчика
           SetTimeOut(350); // зададим таймаут в 350 ms
           break;

          case 4: // сумма, проход 1
           T.ul = reg_tmp;
           RH.ul = reg_rh;
           hmfuncs++;
           break;

          case 7: // сумма, проход 2
           T.ul += reg_tmp;
//           mouts.rt = T.ui[0];
           RH.ul += reg_rh;
//           mouts.rh = RH.ui[0];
           hmfuncs++;
           break;

          case 8: // расчет, часть 1
#if HDT14BIT
           T.d=((float)(T.ul))*0.005 - PTATD1; //calc. Temperature from ticks to [C]      36.92 0.3
#else
           T.d=((float)(T.ul))*0.002 - PTATD1; //calc. Temperature from ticks to [C]
#endif
           RH.d=(float)(RH.ul)*0.5;
#if HDT14BIT
           RH.d=(T.d-25.0)*(0.01+0.00008*RH.d)-0.0000028*RH.d*RH.d+0.0405*RH.d-4.0;
#else
           RH.d=(T.d-25.0)*(0.01+0.00128*RH.d)-0.00072*RH.d*RH.d+0.648*RH.d-4.0;
#endif
           if(RH.d>100.0) RH.d=100.0;
           else if(RH.d<0.1) RH.d=0.1;
/*           hmfuncs++;
           break;
          case 9: // расчет, часть 2
           Dp.d = (log10(RH.d)-2)/0.4343 + (17.62*T.d)/(243.12+T.d);
           Dp.d = 243.12*Dp.d/(17.62-Dp.d);


           ets_printf("T=%d, RH=%d, DP=%d\n", (int)(T.d*100.0), (int)(RH.d*100.0), (int)(Dp.d*100.0) );
*/
           // перевод float в int.01
           hms_tmp = (int)(T.d*100.0);
           hms_rh = (int)(RH.d*100.0);
           hms_count++;
       	   hms_errflg = 0; // сбросить  неисправность сенсора влажности
//           ets_printf("T=%d, RH=%d\n", hms_tmp, hms_rh);
           hmerrcnt=0; // сбросить счетчик ошибок
           hmfuncs=2; // на начало опроса
           break;
        }
}
Esempio n. 28
0
int main(void)
{
	int i;	

	// uart initial
	fprintf(stderr, "This is a test for the Contex-A8...\n");
	serial_initial("/dev/ttySAC1", &GsmDevice, 9600);
	AtTransmitInit(&GsmDevice);
	usleep(10000);
	SEQ_Init();	

	// GPS uart init
	GPS_Init();

	// FIFO initial
	Open_ImageFIFO(ImageFIFO);	

#ifdef	_EN_INITIAL_GSM_
	// config the gprs network
	NetWork_Connection_Config();
#endif
	
	// printf the CSQ info
	GSM_GetPacketInfo(&unread_sum, &packet_sum);
	fprintf(stderr, "Unread packet sum = %d\n",unread_sum);
	fprintf(stderr, "total packet sum  = %d\n",packet_sum);
	
	if(GSM_GetCSQ(&CSQ)!=ERR_NONE){
		fprintf(stderr, "Can't get the CSQ...\n");
	} else{
		fprintf(stderr, "CSQ = %d\n",CSQ);
	}

	for(i=0;i<20;i++){
		usleep(10000);
	}		

	Login_Process(gRxBuff);


	fprintf(stderr, "========= start transmit =========\n");
	
	for(i=0;i<100;i++){
		usleep(10000);
	}


	// =====================================
	GPS_Debug.lat = MSEC2NDeg( (double)81678360 ); 
	GPS_Debug.lon = MSEC2NDeg( (double)409628128 );
	GPS_Debug.speed = 60;	
	GPS_InfoPrintf(&GPS_Debug);
	// =====================================



	// image updata process

	//ImageTransmit_init("/home/plg/linux.jpg");	

	// packet process
	fprintf(stderr,"\r\n****************************\r\n");
	PositionUpdateRule_Initial(&RuleList);
	InZoneCondition_Initial(&InZone_List);
	OutZoneCondition_Initial(&OutZone_List);
	TDSA_Condition_Initial(&TDSA_List);

	Interval_Locate_Init();				// initial the position update process
	ZoneInfo_Report_Init();				// initial the Zone information update process
	Speed_Report_Init();				// initial the speed information update process 

	// task initial
	Task_Init();	
	SetTimeOut(_Task_Heartbeat_,   6);	// execute every 60 seconds
	SetTimeOut(_Task_GPS_Display_, 6);	// execute every 60 seconds
	SetTimeOut(_Task_RE_Login_,   15);	// if we did not receive the heart beat ack in 150 seconds, re login...

	while(1){
		GSM_GetPacketInfo(&unread_sum, &packet_sum);
	
		G_PacketType = TypeX;	
		if(unread_sum>0){
			memset(gRxBuff,'\0',1024);
			UDP_ReceivePacket(&link_num, &data_index, &data_len, gRxBuff);	
			
			fprintf(stderr, "Receive Packet ...\n");
			fprintf(stderr, "link num    = %d\n",link_num);
			fprintf(stderr, "data index  = %d\n",data_index);
			fprintf(stderr, "data length = %d\n",data_len);

			Packet.length = data_len;
			memcpy(&(Packet.Data[0]), gRxBuff, data_len);	
			res = TLP_PacketDevide(&Packet, &APP_Packet, &G_PacketType);
			
			// A type input
			if((res == ERROR_NONE)&&(G_PacketType == TypeA)){
				
				InputCommandHandle(&APP_Packet);
				ShowRules(&RuleList);
				ShowCondition(&InZone_List);
				ShowCondition(&OutZone_List);
				ShowSpeedCondition(&TDSA_List);
			}
			
			// B type input
			if(G_PacketType == TypeB){
				ReportUpdata_Loop(0);
			}
			
			// D type input
			if(G_PacketType == TypeD){
 				ImageTransmit_loop(0);
			}
		}
	
		// check the fifo, if we got a new image, send it...	
		DrowsyImage_Check();
		DrowsyImage_Send();

		// if the image transmit is in working, the other update mesage is delay	
		if(Get_DT_State()==DT_Idle){		

			Interval_Locate_Check(&RuleList);									// position update process
			Interval_Locate_Updata(&GPS_Msg);

			ZoneInfo_Condition_Check(&InZone_List, &OutZone_List, &GPS_Msg);	// Zone information process
			ZoneInfo_Update(&GPS_Msg);

			Speed_Condition_Check(&TDSA_List,&GPS_Debug);
			SpeedReport_Update(&GPS_Debug);

			if( isTimeOut(_Task_Heartbeat_)==1 ){
				HeartBeat_Request(NULL);
				ClearTimeOut(_Task_Heartbeat_);	
			}

			if( isTimeOut(_Task_RE_Login_)==1 ){
			
				// reconfig the network
				NetWork_Connection_Config();
				Login_Process(gRxBuff);
				ClearTimeOut(_Task_RE_Login_);	
			}
		}

		// GPS information
		GPS_Read(&GPS_Msg);
		if( isTimeOut(_Task_GPS_Display_)==1 ){
			GPS_InfoPrintf(&GPS_Msg);
			ClearTimeOut(_Task_GPS_Display_);	
		}
		
		usleep(500000);
	}

	GSM_CloseConnection();

	for(i=0;i<100;i++){
		usleep(20000);
	}	

	GSM_Reset();	

	serial_close(&GsmDevice);
	
	return 0;
}
Esempio n. 29
0
static void VerifyExec(Attributes a, Promise *pp)
{
    CfLock thislock;
    char unsafeLine[CF_BUFSIZE], line[sizeof(unsafeLine) * 2], eventname[CF_BUFSIZE];
    char comm[20];
    char execstr[CF_EXPANDSIZE];
    int outsourced, count = 0;
    mode_t maskval = 0;
    FILE *pfp;
    char cmdOutBuf[CF_BUFSIZE];
    int cmdOutBufPos = 0;
    int lineOutLen;

    if (!IsExecutable(GetArg0(pp->promiser)))
    {
        cfPS(cf_error, CF_FAIL, "", pp, a, "%s promises to be executable but isn't\n", pp->promiser);

        if (strchr(pp->promiser, ' '))
        {
            CfOut(cf_verbose, "", "Paths with spaces must be inside escaped quoutes (e.g. \\\"%s\\\")", pp->promiser);
        }

        return;
    }
    else
    {
        CfOut(cf_verbose, "", " -> Promiser string contains a valid executable (%s) - ok\n", GetArg0(pp->promiser));
    }

    DeleteScalar("this", "promiser");
    NewScalar("this", "promiser", pp->promiser, cf_str);

    if (a.args)
    {
        snprintf(execstr, CF_EXPANDSIZE - 1, "%s %s", pp->promiser, a.args);
    }
    else
    {
        strncpy(execstr, pp->promiser, CF_BUFSIZE);
    }

    thislock = AcquireLock(execstr, VUQNAME, CFSTARTTIME, a, pp, false);

    if (thislock.lock == NULL)
    {
        return;
    }

    PromiseBanner(pp);

    CfOut(cf_inform, "", " -> Executing \'%s\' ...(timeout=%d,owner=%ju,group=%ju)\n", execstr, a.contain.timeout,
          (uintmax_t)a.contain.owner, (uintmax_t)a.contain.group);

    BeginMeasure();

    if (DONTDO && !a.contain.preview)
    {
        CfOut(cf_error, "", "-> Would execute script %s\n", execstr);
    }
    else if (a.transaction.action != cfa_fix)
    {
        cfPS(cf_error, CF_WARN, "", pp, a, " !! Command \"%s\" needs to be executed, but only warning was promised",
             execstr);
    }
    else
    {
        CommPrefix(execstr, comm);

        if (a.transaction.background)
        {
#ifdef MINGW
            outsourced = true;
#else
            CfOut(cf_verbose, "", " -> Backgrounding job %s\n", execstr);
            outsourced = fork();
#endif
        }
        else
        {
            outsourced = false;
        }

        if (outsourced || !a.transaction.background)    // work done here: either by child or non-background parent
        {
            if (a.contain.timeout != CF_NOINT)
            {
                SetTimeOut(a.contain.timeout);
            }

#ifndef MINGW
            CfOut(cf_verbose, "", " -> (Setting umask to %jo)\n", (uintmax_t)a.contain.umask);
            maskval = umask(a.contain.umask);

            if (a.contain.umask == 0)
            {
                CfOut(cf_verbose, "", " !! Programming %s running with umask 0! Use umask= to set\n", execstr);
            }
#endif /* NOT MINGW */

            if (a.contain.useshell)
            {
                pfp =
                    cf_popen_shsetuid(execstr, "r", a.contain.owner, a.contain.group, a.contain.chdir, a.contain.chroot,
                                      a.transaction.background);
            }
            else
            {
                pfp =
                    cf_popensetuid(execstr, "r", a.contain.owner, a.contain.group, a.contain.chdir, a.contain.chroot,
                                   a.transaction.background);
            }

            if (pfp == NULL)
            {
                cfPS(cf_error, CF_FAIL, "cf_popen", pp, a, "!! Couldn't open pipe to command %s\n", execstr);
                YieldCurrentLock(thislock);
                return;
            }

            while (!feof(pfp))
            {
                if (ferror(pfp))        /* abortable */
                {
                    cfPS(cf_error, CF_TIMEX, "ferror", pp, a, "!! Command pipe %s\n", execstr);
                    cf_pclose(pfp);
                    YieldCurrentLock(thislock);
                    return;
                }

                CfReadLine(unsafeLine, CF_BUFSIZE - 1, pfp);
                ReplaceStr(unsafeLine, line, sizeof(line), "%", "%%");  // escape format char

                if (strstr(line, "cfengine-die"))
                {
                    break;
                }

                if (ferror(pfp))        /* abortable */
                {
                    cfPS(cf_error, CF_TIMEX, "ferror", pp, a, "!! Command pipe %s\n", execstr);
                    cf_pclose(pfp);
                    YieldCurrentLock(thislock);
                    return;
                }

                if (a.contain.preview)
                {
                    PreviewProtocolLine(line, execstr);
                }

                if (a.module)
                {
                    ModuleProtocol(execstr, line, !a.contain.nooutput);
                }
                else if (!a.contain.nooutput && NonEmptyLine(line))
                {
                    lineOutLen = strlen(comm) + strlen(line) + 12;

                    // if buffer is to small for this line, output it directly
                    if (lineOutLen > sizeof(cmdOutBuf))
                    {
                        CfOut(cf_cmdout, "", "Q: \"...%s\": %s\n", comm, line);
                    }
                    else
                    {
                        if (cmdOutBufPos + lineOutLen > sizeof(cmdOutBuf))
                        {
                            CfOut(cf_cmdout, "", "%s", cmdOutBuf);
                            cmdOutBufPos = 0;
                        }
                        sprintf(cmdOutBuf + cmdOutBufPos, "Q: \"...%s\": %s\n", comm, line);
                        cmdOutBufPos += (lineOutLen - 1);
                    }
                    count++;
                }
            }
#ifdef MINGW
            if (outsourced)     // only get return value if we waited for command execution
            {
                cf_pclose(pfp);
            }
            else
            {
                cf_pclose_def(pfp, a, pp);
            }
#else /* NOT MINGW */
            cf_pclose_def(pfp, a, pp);
#endif
        }

        if (count)
        {
            if (cmdOutBufPos)
            {
                CfOut(cf_cmdout, "", "%s", cmdOutBuf);
            }

            CfOut(cf_cmdout, "", "I: Last %d quoted lines were generated by promiser \"%s\"\n", count, execstr);
        }

        if (a.contain.timeout != CF_NOINT)
        {
            alarm(0);
            signal(SIGALRM, SIG_DFL);
        }

        CfOut(cf_inform, "", " -> Completed execution of %s\n", execstr);
#ifndef MINGW
        umask(maskval);
#endif
        YieldCurrentLock(thislock);

        snprintf(eventname, CF_BUFSIZE - 1, "Exec(%s)", execstr);

#ifndef MINGW
        if (a.transaction.background && outsourced)
        {
            CfOut(cf_verbose, "", " -> Backgrounded command (%s) is done - exiting\n", execstr);
            exit(0);
        }
#endif /* NOT MINGW */
    }
}
Esempio n. 30
0
static ActionResult RepairExec(EvalContext *ctx, Attributes a, Promise *pp)
{
    char line[CF_BUFSIZE], eventname[CF_BUFSIZE];
    char cmdline[CF_BUFSIZE];
    char comm[20];
    int outsourced, count = 0;
#if !defined(__MINGW32__)
    mode_t maskval = 0;
#endif
    FILE *pfp;
    char cmdOutBuf[CF_BUFSIZE];
    int cmdOutBufPos = 0;
    int lineOutLen;

    if (IsAbsoluteFileName(CommandArg0(pp->promiser)) || a.contain.shelltype == SHELL_TYPE_NONE)
    {
        if (!IsExecutable(CommandArg0(pp->promiser)))
        {
            cfPS(ctx, LOG_LEVEL_ERR, PROMISE_RESULT_FAIL, pp, a, "'%s' promises to be executable but isn't", pp->promiser);

            if (strchr(pp->promiser, ' '))
            {
                Log(LOG_LEVEL_VERBOSE, "Paths with spaces must be inside escaped quoutes (e.g. \\\"%s\\\")", pp->promiser);
            }

            return ACTION_RESULT_FAILED;
        }
        else
        {
            Log(LOG_LEVEL_VERBOSE, "Promiser string contains a valid executable '%s' - ok", CommandArg0(pp->promiser));
        }
    }

    char timeout_str[CF_BUFSIZE];
    if (a.contain.timeout == CF_NOINT)
    {
        snprintf(timeout_str, CF_BUFSIZE, "no timeout");
    }
    else
    {
        snprintf(timeout_str, CF_BUFSIZE, "timeout=%ds", a.contain.timeout);
    }

    char owner_str[CF_BUFSIZE] = "";
    if (a.contain.owner != -1)
    {
        snprintf(owner_str, CF_BUFSIZE, ",uid=%ju", (uintmax_t)a.contain.owner);
    }

    char group_str[CF_BUFSIZE] = "";
    if (a.contain.group != -1)
    {
        snprintf(group_str, CF_BUFSIZE, ",gid=%ju", (uintmax_t)a.contain.group);
    }

    snprintf(cmdline, CF_BUFSIZE, "%s%s%s", pp->promiser, a.args ? " " : "", a.args ? a.args : "");

    Log(LOG_LEVEL_INFO, "Executing '%s%s%s' ... '%s'", timeout_str, owner_str, group_str, cmdline);

    BeginMeasure();

    if (DONTDO && (!a.contain.preview))
    {
        Log(LOG_LEVEL_ERR, "Would execute script '%s'", cmdline);
        return ACTION_RESULT_OK;
    }

    if (a.transaction.action != cfa_fix)
    {
        Log(LOG_LEVEL_ERR, "Command '%s' needs to be executed, but only warning was promised", cmdline);
        return ACTION_RESULT_OK;
    }

    CommandPrefix(cmdline, comm);

    if (a.transaction.background)
    {
#ifdef __MINGW32__
        outsourced = true;
#else
        Log(LOG_LEVEL_VERBOSE, "Backgrounding job '%s'", cmdline);
        outsourced = fork();
#endif
    }
    else
    {
        outsourced = false;
    }

    if (outsourced || (!a.transaction.background))    // work done here: either by child or non-background parent
    {
        if (a.contain.timeout != CF_NOINT)
        {
            SetTimeOut(a.contain.timeout);
        }

#ifndef __MINGW32__
        Log(LOG_LEVEL_VERBOSE, "(Setting umask to %jo)", (uintmax_t)a.contain.umask);
        maskval = umask(a.contain.umask);

        if (a.contain.umask == 0)
        {
            Log(LOG_LEVEL_VERBOSE, "Programming '%s' running with umask 0! Use umask= to set", cmdline);
        }
#endif /* !__MINGW32__ */

        if (a.contain.shelltype == SHELL_TYPE_POWERSHELL)
        {
#ifdef __MINGW32__
            pfp =
                cf_popen_powershell_setuid(cmdline, "r", a.contain.owner, a.contain.group, a.contain.chdir, a.contain.chroot,
                                           a.transaction.background);
#else // !__MINGW32__
            Log(LOG_LEVEL_ERR, "Powershell is only supported on Windows");
            return ACTION_RESULT_FAILED;
#endif // !__MINGW32__
        }
        else if (a.contain.shelltype == SHELL_TYPE_USE)
        {
            pfp =
                cf_popen_shsetuid(cmdline, "r", a.contain.owner, a.contain.group, a.contain.chdir, a.contain.chroot,
                                  a.transaction.background);
        }
        else
        {
            pfp =
                cf_popensetuid(cmdline, "r", a.contain.owner, a.contain.group, a.contain.chdir, a.contain.chroot,
                               a.transaction.background);
        }

        if (pfp == NULL)
        {
            Log(LOG_LEVEL_ERR, "Couldn't open pipe to command '%s'. (cf_popen: %s)", cmdline, GetErrorStr());
            return ACTION_RESULT_FAILED;
        }

        for (;;)
        {
            ssize_t res = CfReadLine(line, CF_BUFSIZE, pfp);

            if (res == 0)
            {
                break;
            }

            if (res == -1)
            {
                Log(LOG_LEVEL_ERR, "Unable to read output from command '%s'. (fread: %s)", cmdline, GetErrorStr());
                cf_pclose(pfp);
                return ACTION_RESULT_FAILED;
            }

            if (strstr(line, "cfengine-die"))
            {
                break;
            }

            if (a.contain.preview)
            {
                PreviewProtocolLine(line, cmdline);
            }

            if (a.module)
            {
                ModuleProtocol(ctx, cmdline, line, !a.contain.nooutput, PromiseGetNamespace(pp));
            }
            else if ((!a.contain.nooutput) && (!EmptyString(line)))
            {
                lineOutLen = strlen(comm) + strlen(line) + 12;

                // if buffer is to small for this line, output it directly
                if (lineOutLen > sizeof(cmdOutBuf))
                {
                    Log(LOG_LEVEL_NOTICE, "Q: '%s': %s", comm, line);
                }
                else
                {
                    if (cmdOutBufPos + lineOutLen > sizeof(cmdOutBuf))
                    {
                        Log(LOG_LEVEL_NOTICE, "%s", cmdOutBuf);
                        cmdOutBufPos = 0;
                    }
                    sprintf(cmdOutBuf + cmdOutBufPos, "Q: \"...%s\": %s\n", comm, line);
                    cmdOutBufPos += (lineOutLen - 1);
                }
                count++;
            }
        }
#ifdef __MINGW32__
        if (outsourced)     // only get return value if we waited for command execution
        {
            cf_pclose(pfp);
        }
        else
#endif /* __MINGW32__ */
        {
            int ret = cf_pclose(pfp);

            if (ret == -1)
            {
                cfPS(ctx, LOG_LEVEL_INFO, PROMISE_RESULT_FAIL, pp, a, "Finished script '%s' - failed (abnormal termination)", pp->promiser);
            }
            else
            {
                VerifyCommandRetcode(ctx, ret, true, a, pp);
            }
        }
    }

    if (count)
    {
        if (cmdOutBufPos)
        {
            Log(LOG_LEVEL_NOTICE, "%s", cmdOutBuf);
        }

        Log(LOG_LEVEL_INFO, "Last %d quoted lines were generated by promiser '%s'", count, cmdline);
    }

    if (a.contain.timeout != CF_NOINT)
    {
        alarm(0);
        signal(SIGALRM, SIG_DFL);
    }

    Log(LOG_LEVEL_INFO, "Completed execution of '%s'", cmdline);
#ifndef __MINGW32__
    umask(maskval);
#endif

    snprintf(eventname, CF_BUFSIZE - 1, "Exec(%s)", cmdline);

#ifndef __MINGW32__
    if ((a.transaction.background) && outsourced)
    {
        Log(LOG_LEVEL_VERBOSE, "Backgrounded command '%s' is done - exiting", cmdline);
        exit(0);
    }
#endif /* !__MINGW32__ */

    return ACTION_RESULT_OK;
}