Exemple #1
0
static int tss_err_pwd(TSS_RESULT err, int pwd_error)
{
	_gnutls_debug_log("TPM (%s) error: %s (%x)\n",
			  Trspi_Error_Layer(err), Trspi_Error_String(err),
			  (unsigned int) Trspi_Error_Code(err));

	switch (ERROR_LAYER(err)) {
	case TSS_LAYER_TPM:
		switch (ERROR_CODE(err)) {
		case TPM_E_AUTHFAIL:
			return pwd_error;
		case TPM_E_NOSRK:
			return GNUTLS_E_TPM_UNINITIALIZED;
		default:
			return gnutls_assert_val(GNUTLS_E_TPM_ERROR);
		}
	case TSS_LAYER_TCS:
	case TSS_LAYER_TSP:
		switch (ERROR_CODE(err)) {
		case TSS_E_COMM_FAILURE:
		case TSS_E_NO_CONNECTION:
		case TSS_E_CONNECTION_FAILED:
		case TSS_E_CONNECTION_BROKEN:
			return GNUTLS_E_TPM_SESSION_ERROR;
		case TSS_E_PS_KEY_NOTFOUND:
			return GNUTLS_E_TPM_KEY_NOT_FOUND;
		default:
			return gnutls_assert_val(GNUTLS_E_TPM_ERROR);
		}
	default:
		return gnutls_assert_val(GNUTLS_E_TPM_ERROR);
	}
}
Exemple #2
0
unsigned int flat1_gethdr(void)
{
	struct flathdr1 hdr;

	if (flat_seek(0L, SEEK_SET) != 0L)
		return ERROR_CODE();
	if (flat_read(&hdr, sizeof(hdr)) != sizeof(hdr))
		return ERROR_CODE();
        return hdr.magic;
}
Exemple #3
0
int flat1_checkfs(void)
{
	struct flathdr1 hdr;
	unsigned int len, size, sum;
	unsigned char buf[BUF_SIZE];
	unsigned int n = 0;

	if (flat_seek(0L, SEEK_SET) != 0L)
		return ERROR_CODE();

	/* Check that header is a valid version 1/2 header */
	if (flat_read(&hdr, sizeof(hdr)) != sizeof(hdr))
		return ERROR_CODE();

	if ((hdr.magic != FLATFS_MAGIC) && (hdr.magic != FLATFS_MAGIC_V2))
		return ERROR_CODE();

	len = flat_dev_length();

	/* XXX - mn
	 * We calculate the checksum wrongly here.
	 *
	 * The trick to the bug is that size != position in file,  since the
	 * first time through we read size==sizeof(hdr),  but increment size by
	 * sizeof(buf).
	 *
	 * Because sizeof(hdr) == 8 and sizeof(buf) == 1024,  we end up not
	 * including the last 1008 bytes, since we start reading 1024 bytes
	 * chunks from position 16.
	 */
	for (sum = 0, size = sizeof(hdr); (size < len); size += sizeof(buf)) {
		n = (size > sizeof(buf)) ? sizeof(buf) :  size;
		if (flat_read(&buf[0], n) != n)
			return ERROR_CODE();
		sum += chksum(&buf[0], n);
	}

#ifdef DEBUG
	syslog(LOG_DEBUG, "flat_checkfs() calculated checksum over %d "
		"bytes = %u", len, sum);
#endif

	if (sum != hdr.chksum) {
		syslog(LOG_ERR, "bad header checksum");
		return ERROR_CODE();
	}

	return 0;
}
Exemple #4
0
void Server::PostSend(Client* client, Packet* packet)
{
    assert(client);
    assert(packet);

    WSABUF recvBufferDescriptor;
    recvBufferDescriptor.buf = reinterpret_cast<char*>(packet->GetData());
    recvBufferDescriptor.len = packet->GetSize();

    DWORD sendFlags = 0;

    IOEvent* event = IOEvent::Create(IOEvent::SEND, client, packet);
    assert(event);

    StartThreadpoolIo(client->GetTPIO());

    if (WSASend(client->GetSocket(), &recvBufferDescriptor, 1, NULL, sendFlags,
                &event->GetOverlapped(), NULL) == SOCKET_ERROR)
    {
        int error = WSAGetLastError();

        if (error != ERROR_IO_PENDING)
        {
            CancelThreadpoolIo(client->GetTPIO());

            ERROR_CODE(error, "WSASend() failed.");

            RemoveClient(client);
        }
    }
    else
    {
        // In this case, the completion callback will have already been scheduled to be called.
    }
}
Exemple #5
0
void Server::OnRecv(IOEvent* event, DWORD dwNumberOfBytesTransfered)
{
    assert(event);

    TRACE("[%d] Enter OnRecv()", GetCurrentThreadId());

    BYTE* buff = event->GetClient()->GetRecvBuff();
    buff[dwNumberOfBytesTransfered] = '\0';
    TRACE("[%d] OnRecv : %s", GetCurrentThreadId(), buff);

    // Create packet by copying recv buff.
    Packet* packet = Packet::Create(event->GetClient(), event->GetClient()->GetRecvBuff(),
                                    dwNumberOfBytesTransfered);

    // If whatever logics relying on the packet are fast enough, we can manage them here but
    // assume they are slow.
    // it's better to request receiving ASAP and handle packets received in another thread.
    if (!TrySubmitThreadpoolCallback(Server::WorkerProcessRecvPacket, packet, NULL))
    {
        ERROR_CODE(GetLastError(), "Could not start WorkerProcessRecvPacket. call it directly.");

        Echo(packet);
    }

    PostRecv(event->GetClient());

    TRACE("[%d] Leave OnRecv()", GetCurrentThreadId());
}
void Server::OnAccept(PollingSocket* listenSocket)
{
	SOCKET socket = accept(mListenSocket.GetSocket(), NULL, NULL);

    if (socket == INVALID_SOCKET) 
	{
		assert(WSAEWOULDBLOCK != WSAGetLastError());
		ERROR_CODE(WSAGetLastError(), "Server::OnAccept() - failed");
		mListenSocket.Shutdown();
		return;
	}

	PollingSocket* newClient = new PollingSocket;
	PollingSocket::OnRecvFunc onRecv = boost::bind(&Server::OnRecv, this, _1, _2, _3);
	PollingSocket::OnCloseFunc onClose = boost::bind(&Server::OnClose, this, _1);

	newClient->InitAccept(socket, onRecv, onClose);

	mClientSockets.push_back(newClient);

	std::string address;
	unsigned short port;
	Network::GetRemoteAddress(socket, address, port);
	LOG("Server::OnAccept() - client [%s:%d]", address.c_str(), port);
}
static void JNIThrowOnError(JNIEnv *env, RBook::Error error) {
    switch (ERROR_CODE(error)) {
    case RBook::ERROR_OK:
        break;
    case RBook::RoadBook::ERROR_MAL_FORMATTED_BOOK:
    case RBook::RoadBook::ERROR_CANNOT_SAVE:
    case RBook::RoadBook::ERROR_BOOK_NOT_FOUND:
    case RBook::FileUtils::ERROR_DIR_NOT_FOUND:
    case RBook::FileUtils::ERROR_FILE_NOT_FOUND:
        LOG_E(TAG, "java/io/IOException");
        JNIThrowException(env, "java/io/IOException", NULL);
        break;
    case RBook::BookManager::ERROR_ROADBOOK_EXISTS:
        LOG_E(TAG, "java/lang/IllegalArgumentException");
        JNIThrowException(env, "java/lang/IllegalArgumentException", NULL);
        break;
    case RBook::RoadBook::ERROR_EMPTY_LIST:
    case RBook::BookManager::ERROR_EMPTY_LIST:
    case RBook::BookManager::ERROR_BOOKNAME_NOT_FOUND:
        LOG_E(TAG, "java/lang/IndexOutOfBoundsException");
        JNIThrowException(env, "java/lang/IndexOutOfBoundsException", NULL);
        break;
    default:
        LOG_E(TAG, "java/lang/RuntimeException");
        JNIThrowException(env, "java/lang/RuntimeException", "unknown error");
        break;
    }
}
Exemple #8
0
void Server::AddClient(Client* client)
{
    assert(client);

    // The socket sAcceptSocket does not inherit the properties of the socket associated with
    // sListenSocket parameter until SO_UPDATE_ACCEPT_CONTEXT is set on the socket.
    if (setsockopt(client->GetSocket(), SOL_SOCKET, SO_UPDATE_ACCEPT_CONTEXT,
                   reinterpret_cast<const char*>(&m_listenSocket),
                   sizeof(m_listenSocket)) == SOCKET_ERROR)
    {
        ERROR_CODE(WSAGetLastError(), "setsockopt() for AcceptEx() failed.");

        RemoveClient(client);
    }
    else
    {
        client->SetState(Client::ACCEPTED);

        // Connect the socket to IOCP
        TP_IO* pTPIO = CreateThreadpoolIo(reinterpret_cast<HANDLE>(client->GetSocket()),
                                          Server::IoCompletionCallback, NULL, NULL);
        if (pTPIO == NULL)
        {
            ERROR_CODE(GetLastError(), "CreateThreadpoolIo failed for a client.");

            RemoveClient(client);
        }
        else
        {
            std::string ip;
            u_short port = 0;
            Network::GetRemoteAddress(client->GetSocket(), ip, port);
            TRACE("[%d] Accept succeeded. client address : ip[%s], port[%d]", GetCurrentThreadId(),
                  ip.c_str(), port);

            client->SetTPIO(pTPIO);

            EnterCriticalSection(&m_CSForClients);
            m_Clients.push_back(client);
            LeaveCriticalSection(&m_CSForClients);

            PostRecv(client);
        }
    }
}
Exemple #9
0
	void Cleanup()
	{
		EnterCriticalSection(&logCS);

		if(false == FreeLibrary(libModule))
		{
			ERROR_CODE(GetLastError(), "Log::CleanUp() - FreeLibrary() failed.");
		}

		DeleteCriticalSection(&logCS);
	}
