//!
//! Function description.
//!
//! @param[in] ipsh pointer to the IP set handler structure
//! @param[in] setname a string pointer to the ipset name
//! @param[in] ipname a string pointer to the ip address
//! @param[in] nmname the netmask address
//!
//! @return
//!
//! @see
//!
//! @pre
//!
//! @post
//!
//! @note
//!
int ips_set_add_net(ips_handler * ipsh, char *setname, char *ipname, int nmname)
{
    ips_set *set = NULL;
    u32 *ip = NULL;
    if (!ipsh || !setname || !ipname || !ipsh->init) {
        return (1);
    }

    set = ips_handler_find_set(ipsh, setname);
    if (!set) {
        return (1);
    }

    ip = ips_set_find_net(ipsh, setname, ipname, nmname);
    if (!ip) {
        set->member_ips = realloc(set->member_ips, sizeof(u32) * (set->max_member_ips + 1));
        if (!set->member_ips) {
            LOGFATAL("out of memory!\n");
            exit(1);
        }
        set->member_nms = realloc(set->member_nms, sizeof(int) * (set->max_member_ips + 1));
        if (!set->member_nms) {
            LOGFATAL("out of memory!\n");
            exit(1);
        }

        bzero(&(set->member_ips[set->max_member_ips]), sizeof(u32));
        bzero(&(set->member_nms[set->max_member_ips]), sizeof(int));
        set->member_ips[set->max_member_ips] = dot2hex(ipname);
        set->member_nms[set->max_member_ips] = nmname;
        set->max_member_ips++;
        set->ref_count++;
    }
    return (0);
}
Example #2
0
	bool SendHeartbeat (bool bWithStash) {
		LOGDEBUG (TEXT ("Sending heartbeat message"));
		FudgeStatus status;
		FudgeMsg msg;
		if ((status = FudgeMsg_create (&msg)) != FUDGE_OK) {
			LOGFATAL (TEXT ("Couldn't create message, status ") << status);
			assert (0);
			return false;
		}
		if ((status = ConnectorMessage_setOperation (msg, HEARTBEAT)) != FUDGE_OK) {
			FudgeMsg_release (msg);
			LOGFATAL (TEXT ("Couldn't create message, status ") << status);
			assert (0);
			return false;
		}
		if (bWithStash) {
			m_oStashMutex.Enter ();
			if (m_msgStash) {
				if ((status = ConnectorMessage_setStash (msg, m_msgStash)) != FUDGE_OK) {
					LOGFATAL (TEXT ("Couldn't create message, status ") << status);
					assert (0);
					status = FUDGE_OK;
					// Not good, but can carry on
				}
			}
			m_oStashMutex.Leave ();
		}
		bool bResult = m_poService->Send (MESSAGE_DIRECTIVES_CLIENT, msg);
		FudgeMsg_release (msg);
		return bResult;
	}
Example #3
0
bool CClientService::ConnectPipes () {
	LOGINFO (TEXT ("Connecting pipes to JVM"));
	m_oPipesSemaphore.Wait ();
	if (!m_poPipes) {
		m_oPipesSemaphore.Signal ();
		LOGFATAL (TEXT ("Pipes not created"));
		assert (0);
		return false;
	}
	if (!m_poJVM) {
		m_oPipesSemaphore.Signal ();
		LOGFATAL (TEXT ("JVM not created"));
		assert (0);
		return false;
	}
	CSettings oSettings;
	const TCHAR *pszPipeName = oSettings.GetConnectionPipe ();
	LOGDEBUG (TEXT ("Connecting to ") << pszPipeName);
	unsigned long lTimeout = m_poJVM->FirstConnection () ? oSettings.GetStartTimeout () : oSettings.GetConnectTimeout ();
	m_lSendTimeout = lTimeout;
	m_lShortTimeout = oSettings.GetSendTimeout ();
	unsigned long lTime = GetTickCount ();
	CNamedPipe *poPipe;
	do {
		poPipe = CNamedPipe::ClientWrite (pszPipeName);
		if (poPipe) {
			break;
		} else {
			int ec = GetLastError ();
			if (ec == ENOENT) {
				if (GetTickCount () - lTime > lTimeout) {
					m_oPipesSemaphore.Signal ();
					LOGWARN (TEXT ("Timeout waiting for JVM service to open ") << pszPipeName);
					return false;
				} else {
					if (m_poJVM->IsAlive ()) {
						LOGDEBUG (TEXT ("Waiting for JVM service to open pipe"));
						CThread::Sleep (oSettings.GetServicePoll ());
					} else {
						m_oPipesSemaphore.Signal ();
						LOGWARN (TEXT ("JVM service terminated before opening ") << pszPipeName);
						return false;
					}
				}
			} else {
				m_oPipesSemaphore.Signal ();
				LOGWARN (TEXT ("Couldn't connect to ") << pszPipeName << TEXT (", error ") << ec);
				return false;
			}
		}
	} while (true);
	LOGDEBUG (TEXT ("Connected to service"));
	bool bResult = m_poPipes->Connect (m_pszLanguageID, poPipe, lTimeout);
	if (!bResult) {
		LOGWARN (TEXT ("Couldn't connect to JVM service, error ") << GetLastError ());
	}
	delete poPipe;
	m_oPipesSemaphore.Signal ();
	return bResult;
}
/**
 * Invokes realloc() and perform error checking.
 * @param nmemb [in] see calloc() man pages.
 * @param size [in] see calloc() man pages.
 * @return pointer to the allocated memory.
 */
