コード例 #1
0
DWORD PCIE_SW_EventUnregister(WDC_DEVICE_HANDLE hDev)
{
    DWORD dwStatus;
    
    TraceLog("PCIE_SW_EventUnregister entered. Device handle: 0x%p\n", hDev);
    
    if (!IsValidDevice((PWDC_DEVICE)hDev, "PCIE_SW_EventUnregister"))
        return WD_INVALID_PARAMETER;

    if (!WDC_EventIsRegistered(hDev))
    {
        ErrLog("Cannot unregister events - no events currently registered ...\n");
        return WD_OPERATION_ALREADY_DONE;
    }

    dwStatus = WDC_EventUnregister(hDev);
    
    if (WD_STATUS_SUCCESS != dwStatus)
    {
        ErrLog("Failed to unregister events. Error 0x%lx - %s\n",
            dwStatus, Stat2Str(dwStatus));
    }

    return dwStatus;
}
コード例 #2
0
DWORD PCIE_SW_IntDisable(WDC_DEVICE_HANDLE hDev)
{
    DWORD dwStatus;
    PWDC_DEVICE pDev = (PWDC_DEVICE)hDev;
    PPCIE_SW_DEV_CTX pDevCtx;

    TraceLog("PCIE_SW_IntDisable entered. Device handle: 0x%p\n", hDev);

    if (!IsValidDevice(pDev, "PCIE_SW_IntDisable"))
        return WD_INVALID_PARAMETER;

    pDevCtx = (PPCIE_SW_DEV_CTX)WDC_GetDevContext(pDev);
 
    if (!WDC_IntIsEnabled(hDev))
    {
        ErrLog("Interrupts are already disabled ...\n");
        return WD_OPERATION_ALREADY_DONE;
    }

    /* TODO: You can add code here to write to the device in order
             to physically disable the hardware interrupts */

    /* Disable the interrupts */
    dwStatus = WDC_IntDisable(hDev);
    if (WD_STATUS_SUCCESS != dwStatus)
    {
        ErrLog("Failed disabling interrupts. Error 0x%lx - %s\n",
            dwStatus, Stat2Str(dwStatus));
    }

    return dwStatus;
}
コード例 #3
0
ファイル: eden_lib.c プロジェクト: SlavaC1/ControlSW
/* -----------------------------------------------
    Device open/close
   ----------------------------------------------- */
WDC_DEVICE_HANDLE EDEN_DeviceOpen(const WD_PCI_CARD_INFO *pDeviceInfo)
{
    DWORD dwStatus;
    PEDEN_DEV_CTX pDevCtx = NULL;
    WDC_DEVICE_HANDLE hDev = NULL;
    EDEN_DEV_ADDR_DESC devAddrDesc;
    PWDC_DEVICE pDev;

    /* Validate arguments */
    if (!pDeviceInfo)
    {
        ErrLog("EDEN_DeviceOpen: Error - NULL device information struct pointer\n");
        return NULL;
    }

    /* Allocate memory for the EDEN device context */
    pDevCtx = (PEDEN_DEV_CTX)malloc(sizeof (EDEN_DEV_CTX));
    if (!pDevCtx)
    {
        ErrLog("Failed allocating memory for EDEN device context\n");
        return NULL;
    }

    BZERO(*pDevCtx);

    /* Open a WDC device handle */
    dwStatus = WDC_PciDeviceOpen(&hDev, pDeviceInfo, pDevCtx, NULL, NULL, NULL);
    if (WD_STATUS_SUCCESS != dwStatus)
    {
        ErrLog("Failed opening a WDC device handle. Error 0x%lx - %s\n",
            dwStatus, Stat2Str(dwStatus));
        goto Error;
    }

    pDev = hDev;
    devAddrDesc.dwNumAddrSpaces = pDev->dwNumAddrSpaces;
    devAddrDesc.pAddrDesc = pDev->pAddrDesc;

    /* Open a handle to a Kernel PlugIn driver */
    WDC_KernelPlugInOpen(hDev, KP_EDEN_DRIVER_NAME, &devAddrDesc);

    /* Validate device information */
    if (!DeviceValidate((PWDC_DEVICE)hDev))
        goto Error;

    /* Return handle to the new device */
    TraceLog("EDEN_DeviceOpen: Opened a EDEN device (handle 0x%p)\n"
        "Device uses a Kernel PlugIn driver (%s)\n", hDev, KP_EDEN_DRIVER_NAME);
    return hDev;

Error:    
    if (hDev)
        EDEN_DeviceClose(hDev);
    else
        free(pDevCtx);

    return NULL;
}
コード例 #4
0
DWORD PCIE_SW_IntEnable(WDC_DEVICE_HANDLE hDev, PCIE_SW_INT_HANDLER funcIntHandler)
{
    DWORD dwStatus;
    PWDC_DEVICE pDev = (PWDC_DEVICE)hDev;
    PPCIE_SW_DEV_CTX pDevCtx;

    TraceLog("PCIE_SW_IntEnable entered. Device handle: 0x%p\n", hDev);

    if (!IsValidDevice(pDev, "PCIE_SW_IntEnable"))
        return WD_INVALID_PARAMETER;

    if (!IsItemExists(pDev, ITEM_INTERRUPT))
        return WD_OPERATION_FAILED;

    pDevCtx = (PPCIE_SW_DEV_CTX)WDC_GetDevContext(pDev);

    /* Check if interrupts are already enabled */
    if (WDC_IntIsEnabled(hDev))
    {
        ErrLog("Interrupts are already enabled ...\n");
        return WD_OPERATION_ALREADY_DONE;
    }

    /* Define the number of interrupt transfer commands to use */
    #define NUM_TRANS_CMDS 0

    /* NOTE: In order to correctly handle PCI interrupts, you need to
             ADD CODE HERE to set up transfer commands to read/write the
             relevant register(s) in order to correctly acknowledge the
             interrupts, as dictated by your hardware's specifications.
             When adding transfer commands, be sure to also modify the
             definition of NUM_TRANS_CMDS (above) accordingly. */

    /* Store the diag interrupt handler routine, which will be executed by
       PCIE_SW_IntHandler() when an interrupt is received */
    pDevCtx->funcDiagIntHandler = funcIntHandler;
    
    /* Enable the interrupts */
    /* NOTE: When adding read transfer commands, set the INTERRUPT_CMD_COPY flag
             in the 4th argument (dwOptions) passed to WDC_IntEnable() */
    dwStatus = WDC_IntEnable(hDev, NULL, 0, 0,
        PCIE_SW_IntHandler, (PVOID)pDev, WDC_IS_KP(hDev));
        
    if (WD_STATUS_SUCCESS != dwStatus)
    {
        ErrLog("Failed enabling interrupts. Error 0x%lx - %s\n",
            dwStatus, Stat2Str(dwStatus));
        
        return dwStatus;
    }

    /* TODO: You can add code here to write to the device in order
             to physically enable the hardware interrupts */

    TraceLog("PCIE_SW_IntEnable: Interrupts enabled\n");

    return WD_STATUS_SUCCESS;
}
コード例 #5
0
BOOL PCIE_SW_GetAddrSpaceInfo(WDC_DEVICE_HANDLE hDev, PCIE_SW_ADDR_SPACE_INFO *pAddrSpaceInfo)
{
    PWDC_DEVICE pDev = (PWDC_DEVICE)hDev;
    WDC_ADDR_DESC *pAddrDesc;
    DWORD dwAddrSpace, dwMaxAddrSpace;
    BOOL fIsMemory;
    
    if (!IsValidDevice(pDev, "PCIE_SW_GetAddrSpaceInfo"))
        return FALSE;

#if defined(DEBUG)
    if (!pAddrSpaceInfo)
    {
        ErrLog("PCIE_SW_GetAddrSpaceInfo: Error - NULL address space information pointer\n");
        return FALSE;
    }
#endif

    dwAddrSpace = pAddrSpaceInfo->dwAddrSpace;
    dwMaxAddrSpace = pDev->dwNumAddrSpaces - 1;

    if (dwAddrSpace > dwMaxAddrSpace)
    {
        ErrLog("PCIE_SW_GetAddrSpaceInfo: Error - Address space %ld is out of range (0 - %ld)\n",
            dwAddrSpace, dwMaxAddrSpace);
        return FALSE;
    }

    pAddrDesc = &pDev->pAddrDesc[dwAddrSpace];

    fIsMemory = WDC_ADDR_IS_MEM(pAddrDesc);
    
    snprintf(pAddrSpaceInfo->sName, MAX_NAME - 1, "BAR %ld", dwAddrSpace);
    snprintf(pAddrSpaceInfo->sType, MAX_TYPE - 1, fIsMemory ? "Memory" : "I/O");
        
    if (WDC_AddrSpaceIsActive(pDev, dwAddrSpace))
    {
        WD_ITEMS *pItem = &pDev->cardReg.Card.Item[pAddrDesc->dwItemIndex];
        DWORD dwAddr = fIsMemory ? pItem->I.Mem.dwPhysicalAddr : (DWORD)pItem->I.IO.dwAddr;
        
        snprintf(pAddrSpaceInfo->sDesc, MAX_DESC - 1, "0x%0*lX - 0x%0*lX (0x%lx bytes)",
            (int)WDC_SIZE_32 * 2, dwAddr,
            (int)WDC_SIZE_32 * 2, dwAddr + pAddrDesc->dwBytes - 1,
            pAddrDesc->dwBytes);
    }
    else
        snprintf(pAddrSpaceInfo->sDesc, MAX_DESC - 1, "Inactive address space");

    /* TODO: You can modify the code above to set a different address space name/description */

    return TRUE;
}
コード例 #6
0
/* -----------------------------------------------
    Device open/close
   ----------------------------------------------- */