Exemple #10
0
/* static */ void CALLBACK
Server::IoCompletionCallback(PTP_CALLBACK_INSTANCE /* Instance */, PVOID /* Context */,
                             PVOID Overlapped, ULONG IoResult, ULONG_PTR NumberOfBytesTransferred,
                             PTP_IO /* Io */)
{
    IOEvent* event = CONTAINING_RECORD(Overlapped, IOEvent, GetOverlapped());
    assert(event);

    if (IoResult != ERROR_SUCCESS)
    {
        ERROR_CODE(IoResult, "I/O operation failed. type[%d]", event->GetType());

        switch (event->GetType())
        {
        case IOEvent::SEND:
            Server::Instance()->OnSend(event, NumberOfBytesTransferred);
            break;
        }

        Server::Instance()->OnClose(event);
    }
    else
    {
        switch (event->GetType())
        {
        case IOEvent::ACCEPT:
            Server::Instance()->OnAccept(event);
            break;

        case IOEvent::RECV:
            if (NumberOfBytesTransferred > 0)
            {
                Server::Instance()->OnRecv(event, NumberOfBytesTransferred);
            }
            else
            {
                Server::Instance()->OnClose(event);
            }
            break;

        case IOEvent::SEND:
            Server::Instance()->OnSend(event, NumberOfBytesTransferred);
            break;

        default:
            assert(false);
            break;
        }
    }

    IOEvent::Destroy(event);
}
Exemple #11
0
LTRESULT dsi_SetupMessage(char *pMsg, int maxMsgLen, LTRESULT dResult, va_list marker) {
    int i;
    unsigned long resultCode, stringID;
    LTBOOL bFound;
    uint32 args[4], nBytes;
    char tempBuffer[500];

    pMsg[0] = 0;

    if (!g_hResourceModule) {
        LTSNPrintF(pMsg, maxMsgLen, "<missing resource DLL>");
        return LT_ERROR;
    }

    // Try to find the error code.
    bFound = LTFALSE;
    resultCode = ERROR_CODE(dResult);
    for (i=0; i < STRINGMAP_SIZE; i++) {
        if (g_StringMap[i].dResult == resultCode) {
            bFound = LTTRUE;
            stringID = g_StringMap[i].string_id;
            break;
        }
    }

    if (bFound) {
        nBytes = LoadString(g_hResourceModule, stringID, tempBuffer, sizeof(tempBuffer)-1);
        if (nBytes > 0) {
            // Format it.
            nBytes = FormatMessage(FORMAT_MESSAGE_FROM_STRING, tempBuffer, 0, 0, pMsg, maxMsgLen, &marker);

            if (nBytes > 0)
                return LT_OK;
        }
    }

    // Ok, format the default message.
    args[0] = resultCode;
    nBytes = FormatMessage(FORMAT_MESSAGE_FROM_HMODULE|FORMAT_MESSAGE_ARGUMENT_ARRAY,
        g_hResourceModule, IDS_GENERIC_ERROR, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
        pMsg, maxMsgLen, (va_list*)args);

    if (nBytes > 0) {
        return LT_OK;
    }
    else {
        LTSNPrintF(pMsg, maxMsgLen, "<invalid resource DLL>");
        return LT_ERROR;
    }
}
Exemple #12
0
void Server::OnClose(IOEvent* event)
{
    assert(event);

    TRACE("Client's socket has been closed.");

    // If whatever game logics about this event are fast enough, we can manage them here but I
    // assume they are slow.
    if (!m_ShuttingDown &&
        !TrySubmitThreadpoolCallback(Server::WorkerRemoveClient, event->GetClient(), &m_ClientTPENV))
    {
        ERROR_CODE(GetLastError(), "can't start WorkerRemoveClient. call it directly.");

        RemoveClient(event->GetClient());
    }
}
Exemple #13
0
void Server::PostAccept()
{
    // If the number of clients is too big, we can just stop posting accept.
    // That's one of the benefits from AcceptEx.
    int count = m_MaxPostAccept - m_NumPostAccept;
    if (count > 0)
    {
        int i = 0;
        for (; i < count; ++i)
        {
            Client* client = new Client();
            if (!client->Create())
            {
                delete client;
                break;
            }

            IOEvent* event = IOEvent::Create(IOEvent::ACCEPT, client);
            assert(event);

            StartThreadpoolIo(m_pTPIO);
            if (!Network::AcceptEx(m_listenSocket, client->GetSocket(), &event->GetOverlapped()))
            {
                int error = WSAGetLastError();

                if (error != ERROR_IO_PENDING)
                {
                    CancelThreadpoolIo(m_pTPIO);

                    ERROR_CODE(error, "AcceptEx() failed.");
                    delete client;
                    IOEvent::Destroy(event);
                    break;
                }
            }
            else
            {
                OnAccept(event);
                IOEvent::Destroy(event);
            }
        }

        InterlockedExchangeAdd(&m_NumPostAccept, i);

        TRACE("[%d] Post AcceptEx : %d", GetCurrentThreadId(), m_NumPostAccept);
    }
}
Exemple #14
0
void Server::OnAccept(IOEvent* event)
{
    assert(event);

    TRACE("[%d] Enter OnAccept()", GetCurrentThreadId());
    assert(event->GetType() == IOEvent::ACCEPT);

    // Check if we need to post more accept requests.
    InterlockedDecrement(&m_NumPostAccept);

    // Add client in a different thread.
    // It is because we need to return this function ASAP so that this IO worker thread can process
    // the other IO notifications.
    // If adding client is fast enough, we can call it here but I assume it's slow.
    if (!m_ShuttingDown &&
        !TrySubmitThreadpoolCallback(Server::WorkerAddClient, event->GetClient(), &m_ClientTPENV))
    {
        ERROR_CODE(GetLastError(), "Could not start WorkerAddClient.");

        AddClient(event->GetClient());
    }

    TRACE("[%d] Leave OnAccept()", GetCurrentThreadId());
}
Exemple #15
0
void Server::PostRecv(Client* client)
{
    assert(client);

    WSABUF recvBufferDescriptor;
    recvBufferDescriptor.buf = reinterpret_cast<char*>(client->GetRecvBuff());
    recvBufferDescriptor.len = Client::MAX_RECV_BUFFER;

    DWORD numberOfBytes = 0;
    DWORD recvFlags = 0;

    IOEvent* event = IOEvent::Create(IOEvent::RECV, client);
    assert(event);

    StartThreadpoolIo(client->GetTPIO());

    if (WSARecv(client->GetSocket(), &recvBufferDescriptor, 1, &numberOfBytes, &recvFlags,
                &event->GetOverlapped(), NULL) == SOCKET_ERROR)
    {
        int error = WSAGetLastError();

        if (error != ERROR_IO_PENDING)
        {
            CancelThreadpoolIo(client->GetTPIO());

            ERROR_CODE(error, "WSARecv() failed.");

            OnClose(event);
            IOEvent::Destroy(event);
        }
    }
    else
    {
        // In this case, the completion callback will have already been scheduled to be called.
    }
}
Exemple #16
0
bool Server::Create(short port, int maxPostAccept)
{
    assert(maxPostAccept > 0);

    m_MaxPostAccept = maxPostAccept;

    // Create Client Work Thread Env for using cleaning group. We need this for shutting down
    // properly.
    InitializeThreadpoolEnvironment(&m_ClientTPENV);
    m_ClientTPCLEAN = CreateThreadpoolCleanupGroup();
    if (m_ClientTPCLEAN == NULL)
    {
        ERROR_CODE(GetLastError(), "Could not create client cleaning group.");
        return false;
    }
    SetThreadpoolCallbackCleanupGroup(&m_ClientTPENV, m_ClientTPCLEAN, NULL);

    // Create Listen Socket
    m_listenSocket = Network::CreateSocket(true, port);
    if (m_listenSocket == INVALID_SOCKET)
    {
        return false;
    }

    // Make the address re-usable to re-run the same server instantly.
    bool reuseAddr = true;
    if (setsockopt(m_listenSocket, SOL_SOCKET, SO_REUSEADDR,
                   reinterpret_cast<const char*>(&reuseAddr), sizeof(reuseAddr)) == SOCKET_ERROR)
    {
        ERROR_CODE(WSAGetLastError(), "setsockopt() failed with SO_REUSEADDR.");
        Destroy();
        return false;
    }

    // Create & Start ThreaddPool for socket IO
    m_pTPIO = CreateThreadpoolIo(reinterpret_cast<HANDLE>(m_listenSocket),
                                 Server::IoCompletionCallback, NULL, NULL);
    if (m_pTPIO == NULL)
    {
        ERROR_CODE(WSAGetLastError(), "Could not assign the listen socket to the IOCP handle.");
        Destroy();
        return false;
    }

    // Start listening
    StartThreadpoolIo(m_pTPIO);
    if (listen(m_listenSocket, SOMAXCONN) == SOCKET_ERROR)
    {
        ERROR_CODE(WSAGetLastError(), "listen() failed.");
        return false;
    }

    // Create critical sections for m_Clients
    InitializeCriticalSection(&m_CSForClients);

    // Create Accept worker
    m_AcceptTPWORK = CreateThreadpoolWork(Server::WorkerPostAccept, this, NULL);
    if (m_AcceptTPWORK == NULL)
    {
        ERROR_CODE(GetLastError(), "Could not create AcceptEx worker TPIO.");
        Destroy();
        return false;
    }

    m_ShuttingDown = false;

    SubmitThreadpoolWork(m_AcceptTPWORK);

    return true;
}
Exemple #17
0
int flat_new(const char *dir)
{
	DIR *dirp;
	struct stat st;
	struct dirent *dp;
	unsigned int size, n;
	int fddefault, fdconfig;
	char filename[512];
	unsigned char buf[1024];

	if (chdir(dir) < 0)
		return ERROR_CODE();

	/* Scan directory */
	if ((dirp = opendir(".")) == NULL)
		return ERROR_CODE();

	numfiles = 0;
	numbytes = 0;
	numdropped = 0;

	while ((dp = readdir(dirp)) != NULL) {

		if ((strcmp(dp->d_name, ".") == 0) ||
		    (strcmp(dp->d_name, "..") == 0))
			continue;

		if (stat(dp->d_name, &st) < 0)
			return ERROR_CODE();

		strcpy(filename, SRCDIR);
		strcat(filename, "/");
		strcat(filename, dp->d_name);

		/* Write the contents of the file. */
		if ((fddefault = open(dp->d_name, O_RDONLY)) < 0)
			return ERROR_CODE();
		fdconfig = open(filename, O_WRONLY | O_TRUNC | O_CREAT, st.st_mode);
		if (fdconfig < 0)
			return ERROR_CODE();

		for (size = st.st_size; (size > 0); size -= n) {
			n = (size > sizeof(buf)) ? sizeof(buf) : size;
			if (read(fddefault, &buf[0], n) != n)
				break;
			if (write(fdconfig, (void *) &buf[0], n) != n)
				break;
		}
		close(fdconfig);
		close(fddefault);

		if (size > 0) {
			numdropped++;
		} else {
			numfiles++;
			numbytes += st.st_size;
		}
	}

	closedir(dirp);
	return 0;
}
Exemple #18
0
int flat1_restorefs(int version, int dowrite)
{
	unsigned int size, n = 0;
	struct flatent ent;
	char filename[128];
	unsigned char buf[BUF_SIZE];
	char *confbuf;
	mode_t mode;
	int fdfile, rc;

	if ((rc = flat1_checkfs()) != 0)
		return rc;

	/*
	 * Get back to the real data we want.
	 */
	if (flat_seek(sizeof(struct flathdr1), SEEK_SET) != sizeof(struct flathdr1))
		return ERROR_CODE();

	for (numfiles = 0, numbytes = 0; ; numfiles++) {
		/* Get the name of next file. */
		if (flat_read(&ent, sizeof(ent)) != sizeof(ent))
			return ERROR_CODE();

		if (ent.filelen == FLATFS_EOF)
			break;

		n = ((ent.namelen + 3) & ~0x3);
		if (n > sizeof(filename))
			return ERROR_CODE();

		if (flat_read(&filename[0], n) != n)
			return ERROR_CODE();

		if (version >= 2) {
			if (flat_read(&mode, sizeof(mode)) != sizeof(mode)) {
				flat_close(1, 0);
				return ERROR_CODE();
			}
		} else {
			mode = 0644;
		}

		if (strcmp(filename, FLATFSD_CONFIG) == 0) {
			/* Read our special flatfsd config file into memory */
			if (ent.filelen == 0) {
#ifndef HAS_RTC
				/* This file was not written correctly, so just ignore it */
				syslog(LOG_WARNING, "%s is zero length, ignoring", filename);
#endif
			}
			else if ((confbuf = malloc(ent.filelen)) == 0) {
				syslog(LOG_ERR, "Failed to allocate memory for %s -- ignoring it", filename);
			}
			else {
				if (flat_read(confbuf, ent.filelen) != ent.filelen) {
					free(confbuf);
					return ERROR_CODE();
				}

#ifndef HAS_RTC
				parseconfig(confbuf);
#endif
				free(confbuf);
			}
		} else {
			/* Write contents of file out for real. */
			fdfile = open(filename, (O_WRONLY | O_TRUNC | O_CREAT), mode);
			if (fdfile < 0)
				return ERROR_CODE();
			
			for (size = ent.filelen; (size > 0); size -= n) {
				n = (size > sizeof(buf)) ? sizeof(buf) : size;
				if (flat_read(&buf[0], n) != n)
					return ERROR_CODE();
				if (write(fdfile, (void *) &buf[0], n) != n)
					return ERROR_CODE();
			}

			close(fdfile);
		}

		/* Read alignment padding */
		n = ((ent.filelen + 3) & ~0x3) - ent.filelen;
		if (flat_read(&buf[0], n) != n)
			return ERROR_CODE();

		numbytes += ent.filelen;
	}

	return 0;
}
Exemple #19
0
static int writefile(char *name, unsigned int *ptotal, int dowrite)
{
	struct flatent ent;
	struct stat st;
	unsigned int size;
	int fdfile, zero = 0;
	mode_t mode;
	char buf[BUF_SIZE];
	int n, written;

	/*
	 * Write file entry into flat fs. Names and file
	 * contents are aligned on long word boundaries.
	 * They are padded to that length with zeros.
	 */
	if (stat(name, &st) < 0)
		return ERROR_CODE();

	size = strlen(name) + 1;
	if (size > 128) {
		numdropped++;
		return ERROR_CODE();
	}

	ent.namelen = size;
	ent.filelen = st.st_size;
	if (dowrite && flat_write(*ptotal, &ent, sizeof(ent)) < 0)
		return ERROR_CODE();
	*ptotal += sizeof(ent);

	/* Write file name out, with padding to align */
	if (dowrite && flat_write(*ptotal, name, size) < 0)
		return ERROR_CODE();
	*ptotal += size;
	size = ((size + 3) & ~0x3) - size;
	if (dowrite && flat_write(*ptotal, &zero, size) < 0)
		return ERROR_CODE();
	*ptotal += size;

	/* Write out the permissions */
	mode = (mode_t) st.st_mode;
	size = sizeof(mode);
	if (dowrite && flat_write(*ptotal, &mode, size) < 0)
		return ERROR_CODE();
	*ptotal += size;

	/* Write the contents of the file. */
	size = st.st_size;

	written = 0;

	if (size > 0) {
		if (dowrite) {
			if ((fdfile = open(name, O_RDONLY)) < 0)
				return ERROR_CODE();
			while (size>written) {
				int bytes_read;
				n = ((size-written) > sizeof(buf))?sizeof(buf):(size-written);
				if ((bytes_read = read(fdfile, buf, n)) != n) {
					/* Somebody must have trunced the file - Log it. */
					syslog(LOG_WARNING, "File %s was shorter than expected.",
						name);
					if (bytes_read <= 0)
						break;
				}
				if (dowrite && flat_write(*ptotal, buf, bytes_read) < 0) {
					close(fdfile);
					return (ERROR_CODE());
				}
				*ptotal += bytes_read;
				written += bytes_read;
			}
			if (lseek(fdfile, 0, SEEK_END) != written) {
				/* 
				 * Log the file being longer than expected.
				 * We can't write more than expected because
				 * the size is already written.
				 */
				syslog(LOG_WARNING, "File %s was longer than expected.", name);
			}
			close(fdfile);
		} else {
			*ptotal += st.st_size;
		}

		/* Pad to align */
		written = ((st.st_size + 3) & ~0x3) - st.st_size;
		if (dowrite && flat_write(*ptotal, &zero, written) < 0)
			return ERROR_CODE();
		*ptotal += written;
	}

	numfiles++;
	numbytes += ent.filelen;

	return 0;
}
Exemple #20
0
/*
 * Writes out the contents of all files.
 * Does not actually do the write if 'dowrite'
 * is not set. In this case, it just checks
 * to see that the config will fit.
 * The total length of data written (or simulated) is stored
 * in *total.
 * Does not remove .flatfsd
 *
 * Note that if the flash has been erased, aborting
 * early will just lose data. So we try to work around
 * problems as much as possible.
 *
 * Returns 0 if OK, or < 0 if error.
 */