void *realloc_check(void *ptr, size_t nmemb, size_t size) {
    void *ret = realloc(ptr, nmemb * size);
    if ((ret == NULL) && ((nmemb * size) != 0)) {
        LOGFATAL("out of memory - realloc nmemb %zd, size %zd.\n", nmemb, size);
        LOGFATAL("Shutting down eucanetd.\n");
        get_stack_trace();
        exit(1);
    }
    return (ret);
}
Example #5
0
/// Schedules an operation for later execution on the execution thread. If no thread
/// currently exists, one is started. The callback service will take ownership of
/// the operation after this call. If the return value is true, the caller may no
/// longer use the object. It will be deleted by the asynchronous framework.
///
/// @param[in] poOperation operation to schedule, never NULL
/// @return true if the operation was scheduled (or discarded), false otherwise
bool CAsynchronous::Run (COperation *poOperation) {
	if (!poOperation) {
		LOGWARN ("NULL pointer passed");
		return false;
	}
	bool bResult = true;
	EnterCriticalSection ();
	if (!m_bPoison) {
		if (!m_poRunner) {
			m_poRunner = new CAsynchronousRunnerThread (this);
			if (!m_poRunner) {
				LOGFATAL (TEXT ("Out of memory"));
				bResult = false;
				goto abortRun;
			} else if (m_poRunner->Start ()) {
				LOGINFO (TEXT ("Callback thread created, ID ") << m_poRunner->GetThreadId ());
			} else {
				LOGFATAL (TEXT ("Couldn't create callback thread, error ") << GetLastError ());
				CThread::Release (m_poRunner);
				m_poRunner = NULL;
				bResult = false;
				goto abortRun;
			}
		}
		if (poOperation->OnScheduled ()) {
			if (m_poTail) {
				m_poTail->m_poNext = poOperation;
			} else {
				m_poHead = poOperation;
				if (m_bWaiting) {
					LOGDEBUG ("Signalling semaphore");
					if (!m_semQueue.Signal ()) {
						LOGWARN (TEXT ("Couldn't signal semaphore, error ") << GetLastError ());
					}
					// Clear the waiting flag, e.g. if there is another call to Run before the
					// dispatch thread completes its wait and clears it itself.
					m_bWaiting = false;
				}
			}
			m_poTail = poOperation;
			poOperation->m_poNext = NULL;
			poOperation->m_nMustReschedule = 0;
		} else {
			LOGDEBUG (TEXT ("Operation refused to schedule"));
			delete poOperation;
		}
	} else {
		LOGWARN ("Caller has been poisoned");
		bResult = false;
	}
abortRun:
	LeaveCriticalSection ();
	return bResult;
}
/**
 * Appends pointer ptr to the end of the given pointer array arr. The array should
 * have been malloc'd. The allocation is adjusted as needed.
 * @param arr [i/o] arr pointer to an array of pointers
 * @param max_arr [i/o] max_arr the number of array entries.
 * @param ptr (in] pointer to be appended to the array.
 * @return 0 on success. 1 otherwise.
 */