WDC_DEVICE_HANDLE PCIE_SW_DeviceOpen(const WD_PCI_CARD_INFO *pDeviceInfo)
{
    DWORD dwStatus;
    PPCIE_SW_DEV_CTX pDevCtx = NULL;
    WDC_DEVICE_HANDLE hDev = NULL;

    /* Validate arguments */
    if (!pDeviceInfo)
    {
        ErrLog("PCIE_SW_DeviceOpen: Error - NULL device information struct pointer\n");
        return NULL;
    }

    /* Allocate memory for the PCIE_SW device context */
    pDevCtx = (PPCIE_SW_DEV_CTX)malloc(sizeof (PCIE_SW_DEV_CTX));
    if (!pDevCtx)
    {
        ErrLog("Failed allocating memory for PCIE_SW device context\n");
        return NULL;
    }

    BZERO(*pDevCtx);

    /* Open a WDC device handle */
    dwStatus = WDC_PciDeviceOpen(&hDev, pDeviceInfo, pDevCtx, NULL, NULL, NULL);
    if (WD_STATUS_SUCCESS != dwStatus)
    {
        ErrLog("Failed opening a WDC device handle. Error 0x%lx - %s\n",
            dwStatus, Stat2Str(dwStatus));
        goto Error;
    }

    /* Validate device information */
    if (!DeviceValidate((PWDC_DEVICE)hDev))
        goto Error;

    /* Return handle to the new device */
    TraceLog("PCIE_SW_DeviceOpen: Opened a PCIE_SW device (handle 0x%p)\n", hDev);
    return hDev;

Error:    
    if (hDev)
        PCIE_SW_DeviceClose(hDev);
    else
        free(pDevCtx);

    return NULL;
}
コード例 #7
0
ファイル: eden_lib.c プロジェクト: SlavaC1/ControlSW
DWORD EDEN_IntEnable(WDC_DEVICE_HANDLE hDev, EDEN_INT_HANDLER funcIntHandler)
{
    DWORD dwStatus;
    PWDC_DEVICE pDev = (PWDC_DEVICE)hDev;
    PEDEN_DEV_CTX pDevCtx;

    TraceLog("EDEN_IntEnable entered. Device handle: 0x%p\n", hDev);

    if (!IsValidDevice(pDev, "EDEN_IntEnable"))
        return WD_INVALID_PARAMETER;

    if (!IsItemExists(pDev, ITEM_INTERRUPT))
        return WD_OPERATION_FAILED;

    pDevCtx = (PEDEN_DEV_CTX)WDC_GetDevContext(pDev);

    /* Check if interrupts are already enabled */
    if (WDC_IntIsEnabled(hDev))
    {
        ErrLog("Interrupts are already enabled ...\n");
        return WD_OPERATION_ALREADY_DONE;
    }

    /* Store the diag interrupt handler routine, which will be executed by
       EDEN_IntHandler() when an interrupt is received */
    pDevCtx->funcDiagIntHandler = funcIntHandler;
    
    /* Enable the interrupts */
    /* NOTE: When adding read transfer commands, set the INTERRUPT_CMD_COPY flag
             in the 4th argument (dwOptions) passed to WDC_IntEnable() */
    dwStatus = WDC_IntEnable(hDev, NULL, 0, 0,
        EDEN_IntHandler, (PVOID)pDev, WDC_IS_KP(hDev));
        
    if (WD_STATUS_SUCCESS != dwStatus)
    {
        ErrLog("Failed enabling interrupts. Error 0x%lx - %s\n",
            dwStatus, Stat2Str(dwStatus));
        
        return dwStatus;
    }

    /* TODO: You can add code here to write to the device in order
             to physically enable the hardware interrupts */

    TraceLog("EDEN_IntEnable: Interrupts enabled\n");

    return WD_STATUS_SUCCESS;
}
コード例 #8
0
ファイル: JavTgmServer.c プロジェクト: dcobas/timlib
int OpenPort (unsigned short port)
{

    struct sockaddr_in sin;

    int s, on, off, val;

    if (!ssock) {

        s = socket (PF_INET, SOCK_STREAM, 0);
        if (s < 0) {
            ErrLog (ErrWARNING, APP_NAME ":OpenPort:Socket:Error:Cant open sockets (err=%s)", strerror (errno));
            return FAIL;
        }
        ssock = s;
        on = 1;
        off = 0;
        val = 5;
        setsockopt (ssock, SOL_SOCKET, SO_REUSEADDR, &on, sizeof (int));
        setsockopt (ssock, SOL_TCP, TCP_DEFER_ACCEPT, &off, sizeof (int));
        setsockopt (ssock, SOL_TCP, TCP_QUICKACK, &on, sizeof (int));
        setsockopt (ssock, SOL_TCP, TCP_KEEPCNT, &on, sizeof (int));
        setsockopt (ssock, SOL_TCP, TCP_KEEPIDLE, &val, sizeof (int));
        setsockopt (ssock, SOL_TCP, TCP_KEEPINTVL, &val, sizeof (int));
        setsockopt (ssock, SOL_TCP, TCP_LINGER2, &val, sizeof (int));
        setsockopt (ssock, SOL_TCP, TCP_NODELAY, &on, sizeof (int));
        setsockopt (ssock, SOL_TCP, TCP_SYNCNT, &val, sizeof (int));

        bzero ((void *) &sin, SinSIZE);
        sin.sin_family = PF_INET;
        sin.sin_port = htons (port);
        sin.sin_addr.s_addr = htonl (INADDR_ANY);
        if (bind (s, (struct sockaddr *) &sin, SinSIZE) < 0) {
            ErrLog (ErrWARNING, APP_NAME ":OpenPort:Bind:Error:Cant bind port:%d (Err=%s)", port, strerror (errno));
            close (s);
            ssock = 0;
            return FAIL;
        }
        if (listen (s, BACK_LOG) < 0) {
            ErrLog (ErrWARNING, APP_NAME ":Listen:Error:Port:%d (Err=%s)", port, strerror (errno));
            close (s);
            ssock = 0;
            return FAIL;
        }
    }
    return ssock;
}
コード例 #9
0
ファイル: cpluginloader.cpp プロジェクト: asshole52/verlihub
void * cPluginLoader::LoadSym(const char *name)
{
	#ifdef _WIN32
	void *func = (void *) GetProcAddress(mHandle, name);
	if(func == NULL) {
		if(ErrLog(1)) LogStream() << "Can't load " << name <<" exported interface :" << GetLastError() << endl;
		return NULL;
	}
	#else
	void *func = dlsym( mHandle, name);
	if(IsError())
	{
		if(ErrLog(1)) LogStream() << "Can't load " << name <<" exported interface :" << Error() << endl;
		return NULL;
	}
	#endif
	return func;
}
コード例 #10
0
int SocketConnectionHandler (int socketfd, int timeout_secs)
{
	int returnVal;
	fd_set set;
	struct timeval timeout;

	FD_ZERO(&set);
	FD_SET(socketfd, &set);

	timeout.tv_sec = timeout_secs;
	timeout.tv_usec = 0;

	returnVal = select(socketfd + 1, &set, NULL, NULL, &timeout);
	if (returnVal == -1) {
		ErrLog("select failed on socket connection, errno 0x%X.", errno);
		return FALSE;
	} else if (returnVal == 0) {
		// select call timed out, return
		return FALSE;
	} else {
		struct sockaddr_un address;
		socklen_t address_length = sizeof(address);

		int connectionfd = accept(socketfd,
				         (struct sockaddr *) &address,
					 &address_length);
		if (connectionfd < 0) {
			if (errno != EAGAIN && errno != EWOULDBLOCK) {
				/* These errors are allowed since
				 * socket is non-blocking
				 */
				ErrLog("Failed to accept socket connection, errno 0x%X.", errno);
			}
			return FALSE;
		}
		if (write(connectionfd, &socketData, sizeof(socketData)) != sizeof(socketData)) {
			ErrLog("Failed to write socket data, errno 0x%X.", errno);
			close(connectionfd);
			return FALSE;
		}
		close(connectionfd);
		return TRUE;
	}
}
コード例 #11
0
ファイル: cserverdc.cpp プロジェクト: Sorin91/verlihub
bool cServerDC::AddToList(cUser *usr)
{
	if(!usr) {
		if(ErrLog(1)) LogStream() << "Adding a NULL user to userlist" << endl;
		return false;
	}
	if(usr->mInList) {
		if(ErrLog(2)) LogStream() << "User is already in the user list, he says it " << endl;
		return false;
	}

	tUserHash Hash = mUserList.Nick2Hash(usr->mNick);

	if(!mUserList.AddWithHash(usr, Hash)) {
		if(ErrLog(2)) LogStream() << "Adding twice user with same hash " << usr->mNick << endl;
		usr->mInList = false;
		return false;
	}

	usr->mInList = true;
	if(!usr->IsPassive)
		mActiveUsers.AddWithHash(usr, Hash);
	if(usr->IsPassive)
		mPassiveUsers.AddWithHash(usr, Hash);
	if(usr->mClass >= eUC_OPERATOR && ! (usr->mxConn && usr->mxConn->mRegInfo && usr->mxConn->mRegInfo->mHideKeys))
		mOpList.AddWithHash(usr, Hash);
	if(usr->Can(eUR_OPCHAT, mTime.Sec()))
		mOpchatList.AddWithHash(usr, Hash);
	if(usr->mxConn && !(usr->mxConn->mFeatures & eSF_NOHELLO))
		mHelloUsers.AddWithHash(usr, Hash);

	if ((usr->mClass >= eUC_OPERATOR) || mC.chat_default_on)
		mChatUsers.AddWithHash(usr, Hash);
	else
		DCPublicHS(_("You won't see public chat messages, to restore use +chat command."), usr->mxConn);

	if(usr->mxConn && usr->mxConn->Log(3))
		usr->mxConn->LogStream() << "Adding at the end of Nicklist" << endl;

	if(usr->mxConn && usr->mxConn->Log(3))
		usr->mxConn->LogStream() << "Becomes in list" << endl;

	return true;
}
コード例 #12
0
ファイル: CLauncher.cpp プロジェクト: aosm/DirectoryService
void CLauncher::StartThread ( void )
{
	if ( this == nil )
	{
		ErrLog( kLogApplication, "Launcher StartThread failed with memory error on itself" );
		throw((SInt32)eMemoryError);
	}

	this->Resume();
} // StartThread
コード例 #13
0
DWORD PCIE_SW_EventRegister(WDC_DEVICE_HANDLE hDev, PCIE_SW_EVENT_HANDLER funcEventHandler)
{
    DWORD dwStatus;
    PWDC_DEVICE pDev = (PWDC_DEVICE)hDev;
    PPCIE_SW_DEV_CTX pDevCtx;
    DWORD dwActions = WD_ACTIONS_ALL;
    /* TODO: Modify the above to set up the plug-and-play/power management
             events for which you wish to receive notifications.
             dwActions can be set to any combination of the WD_EVENT_ACTION
             flags defined in windrvr.h */

    TraceLog("PCIE_SW_EventRegister entered. Device handle: 0x%p\n", hDev);
    
    if (!IsValidDevice(pDev, "PCIE_SW_EventRegister"))
        return WD_INVALID_PARAMETER;

    pDevCtx = (PPCIE_SW_DEV_CTX)WDC_GetDevContext(pDev);

    /* Check if event is already registered */
    if (WDC_EventIsRegistered(hDev))
    {
        ErrLog("Events are already registered ...\n");
        return WD_OPERATION_ALREADY_DONE;
    }

    /* Store the diag event handler routine to be executed from PCIE_SW_EventHandler() upon an event */
    pDevCtx->funcDiagEventHandler = funcEventHandler;

    /* Register event */
    dwStatus = WDC_EventRegister(hDev, dwActions, PCIE_SW_EventHandler, hDev, FALSE);
    
    if (WD_STATUS_SUCCESS != dwStatus)
    {
        ErrLog("Failed to register events. Error 0x%lx - %s\n",
            dwStatus, Stat2Str(dwStatus));
        return dwStatus;
    }

    TraceLog("Events registered\n");

    return WD_STATUS_SUCCESS;
}
コード例 #14
0
BOOL PCIE_SW_DeviceClose(WDC_DEVICE_HANDLE hDev)
{
    DWORD dwStatus;
    PWDC_DEVICE pDev = (PWDC_DEVICE)hDev;
    PPCIE_SW_DEV_CTX pDevCtx;
    
    TraceLog("PCIE_SW_DeviceClose entered. Device handle: 0x%p\n", hDev);

    if (!hDev)
    {
        ErrLog("PCIE_SW_DeviceClose: Error - NULL device handle\n");
        return FALSE;
    }

    pDevCtx = (PPCIE_SW_DEV_CTX)WDC_GetDevContext(pDev);
    
    /* Disable interrupts */
    if (WDC_IntIsEnabled(hDev))
    {
        dwStatus = PCIE_SW_IntDisable(hDev);
        if (WD_STATUS_SUCCESS != dwStatus)
        {
            ErrLog("Failed disabling interrupts. Error 0x%lx - %s\n",
                dwStatus, Stat2Str(dwStatus));
        }
    }

    /* Close the device */
    dwStatus = WDC_PciDeviceClose(hDev);
    if (WD_STATUS_SUCCESS != dwStatus)
    {
        ErrLog("Failed closing a WDC device handle (0x%p). Error 0x%lx - %s\n",
            hDev, dwStatus, Stat2Str(dwStatus));
    }

    /* Free PCIE_SW device context memory */
    if (pDevCtx)
        free (pDevCtx);
    
    return (WD_STATUS_SUCCESS == dwStatus);
}
コード例 #15
0
static inline BOOL IsValidDevice(PWDC_DEVICE pDev, const CHAR *sFunc)
{
    if (!pDev || !WDC_GetDevContext(pDev))
    {
        snprintf(gsPCIE_SW_LastErr, sizeof(gsPCIE_SW_LastErr) - 1, "%s: NULL device %s\n",
            sFunc, !pDev ? "handle" : "context");
        ErrLog(gsPCIE_SW_LastErr);
        return FALSE;
    }

    return TRUE;
}
コード例 #16
0
ファイル: CLauncher.cpp プロジェクト: aosm/DirectoryService
void CLauncher::StopThread ( void )
{
	if ( this == nil )
	{
		ErrLog( kLogApplication, "Launcher StopThread failed with memory error on itself" );
		throw((SInt32)eMemoryError);
	}

	// Check that the current thread context is not our thread context

	SetThreadRunState( kThreadStop );		// Tell our thread to stop

} // StopThread
コード例 #17
0
ファイル: CLauncher.cpp プロジェクト: aosm/DirectoryService
CLauncher::CLauncher ( CServerPlugin *inPlugin ) : DSCThread(kTSLauncherThread)
{
	fThreadSignature = kTSLauncherThread;

	if ( inPlugin == nil )
	{
		ErrLog( kLogApplication, "Launcher failed create with no plugin pointer provided" );
		throw((SInt32)eParameterError);
	}

	fPlugin = inPlugin;

} // CLauncher
コード例 #18
0
/* -----------------------------------------------
    PCIE_SW and WDC library initialize/uninit
   ----------------------------------------------- */