int flat1_savefs(int dowrite, unsigned *total)
{
	struct flathdr1 hdr;
	struct flatent ent;
	struct dirent *dp;
	DIR *dirp;
	int rc, ret = 0;

#ifdef DEBUG
	syslog(LOG_DEBUG, "flat1_savefs(dowrite=%d)", dowrite);
#endif

	/* Lets go, erase the flash first */
	if ((rc = flat_erase()) < 0)
		return rc;

	/* Write out contents of all files, skip over header */
	numfiles = 0;
	numbytes = 0;
	numdropped = 0;
	*total = sizeof(hdr);

#ifndef HAS_RTC
	rc = writefile(FLATFSD_CONFIG, total, dowrite);
	if (rc < 0 && !ret)
		ret = rc;
#endif

	/* Scan directory */
	if ((dirp = opendir(".")) == NULL) {
		rc = ERROR_CODE();
		if (rc < 0 && !ret)
			ret = rc;
		/* Really nothing we can do at this point */
		return ret;
	}

	while ((dp = readdir(dirp)) != NULL) {

		if ((strcmp(dp->d_name, ".") == 0) ||
		    (strcmp(dp->d_name, "..") == 0) ||
		    (strcmp(dp->d_name, FLATFSD_CONFIG) == 0))
			continue;

		rc = writefile(dp->d_name, total, dowrite);
		if (rc < 0) {
			syslog(LOG_ERR, "Failed to write write file %s (%d): %m %d",
				dp->d_name, rc, errno);
			if (!ret)
				ret = rc;
		}
	}
	closedir(dirp);

	/* Write the terminating entry */
	if (dowrite) {
		ent.namelen = FLATFS_EOF;
		ent.filelen = FLATFS_EOF;
		rc = flat_write(*total, &ent, sizeof(ent));
		if (rc < 0 && !ret)
			ret = rc;
	}

	*total += sizeof(ent);

#ifdef USING_MTD_DEVICE
	/*
	 * We need to account for the fact that we checksum the entire device,
	 * not just the data we wrote. On MTD devices, this data is 0xFF.
	 */
	{
		int checksum_len = flat_dev_length() - (BUF_SIZE - (sizeof(struct flathdr1) * 2));

		flat_sum += 0xFFu * (checksum_len - *total);

#ifdef DEBUG
		syslog(LOG_DEBUG, "flat_savefs(): added %d 0xFF bytes to "
			"checksum -> flat_sum=%u",
			checksum_len - *total, flat_sum);
#endif
	}
#endif

	if (dowrite) {
		/* Construct header */
		hdr.magic = FLATFS_MAGIC_V2;
		hdr.chksum = flat_sum;

#ifdef DEBUG
		syslog(LOG_DEBUG, "flat_savefs(): final checksum=%u, total=%d",
			flat_sum, *total);
#endif

		rc = flat_write(0L, &hdr, sizeof(hdr));
		if (rc < 0 && !ret)
			ret = rc;
	}

#ifdef DEBUG
	syslog(LOG_DEBUG, "flat_savefs() returning ret=%d, total=%u", ret, *total);
#endif

	return ret;
}
Exemple #21
0
void NetworkError::initErrorCode()
{
	if(!Error_Codes.empty()) return;

#define ERROR_CODE(state, description) Error_Codes.insert(state, description);
	// {{{
	ERROR_CODE(QNetworkReply::NoError,                         "No error");
	ERROR_CODE(QNetworkReply::TimeoutError,                    "The connection to the remote server timed out.");
	ERROR_CODE(QNetworkReply::HostNotFoundError,               "The remote host name was not found (invalid hostname).");
	ERROR_CODE(QNetworkReply::ConnectionRefusedError,          "The remote server refused the connection (the server is not accepting requests).");
	ERROR_CODE(QNetworkReply::SslHandshakeFailedError,         "The SSL/TLS handshake failed and the encrypted channel could not be established.");
	ERROR_CODE(QNetworkReply::OperationCanceledError,          "The operation was canceled via calls to abort() or close() before it was finished.");
	ERROR_CODE(QNetworkReply::ProxyConnectionRefusedError,     "The connection to the proxy server was refused (the proxy server is not accepting requests).");
	ERROR_CODE(QNetworkReply::RemoteHostClosedError,           "The remote server closed the connection prematurely, before the entire reply was received and processed.");
	ERROR_CODE(QNetworkReply::TemporaryNetworkFailureError,    "The connection was broken due to disconnection from the network, however the system has initiated \
															   roaming to another access point. The request should be resubmitted and will be processed as soon as \
															   the connection is re-established.");
	ERROR_CODE(QNetworkReply::ProxyAuthenticationRequiredError, "The proxy requires authentication in order to honour the request but did not accept any credentials offered (if any).");
	ERROR_CODE(QNetworkReply::ProxyTimeoutError,                "The connection to the proxy timed out or the proxy did not reply in time to the request sent.");
	ERROR_CODE(QNetworkReply::ProxyNotFoundError,               "The proxy host name was not found (invalid proxy hostname).");
	ERROR_CODE(QNetworkReply::ProxyConnectionClosedError,       "The proxy server closed the connection prematurely, before the entire reply was received and processed.");
	ERROR_CODE(QNetworkReply::ContentAccessDenied,              "The access to the remote content was denied (similar to HTTP error 401).");
	ERROR_CODE(QNetworkReply::ContentOperationNotPermittedError,"The operation requested on the remote content is not permitted.");
	ERROR_CODE(QNetworkReply::ContentNotFoundError,             "The remote content was not found at the server (similar to HTTP error 404).");
	ERROR_CODE(QNetworkReply::UnknownNetworkError,				"An unknown network-related error was detected.");
	ERROR_CODE(QNetworkReply::UnknownProxyError,				"An unknown proxy-related error was detected.");
	ERROR_CODE(QNetworkReply::ProtocolInvalidOperationError,	"The requested operation is invalid for this protocol.");
	ERROR_CODE(QNetworkReply::ProtocolUnknownError,				"The Network Access API cannot honor the request because the protocol is not known.");
	ERROR_CODE(QNetworkReply::ContentReSendError,				"The request needed to be sent again, but this failed for example because the upload data could not be read a second time.");
	ERROR_CODE(QNetworkReply::AuthenticationRequiredError,      "The remote server requires authentication to serve the content but the credentials provided were not accepted (if any).");
	ERROR_CODE(QNetworkReply::UnknownContentError,				"An unknown error related to the remote content was detected.");
	ERROR_CODE(QNetworkReply::ProtocolFailure,					 "A breakdown in protocol was detected (parsing error, invalid or unexpected responses, etc.).");
	// }}}
}