void *append_ptrarr(void *arr, int *max_arr, void *ptr) {
    arr = EUCA_REALLOC(arr, *max_arr + 1, sizeof (void *));
    if (arr == NULL) {
        LOGFATAL("out of memory: failed to (re)allocate array of pointers\n");
        LOGFATAL("Shutting down eucanetd.\n");
        get_stack_trace();
        exit (1);
    }
    void **parr = arr;
    parr[*max_arr] = ptr;
    (*max_arr)++;
    return (arr);    
}
Example #7
0
//!
//! Function description.
//!
//! @param[in] ebth pointer to the EB table handler structure
//! @param[in] tablename a string pointer to the table name
//! @param[in] chainname a string pointer to the chain name
//! @param[in] newrule a string pointer to the new rule
//!
//! @return
//!
//! @see
//!
//! @pre
//!
//! @post
//!
//! @note
//!
int ebt_chain_add_rule(ebt_handler * ebth, char *tablename, char *chainname, char *newrule)
{
    ebt_table *table = NULL;
    ebt_chain *chain = NULL;
    ebt_rule *rule = NULL;

    LOGDEBUG("adding rules (%s) to chain %s to table %s\n", newrule, chainname, tablename);
    if (!ebth || !tablename || !chainname || !newrule || !ebth->init) {
        return (1);
    }

    table = ebt_handler_find_table(ebth, tablename);
    if (!table) {
        return (1);
    }

    chain = ebt_table_find_chain(ebth, tablename, chainname);
    if (!chain) {
        return (1);
    }

    rule = ebt_chain_find_rule(ebth, tablename, chainname, newrule);
    if (!rule) {
        chain->rules = realloc(chain->rules, sizeof(ebt_rule) * (chain->max_rules + 1));
        if (!chain->rules) {
            LOGFATAL("out of memory!\n");
            exit(1);
        }
        bzero(&(chain->rules[chain->max_rules]), sizeof(ebt_rule));
        snprintf(chain->rules[chain->max_rules].ebtrule, 1024, "%s", newrule);
        chain->max_rules++;
    }
    return (0);
}
Example #8
0
int GetFileData(const char* pszFileName, char* pszFileData, int nMaxLen)
{
	assert(pszFileName!=NULL && pszFileData!=NULL);
	int nRead = 0, nReadTotal = 0;
	int nReadBufferLen = BUFFER_MAX_LEN;
	
	FILE *pFile = NULL;
	pFile = fopen(pszFileName, "r");
	if (pFile != NULL) {
		while (!feof(pFile)) {
			if (nReadTotal+BUFFER_MAX_LEN > nMaxLen)
				nReadBufferLen = nMaxLen - nReadTotal;
			
			nRead = fread(pszFileData+nReadTotal, sizeof(char), nReadBufferLen, pFile); 
			nReadTotal += nRead;

			if (nReadTotal == nMaxLen)
				break;
		}

		pszFileData[nReadTotal] = '\0';
		fclose(pFile);
	} else {
		LOGFATAL("'%s' dont exist.", pszFileName);
		ASSERT(0);
	}

	return nReadTotal;
}
Example #9
0
/// Report the service state back to the service control manager.
///
/// @param[in] dwStateCode service state code
/// @param[in] dwExitCode service exit code (if applicable, use 0 otherwise)
/// @param[in] bInfo TRUE to log at INFO level, FALSE to log at DEBUG only
/// @param[in] pszLabel textual description of the state to log, never NULL
static void _ReportState (DWORD dwStateCode, DWORD dwExitCode, bool bInfo, PCTSTR pszLabel) {
	SERVICE_STATUS sta;
	ZeroMemory (&sta, sizeof (sta));
	if (bInfo) {
		LOGINFO (pszLabel);
	} else {
		LOGDEBUG (pszLabel);
	}
	switch (dwStateCode) {
	case SERVICE_START_PENDING :
		sta.dwCheckPoint = ++g_dwServiceCheckPoint;
		break;
	case SERVICE_RUNNING :
		sta.dwControlsAccepted = SERVICE_ACCEPT_STOP;
		break;
	case SERVICE_STOP_PENDING :
		sta.dwCheckPoint = ++g_dwServiceCheckPoint;
		break;
	case SERVICE_STOPPED :
		break;
	default :
		LOGFATAL (TEXT ("Unexpected service state code ") << dwStateCode);
		break;
	}
	if (g_hServiceStatus) {
		sta.dwServiceType = SERVICE_WIN32_OWN_PROCESS;
		sta.dwCurrentState = dwStateCode;
		sta.dwWin32ExitCode = dwExitCode;
		sta.dwWaitHint = g_lBusyTimeout * 2;
		SetServiceStatus (g_hServiceStatus, &sta);
	}
}
Example #10
0
/// Attempts to terminate any existing execution thread and start another in its place. Any
/// non-vital operations in the queue will be discarded in the process. Any vital operations
/// will be executed by the terminating thread before the new one proceeds.
///
/// @return true if the threads were recycled, false if there was an error or there was
///         no execution thread
bool CAsynchronous::RecycleThread () {
	bool bResult = false;
	EnterCriticalSection ();
	if (m_poRunner) {
		CAsynchronousRunnerThread *poNewThread = new CAsynchronousRunnerThread (this);
		if (poNewThread) {
			if (poNewThread->Start ()) {
				LOGINFO (TEXT ("Callback thread created, ID ") << poNewThread->GetThreadId ());
				CThread::Release (m_poRunner);
				m_poRunner = poNewThread;
				if (m_bWaiting) {
					LOGDEBUG (TEXT ("Signalling semaphore"));
					if (!m_semQueue.Signal ()) {
						LOGWARN (TEXT ("Couldn't signal semaphore, error ") << GetLastError ());
					}
					// Clear the waiting flag, e.g. if there is another call to Run or RecycleThread
					// before the dispatch thread completes its wait and clear it itself.
					m_bWaiting = false;
				}
				bResult = true;
			} else {
				LOGERROR (TEXT ("Couldn't create callback thread, error ") << GetLastError ());
				CThread::Release (poNewThread);
			}
		} else {
			LOGFATAL (TEXT ("Out of memory"));
		}
	} else {
		LOGWARN (TEXT ("Runner thread not active"));
	}
	LeaveCriticalSection ();
	return bResult;
}
Example #11
0
Converter* ConverterFactory::GetConverter(const std::string&  sourceCharset, const std::string&  targetCharset) {
	XR::CSingleLock lock(m_critSect);

	if (sourceCharset.empty() || sourceCharset.empty()) {
		LOGERR("One of the charsets missing!");
		return nullptr;
	}
	std::string ident = sourceCharset + targetCharset;

	for (unsigned int i = 0; i < m_vConverters.size(); ++i)
	{
		ConverterUnit& converterunit = m_vConverters[i];
		if (converterunit.m_ident == ident) {
			converterunit.m_unloadDelayStartTick = XR::SystemClockMillis();
			return converterunit.m_converter;
		}
	}

	//Converter not present, sooo.... Let's create one for us;
	LOGDEBUG("Converter (%s --> %s) not exist, creating new.", sourceCharset.c_str(), targetCharset.c_str());
	Converter* pNewConverter = nullptr;
	lock.Leave();
	if (targetCharset == "UTF-8")
		pNewConverter = CreateConverter(sourceCharset, targetCharset, 4);
	else
		pNewConverter = CreateConverter(sourceCharset, targetCharset);

	if (nullptr == pNewConverter)
		LOGFATAL("Cannot create new converter! (not enough of memory?)");
	lock.Enter();
	return pNewConverter;
}
Example #12
0
/****************************************************************************
PARAMETERS:
dc          - Device context to fill in
driver      - Pointer to device driver driver to use
mode        - Pointer to mode entry for driver (NULL if not needed)
hwnd        - Handle to OS fullscreen window
virtualX    - Virtual X coordinate for display DC
virutalY    - Virtual Y coordinate for display DC
numBufffers - Number of display buffers requested
stereo      - True if stereo should be enabled
refreshRate - Refresh rate to set for the mode

RETURNS:
True on success, false on failure.

REMARKS:
Attempts to initialize the low level device driver. If this is a display
device driver, it will start the specified graphics mode. If this is
a memory device driver, it will allocate the memory for the display surface.
First we allocate all resources for the device driver, and then intialise it
to fill in the device context vector tables.
{secret}
****************************************************************************/
ibool _MGL_initDC(
    MGLDC *dc,
    driverent *driver,
    modeent *mode,
    MGL_HWND hwnd,
    int virtualX,
    int virtualY,
    int numBuffers,
    ibool stereo,
    int refreshRate)
{
    /* Check to ensure that the driver was actually found. If the driver
     * was not registered, then we need to catch this.
     */
    __MGL_result = grOK;
    if (!driver->driver) {
        LOGFATAL("Driver not registered!");
        return false;
        }

    /* Initialise the driver and set the graphics mode */
    if (!driver->driver->initDriver(driver->data,dc,mode,(ulong)hwnd,virtualX,
            virtualY,numBuffers,stereo,refreshRate,__MGL_useLinearBlits)) {
        __MGL_result = grNoModeSupport;
        return false;
        }

    /* Initialise internal dimensions */
    if (dc->bounds.right == 0) {
        dc->bounds.left = 0;
        dc->bounds.top = 0;
        dc->bounds.right = dc->mi.xRes+1;
        dc->bounds.bottom = dc->mi.yRes+1;
        dc->size = dc->bounds;
        }

    /* Initialise the default window manager clip rectangles to full size
     * unless the driver has already started a clip list for windowed context.
     */
    if (MGL_emptyRect(dc->visRectWin))
        dc->visRectWin = dc->size;
    dc->visRectWM = dc->visRectWin;

    /* Allocate color lookup table cache - make sure it is cleared */
    if ((dc->colorTab = PM_calloc(1,sizeof(color_t) * 256)) == NULL) {
        __MGL_result = grNoMem;
        return false;
        }

    /* Initialise the default palette */
    if (dc->deviceType != MGL_MEMORY_DEVICE) {
        MGL_setDefaultPalette(dc);
        MGL_realizePalette(dc,MGL_getPaletteSize(dc),0,false);
        }
    MGL_defaultAttributes(dc);
    return __MGL_result == grOK;
}
Example #13
0
/// Returns the number of times the operation has been rescheduled (if any). An operation
/// implementation may use this to determine whether to reschedule itself rather than rely
/// on the timeouts.
///
/// @return zero if the operation has not been rescheduled, otherwise the number of times.
int CAsynchronous::COperation::WasRescheduled () const {
	if (m_nMustReschedule == 0) {
		return 0;
	} else if (m_nMustReschedule < 0) {
		return -m_nMustReschedule;
	} else {
		LOGFATAL ("WasRescheduled cannot be called after MustReschedule");
		return 0;
	}
}
Example #14
0
// This must only be called from the thread that creates and connects the pipes. This then
// doesn't need to acquire the pipe semaphore as the object won't be modified concurrently.
// Another thread might be sending, but that's it.
bool CClientService::DispatchAndRelease (FudgeMsgEnvelope env) {
	FudgeMsg msg = FudgeMsgEnvelope_getMessage (env);
	switch (FudgeMsgEnvelope_getDirectives (env)) {
	case MESSAGE_DIRECTIVES_CLIENT : {
		Operation op;
		if (ConnectorMessage_getOperation (msg, &op) == FUDGE_OK) {
			switch (op) {
			case HEARTBEAT :
				LOGDEBUG (TEXT ("Heartbeat received"));
				break;
			case POISON :
				// This shouldn't be sent by the Java stack
				LOGFATAL (TEXT ("Received poison from Java framework"));
				assert (0);
				break;
			case STASH : {
				FudgeMsg msgStash;
				if (ConnectorMessage_getStash (msg, &msgStash) == FUDGE_OK) {
					LOGDEBUG (TEXT ("Storing stash message"));
					m_oStateMutex.Enter ();
					if (m_poRunner) {
						m_poRunner->SetStash (msgStash);
					} else {
						LOGWARN (TEXT ("No runner thread"));
					}
					m_oStateMutex.Leave ();
					FudgeMsg_release (msgStash);
				} else {
					LOGWARN (TEXT ("No stash message attached"));
				}
				break;
						 }
			default :
				LOGWARN (TEXT ("Invalid client message - operation ") << op);
				break;
			}
		} else {
			LOGWARN (TEXT ("Invalid client message"));
		}
		break;
										}
	case MESSAGE_DIRECTIVES_USER :
		m_oMessageReceivedMutex.Enter ();
		if (m_poMessageReceivedCallback) {
			m_poMessageReceivedCallback->OnMessageReceived (msg);
		}
		m_oMessageReceivedMutex.Leave ();
		break;
	default :
		LOGWARN (TEXT ("Unknown message delivery directive ") << FudgeMsgEnvelope_getDirectives (env));
		break;
	}
	FudgeMsgEnvelope_release (env);
	return m_poPipes->IsConnected ();
}
Example #15
0
CClientService::~CClientService () {
	if (!Stop ()) {
		LOGFATAL (TEXT ("Couldn't stop running service"));
		assert (0);
	}
	if (m_poPipes) {
		LOGFATAL (TEXT ("Pipes exist at shutdown"));
		delete m_poPipes;
		assert (0);
	}
	if (m_poRunner) {
		LOGFATAL (TEXT ("Runner thread exists at shutdown"));
		CThread::Release (m_poRunner);
		assert (0);
	}
	if (m_poJVM) {
		delete m_poJVM;
	}
	delete (m_pszLanguageID);
}
Example #16
0
/// Destroys a synchronous call manager.
CSynchronousCalls::~CSynchronousCalls () {
    if (m_nFreeSlots != m_nAllocatedSlots) {
        LOGFATAL (TEXT ("Not all slots released at destruction (") << (m_nAllocatedSlots - m_nFreeSlots) << TEXT (" outstanding"));
        assert (0);
    }
    int i;
    for (i = 0; i < m_nAllocatedSlots; i++) {
        delete m_ppoSlots[i];
    }
    delete m_ppoSlots;
    delete m_ppoFreeSlots;
}
Example #17
0
/**
 * Deletes a ebtables rule specified in the argument.
 *
 * @param ebth [in] pointer to the EB table handler structure
 * @param tablename [in] a string pointer to the table name
 * @param chainname [in] a string pointer to the chain name
 * @param findrule [in] a string pointer to the rule to be deleted
 *
 * @return 0 if the rule given in the argument is successfully deleted. 1 otherwise.
 */