DWORD PCIE_SW_LibInit(void)
{
    DWORD dwStatus;
 
    /* init only once */
    if (++LibInit_count > 1)
        return WD_STATUS_SUCCESS;
 
#if defined(WD_DRIVER_NAME_CHANGE)
    /* Set the driver name */
    if (!WD_DriverName(PCIE_SW_DEFAULT_DRIVER_NAME))
    {
        ErrLog("Failed to set the driver name for WDC library.\n");
        return WD_SYSTEM_INTERNAL_ERROR;
    }
#endif

    /* Set WDC library's debug options (default: level TRACE, output to Debug Monitor) */
    dwStatus = WDC_SetDebugOptions(WDC_DBG_DEFAULT, NULL);
    if (WD_STATUS_SUCCESS != dwStatus)
    {
        ErrLog("Failed to initialize debug options for WDC library.\n"
            "Error 0x%lx - %s\n", dwStatus, Stat2Str(dwStatus));
        
        return dwStatus;
    }

    /* Open a handle to the driver and initialize the WDC library */
    dwStatus = WDC_DriverOpen(WDC_DRV_OPEN_DEFAULT, PCIE_SW_DEFAULT_LICENSE_STRING);
    if (WD_STATUS_SUCCESS != dwStatus)
    {
        ErrLog("Failed to initialize the WDC library. Error 0x%lx - %s\n",
            dwStatus, Stat2Str(dwStatus));
        
        return dwStatus;
    }

    return WD_STATUS_SUCCESS;
}
コード例 #19
0
ファイル: cserverdc.cpp プロジェクト: Sorin91/verlihub
bool cServerDC::VerifyUniqueNick(cConnDC *conn)
{
	string UsrKey, omsg;
	mUserList.Nick2Key(conn->mpUser->mNick,UsrKey);
	/// add user to the list or fail
	if(mUserList.ContainsKey(UsrKey)) {
		bool CloseOld = false;
		cUser *old_usr = mUserList.GetUserByKey(UsrKey);

		if(conn->mpUser->mClass >= eUC_REGUSER) CloseOld = true;
		if (    !CloseOld &&
			old_usr->mxConn &&
			(conn->AddrIP() == old_usr->mxConn->AddrIP()) &&
			(conn->mpUser->mShare == old_usr->mShare) &&
			(conn->mpUser->mMyINFO_basic == old_usr->mMyINFO_basic)
		) CloseOld = true;

		if (CloseOld) {
			if(old_usr) {
				if(old_usr->mxConn) {
					if(old_usr->mxConn->Log(2))
						old_usr->mxConn->LogStream() << "Closing because of a new connection" << endl;
					omsg = _("Another user has logged in with same nick and IP address.");
					//old_usr->mxConn->Send(omsg,true);
					DCPublicHS(omsg, old_usr->mxConn);
					old_usr->mxConn->CloseNow();
				} else {
					if(ErrLog(1))
					    LogStream() << "[CRITICAL] Found user '" << old_usr->mNick << "' without a valid conneciton pointer" << endl;
				}
				RemoveNick(old_usr);
			} else {
				// This else block is not usefull since old_user pointer is used to access CUser class property above
				//if(ErrLog(0))
				//	LogStream() << "[CRITICAL] Found user '" << old_usr->mNick << "' without a valid conneciton pointer" << endl;
				conn->CloseNow();
				return false;
			}
		}
		else
		{
			omsg = _("Your nick is already in use.");
			DCPublicHS(omsg, conn);
			omsg = "$ValidateDenide " + conn->mpUser->mNick; conn->Send(omsg);
			// @todo: add redirect
			conn->CloseNow();
			return false;
		}
	}
	return true;
}
コード例 #20
0
// Creates the daemon's listener socket, to which clients will connect and
// retrieve slot information through.  Returns the file descriptor of the
// created socket.
int CreateListenerSocket (void) {
	struct sockaddr_un address;
	struct group *grp;
	int socketfd;

	socketfd = socket(PF_UNIX, SOCK_STREAM | SOCK_NONBLOCK, 0);
	if (socketfd < 0) {
		ErrLog("Failed to create listener socket, errno 0x%X.", errno);
		return -1;
	}
	if (unlink(SOCKET_FILE_PATH) && errno != ENOENT) {
		ErrLog("Failed to unlink socket file, errno 0x%X.", errno);
		close(socketfd);
		return -1;
	}

	memset(&address, 0, sizeof(struct sockaddr_un));
	address.sun_family = AF_UNIX;
	strcpy(address.sun_path, SOCKET_FILE_PATH);

	if (bind(socketfd, (struct sockaddr *) &address, sizeof(struct sockaddr_un)) != 0) {
		ErrLog("Failed to bind to socket, errno 0x%X.", errno);
		close(socketfd);
		return -1;
	}

	// make socket file part of the pkcs11 group, and write accessable
	// for that group
	grp = getgrnam("pkcs11");
	if (!grp) {
		ErrLog("Group PKCS#11 does not exist");
		DetachSocketListener(socketfd);
		return -1;
	}
	if (chown(SOCKET_FILE_PATH, 0, grp->gr_gid)) {
		ErrLog("Could not change file group on socket, errno 0x%X.", errno);
		DetachSocketListener(socketfd);
		return -1;
	}
	if (chmod(SOCKET_FILE_PATH, S_IRUSR|S_IRGRP|S_IWUSR|S_IWGRP|S_IXUSR|S_IXGRP)) {
		ErrLog("Could not change file permissions on socket, errno 0x%X.", errno);
		DetachSocketListener(socketfd);
		return -1;
	}

	if(listen(socketfd, 20) != 0) {
		ErrLog("Failed to listen to socket, errno 0x%X.", errno);
		DetachSocketListener(socketfd);
		return -1;
	}

	return socketfd;
}
コード例 #21
0
int InitSocketData (Slot_Mgr_Socket_t *socketData)
{
	int processed = 0;

	PopulateCKInfo(&(socketData->ck_info));
	socketData->num_slots = NumberSlotsInDB;
	PopulateSlotInfo(socketData->slot_info, &processed);

	/* check that we read in correct amount of slots */
	if (processed != NumberSlotsInDB) {
		ErrLog("Failed to populate slot info.\n");
		return FALSE;
	} else
		return TRUE;
}
コード例 #22
0
DWORD PCIE_SW_LibUninit(void)
{
    DWORD dwStatus;

    if (--LibInit_count > 0)
        return WD_STATUS_SUCCESS;
 
    /* Uninit the WDC library and close the handle to WinDriver */
    dwStatus = WDC_DriverClose();
    if (WD_STATUS_SUCCESS != dwStatus)
    {
        ErrLog("Failed to uninit the WDC library. Error 0x%lx - %s\n",
            dwStatus, Stat2Str(dwStatus));
    }

    return dwStatus;
}
コード例 #23
0
ファイル: shmem.c プロジェクト: BillTheBest/OpenCryptoki
void DetachFromSharedMemory ( void ) {

#if !MMAP
  if ( shmp == NULL ) return;

  if ( shmdt(shmp) != 0 ) {
    ErrLog("Attempted to detach from an invalid shared memory pointer");
  }

  shmp = NULL;
  return;
#else
  if ( shmp == NULL ) return;
  
  munmap((void *)shmp,sizeof(*shmp));

  unlink(MAPFILENAME);
#endif

}
コード例 #24
0
ファイル: shmem.c プロジェクト: BillTheBest/OpenCryptoki
int AttachToSharedMemeory ( void ) {

#if !MMAP
   shmp = NULL;
   shmp = (Slot_Mgr_Shr_t *) shmat( shmid, NULL, 0 );

   if ( !shmp ) {
      ErrLog("Shared memory attach failed (0x%X)\n", errno);
      return FALSE;
   }

   /* Initizalize the memory to 0  */
   memset ( shmp, '\0', sizeof(*shmp) );

   return TRUE;
#else
{
#warning "EXPERIMENTAL"
   int fd;
   int i;
   char *buffer;

    fd = open(MAPFILENAME,O_RDWR,MODE);
    if (fd < 0 ){
   	return FALSE;  //Failed
    }
   shmp = (Slot_Mgr_Shr_t *)mmap(NULL,sizeof(Slot_Mgr_Shr_t),PROT_READ|PROT_WRITE,
				    MAP_SHARED,fd,0);
   close(fd);
   if ( ! shmp ) {
      return FALSE;
   }
   return TRUE;
}
#endif

}
コード例 #25
0
ファイル: rtserver.c プロジェクト: ajribeiro/VT_RST3
int operate(pid_t parent,int sock,int port) {
 
  int s,i;
  int msg,rmsg;

  unsigned char *cbufadr=NULL;
  size_t cbuflen;
  int outpipe=-1;

  unsigned char *bufadr=NULL;
  int bufsze;

  outpipe=forkinet(port);


  while(1) {

    s=TCPIPMsgRecv(sock,&msg,sizeof(int));

    if (s !=sizeof(int)) break;
    rmsg=TASK_OK;
    switch (msg) {
    
    case TASK_OPEN:
      ErrLog(errsock,taskname,"Opening file.");
      rmsg=RMsgRcvDecodeOpen(sock,&cbuflen,&cbufadr);
      break;
    case TASK_CLOSE:
      ErrLog(errsock,taskname,"Closing file.");
      break;
    case TASK_RESET:
      ErrLog(errsock,taskname,"Reset.");
      break;
    case TASK_QUIT:
      ErrLog(errsock,taskname,"Stopped.");
      TCPIPMsgSend(sock,&rmsg,sizeof(int));
      exit(0);
      break;
    case TASK_DATA:
      ErrLog(errsock,taskname,"Received Data.");
      rmsg=RMsgRcvDecodeData(sock,&rblk,&store);    
    default:
      break;  
    }
    TCPIPMsgSend(sock,&rmsg,sizeof(int));

    if (msg==TASK_DATA) {
      dnum=0;
      for (i=0;i<rblk.num;i++) {
        for (dptr=0;dptr<dnum;dptr++) 
          if (dmsg[dptr].tag==rblk.data[i].tag) break;
          if (dptr==dnum) {
            dmsg[dptr].tag=rblk.data[i].tag;
            dmsg[dptr].pbuf=NULL;
            dmsg[dptr].fbuf=NULL;
            dnum++;
	  }
          switch (rblk.data[i].type) {
	  case PRM_TYPE:
            dmsg[dptr].pbuf=rblk.ptr[rblk.data[i].index];
	    break;
          case FIT_TYPE:
            dmsg[dptr].fbuf=rblk.ptr[rblk.data[i].index];
	    break;
          default:
            break;
	  }
      }




      for (dptr=0;dptr<dnum;dptr++) {

	if (dmsg[dptr].pbuf==NULL) continue;
        if (dmsg[dptr].fbuf==NULL) continue;
        RadarParmExpand(prm,dmsg[dptr].pbuf);
        FitExpand(fit,prm->nrang,dmsg[dptr].fbuf);

        if ((channel !=-1) && (prm->channel !=0)) {
          if ((channel==1) && (prm->channel==2)) continue;
          if ((channel==2) && (prm->channel!=2)) continue;
        }
        if (outpipe==-1) {
          sprintf(errbuf,"Child process died - Restarting.");
          ErrLog(errsock,taskname,errbuf);  
          outpipe=forkinet(port);
        }
        bufadr=fitpacket(prm,fit,&bufsze);
        if (bufadr !=NULL) {
          if (outpipe !=-1) s=ConnexWriteIP(outpipe,bufadr,bufsze);
          free(bufadr);
	}       
      }


      
      if (store !=NULL) free(store);
      store=NULL;
    }  
  }

  return 0;
}
コード例 #26
0
ファイル: rtserver.c プロジェクト: ajribeiro/VT_RST3
int main(int argc,char *argv[]) {
  
  int rport=DEF_PORT,tport=1024,arg=0;
  int sock;

  int sc_reuseaddr=1,temp;

  unsigned char help=0; 
  unsigned char option=0; 

  socklen_t length;
  socklen_t clength;

  struct sockaddr_in server;
  struct sockaddr_in client;

  fd_set ready;

  struct hostent *gethostbyname();
  pid_t root;

  char *chstr=NULL;

  int msgsock=0;

  prm=RadarParmMake();
  fit=FitMake();

  OptionAdd(&opt,"-help",'x',&help);
  OptionAdd(&opt,"-option",'x',&option);

  OptionAdd(&opt,"rp",'i',&rport);
  OptionAdd(&opt,"tp",'i',&tport);


  OptionAdd(&opt,"eh",'t',&errhost);
  OptionAdd(&opt,"ep",'i',&errport);

  OptionAdd(&opt,"c",'t',&chstr);

  arg=OptionProcess(1,argc,argv,&opt,NULL);

  if (help==1) {
    OptionPrintInfo(stdout,hlpstr);
    exit(0);
  }

  if (option==1) {
    OptionDump(stdout,&opt);
    exit(0);
  }

  if (chstr !=NULL) {
    if (tolower(chstr[0])=='a') channel=1;
    if (tolower(chstr[0])=='b') channel=2;
  }


  if (errhost==NULL) errhost=derrhost;
  errsock=TCPIPMsgOpen(errhost,errport);

  sprintf(errbuf,"Started (version %s.%s) listening on port %d for control program, and on port %d for clients",
          MAJOR_VERSION,MINOR_VERSION,rport,tport);
  ErrLog(errsock,taskname,errbuf);  


  signal(SIGCHLD,SIG_IGN); 
  signal(SIGPIPE,SIG_IGN);

  root=getpid();

  sock=socket(AF_INET,SOCK_STREAM,0); /* create our listening socket */
  if (sock<0) {
    perror("opening stream socket");
    exit(1);
  }

  /* set socket options */
  temp=setsockopt(sock,SOL_SOCKET,SO_REUSEADDR,&sc_reuseaddr,
                 sizeof(sc_reuseaddr));

  /* name and bind socket to an address and port number */

  server.sin_family=AF_INET;
  server.sin_addr.s_addr=INADDR_ANY;
  if (rport !=0) server.sin_port=htons(rport); 
  else server.sin_port=0;
  
  if (bind(sock,(struct sockaddr *) &server,sizeof(server))) {
     perror("binding stream socket");
     exit(1);
  }

  /* Find out assigned port number and print it out */

  length=sizeof(server);
  if (getsockname(sock,(struct sockaddr *) &server,&length)) {
     perror("getting socket name");
     exit(1);
  }

  listen(sock,5); /* mark our socket willing to accept connections */
  
  do {

      /* block until someone wants to attach to us */

      FD_ZERO(&ready);
      FD_SET(sock,&ready);
      if (select(sock+1,&ready,0,0,NULL) < 0) { 
       perror("while testing for connections");
       continue;
      }
     
      /* Accept the connection from the client */

      fprintf(stdout,"Accepting a new connection...\n");
      clength=sizeof(client);
      msgsock=accept(sock,(struct sockaddr *) &client,&clength);
        
      if (msgsock==-1) {
         perror("accept"); 
         continue;
      }

      if (fork() == 0) {
        close(sock);
        operate(root,msgsock,tport);
        exit(0);
      }
      close (msgsock);
  } while(1);

 
  return 0;

}
コード例 #27
0
ファイル: shmem.c プロジェクト: BillTheBest/OpenCryptoki
int CreateSharedMemory ( void ) {

  struct stat statbuf;
  char *Path = NULL;
  struct group *grp;
  struct shmid_ds shm_info;

#if !MMAP
  if ( ((Path = getenv("PKCS11_SHMEM_FILE")) == NULL ) || ( Path[0] == '\0' ) ) {
    Path = TOK_PATH;
  }
  InfoLog( "Shared memory file is %s", Path);

   // Get shared memory key token all users of the shared memory
   // need to get the same token

   if ( stat(Path, &statbuf) < 0 ) {
      ErrLog("Shared Memory Key Token creation file does not exist");
      return FALSE;
   }
   // SAB  Get the group information for the PKCS#11 group... fail if
   // it does not exist
   grp = getgrnam("pkcs11");
   if ( !grp ) {
     ErrLog("Group PKCS#11 does not exist ");
     return FALSE;  // Group does not exist... setup is wrong..
   }


   tok = ftok(Path ,'b');
   // Allocate the shared memory... Fail if the memory is already
   // allocated since the slot mgr is the owner of it.

   // Is this some attempt at exclusivity, or is that just a side effect? - SCM 9/1

   shmid = shmget( tok, sizeof( Slot_Mgr_Shr_t ),
                   IPC_CREAT | IPC_EXCL |  S_IRUSR |
	           S_IRGRP  | S_IWUSR | S_IWGRP   );

   // Explanation of options to shmget():

   /* 
    *  IPC_CREAT  Creates the data structure if it does not already exist.
    *  IPC_EXCL   Causes the shmget subroutine to be unsuccessful if the 
    *             IPC_CREAT flag is also set, and the data structure already exists.
    *  S_IRUSR    Permits the process that owns the data structure to read it.
    *  S_IWUSR    Permits the process that owns the data structure to modify it.
    *  S_IRGRP    Permits the group associated with the data structure to read it.
    *  S_IWGRP    Permits the group associated with the data structure to modify it.
    *
    *
    *  WE DON"T WANT OTHERS
    *  S_IROTH    Permits others to read the data structure.
    *  S_IWOTH    Permits others to modify the data structure.
    */


   if ( shmid < 0 ) {
      ErrLog("Shared memory creation failed (0x%X)\n", errno);
      ErrLog("Reclaiming 0x%X\n", tok);
      shmid = shmget( tok, sizeof( Slot_Mgr_Shr_t ), 0 );
      DestroySharedMemory();
      shmid = shmget( tok, sizeof( Slot_Mgr_Shr_t ),
                      IPC_CREAT | IPC_EXCL |  S_IRUSR |
	              S_IRGRP  | S_IWUSR | S_IWGRP   );
      if ( shmid < 0 ) {
          ErrLog("Shared memory reclamation failed (0x%X)\n", errno);
          ErrLog("perform ipcrm -M 0x%X\n", tok);
          return FALSE;
      }
   }

   // SAB Set the group ownership of the shared mem segment..
   // we already have the group structure..
   
   if ( shmctl(shmid, IPC_STAT,&shm_info) == 0 ) {

        shm_info.shm_perm.gid = grp->gr_gid;

        if (shmctl(shmid,IPC_SET,&shm_info) == -1) {
             ErrLog("Failed to set group ownership for shm \n");
             shmctl(shmid, IPC_RMID,NULL);        
        }

   } else {
        ErrLog("Can't get status of shared memory %d\n",errno);
        // we know it was created... we need to destroy it...
        shmctl(shmid, IPC_RMID,NULL);        

   }
   


   return TRUE;
#else   
{
#warning "EXPERIMENTAL"
   int fd;
   int i;
   char *buffer;
   
   grp = getgrnam("pkcs11");
   if ( !grp ) {
     ErrLog("Group \"pkcs11\" does not exist! Please run %s/pkcs11_startup.",
		     SBIN_PATH);
     return FALSE;  // Group does not exist... setup is wrong..
   }

   fd = open(MAPFILENAME,O_RDWR,MODE);
   if (fd < 0 ) {
     // File does not exist... this is cool, we creat it here
     fd = open(MAPFILENAME,O_RDWR|O_CREAT,MODE); // Create the file
     if (fd < 0 ){ // We are really hosed here, since we should be able
       // to create the file now
       ErrLog("%s: open(%s): %s", __FUNCTION__, MAPFILENAME, strerror(errno));
       return FALSE;
     } else {
       if (fchmod(fd, MODE) == -1) {
	 ErrLog("%s: fchmod(%s): %s", __FUNCTION__, MAPFILENAME, strerror(errno));
	 close(fd);
	 return FALSE;
       }
       if (fchown(fd, 0, grp->gr_gid) == -1) {
	 ErrLog("%s: fchown(%s, root, pkcs11): %s", __FUNCTION__, MAPFILENAME,
		strerror(errno));
	 close(fd);
	 return FALSE;
       }
       // Create a buffer and make the file the right length
       i = sizeof(Slot_Mgr_Shr_t);
       buffer = malloc(sizeof(Slot_Mgr_Shr_t));
       memset(buffer,'\0',i);
       write(fd,buffer,i);
       free(buffer);
       close(fd);
     }
   } else {
     ErrLog("%s: [%s] exists; you may already have a pkcsslot daemon running. If this "
	    "is not the case, then the prior daemon was not shut down cleanly. "
	    "Please delete this file and try again\n", __FUNCTION__, MAPFILENAME);
     close(fd); 
     return FALSE;
   }
   return TRUE;
}

#endif

}
コード例 #28
0
ファイル: CLauncher.cpp プロジェクト: aosm/DirectoryService
SInt32 CLauncher::ThreadMain ( void )
{
    			bool		done		= false;
				SInt32		siResult 	= eDSNoErr;
				UInt32		uiCntr		= 0;
				UInt32		uiAttempts	= 100;
    volatile	UInt32		uiWaitTime 	= 1;
				sHeader		aHeader;
				ePluginState		pluginState	= kUnknownState;

	CInternalDispatch::AddCapability();

	if ( gPlugins != nil )
	{
		while ( !done )
		{
			uiCntr++;

			// Attempt to initialize it
			siResult = fPlugin->Initialize();
			if ( ( siResult != eDSNoErr ) && ( uiCntr == 1 ) )
			{
				ErrLog( kLogApplication, "Attempt #%l to initialize plug-in %s failed.\n  Will retry initialization at most 100 times every %l second.", uiCntr, fPlugin->GetPluginName(), uiWaitTime );
				DbgLog( kLogApplication, "Attempt #%l to initialize plug-in %s failed.\n  Will retry initialization at most 100 times every %l second.", uiCntr, fPlugin->GetPluginName(), uiWaitTime );
			}
			
			if ( siResult == eDSNoErr )
			{
				DbgLog( kLogApplication, "Initialization of plug-in %s succeeded with #%l attempt.", fPlugin->GetPluginName(), uiCntr );

				gPlugins->SetState( fPlugin->GetPluginName(), kInitialized );

				//provide the CFRunLoop to the plugins that need it
				if (gPluginRunLoop != NULL)
				{
					aHeader.fType			= kServerRunLoop;
					aHeader.fResult			= eDSNoErr;
					aHeader.fContextData	= (void *)gPluginRunLoop;
					siResult = fPlugin->ProcessRequest( (void*)&aHeader ); //don't handle return
				}
				
				// provide the Kerberos Mutex to plugins that need it
				if (gKerberosMutex != NULL)
				{
					aHeader.fType			= kKerberosMutex;
					aHeader.fResult			= eDSNoErr;
					aHeader.fContextData	= (void *)gKerberosMutex;
					fPlugin->ProcessRequest( (void*)&aHeader ); // don't handle return
				}

#ifndef DISABLE_CONFIGURE_PLUGIN
				pluginState = gPluginConfig->GetPluginState( fPlugin->GetPluginName() );
#else
				pluginState = kActive;
#endif
				if ( pluginState == kInactive )
				{
					siResult = fPlugin->SetPluginState( kInactive );
					if ( siResult == eDSNoErr )
					{
						SrvrLog( kLogApplication, "Plug-in %s state is now inactive.", fPlugin->GetPluginName() );
				
						gPlugins->SetState( fPlugin->GetPluginName(), kInactive );
					}
					else
					{
						ErrLog( kLogApplication, "Unable to set %s plug-in state to inactive.  Received error %l.", fPlugin->GetPluginName(), siResult );
					}
				}
				else
				{
					// we assume the plugin is going to activate since we initialized successfully
					// this is because we expect they will start accepting answers the second we send to them
					siResult = gPlugins->SetState( fPlugin->GetPluginName(), kActive );
					if ( siResult == eDSNoErr )
					{
						SrvrLog( kLogApplication, "Plug-in %s state is now active.", fPlugin->GetPluginName() );
					}
					else
					{
						gPlugins->SetState( fPlugin->GetPluginName(), kInactive );
						ErrLog( kLogApplication, "Unable to set %s plug-in state to active.  Received error %l.", fPlugin->GetPluginName(), siResult );
					}
				}
				
				done = true;
			}

			if ( !done )
			{
				// We will try this 100 times before we bail
				if ( uiCntr == uiAttempts )
				{
					ErrLog( kLogApplication, "%l attempts to initialize plug-in %s failed.\n  Setting plug-in state to inactive.", uiCntr, fPlugin->GetPluginName() );

					siResult = gPlugins->SetState( fPlugin->GetPluginName(), kInactive | kFailedToInit );

					done = true;
				}
				else
				{
					fWaitToInit.WaitForEvent( uiWaitTime * kMilliSecsPerSec );
				}
			}
		}
	}
	
	return( 0 );

} // ThreadMain
コード例 #29
0
void cMySQL::Error(int level, string text)
{
	if(ErrLog(level)) LogStream() << text << mysql_error(mDBHandle) << endl;
}
コード例 #30
0
int main(int argc,char *argv[]) {

  int ptab[8] = {0,14,22,24,27,31,42,43};

  int lags[LAG_SIZE][2] = {
    { 0, 0},		/*  0 */
    {42,43},		/*  1 */
    {22,24},		/*  2 */
    {24,27},		/*  3 */
    {27,31},		/*  4 */
    {22,27},		/*  5 */

    {24,31},		/*  7 */
    {14,22},		/*  8 */
    {22,31},		/*  9 */
    {14,24},		/* 10 */
    {31,42},		/* 11 */
    {31,43},		/* 12 */
    {14,27},		/* 13 */
    { 0,14},		/* 14 */
    {27,42},		/* 15 */
    {27,43},		/* 16 */
    {14,31},		/* 17 */
    {24,42},		/* 18 */
    {24,43},		/* 19 */
    {22,42},		/* 20 */
    {22,43},		/* 21 */
    { 0,22},		/* 22 */

    { 0,24},		/* 24 */

    {43,43}};		/* alternate lag-0  */

  char logtxt[1024];

  int exitpoll=0;
  int scannowait=0;
  int rank=0;
 
  int scnsc=120;
  int scnus=0;
  int skip;
  int cnt=0;

  unsigned char fast=0;
  unsigned char discretion=0;

  int status=0,n;


  /* Variables for sounding */
  char snd_filename[ 100];
  FILE *snd_dat;
  /* If the file $SD_HDWPATH/sounder.dat exists, the next three parameters are read from it */
  /* the file contains one integer value per line */
  int freq_dwell=15; /* after so many minutes a new optimal frequency is evaluated */

/* MCM*/
/*
 *   int sounder_freqs_total=9;
 *     int sounder_freqs[ MAX_SND_FREQS]= { 9350, 10750 , 11600, 12500, 13750, 14550, 15250, 16650, 17850, 0,0, 0 };
*/
/* KOD */
  int sounder_freqs_total=8;
  int sounder_freqs[ MAX_SND_FREQS]= { 10400 , 11500, 12100, 13500, 14600, 15800, 16200, 17200, 0, 0, 0 };
/* ADAK */
/*
*  int sounder_freqs_total=8;
*  int sounder_freqs[ MAX_SND_FREQS]= { 10400,10900, 12000, 13000, 14500, 15000, 16000, 17000, 18000, 0, 0, 0 };
*/

  time_t last_freq_search, t_now;
  int fw=0; /* frequency weighting flag used in selecting the optimal freq */
  int sounder_beams[]={0,2,4,6,8,10,12,14};
  int sounder_freq_count=0, sounder_beam_count=0;
  int sounder_beams_total=8, odd_beams=0;
  int sounder_freq;
  int sounder_beam_loop=1;
  int normal_intt=6;
  int fast_intt=3;
  int sounder_intt=2;
  int do_new_freq_search=0;
  struct stat file_stat;
  int rval=0,last_mtime=0;
  float sounder_time, time_needed=1.25;
  int cutlass=0;
  struct sounder_struct *sounder_data;
  struct scatter_struct *scatter_data;
  int act_snd_rec= 0;

  char *snd_dir;
  char data_path[100];
  time(&last_freq_search);

  rval=stat("/tmp/freq_qsort_01.dat",&file_stat);
  if(rval==0) {
    last_mtime=file_stat.st_mtime; 
  } else { 
    last_mtime=last_freq_search; 
    file_stat.st_mtime=last_mtime;
  }

  snd_dir= getenv("SD_SND_PATH");
  if( snd_dir==NULL )
    sprintf( data_path,"/data/ros/snd/");
  else
    memcpy( data_path,snd_dir,strlen(snd_dir));
  sprintf( snd_filename,"%s/sounder.dat", data_path);
  fprintf(stderr,"Checking Sounder File: %s\n",snd_filename);
  snd_dat= fopen( snd_filename, "r");
  if( snd_dat != NULL ) {
    fscanf( snd_dat, "%d", &freq_dwell);
    fscanf( snd_dat, "%d", &sounder_freqs_total);
    if (sounder_freqs_total > 12) sounder_freqs_total= 12;
    for ( sounder_freq_count=0; sounder_freq_count < sounder_freqs_total; sounder_freq_count++ )
      fscanf( snd_dat, "%d", &sounder_freqs[ sounder_freq_count] );
    sounder_freq_count= 0;
    fclose( snd_dat);
    fprintf(stderr,"Sounder File: %s read\n",snd_filename);
  } else {
    fprintf(stderr,"Sounder File: %s not found\n",snd_filename);
  }
  sounder_data= ( struct sounder_struct *) calloc( sizeof( struct sounder_struct), NUM_SND_DATA);
  scatter_data= ( struct scatter_struct *) calloc( sizeof( struct scatter_struct), MAX_SND_FREQS+1);

  cp=155;
  intsc=normal_intt;
  intus=0;
  mppul=8;
  mplgs=23;
  mpinc=1500;
  dmpinc=1500;
  nrang=75;
  rsep=45;
  txpl=300;

  /* ========= PROCESS COMMAND LINE ARGUMENTS ============= */

  OptionAdd(&opt,"di",'x',&discretion);
  OptionAdd(&opt,"c",'i',&cnum);

  OptionAdd(&opt,"frang",'i',&frang);
  OptionAdd(&opt,"rsep",'i',&rsep);

  OptionAdd( &opt, "dt", 'i', &day);
  OptionAdd( &opt, "nt", 'i', &night);
  OptionAdd( &opt, "df", 'i', &dfrq);
  OptionAdd( &opt, "nf", 'i', &nfrq);
  OptionAdd( &opt, "xcf", 'i', &xcnt);

  OptionAdd(&opt,"ep",'i',&errlog.port);
  OptionAdd(&opt,"sp",'i',&shell.port); 
  OptionAdd(&opt,"bp",'i',&baseport); 
  OptionAdd(&opt,"ros",'t',&roshost);
  OptionAdd(&opt,"stid",'t',&ststr); 
  OptionAdd(&opt,"fast",'x',&fast);
  OptionAdd( &opt, "nowait", 'x', &scannowait);
  OptionAdd(&opt,"sb",'i',&sbm);
  OptionAdd(&opt,"eb",'i',&ebm);
  OptionAdd(&opt,"rank",'i',&rank);
   
  arg=OptionProcess(1,argc,argv,&opt,NULL);  
 
  if (ststr==NULL) ststr=dfststr;

  if (roshost==NULL) roshost=getenv("ROSHOST");
  if (roshost==NULL) roshost=droshost;


  if ((errlog.sock=TCPIPMsgOpen(errlog.host,errlog.port))==-1) {    
    fprintf(stderr,"Error connecting to error log.\n");
  }

  if ((shell.sock=TCPIPMsgOpen(shell.host,shell.port))==-1) {    
    fprintf(stderr,"Error connecting to shell.\n");
  }

  for (n=0;n<tnum;n++) task[n].port+=baseport;

  OpsStart(ststr);

  status=SiteBuild(ststr,NULL); /* second argument is version string */

  if (status==-1) {
    fprintf(stderr,"Could not identify station.\n");
    exit(1);
  }

  SiteStart(roshost);
  arg=OptionProcess(1,argc,argv,&opt,NULL);  

  strncpy(combf,progid,80);   
 
  OpsSetupCommand(argc,argv);
  OpsSetupShell();
   
  RadarShellParse(&rstable,"sbm l ebm l dfrq l nfrq l dfrang l nfrang l dmpinc l nmpinc l frqrng l xcnt l",                        
                  &sbm,&ebm,                              
                  &dfrq,&nfrq,                  
                  &dfrang,&nfrang,                            
                  &dmpinc,&nmpinc,                            
                  &frqrng,&xcnt);      
  
 
  status=SiteSetupRadar();

  fprintf(stderr,"Status:%d\n",status);
  
  if (status !=0) {
    ErrLog(errlog.sock,progname,"Error locating hardware.");
    exit (1);
  }


  if (fast) {
     cp=157;
     scnsc=60;
     scnus=0;
     intsc=fast_intt;
     intus=0;
  }

  if (discretion) cp= -cp;

  txpl=(rsep*20)/3;

  if (fast) sprintf(progname,"normalsound (fast)");
  else sprintf(progname,"normalsound");



  OpsLogStart(errlog.sock,progname,argc,argv);  

  OpsSetupTask(tnum,task,errlog.sock,progname);

  for (n=0;n<tnum;n++) {
    RMsgSndReset(task[n].sock);
    RMsgSndOpen(task[n].sock,strlen( (char *) command),command);     
  }

  
  OpsFitACFStart();
  tsgid=SiteTimeSeq(ptab);
  TimeReadClock(&yr,&mo,&dy,&hr,&mt,&sc,&us);
/*  Since we are sounding we only want to check Night/Day at operation startup */
  if (OpsDayNight()==1) {
        stfrq=dfrq;
        mpinc=dmpinc;
        frang=dfrang;
  } else {
        stfrq=nfrq;
        mpinc=nmpinc;
        frang=nfrang;
  }        

  do {

    if (SiteStartScan() !=0) continue;
    
    if (OpsReOpen(2,0,0) !=0) {
      ErrLog(errlog.sock,progname,"Opening new files.");
      for (n=0;n<tnum;n++) {
        RMsgSndClose(task[n].sock);
        RMsgSndOpen(task[n].sock,strlen( (char *) command),command);     
      }
    }

    scan=1;
    
    ErrLog(errlog.sock,progname,"Starting scan.");
   
    if (xcnt>0) {
      cnt++;
      if (cnt==xcnt) {
        xcf=1;
        cnt=0;
      } else xcf=0;
    } else xcf=0;

    skip=OpsFindSkip(scnsc,scnus);
    
    if (backward) {
      bmnum=sbm-skip;
      if (bmnum<ebm) bmnum=sbm;
    } else {
      bmnum=sbm+skip;
      if (bmnum>ebm) bmnum=sbm;
    }

    do {

      TimeReadClock(&yr,&mo,&dy,&hr,&mt,&sc,&us);
/*  Since we are sounding we only want to check Night/Day at operation startup      
      if (OpsDayNight()==1) {
        stfrq=dfrq;
        mpinc=dmpinc;
        frang=dfrang;
      } else {
        stfrq=nfrq;
        mpinc=nmpinc;
        frang=nfrang;
      }        
*/
      sprintf(logtxt,"Integrating beam:%d intt:%ds.%dus (%d:%d:%d:%d)",bmnum,
                      intsc,intus,hr,mt,sc,us);
      ErrLog(errlog.sock,progname,logtxt);

      ErrLog(errlog.sock,progname,"Starting Integration.");
            
      SiteStartIntt(intsc,intus);

      ErrLog(errlog.sock,progname,"Doing clear frequency search."); 
   
      sprintf(logtxt, "FRQ: %d %d", stfrq, frqrng);
      ErrLog(errlog.sock,progname, logtxt);

            
      tfreq=SiteFCLR(stfrq,stfrq+frqrng);
      
      sprintf(logtxt,"Transmitting on: %d (Noise=%g)",tfreq,noise);
      ErrLog(errlog.sock,progname,logtxt);

    
      nave=SiteIntegrate(lags);   
      if (nave<0) {
        sprintf(logtxt,"Integration error:%d",nave);
        ErrLog(errlog.sock,progname,logtxt); 
        continue;
      }
      sprintf(logtxt,"Number of sequences: %d",nave);
      ErrLog(errlog.sock,progname,logtxt);

      OpsBuildPrm(prm,ptab,lags);
      
      OpsBuildIQ(iq,&badtr);
            
      OpsBuildRaw(raw);
   
      FitACF(prm,raw,fblk,fit);
      
      msg.num=0;
      msg.tsize=0;

      tmpbuf=RadarParmFlatten(prm,&tmpsze);
      RMsgSndAdd(&msg,tmpsze,tmpbuf,
		PRM_TYPE,0); 

      tmpbuf=IQFlatten(iq,prm->nave,&tmpsze);
      RMsgSndAdd(&msg,tmpsze,tmpbuf,IQ_TYPE,0);

      RMsgSndAdd(&msg,sizeof(unsigned int)*2*iq->tbadtr,
                 (unsigned char *) badtr,BADTR_TYPE,0);
		 
      RMsgSndAdd(&msg,strlen(sharedmemory)+1,(unsigned char *) sharedmemory,
		 IQS_TYPE,0);

      tmpbuf=RawFlatten(raw,prm->nrang,prm->mplgs,&tmpsze);
      RMsgSndAdd(&msg,tmpsze,tmpbuf,RAW_TYPE,0); 
 
      tmpbuf=FitFlatten(fit,prm->nrang,&tmpsze);
      RMsgSndAdd(&msg,tmpsze,tmpbuf,FIT_TYPE,0); 

        
      RMsgSndAdd(&msg,strlen(progname)+1,(unsigned char *) progname,
		NME_TYPE,0);   
     

     
      for (n=0;n<tnum;n++) RMsgSndSend(task[n].sock,&msg); 

      for (n=0;n<msg.num;n++) {
        if (msg.data[n].type==PRM_TYPE) free(msg.ptr[n]);
        if (msg.data[n].type==IQ_TYPE) free(msg.ptr[n]);
        if (msg.data[n].type==RAW_TYPE) free(msg.ptr[n]);
        if (msg.data[n].type==FIT_TYPE) free(msg.ptr[n]); 
      }          

      RadarShell(shell.sock,&rstable);

      if (exitpoll !=0) break;
      scan=0;
      if (bmnum==ebm) break;
      if (backward) bmnum--;
      else bmnum++;

    } while (1);
/*
    ErrLog(errlog.sock,progname,"Waiting for scan boundary."); 
    if ((exitpoll==0) && (scannowait==0)) SiteEndScan(scnsc,scnus);
*/

   if (exitpoll==0) {
      /* In here comes the sounder code */
      /* see if it's time for a new freq search */
      time(&t_now);
      do_new_freq_search= ( freq_dwell>0 && freq_dwell<=((t_now-last_freq_search)/60.) );
      fprintf(stdout,"SND Code 0: %d %d %lf\n",do_new_freq_search,freq_dwell,(double)(t_now-last_freq_search)/60.);
      /* set the "sounder mode" scan variable */
      scan=-2;
      /* set the xcf variable to do cross-correlations (AOA) */
      xcf=1;
      /* we have time until the end of the minute to do sounding */
      /* minus a safety factor given in time_needed */
      TimeReadClock(&yr,&mo,&dy,&hr,&mt,&sc,&us);
      sounder_time= 60.0 - ( sc + us/ 1000000.0);
      /* we do not implement to no sounding mode here */
      /* do a new frequency search if it's time */
      if( do_new_freq_search && sounder_time>=5 ) {
            do_new_freq_search=0;
            stfrq= find_optimal_freq( stfrq, freq_dwell,cutlass, fw, sounder_freqs, sounder_freqs_total, sounder_data, 
                                      scatter_data,act_snd_rec,rank);
            sprintf( logtxt,"New Opt Freq; %d\n", stfrq);
            ErrLog( errlog.sock, progname, logtxt);
            last_freq_search= t_now;
      }
      sounder_beam_loop= ( sounder_time-(float)sounder_intt > time_needed );
      while( sounder_beam_loop ) {
            intsc= sounder_intt;
            /* set the beam */
            bmnum=sounder_beams[sounder_beam_count]+odd_beams;
            /* sounder_freq will be an array of frequencies to step through */
            if( !cutlass )
              sounder_freq=sounder_freqs[sounder_freq_count];
/*
 *         else {
 *           sounder_freq=lsfreq[sounder_freqs[sounder_freq_count]];
 *           frqrng=lfreq_range[sounder_freqs[sounder_freq_count]];
 *         }
 */


          sprintf(logtxt,"Integrating SND beam:%d intt:%ds.%dus (%d:%d:%d:%d)", bmnum, intsc,intus,hr,mt,sc,us);
          ErrLog(errlog.sock,progname,logtxt);
          ErrLog(errlog.sock,progname,"Setting SND beam.");
          SiteStartIntt(intsc,intus);
          ErrLog( errlog.sock, progname, "Doing SND clear frequency search.");
          sprintf(logtxt, "FRQ: %d %d", sounder_freq, frqrng);
          ErrLog(errlog.sock,progname, logtxt);
          tfreq=SiteFCLR( sounder_freq, sounder_freq+frqrng);
          sprintf(logtxt,"Transmitting SND on: %d (Noise=%g)",tfreq,noise);
          ErrLog( errlog.sock, progname, logtxt);
/* JDS: Remove unncessary and costly SiteTimeSeq allocation here */
/*          tsgid= SiteTimeSeq(ptab); */
          nave= SiteIntegrate( lags);
          if (nave < 0) {
            sprintf( logtxt, "SND integration error: %d", nave);
            ErrLog(errlog.sock,progname, logtxt);
            continue;
          }
          sprintf(logtxt,"Number of SND sequences: %d",nave);
          ErrLog(errlog.sock,progname,logtxt);

          OpsBuildPrm(prm,ptab,lags);
          OpsBuildIQ(iq,&badtr);
          OpsBuildRaw(raw);
          FitACF(prm,raw,fblk,fit);

          ErrLog( errlog.sock, progname, "Sending SND messages.");
          msg.num= 0;
          msg.tsize= 0;

          tmpbuf=RadarParmFlatten(prm,&tmpsze);
          RMsgSndAdd(&msg,tmpsze,tmpbuf,
		PRM_TYPE,0); 

          tmpbuf=IQFlatten(iq,prm->nave,&tmpsze);
          RMsgSndAdd(&msg,tmpsze,tmpbuf,IQ_TYPE,0);

          RMsgSndAdd(&msg,sizeof(unsigned int)*2*iq->tbadtr,
                 (unsigned char *) badtr,BADTR_TYPE,0);
		 
          RMsgSndAdd(&msg,strlen(sharedmemory)+1,
                 (unsigned char *) sharedmemory,
		 IQS_TYPE,0);

          tmpbuf=RawFlatten(raw,prm->nrang,prm->mplgs,&tmpsze);
          RMsgSndAdd(&msg,tmpsze,tmpbuf,RAW_TYPE,0); 
 
          tmpbuf=FitFlatten(fit,prm->nrang,&tmpsze);
          RMsgSndAdd(&msg,tmpsze,tmpbuf,FIT_TYPE,0); 

        
          RMsgSndAdd(&msg,strlen(progname)+1,(unsigned char *) progname,
		NME_TYPE,0);   
     
          RMsgSndSend(task[RT_TASK].sock,&msg); 
            for (n=0;n<msg.num;n++) {
            if (msg.data[n].type==PRM_TYPE) free(msg.ptr[n]);
            if (msg.data[n].type==IQ_TYPE) free(msg.ptr[n]);
            if (msg.data[n].type==RAW_TYPE) free(msg.ptr[n]);
            if (msg.data[n].type==FIT_TYPE) free(msg.ptr[n]); 
          }          

          sprintf( logtxt, "SBC: %d  SFC: %d\n", sounder_beam_count, sounder_freq_count);
          ErrLog( errlog.sock, progname, logtxt);
          /* save the sounding mode data */
          write_sounding_record_new( progname,prm,fit, sounder_data, &act_snd_rec);

          ErrLog( errlog.sock, progname, "Polling SND for exit.");

          if (exitpoll !=0) break;
          /* check for the end of a beam loop */
          sounder_freq_count++;
          if( sounder_freq_count >= sounder_freqs_total ) {
            /* reset the freq counter and increment the beam counter */
            sounder_freq_count=0;
            sounder_beam_count++;
            if( sounder_beam_count>=sounder_beams_total ) {
              sounder_beam_count=0;
              if( odd_beams==0 )
                odd_beams=1;
              else
                odd_beams=0;
              sounder_freq_count=0;
            }
          }
          /* see if we have enough time for another go round */
          TimeReadClock( &yr, &mo, &dy, &hr, &mt, &sc, &us);
          sounder_time= 60.0 - ( sc + us/ 1000000.0);
          sounder_beam_loop= ( sounder_time-(float)sounder_intt > time_needed );
      }
     /* Check to see if new sounding data was recorded */

      if(rank > 1 ) {
        rval=stat("/tmp/freq_qsort_01.dat",&file_stat);
        sprintf( logtxt,"Rank %d : rval: %d last mtime %d file_mtime: %d\n", rank,rval,last_mtime,(int)file_stat.st_mtime);
        ErrLog( errlog.sock, progname, logtxt);
        if(rval==0) {
          if(file_stat.st_mtime != last_mtime) {
            last_mtime=file_stat.st_mtime; 
            stfrq= find_optimal_freq( stfrq, freq_dwell,cutlass, fw, sounder_freqs, sounder_freqs_total, sounder_data, scatter_data,act_snd_rec,rank);
            sprintf( logtxt,"Rank 1 sounding data modified: New Opt Freq; %d\n", stfrq);
            ErrLog( errlog.sock, progname, logtxt);
          }
        }
      }

      /* now wait for the next normal_scan */
      intsc=normal_intt;
      if ( fast) intsc= fast_intt;
      if (scannowait==0) SiteEndScan(scnsc,scnus);
   }
  } while (exitpoll==0);
  
  
  for (n=0;n<tnum;n++) RMsgSndClose(task[n].sock);
  

  ErrLog(errlog.sock,progname,"Ending program.");


  SiteExit(0);

  return 0;   
}