int ebt_chain_flush_rule(ebt_handler *ebth, char *tablename, char *chainname, char *findrule) {
    ebt_table *table = NULL;
    ebt_chain *chain = NULL;
    ebt_rule *rule = NULL;
    ebt_rule *newrules = NULL;
    int i;
    int nridx;

    if (!ebth || !tablename || !chainname || !findrule || !ebth->init) {
        return (EUCA_INVALID_ERROR);
    }

    table = ebt_handler_find_table(ebth, tablename);
    if (!table) {
        return (EUCA_INVALID_ERROR);
    }

    chain = ebt_table_find_chain(ebth, tablename, chainname);
    if (!chain) {
        return (EUCA_INVALID_ERROR);
    }

    rule = ebt_chain_find_rule(ebth, tablename, chainname, findrule);
    if (rule) {
        if (chain->max_rules > 1) {
            newrules = realloc(newrules, sizeof (ebt_rule) * (chain->max_rules - 1));
            if (!newrules) {
                LOGFATAL("out of memory!\n");
                exit(1);
            }

            bzero(newrules, sizeof (ebt_rule) * (chain->max_rules - 1));
            nridx = 0;
            for (i = 0; i < chain->max_rules; i++) {
                if (strcmp(chain->rules[i].ebtrule, findrule)) {
                    snprintf(newrules[nridx].ebtrule, 1024, "%s", chain->rules[i].ebtrule);
                    nridx++;
                }
            }
            EUCA_FREE(chain->rules);
            chain->rules = newrules;
            chain->max_rules = nridx;
        } else {
            EUCA_FREE(chain->rules);
            chain->max_rules = 0;
            chain->counters[0] = '\0';
        }
    } else {
        LOGDEBUG("Could not find (%s) from chain %s at table %s\n", findrule, chainname, tablename);
        return (2);
    }
    return (0);
}
//!
//! Function description.
//!
//! @param[in] file
//!
//! @return
//!
//! @see
//!
//! @pre List of pre-conditions
//!
//! @post List of post conditions
//!
//! @note
//!
int atomic_file_sort_tmpfile(atomic_file * file)
{
    int currlines = 0;
    int i = 0;
    int fd = 0;
    int ret = 0;
    char **contents = NULL;
    char buf[4096] = "";
    char tmpfile[EUCA_MAX_PATH] = "";
    FILE *IFH = NULL;
    FILE *OFH = NULL;

    snprintf(tmpfile, EUCA_MAX_PATH, "%s-XXXXXX", file->dest);
    if ((fd = safe_mkstemp(tmpfile)) < 0) {
        LOGERROR("cannot open tmpfile '%s': check permissions\n", tmpfile);
        return (1);
    }
    if (chmod(tmpfile, 0600)) {
        LOGWARN("chmod failed: was able to create tmpfile '%s', but could not change file permissions\n", tmpfile);
    }
    close(fd);

    buf[0] = '\0';
    if ((IFH = fopen(file->tmpfile, "r")) != NULL) {
        while (fgets(buf, 4096, IFH)) {
            currlines++;
            if ((contents = realloc(contents, sizeof(char *) * currlines)) == NULL) {
                LOGFATAL("out of memory!\n");
                exit(1);
            }
            contents[currlines - 1] = strdup(buf);
        }
        fclose(IFH);

        if (contents) {
            qsort(contents, currlines, sizeof(char *), strcmp_ptr);
            if ((OFH = fopen(tmpfile, "w")) != NULL) {
                for (i = 0; i < currlines; i++) {
                    fprintf(OFH, "%s", contents[i]);
                    EUCA_FREE(contents[i]);
                }
                fclose(OFH);
                if (rename(tmpfile, file->tmpfile)) {
                    LOGERROR("could not rename (move) source file '%s' to dest file '%s': check permissions\n", tmpfile, file->tmpfile);
                    ret = 1;
                }
            }
            EUCA_FREE(contents);
        }
    }

    return (ret);
}
Example #19
0
const TCHAR *CAbstractSettings::CachePut (const TCHAR *pszKey, const TCHAR *pszValue) {
	struct _setting *pCache = new struct _setting;
	if (!pCache) {
		LOGFATAL (TEXT ("Out of memory"));
		return NULL;
	} else {
		pCache->pszKey = _tcsdup (pszKey);
		pCache->pszValue = _tcsdup (pszValue);
		pCache->pNext = m_pCache;
		m_pCache = pCache;
		return pCache->pszValue;
	}
}
Example #20
0
/// Finds an existing message entry in the map, or creates a new entry if none is found.
/// The message is returned with an incremented reference count - the caller should call
/// Release when finished with it (unless the reference is offloaded to R).
///
/// @param[in] pData the binary encoding of the message to lock up
/// @param[in] cbData the length of the binary encoding in bytes
CFudgeMsgInfo *CFudgeMsgInfo::GetMessage (const void *pData, size_t cbData) {
	g_oMutex.Enter ();
	FudgeMsg msg = NULL;
	CFudgeMsgInfo *poMessage = NULL;
	void *pDataCopy = NULL;
	do {
		msg = _DecodeFudgeMsg (pData, cbData);
		if (!msg) {
			break;
		}
		TFudgeMsgMap::const_iterator itr = g_oMap.find (msg);
		if (itr != g_oMap.end ()) {
			poMessage = itr->second;
			poMessage->m_nRefCount++;
			break;
		}
		pDataCopy = malloc (cbData);
		if (!pDataCopy) {
			LOGFATAL (TEXT ("Out of memory"));
			break;
		}
		memcpy (pDataCopy, pData, cbData);
		poMessage = new CFudgeMsgInfo (msg, pDataCopy, cbData);
		if (!poMessage) {
			LOGFATAL (TEXT ("Out of memory"));
			break;
		}
		LOGDEBUG (TEXT ("Adding message to map (size = ") << (g_oMap.size () + 1) << TEXT (")"));
		g_oMap.insert (TFudgeMsgMap::value_type (msg, poMessage));
		g_cbData += cbData + MESSAGE_INFO_OVERHEAD;
		pDataCopy = NULL;
	} while (false);
	g_oMutex.Leave ();
	if (msg) FudgeMsg_release (msg);
	if (pDataCopy) free (pDataCopy);
	return poMessage;
}
Example #21
0
//!
//! Function description.
//!
//! @param[in] file
//!
//! @return
//!
//! @see
//!
//! @pre List of pre-conditions
//!
//! @post List of post conditions
//!
//! @note
//!
int atomic_file_sort_tmpfile(atomic_file * file)
{
    int cmp = 0;
    int currlines = 0;
    int i = 0;
    int fd = 0;
    int ret = 0;
    char **contents = NULL;
    char buf[4096] = "";
    char tmpfile[MAX_PATH] = "";
    FILE *IFH = NULL;
    FILE *OFH = NULL;

    snprintf(tmpfile, MAX_PATH, "%s-XXXXXX", file->dest);
    if ((fd = safe_mkstemp(tmpfile)) < 0) {
        LOGERROR("cannot open tmpfile '%s'\n", tmpfile);
        return (1);
    }
    chmod(tmpfile, 0644);
    close(fd);

    buf[0] = '\0';
    if ((IFH = fopen(file->tmpfile, "r")) != NULL) {
        while (fgets(buf, 4096, IFH)) {
            currlines++;
            if ((contents = realloc(contents, sizeof(char *) * currlines)) == NULL) {
                LOGFATAL("out of memory!\n");
                exit(1);
            }
            contents[currlines - 1] = strdup(buf);
        }
        fclose(IFH);

        if (contents) {
            qsort(contents, currlines, sizeof(char *), strcmp_ptr);
            if ((OFH = fopen(tmpfile, "w")) != NULL) {
                for (i = 0; i < currlines; i++) {
                    fprintf(OFH, "%s", contents[i]);
                    EUCA_FREE(contents[i]);
                }
                fclose(OFH);
                rename(tmpfile, file->tmpfile);
            }
            EUCA_FREE(contents);
        }
    }

    return (ret);
}
Example #22
0
/// Returns the current handle to use for the slot. Handles are a composition of the identifier and sequence counter. Lower
/// identifier numbers allow more bits for sequence values allowing better detection of messaging errors. The high order
/// bits are a header that indicates the bit lengths used.
///
/// @return the current handle
fudge_i32 CSynchronousCallSlot::GetHandle () const {
    if (m_nIdentifier >= 0) {
        int nSequence = m_oSequence.Get ();
#ifdef _DEBUG
        if (!(nSequence & 0x07FF)) {
            LOGINFO (TEXT ("Sequence ") << nSequence << TEXT (" on slot ") << m_nIdentifier);
        }
#endif /* ifdef _DEBUG */
        if (m_nIdentifier < 0x400) { // 10-bit identifiers, 19-bit sequences
            return 0x20000000 | (m_nIdentifier << 19) | (nSequence & 0x7FFFF);
        } else if (m_nIdentifier < 0x10000) { // 16-bit identifiers, 14-bit sequences
            return 0x40000000 | (m_nIdentifier << 14) | (nSequence & 0x3FFF);
        } else if (m_nIdentifier < 0x100000) { // 20-bit identifiers, 11-bit sequences
            return 0x80000000 | (m_nIdentifier << 20) | (nSequence & 0x7FF);
        } else {
            LOGFATAL (TEXT ("Identifier too large, ") << m_nIdentifier);
            assert (0);
        }
    } else {
        LOGFATAL (TEXT ("Identifier negative, ") << m_nIdentifier);
        assert (0);
    }
    return 0;
}
Example #23
0
/// Creates a description of the service for registering with the service control
/// manager.
///
/// @return the table
static SERVICE_TABLE_ENTRY *_CreateDispatchTable () {
	CSettings oSettings;
	PCTSTR pszServiceName = oSettings.GetServiceName ();
	size_t cchServiceName = _tcslen (pszServiceName);
	SERVICE_TABLE_ENTRY *pEntry = (SERVICE_TABLE_ENTRY*)malloc (sizeof (SERVICE_TABLE_ENTRY) * 2 + (cchServiceName + 1) * sizeof (TCHAR));
	if (!pEntry) {
		LOGFATAL (TEXT ("Out of memory"));
		return NULL;
	}
	memcpy (pEntry[0].lpServiceName = (PTSTR)(pEntry + 1), pszServiceName, cchServiceName * sizeof (TCHAR));
	pEntry[0].lpServiceProc = ServiceMain;
	pEntry[1].lpServiceName = NULL;
	pEntry[1].lpServiceProc = NULL;
	return pEntry;
}
Example #24
0
	/// Tests if the library is "happy" or not. I.e. did the call to R_init_OpenGamma do
	/// as it should have done.
	SEXP RPROC DllMain_check0 () {
		SEXP result = allocVector (LGLSXP, 1);
		if (result != R_NilValue) {
			if (g_poFunctions && g_poLiveData && g_poProcedures) {
				LOGINFO (TEXT ("Library initialised ok"));
				INTEGER (result)[0] = 1;
			} else {
				LOGWARN (TEXT ("Library failed to initialise"));
				INTEGER (result)[0] = 0;
			}
		} else {
			LOGFATAL (ERR_R_FUNCTION);
		}
		return result;
	}
Example #25
0
/**
 * Inserts rule newrule to chain chainname in table tablename with counter counterstr
 * in the position dictated by order.
 *
 * @param ipth [in] pointer to the IP table handler structure
 * @param tablename [in] a string pointer to the table name
 * @param chainname [in] a string pointer to the chain name
 * @param newrule [in] a string pointer to the new rule
 * @param counterstr [in] a string pointer to the counters
 * @param order [in] the order in which to insert this rule
 *
 * @return 0 on success or 1 if any failure occurred
 */
int ipt_chain_insert_rule(ipt_handler *ipth, char *tablename, char *chainname, char *newrule, char *counterstr, int order) {
    int ret = 0;
    ipt_table *table = NULL;
    ipt_chain *chain = NULL;
    ipt_rule *rule = NULL;

    if (!ipth || !tablename || !chainname || !newrule || !ipth->init) {
        return (1);
    }

    table = ipt_handler_find_table(ipth, tablename);
    if (!table) {
        return (1);
    }

    chain = ipt_table_find_chain(ipth, tablename, chainname);
    if (!chain) {
        return (1);
    }

    rule = ipt_chain_find_rule(ipth, tablename, chainname, newrule);
    if (!rule) {
        chain->rules = realloc(chain->rules, sizeof(ipt_rule) * (chain->max_rules + 1));
        if (!chain->rules) {
            LOGFATAL("out of memory!\n");
            exit(1);
        }
        rule = &(chain->rules[chain->max_rules]);
        bzero(rule, sizeof(ipt_rule));
        snprintf(rule->iptrule, 1024, "%s", newrule);
        snprintf(rule->counterstr, 256, "[0:0]");
        chain->max_rules++;
    }
    if (counterstr && strlen(counterstr)) {
        snprintf(rule->counterstr, 256, "%s", counterstr);
    }
    chain->ruleorder++;
    if (order == IPT_ORDER) {
        rule->order = chain->ruleorder;
    } else if (order == IPT_NO_ORDER) {
        rule->order = INT_MAX;
    } else {
        LOGERROR("BUG: invalid ordering mode passed to routine\n");
    }

    rule->flushed = 0;
    return (ret);
}
Example #26
0
SEXP RExternalRef::Create (SEXP value, SEXP destructor) {
	if (TYPEOF (destructor) != STRSXP) {
		LOGERROR (ERR_PARAMETER_TYPE);
		return R_NilValue;
	}
	char *pszDestructor = strdup (CHAR (STRING_ELT (destructor, 0)));
	if (!pszDestructor) {
		LOGFATAL (ERR_MEMORY);
		return R_NilValue;
	}
	SEXP externalref = R_MakeExternalPtr (pszDestructor, R_NilValue, value);
	PROTECT (externalref);
	R_RegisterCFinalizerEx (externalref, ExternalRef_finalizer, FALSE);
	UNPROTECT (1);
	return externalref;
}
/// Writes a feedback entry to the mechanism.
///
/// @param[in] pszMessage the string to write
void CErrorFeedback::Write (const TCHAR *pszMessage) {
	LOGERROR (TEXT ("A major error occurred"));
	TCHAR *psz = _tcsdup (pszMessage);
	if (psz) {
		// TODO: Implement this as writing to a file in a known location perhaps. The caller will already have
		// logged suitable messages, so we only need to report at DEBUG level.
		TCHAR *pszNext;
		TCHAR *pszLine = _tcstok_s (psz, TEXT ("\n"), &pszNext);
		while (pszLine) {
			LOGWARN (TEXT (">> ") << pszLine);
			pszLine = _tcstok_s (NULL, TEXT ("\n"), &pszNext);
		}
		free (psz);
	} else {
		LOGFATAL (TEXT ("Out of memory"));
	}
}
Example #28
0
/// Creates a new shared string.
///
/// @param[in] pszString string value
/// @return the shared string
PRCSTRING StringCreate (const TCHAR *pszString) {
	if (!pszString) {
		LOGWARN (TEXT ("Create called on NULL pointer"));
		return NULL;
	}
	size_t len = _tcslen (pszString);
	// Note the [1] in the structure will contain the room for the trailing zero, so only need len characters extra
	PRCSTRING pstr = (PRCSTRING)xmalloc (sizeof (RCSTRING) + len * sizeof (TCHAR));
	if (!pstr) {
		LOGFATAL (TEXT ("Out of memory"));
		return NULL;
	}
	pstr->nCount = 1;
	memcpy (pstr->szString, pszString, (len + 1) * sizeof (TCHAR));
	LOGDEBUG (TEXT ("Allocated string '") << pstr->szString << TEXT ("'"));
	return pstr;
}
Example #29
0
/// Program entry point. If invoked from the command line with parameter "run" will run the service. If
/// invoked from the service control manager will register the service handlers and then start the service
/// dispatch logic.
///
/// @param[in] argc number of parameters
/// @param[in] argv parameters
int _tmain (int argc, _TCHAR* argv[]) {
#ifdef _WIN32
#ifndef _DEBUG
    fclose (stderr);
    FreeConsole ();
#endif /*ifndef _DEBUG */
#endif /* ifdef _WIN32 */
    _mainStart ();
    if (argc == 2) {
        if (!_tcscmp (argv[1], TEXT ("run"))) {
            LOGDEBUG (TEXT ("Running inline"));
            ServiceRun (SERVICE_RUN_INLINE);
        } else if (!_tcscmp (argv[1], TEXT ("configure"))) {
            SHELLEXECUTEINFO sei;
            ZeroMemory (&sei, sizeof (sei));
            sei.cbSize = sizeof (sei);
            sei.fMask = SEE_MASK_NOCLOSEPROCESS;
            sei.lpVerb = TEXT ("runas");
            sei.lpFile = argv[0];
            sei.lpParameters = TEXT ("configure-impl");
            if (ShellExecuteEx (&sei)) {
                LOGINFO (TEXT ("Started priviledged process ") << GetProcessId (sei.hProcess));
                WaitForSingleObject (sei.hProcess, INFINITE);
                LOGINFO (TEXT ("Priviledged process terminated"));
                CloseHandle (sei.hProcess);
            } else {
                LOGERROR (TEXT ("Couldn't launch priviledged form"));
            }
        } else if (!_tcscmp (argv[1], TEXT ("configure-impl"))) {
            LOGDEBUG (TEXT ("Configuring service"));
            ServiceConfigure ();
        } else {
            LOGERROR (TEXT ("Unrecognised parameter - ") << argv[1]);
        }
    } else {
        LOGDEBUG (TEXT ("Running as service"));
        SERVICE_TABLE_ENTRY *pServiceEntry = _CreateDispatchTable ();
        if (!StartServiceCtrlDispatcher (pServiceEntry)) {
            LOGFATAL (TEXT ("Couldn't start service control dispatcher, error ") << GetLastError ());
        }
        delete pServiceEntry;
    }
    _mainEnd ();
    return 0;
}
Example #30
0
bool CClientService::CreatePipes () {
	LOGINFO (TEXT ("Creating pipes"));
	m_oPipesSemaphore.Wait ();
	if (m_poPipes) {
		m_oPipesSemaphore.Signal ();
		LOGFATAL (TEXT ("Pipes already created"));
		assert (0);
		return false;
	}
	m_poPipes = CClientPipes::Create ();
	if (m_poPipes) {
		m_oPipesSemaphore.Signal ();
		return true;
	} else {
		m_oPipesSemaphore.Signal ();
		LOGWARN (TEXT ("Couldn't create pipes, error ") << GetLastError ());
		return false;
	}
}