void ProgressivePNGImageFileReader::read_image_attributes(
    ImageAttributes&    attrs)
{
    assert(is_open());
    attrs = impl->m_attributes;
}
void windows_tap_adapter::open(const std::string& _name, boost::system::error_code& ec)
{
    ec = boost::system::error_code();

    if (_name.empty())
    {
        open(ec);

        return;
    }

    PIP_ADAPTER_INFO piai = NULL;
    ULONG size = 0;
    DWORD status;

    status = GetAdaptersInfo(piai, &size);

    if (status != ERROR_BUFFER_OVERFLOW)
    {
        ec = boost::system::error_code(status, boost::system::system_category());

        return;
    }

    std::vector<unsigned char> piai_data(size);
    piai = reinterpret_cast<PIP_ADAPTER_INFO>(&piai_data[0]);

    status = GetAdaptersInfo(piai, &size);

    if (status != ERROR_SUCCESS)
    {
        ec = boost::system::error_code(status, boost::system::system_category());

        return;
    }

    piai_data.resize(size);

    try
    {
        const guid_pair_type adapter = find_tap_adapter_by_guid(_name);

        for (PIP_ADAPTER_INFO pi = piai; pi; pi = pi->Next)
        {
            if (adapter.first == std::string(pi->AdapterName))
            {
                const HANDLE handle = CreateFileA(
                                          (USERMODEDEVICEDIR + adapter.first + TAPSUFFIX).c_str(),
                                          GENERIC_READ | GENERIC_WRITE,
                                          0,
                                          0,
                                          OPEN_EXISTING,
                                          FILE_ATTRIBUTE_SYSTEM | FILE_FLAG_OVERLAPPED,
                                          0
                                      );

                if (handle == INVALID_HANDLE_VALUE)
                {
                    ec = boost::system::error_code(::GetLastError(), boost::system::system_category());

                    return;
                }

                if (descriptor().assign(handle, ec))
                {
                    return;
                }

                set_name(adapter.first);
                m_display_name = adapter.second;
                m_interface_index = pi->Index;

                if (::ConvertInterfaceIndexToLuid(m_interface_index, &m_interface_luid) != NO_ERROR)
                {
                    ec = boost::system::error_code(::GetLastError(), boost::system::system_category());

                    return;
                }

                if (pi->AddressLength != ethernet_address().data().size())
                {
                    if (close(ec))
                    {
                        return;
                    }

                    ec = make_error_code(asiotap_error::no_ethernet_address);

                    return;
                }

                osi::ethernet_address _ethernet_address;
                std::memcpy(_ethernet_address.data().data(), pi->Address, pi->AddressLength);
                set_ethernet_address(_ethernet_address);

                DWORD read_mtu;
                DWORD len;

                if (!DeviceIoControl(descriptor().native_handle(), TAP_IOCTL_GET_MTU, &read_mtu, sizeof(read_mtu), &read_mtu, sizeof(read_mtu), &len, NULL))
                {
                    ec = boost::system::error_code(::GetLastError(), boost::system::system_category());

                    return;
                }

                set_mtu(static_cast<size_t>(read_mtu));

                break;
            }
        }
    }
    catch (const boost::system::system_error& ex)
    {
        ec = ex.code();

        return;
    }

    if (!is_open())
    {
        ec = make_error_code(asiotap_error::no_such_tap_adapter);
    }
}
Example #3
0
 bool is_open_sync()
 {
     return is_open().get();
 }
Example #4
0
/*
 * Returns true/false indicating data successfully read from hypervisor.
 * Used both to get packets for tty connections and to advance the state
 * machine during console handshaking (in which case tty = NULL and we ignore
 * incoming data).
 */
static int hvsi_load_chunk(struct hvsi_struct *hp, struct tty_struct **flip,
		struct tty_struct **hangup, struct hvsi_struct **handshake)
{
	uint8_t *packet = hp->inbuf;
	int chunklen;

	*flip = NULL;
	*hangup = NULL;
	*handshake = NULL;

	chunklen = hvsi_read(hp, hp->inbuf_end, HVSI_MAX_READ);
	if (chunklen == 0) {
		pr_debug("%s: 0-length read\n", __FUNCTION__);
		return 0;
	}

	pr_debug("%s: got %i bytes\n", __FUNCTION__, chunklen);
	dbg_dump_hex(hp->inbuf_end, chunklen);

	hp->inbuf_end += chunklen;

	/* handle all completed packets */
	while ((packet < hp->inbuf_end) && got_packet(hp, packet)) {
		struct hvsi_header *header = (struct hvsi_header *)packet;

		if (!is_header(packet)) {
			printk(KERN_ERR "hvsi%i: got malformed packet\n", hp->index);
			/* skip bytes until we find a header or run out of data */
			while ((packet < hp->inbuf_end) && (!is_header(packet)))
				packet++;
			continue;
		}

		pr_debug("%s: handling %i-byte packet\n", __FUNCTION__,
				len_packet(packet));
		dbg_dump_packet(packet);

		switch (header->type) {
			case VS_DATA_PACKET_HEADER:
				if (!is_open(hp))
					break;
				if (hp->tty == NULL)
					break; /* no tty buffer to put data in */
				*flip = hvsi_recv_data(hp, packet);
				break;
			case VS_CONTROL_PACKET_HEADER:
				hvsi_recv_control(hp, packet, hangup, handshake);
				break;
			case VS_QUERY_RESPONSE_PACKET_HEADER:
				hvsi_recv_response(hp, packet);
				break;
			case VS_QUERY_PACKET_HEADER:
				hvsi_recv_query(hp, packet);
				break;
			default:
				printk(KERN_ERR "hvsi%i: unknown HVSI packet type 0x%x\n",
						hp->index, header->type);
				dump_packet(packet);
				break;
		}

		packet += len_packet(packet);

		if (*hangup || *handshake) {
			pr_debug("%s: hangup or handshake\n", __FUNCTION__);
			/*
			 * we need to send the hangup now before receiving any more data.
			 * If we get "data, hangup, data", we can't deliver the second
			 * data before the hangup.
			 */
			break;
		}
	}

	compact_inbuf(hp, packet);

	return 1;
}
  size_t read_some_at(implementation_type& impl, boost::uint64_t offset,
      const MutableBufferSequence& buffers, boost::system::error_code& ec)
  {
    if (!is_open(impl))
    {
      ec = boost::asio::error::bad_descriptor;
      return 0;
    }
    
    // Find first buffer of non-zero length.
    boost::asio::mutable_buffer buffer;
    typename MutableBufferSequence::const_iterator iter = buffers.begin();
    typename MutableBufferSequence::const_iterator end = buffers.end();
    for (DWORD i = 0; iter != end; ++iter, ++i)
    {
      buffer = boost::asio::mutable_buffer(*iter);
      if (boost::asio::buffer_size(buffer) != 0)
        break;
    }

    // A request to read 0 bytes on a stream handle is a no-op.
    if (boost::asio::buffer_size(buffer) == 0)
    {
      ec = boost::system::error_code();
      return 0;
    }

    overlapped_wrapper overlapped(ec);
    if (ec)
    {
      return 0;
    }

    // Read some data.
    overlapped.Offset = offset & 0xFFFFFFFF;
    overlapped.OffsetHigh = (offset >> 32) & 0xFFFFFFFF;
    BOOL ok = ::ReadFile(impl.handle_,
        boost::asio::buffer_cast<LPVOID>(buffer),
        static_cast<DWORD>(boost::asio::buffer_size(buffer)), 0, &overlapped);
    if (!ok) 
    {
      DWORD last_error = ::GetLastError();
      if (last_error != ERROR_IO_PENDING && last_error != ERROR_MORE_DATA)
      {
        if (last_error == ERROR_HANDLE_EOF)
        {
          ec = boost::asio::error::eof;
        }
        else
        {
          ec = boost::system::error_code(last_error,
              boost::asio::error::get_system_category());
        }
        return 0;
      }
    }

    // Wait for the operation to complete.
    DWORD bytes_transferred = 0;
    ok = ::GetOverlappedResult(impl.handle_,
        &overlapped, &bytes_transferred, TRUE);
    if (!ok)
    {
      DWORD last_error = ::GetLastError();
      if (last_error == ERROR_HANDLE_EOF)
      {
        ec = boost::asio::error::eof;
      }
      else
      {
        ec = boost::system::error_code(last_error,
            boost::asio::error::get_system_category());
      }
      return 0;
    }

    ec = boost::system::error_code();
    return bytes_transferred;
  }
Example #6
0
/**
 * @brief Returns whether this entity is an obstacle for another one.
 * @param other another entity
 * @return true
 */
bool Door::is_obstacle_for(MapEntity& other) {
  return !is_open();
}
Example #7
0
/**
 * @brief Copy file content.
 *
 * @param[in]     src_entry    File to copy from
 * @param[in]     src_offset   Offset start from the source file
 * @param[in]     dst_entry    Destination file to copy to
 * @param[in]     dst_offset   Offset in the dest file
 * @param[out]    count	       Requested bytes to copy
 * @param[out]    copied       Bytes successfully copied
 *
 * @return CACHE_INODE_SUCCESS or various errors
 */
cache_inode_status_t cache_inode_copy(cache_entry_t *src_entry,
				      uint64_t src_offset,
				      cache_entry_t *dst_entry,
				      uint64_t dst_offset, uint64_t count,
				      uint64_t *copied)
{
	fsal_status_t fsal_status = { 0, 0 };
	cache_inode_status_t status;

	/**
	 * To avoid deadlock, we always lock the entry with a smaller address
	 * before the locking the other entry.  Note that "content_lock"
	 * protects "cache content" instead of file content.  So only reader
	 * lock is needed for either file.
	 */
	if ((size_t)src_entry < (size_t)dst_entry) {
		PTHREAD_RWLOCK_rdlock(&src_entry->content_lock);
		PTHREAD_RWLOCK_rdlock(&dst_entry->content_lock);
	} else {
		PTHREAD_RWLOCK_rdlock(&dst_entry->content_lock);
		PTHREAD_RWLOCK_rdlock(&src_entry->content_lock);
	}

	if (!is_open(src_entry) || !is_open(dst_entry)) {
		LogEvent(COMPONENT_CACHE_INODE,
			 "Cannot copy between files that are not open");
		status = NFS4ERR_OPENMODE;
		goto out;
	}

	if (count == UINT64_MAX) {
		count = src_entry->obj_handle->attrs->filesize - src_offset;
		LogDebug(COMPONENT_CACHE_INODE,
			 "0-count has an effective value of %zu", count);
	}

	fsal_status = src_entry->obj_handle->obj_ops.copy(src_entry->obj_handle,
							  src_offset,
							  dst_entry->obj_handle,
							  dst_offset,
							  count,
							  copied);

	if (FSAL_IS_ERROR(fsal_status)) {
		*copied = 0;
		status = cache_inode_error_convert(fsal_status);
		LogEvent(COMPONENT_CACHE_INODE,
			 "File copy failed: major = %d, minor = %d",
			 fsal_status.major, fsal_status.minor);
		goto out;
	}

	/* Update dest file after coping to it. */
	PTHREAD_RWLOCK_wrlock(&dst_entry->attr_lock);
	status = cache_inode_refresh_attrs(dst_entry);
	PTHREAD_RWLOCK_unlock(&dst_entry->attr_lock);

out:
	if ((size_t)src_entry < (size_t)dst_entry) {
		PTHREAD_RWLOCK_unlock(&dst_entry->content_lock);
		PTHREAD_RWLOCK_unlock(&src_entry->content_lock);
	} else {
		PTHREAD_RWLOCK_unlock(&src_entry->content_lock);
		PTHREAD_RWLOCK_unlock(&dst_entry->content_lock);
	}

	return status;
}
int main(int argc, char** argv)
{
	auto verbosity = argc - 1;

	std::array<Dataset, 3> datasets {
			readIrisDataset("../data/iris.csv"),
			readHeartDiseaseDataset("../data/heartDisease.csv"),
			readWineDataset("../data/wine.csv")
	};

	std::array<Dataset, 3> discreteDatasets {
		readIrisDataset("../data/irisDiscrete.csv"),
		readHeartDiseaseDataset("../data/heartDiseaseDiscrete.csv"),
		readWineDataset("../data/wineDiscrete.csv")
	};

	datasets[0].shuffle();
	datasets[1].shuffle();
	datasets[2].shuffle();
	discreteDatasets[0].shuffle();
	discreteDatasets[1].shuffle();
	discreteDatasets[2].shuffle();

	std::array<std::string, 3> datasetLabels = {
			"Iris", "Heart Disease", "Wine"
	};

	std::array<ClassifierType, 4> classifierTypes = {
			ClassifierType::OPTIMAL,
			ClassifierType::NAIVE,
			ClassifierType::LINEAR,
			ClassifierType::DECISION_TREE
	};

	std::array<std::string, 4> classifierTypeLabels = {
			"Optimal Bayes",
			"Naive Bayes",
			"Linear Bayes",
			"Decision Tree"
	};

	// Open final results CSV in append mode, so that we can build up
	// lots of results and do statistics on them.
	auto finalResults = std::ofstream{"output/finalResults.txt",
		std::ofstream::app};
	assert(finalResults.is_open());

	// Output column labels on final results CSV
	for (auto datasetNum = 0; datasetNum < 3; ++datasetNum)
	{
		finalResults << ", " << datasetLabels[datasetNum] << " 10-fold";
		finalResults << ", " << datasetLabels[datasetNum] << " leave-one-out";
	}
	finalResults << std::endl;

	for (auto classifierNum = 0; classifierNum < 4; ++classifierNum)
	{
		// Output row label for final results CSV
		finalResults << classifierTypeLabels[classifierNum];

		for (auto datasetNum = 0; datasetNum < 3; ++datasetNum)
		{
			std::stringstream out2name;
			out2name << "output/"
					 << datasetLabels[datasetNum]
					 << "-" << classifierTypeLabels[classifierNum];

			// 10-fold cross validation
			auto resultsFile = std::ofstream{out2name.str()
				+ "-10fold-results.txt"};
			assert(resultsFile.is_open());
			auto modelFileName  = out2name.str() + "-10fold-model";
			auto& data = classifierNum < 3
					? datasets[datasetNum] : discreteDatasets[datasetNum];
			std::cout << datasetLabels[datasetNum]
					  << " data using 10-fold cross-validation "
					  << "(" << classifierTypeLabels[classifierNum]
					  << " classifier)"
					  << std::endl << std::endl;

			classifyAndTest(data, 10, classifierTypes[classifierNum],
					verbosity, resultsFile, modelFileName, finalResults);
			resultsFile.close();

			// Leave-one-out cross validation
			resultsFile = std::ofstream{out2name.str()
				+ "-leaveOneOut-results.txt"};
			assert(resultsFile.is_open());
			modelFileName  = out2name.str() + "-leaveOneOut-model";
			std::cout << datasetLabels[datasetNum]
					  << " data using leave-one-out cross-validation "
					  << "(" << classifierTypeLabels[classifierNum]
					  << " classifier)"
					  << std::endl << std::endl;
			classifyAndTest(data, datasets[datasetNum].size(),
					classifierTypes[classifierNum], verbosity,
					resultsFile, modelFileName, finalResults);
			resultsFile.close();
		}

		finalResults << std::endl;
	}

	finalResults << std::endl;
	finalResults.close();

	return 0;
}
Example #9
0
 std::unique_ptr<std::istream> FileSystem::OpenStream(const filesystem::path& file)
 {
     auto stream = std::make_unique<std::ifstream>(file.str());
     return stream->is_open() ? std::move(stream) : nullptr;
 }
Example #10
0
cache_inode_status_t
cache_inode_remove(cache_entry_t *entry, const char *name)
{
	cache_entry_t *to_remove_entry = NULL;
	fsal_status_t fsal_status = { 0, 0 };
	cache_inode_status_t status = CACHE_INODE_SUCCESS;
	cache_inode_status_t status_ref_entry = CACHE_INODE_SUCCESS;

	if (entry->type != DIRECTORY) {
		status = CACHE_INODE_NOT_A_DIRECTORY;
		goto out;
	}

	/* Factor this somewhat.  In the case where the directory hasn't
	   been populated, the entry may not exist in the cache and we'd
	   be bringing it in just to dispose of it. */

	/* Looks up for the entry to remove */
	status =
	    cache_inode_lookup_impl(entry, name, &to_remove_entry);

	if (to_remove_entry == NULL) {
		LogFullDebug(COMPONENT_CACHE_INODE, "lookup %s failure %s",
			     name, cache_inode_err_str(status));
		goto out;
	}

	/* Do not remove a junction node or an export root. */
	if (to_remove_entry->type == DIRECTORY) {
		/* Get attr_lock for looking at junction_export */
		PTHREAD_RWLOCK_rdlock(&to_remove_entry->attr_lock);

		if (to_remove_entry->object.dir.junction_export != NULL ||
		    atomic_fetch_int32_t(&to_remove_entry->exp_root_refcount)
		    != 0) {
			/* Trying to remove an export mount point */
			LogCrit(COMPONENT_CACHE_INODE,
				 "Attempt to remove export %s",
				 name);

			/* Release attr_lock */
			PTHREAD_RWLOCK_unlock(&to_remove_entry->attr_lock);

			status = CACHE_INODE_DIR_NOT_EMPTY;
			goto out;
		}

		/* Release attr_lock */
		PTHREAD_RWLOCK_unlock(&to_remove_entry->attr_lock);
	}

	LogDebug(COMPONENT_CACHE_INODE, "%s", name);

	if (is_open(to_remove_entry)) {
		/* entry is not locked and seems to be open for fd caching
		 * purpose.
		 * candidate for closing since unlink of an open file results
		 * in 'silly rename' on certain platforms */
		status =
		    cache_inode_close(to_remove_entry,
				      CACHE_INODE_FLAG_REALLYCLOSE);
		if (status != CACHE_INODE_SUCCESS) {
			/* non-fatal error. log the warning and move on */
			LogCrit(COMPONENT_CACHE_INODE,
				"Error closing %s before unlink: %s.", name,
				cache_inode_err_str(status));
		}
	}

	fsal_status =
	    entry->obj_handle->obj_ops.unlink(entry->obj_handle, name);

	if (FSAL_IS_ERROR(fsal_status)) {
		if (fsal_status.major == ERR_FSAL_STALE)
			cache_inode_kill_entry(entry);

		status = cache_inode_error_convert(fsal_status);

		LogFullDebug(COMPONENT_CACHE_INODE, "unlink %s failure %s",
			     name, cache_inode_err_str(status));

		if (to_remove_entry->type == DIRECTORY
		    && status == CACHE_INODE_DIR_NOT_EMPTY) {
			/* its dirent tree is probably stale, flush it
			 * to try and make things right again */
			PTHREAD_RWLOCK_wrlock(&to_remove_entry->content_lock);
			(void)
			    cache_inode_invalidate_all_cached_dirent
			    (to_remove_entry);
			PTHREAD_RWLOCK_unlock(&to_remove_entry->content_lock);
		}
		goto out;
	}

	/* Remove the entry from parent dir_entries avl */
	PTHREAD_RWLOCK_wrlock(&entry->content_lock);
	status_ref_entry = cache_inode_remove_cached_dirent(entry, name);
	LogDebug(COMPONENT_CACHE_INODE,
		 "cache_inode_remove_cached_dirent %s status %s", name,
		 cache_inode_err_str(status_ref_entry));
	PTHREAD_RWLOCK_unlock(&entry->content_lock);

	status_ref_entry = cache_inode_refresh_attrs_locked(entry);

	if (FSAL_IS_ERROR(fsal_status)) {
		status = cache_inode_error_convert(fsal_status);
		LogFullDebug(COMPONENT_CACHE_INODE,
			     "not sure this code makes sense %s failure %s",
			     name, cache_inode_err_str(status));
		goto out;
	}

	/* Update the attributes for the removed entry */
	(void)cache_inode_refresh_attrs_locked(to_remove_entry);

	status = status_ref_entry;
	if (status != CACHE_INODE_SUCCESS) {
		LogDebug(COMPONENT_CACHE_INODE,
			 "cache_inode_refresh_attrs_locked(entry %p %s) "
			 "returned %s", entry, name,
			 cache_inode_err_str(status_ref_entry));
	}

out:
	LogFullDebug(COMPONENT_CACHE_INODE, "remove %s: status=%s", name,
		     cache_inode_err_str(status));

	/* This is for the reference taken by lookup */
	if (to_remove_entry)
		cache_inode_put(to_remove_entry);

	return status;
}
void classifyAndTest(const Dataset& data,
		unsigned int numFolds,
		ClassifierType ctype,
		int verbosity,
		std::ostream& resultsOut,
		std::string modelOutName,
		std::ostream& finalResults)
{
	std::vector<unsigned int> timesRight(numFolds, 0);
	std::vector<unsigned int> timesWrong(numFolds, 0);
	std::vector<unsigned int> timesUndecided(numFolds, 0);
	auto totalTimesRight = 0;
	auto totalTimesWrong = 0;
	auto totalTimesUndecided = 0;

	// Classify and test the data
	for (auto k = 1; k <= numFolds; ++k)
	{
		// Partition into testing and training sets
		auto indices = kFoldIndices(k, numFolds, data.size());
		auto partitions = data.partition(indices.first, indices.second);

		// Create a classifier for the dataset
		auto c = partitions.training.classifier(ctype);

		// If it's a decision tree, output it
		if (ctype == ClassifierType::DECISION_TREE)
		{
			// Although for leave-one-out testing we only print one
			// tree, since there's ~100 of them and they all look
			// nearly identical.
			if (numFolds <= 20 || k == 1)
			{
				std::stringstream name;
				name << modelOutName << "-" << k << ".dot";
				auto modelOut = std::ofstream{name.str()};
				assert(modelOut.is_open());
				dynamic_cast<DecisionTree*>(c.get())->print(modelOut);
				modelOut.close();
			}
		}

		// Test each point in the testing set
		for (auto i = 0; i < partitions.testing.size(); ++i)
		{
			// Classify
			auto type = c->classify(partitions.testing.getPoint(i));

			if (type == partitions.testing.getType(i))
			{
				resultsOut << "Decided true class " << static_cast<int>(type)
					<< " for " << partitions.testing.getPoint(i) << std::endl;
			}
			else if (type == NoType)
			{
				resultsOut << "Undecided (actual "
					<< static_cast<int>(partitions.testing.getType(i))
					<< ") for " << partitions.testing.getPoint(i) << std::endl;
			}
			else
			{
				resultsOut << "Decided wrong class " << static_cast<int>(type)
					<< " (actual "
					<< static_cast<int>(partitions.testing.getType(i))
					<< ") for " << partitions.testing.getPoint(i) << std::endl;
			}

			// Update counters
			if (type == partitions.testing.getType(i))
			{
				++timesRight[k-1];
			}
			else if (type == NoType)
			{
				++timesUndecided[k-1];
			}
			else
			{
				++timesWrong[k-1];
			}
		}

		// Report the accuracy on this fold (unless we're just doing 1 element)
		if (partitions.testing.size() > 1)
		{
			resultsOut << "Fold " << k << ": timesRight=" << timesRight[k-1]
					  << ", timesWrong=" << timesWrong[k-1]
					  << ", timesUndecided=" << timesUndecided[k-1]
		              << ", accuracy: " << timesRight[k-1]/
					     static_cast<double>(timesWrong[k-1]
										+timesRight[k-1]+timesUndecided[k-1])
				      << std::endl << std::endl;
		}

		// Update overall accuracy
		totalTimesRight += timesRight[k-1];
		totalTimesUndecided += timesUndecided[k-1];
		totalTimesWrong += timesWrong[k-1];
	}

	// Report overall accuracy
	auto accuracy = totalTimesRight / static_cast<double>(totalTimesRight
		    		  + totalTimesWrong + totalTimesUndecided);
	resultsOut << "Total: timesRight=" << totalTimesRight
			  << ", timesWrong=" << totalTimesWrong
			  << ", timesUndecided=" << totalTimesUndecided
			  << ", accuracy=" << accuracy
			  << std::endl << std::endl << std::endl;

	finalResults << "," << accuracy;
}
Example #12
0
void Gobby::Server::open(unsigned int port,
                         InfXmppConnectionSecurityPolicy security_policy,
                         InfCertificateCredentials* creds,
                         InfSaslContext* context,
                         const char* sasl_mechanisms)
{
	// If we can open one of tcp4 or tcp6 that's a success.
	InfdTcpServer* tcp4;
	InfdTcpServer* tcp6;

	// If the server is already open and we do not need to change the
	// port, then just change the credentials and SASL context without
	// doing anything else.
	if(is_open() && get_port() == port)
	{
		set_credentials(security_policy, creds);
		set_sasl_context(context, sasl_mechanisms);
		return;
	}

	static const guint8 ANY6_ADDR[16] =
		{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
	InfIpAddress* any6 = inf_ip_address_new_raw6(ANY6_ADDR);

	tcp4 = INFD_TCP_SERVER(g_object_new(
		INFD_TYPE_TCP_SERVER,
		"io", m_io, "local-address", NULL,
		"local-port", port,
		NULL));
	tcp6 = INFD_TCP_SERVER(g_object_new(
		INFD_TYPE_TCP_SERVER,
		"io", m_io, "local-address", any6,
		"local-port", port,
		NULL));
	inf_ip_address_free(any6);

	if(!infd_tcp_server_open(tcp6, NULL))
	{
		g_object_unref(tcp6);
		tcp6 = NULL;

		GError* error = NULL;
		if(!infd_tcp_server_open(tcp4, &error))
		{
			g_object_unref(tcp4);

			const std::string message = error->message;
			g_error_free(error);

			throw std::runtime_error(message);
		}
	}
	else
	{
		if(!infd_tcp_server_open(tcp4, NULL))
		{
			g_object_unref(tcp4);
			tcp4 = NULL;
		}
	}

	// We have the new server open, from this point on there is nothing
	// that can go wrong anymore. Therefore, close the old server and
	// take over the new one.
	if(is_open()) close();

	InfXmppConnectionSecurityPolicy policy =
		INF_XMPP_CONNECTION_SECURITY_ONLY_UNSECURED;
	if(creds != NULL) policy = security_policy;

	if(tcp4)
	{
		m_xmpp4 = infd_xmpp_server_new(
			tcp4, security_policy, creds,
			context, sasl_mechanisms);
		g_object_unref(tcp4);
	}

	if(tcp6)
	{
		m_xmpp6 = infd_xmpp_server_new(
			tcp6, security_policy, creds,
			context, sasl_mechanisms);
		g_object_unref(tcp6);
	}

	if(m_pool)
	{
		if(m_xmpp4 != NULL)
		{
			infd_server_pool_add_server(
				m_pool, INFD_XML_SERVER(m_xmpp4));
			infd_server_pool_add_local_publisher(
				m_pool, m_xmpp4, m_publisher);
		}

		if(m_xmpp6 != NULL)
		{
			infd_server_pool_add_server(
				m_pool, INFD_XML_SERVER(m_xmpp6));
			infd_server_pool_add_local_publisher(
				m_pool, m_xmpp6, m_publisher);
		}
	}
}
// Close the image file.
void ProgressiveEXRImageFileWriter::close()
{
    assert(is_open());
    impl->m_file.reset();
}
// Open an image file for writing.
void ProgressiveEXRImageFileWriter::open(
    const char*             filename,
    const CanvasProperties& props,
    const ImageAttributes&  attrs)
{
    assert(filename);
    assert(!is_open());

    try
    {
        // todo: lift this limitation.
        assert(props.m_channel_count <= 4);

        // Figure out the pixel type, based on the pixel format of the image.
        impl->m_pixel_type = FLOAT;
        switch (props.m_pixel_format)
        {
          case PixelFormatUInt32: impl->m_pixel_type = UINT; break;
          case PixelFormatHalf: impl->m_pixel_type = HALF; break;
          case PixelFormatFloat: impl->m_pixel_type = FLOAT; break;
          default: throw ExceptionUnsupportedImageFormat();
        }

        // Construct TileDescription object.
        const TileDescription tile_desc(
            static_cast<unsigned int>(props.m_tile_width),
            static_cast<unsigned int>(props.m_tile_height),
            ONE_LEVEL);

        // Construct ChannelList object.
        ChannelList channels;
        for (size_t c = 0; c < props.m_channel_count; ++c)
            channels.insert(ChannelName[c], Channel(impl->m_pixel_type));

        // Construct Header object.
        Header header(
            static_cast<int>(props.m_canvas_width),
            static_cast<int>(props.m_canvas_height),
            static_cast<float>(props.m_canvas_width) / props.m_canvas_height);
        header.setTileDescription(tile_desc);
        header.channels() = channels;

        // Add image attributes to the Header object.
        add_attributes(attrs, header);

        // Create the output file.
        impl->m_file.reset(
            new TiledOutputFile(
                filename,
                header,
                impl->m_thread_count));

        // Store the canvas properties.
        impl->m_props = props;
    }
    catch (const BaseExc& e)
    {
        // I/O error.
        throw ExceptionIOError(e.what());
    }
}
Example #15
0
 session::~session()
 {
     if (is_open()) {
         close();
     }
 }
Example #16
0
 bool Session::is_closed( void ) const
 {
     return not is_open( );
 }
Example #17
0
Uart0::Error Uart0::config_uart() {

  if (is_open())
    return kPortAlreadyOpen;

  uint32_t data_bits_cc3200;
  switch (data_bits) {
  case 5:
    data_bits_cc3200 = UART_CONFIG_WLEN_5;
    break;
  case 6:
    data_bits_cc3200 = UART_CONFIG_WLEN_6;
    break;
  case 7:
    data_bits_cc3200 = UART_CONFIG_WLEN_7;
    break;
  case 8:
    data_bits_cc3200 = UART_CONFIG_WLEN_8;
    break;
  default:
    return kUnsuportedFeature;
  }

  uint32_t stop_bits_cc3200;
  switch (stop_bits) {
  case 1:
    stop_bits_cc3200 = UART_CONFIG_STOP_ONE;
    break;
  case 2:
    stop_bits_cc3200 = UART_CONFIG_STOP_TWO;
    break;
  default:
    return kUnsuportedFeature;
  }

  uint32_t parity_cc3200;
  switch (parity) {
  case kParityEven:
    parity_cc3200 = UART_CONFIG_PAR_EVEN;
    break;
  case kParityMark:
    parity_cc3200 = UART_CONFIG_PAR_ONE;
    break;
  case kParityNone:
    parity_cc3200 = UART_CONFIG_PAR_NONE;
    break;
  case kParityOdd:
    parity_cc3200 = UART_CONFIG_PAR_ODD;
    break;
  case kParitySpace:
    parity_cc3200 = UART_CONFIG_PAR_ZERO;
    break;
  default:
    return kUnsuportedFeature;
  }

  MAP_UARTConfigSetExpClk(UARTA0_BASE, 80000000, baud,
      (data_bits_cc3200 | stop_bits_cc3200 | parity_cc3200));

  /*
   * Disable UART to modify the configuration.
   * This is needed because the SetExpClk function enables the UART
   */
  MAP_UARTDisable(UARTA0_BASE);

  switch (flow_control) {
  case kFlowControlNone:
    MAP_UARTFlowControlSet(UARTA0_BASE, UART_FLOWCONTROL_NONE);
    break;
  case kFlowControlHardware:
    /* Enable RTS/CTS Flow Control */
    if (mode == kModeDuplex)
      MAP_UARTFlowControlSet(UARTA0_BASE,
      UART_FLOWCONTROL_TX | UART_FLOWCONTROL_RX);
    if (mode == kModeRxOnly)
      MAP_UARTFlowControlSet(UARTA0_BASE,
      UART_FLOWCONTROL_RX);
    if (mode == kModeTxOnly)
      MAP_UARTFlowControlSet(UARTA0_BASE,
      UART_FLOWCONTROL_TX);
    break;
  default:
    return kUnsuportedFeature;
    break;
  }

  /* Register Interrupt */
  MAP_UARTIntRegister(UARTA0_BASE, isr);

  /* Enable Interrupt */
  MAP_UARTTxIntModeSet(UARTA0_BASE, UART_TXINT_MODE_EOT);
  MAP_UARTIntClear(UARTA0_BASE, UART_INT_TX | UART_INT_RX);

  uint32_t interrupts = 0;
  if ((mode == kModeDuplex) || (mode == kModeTxOnly))
    interrupts |= UART_INT_TX;

  if ((mode == kModeDuplex) || (mode == kModeRxOnly))
    interrupts |= UART_INT_RX;

  MAP_UARTIntEnable(UARTA0_BASE, interrupts);

  /* Enable UART */
  MAP_UARTEnable(UARTA0_BASE);

  /* Disable Fifo */
  MAP_UARTFIFODisable(UARTA0_BASE);

  return kOK;
}
Example #18
0
int
main (void)
{
  int i;
  int fd;

  /* We close fd 2 later, so save it in fd 10.  */
  if (dup2 (STDERR_FILENO, BACKUP_STDERR_FILENO) != BACKUP_STDERR_FILENO
      || (myerr = fdopen (BACKUP_STDERR_FILENO, "w")) == NULL)
    return 2;

  /* Create file for later checks.  */
  fd = creat (witness, 0600);
  ASSERT (STDERR_FILENO < fd);

  /* Four iterations, with progressively more standard descriptors
     closed.  */
  for (i = -1; i <= STDERR_FILENO; i++)
    {
      if (0 <= i)
        ASSERT (close (i) == 0);

      /* Detect errors.  */
      errno = 0;
      ASSERT (dup (-1) == -1);
      ASSERT (errno == EBADF);
      errno = 0;
      ASSERT (dup (10000000) == -1);
      ASSERT (errno == EBADF);
      close (fd + 1);
      errno = 0;
      ASSERT (dup (fd + 1) == -1);
      ASSERT (errno == EBADF);

      /* Preserve text vs. binary.  */
      setmode (fd, O_BINARY);
      ASSERT (dup (fd) == fd + 1);
      ASSERT (is_open (fd + 1));
      ASSERT (is_inheritable (fd + 1));
      ASSERT (is_mode (fd + 1, O_BINARY));

      ASSERT (close (fd + 1) == 0);
      setmode (fd, O_TEXT);
      ASSERT (dup (fd) == fd + 1);
      ASSERT (is_open (fd + 1));
      ASSERT (is_inheritable (fd + 1));
      ASSERT (is_mode (fd + 1, O_TEXT));

      /* Create cloexec copy.  */
      ASSERT (close (fd + 1) == 0);
      ASSERT (fd_safer_flag (dup_cloexec (fd), O_CLOEXEC) == fd + 1);
      ASSERT (set_cloexec_flag (fd + 1, true) == 0);
      ASSERT (is_open (fd + 1));
      ASSERT (!is_inheritable (fd + 1));
      ASSERT (close (fd) == 0);

      /* dup always creates inheritable copies.  Also, check that
         earliest slot past std fds is used.  */
      ASSERT (dup (fd + 1) == fd);
      ASSERT (is_open (fd));
      ASSERT (is_inheritable (fd));
      ASSERT (close (fd + 1) == 0);
    }

  /* Cleanup.  */
  ASSERT (close (fd) == 0);
  ASSERT (unlink (witness) == 0);

  return 0;
}
	// PRECONDITIONS: none
    // POSTCONDITION: The object has been placed in the drawing queue, to be
    //                 drawn at the next glFlush()
	void CircuitObject::draw() const
	{
		if(type() == "SWITCH")
		{
			// Draw the button if necessary
			if(has_button())
			{
				GLcolor3(0.2, 0.0, 0.0).glColor();
				glRectf(left(), bottom(), left() + BUTTON_WIDTH, bottom() + BUTTON_HEIGHT);
				GLred3.glColor();
				glRectf(left() + BUTTON_WIDTH/4, bottom() + BUTTON_HEIGHT/4, left() + 3*BUTTON_WIDTH/4, top() - BUTTON_HEIGHT/4);			
			}
			// Draw the 1
			ONE_COLOR.glColor();
			glRectf(left() + 2*width()/3, top() - 2*height()/5, 
					left() + 2*width()/3 + width()/9, top());
			
			// Draw the 0
			ZERO_COLOR.glColor();
			glRectf(left() + 2*width()/3 - width()/12, bottom() + 3*height()/8,
					left() + 2*width()/3 + width()/12, bottom() + height()/2);
			glRectf(left() + 2*width()/3 - width()/12, bottom(),			     
					left() + 2*width()/3, bottom() + height()/2);
			glRectf(left() + 2*width()/3 + width()/12, bottom(),				
					left() + 2*width()/3 + 3*width()/24, bottom() + height()/2);
			glRectf(left() + 2*width()/3, bottom(), 
					left() + 2*width()/3 + width()/12, bottom() + height()/8);
			
			if(output_value() == 1)
			{
				// Draw wire from the one
				ONE_COLOR.glColor();
				glBegin(GL_LINES);
				glVertex2f(left() + 2*width()/3 + width()/6, top() - height()/4);
				glVertex2f(left() + width(), bottom() + height()/2);
				glEnd();
			}
			else
			{
				// Draw wire from the zero
				ZERO_COLOR.glColor();
				glBegin(GL_LINES);
				glVertex2f(left() + 2*width()/3 + width()/6, bottom() + height()/4);
				glVertex2f(left() + width(), bottom() + height()/2);
				glEnd();
			}			
		}
		else if(type() == "NOT")
		{
			GATE_COLOR.glColor();
			// Draw triangle
			glBegin(GL_POLYGON);
			glVertex2f(left(), bottom());
			glVertex2f(left(), top());
			glVertex2f(left()+2*width()/3, bottom() + height()/2);
			glEnd();
			// Draw circle
			glBegin(GL_POLYGON);
			glVertex2f(left()+2*width()/3, bottom() + height()/2);
			glVertex2f(left()+5*width()/6, bottom() + 3*height()/5);
			glVertex2f(left()+6*width()/6, bottom() + height()/2);
			glVertex2f(left()+5*width()/6, bottom() + 2*height()/5);
			glEnd();
		}
		else if(type() == "AND")
		{
			GATE_COLOR.glColor();
			glBegin(GL_POLYGON);
			glVertex2f(left(), bottom());
			glVertex2f(left(), top());
			glVertex2f(left()+width()/2, top());
			glVertex2f(right(), bottom() + 2*height()/3);
			glVertex2f(right(), bottom() + 1*height()/3);
			glVertex2f(left()+width()/2, bottom());
			glEnd();
			// Draw the dot
			GLblack3.glColor();
			glRectf(left()+2*width()/5, bottom()+2*height()/5, left()+3*width()/5, bottom()+3*height()/5);
			glEnd();			
		}
		else if(type() == "OR")
		{
			GATE_COLOR.glColor();
			// Top of the gate
			glBegin(GL_POLYGON);
			glVertex2f(left()+width()/3, bottom()+height()/2);
			glVertex2f(left(), top());
			glVertex2f(left()+2*width()/3, top());
			glVertex2f(right(), bottom() + height()/2);
			glEnd();
			// Bottom of the gate
			glBegin(GL_POLYGON);
			glVertex2f(left()+width()/3, bottom()+height()/2);
			glVertex2f(left(), bottom());
			glVertex2f(left()+2*width()/3, bottom());
			glVertex2f(right(), bottom() + height()/2);
			glEnd();
			// Draw the +
			GLblack3.glColor();
			glBegin(GL_LINES);
			glVertex2f(left()+4*width()/7, top()-height()/4);
			glVertex2f(left()+4*width()/7, bottom()+height()/4);
			glVertex2f(left()+2*width()/5, top()-height()/2);
			glVertex2f(left()+4*width()/5, top()-height()/2);
			glEnd();			
		}	
		else if(type() == "EXIT")
		{
			if(!is_open())
			{
				// Draw the door
				DOOR_COLOR.glColor();
				glBegin(GL_POLYGON);
				glVertex2f(left(), bottom());
				glVertex2f(left(), top() - height()/2);
				glVertex2f(right(), top());
				glVertex2f(right(), top() - height()/2);
				glEnd();
			}
			// Draw the wall
			WALL_COLOR.glColor();
			glBegin(GL_POLYGON);
			glVertex2f(left(), bottom());
			glVertex2f(right(), top() - height()/2);
			glVertex2f(right(), bottom());
			glEnd();			
		}
    }	
Example #20
0
				void open() {
					if(is_open())return;
				}
Example #21
0
 bool Http::is_closed( const shared_ptr< Request >& value )
 {
     return not is_open( value );
 }
Example #22
0
int
main ()
{
  int use_cloexec;

#if O_CLOEXEC
  for (use_cloexec = 0; use_cloexec <= 1; use_cloexec++)
#else
  use_cloexec = 0;
#endif
    {
      const char *file = "test-dup3.tmp";
      int fd = open (file, O_CREAT | O_TRUNC | O_RDWR, 0600);
      int o_flags;
      char buffer[1];

      o_flags = 0;
#if O_CLOEXEC
      if (use_cloexec)
        o_flags |= O_CLOEXEC;
#endif

      /* Assume std descriptors were provided by invoker.  */
      ASSERT (STDERR_FILENO < fd);
      ASSERT (is_open (fd));
      /* Ignore any other fd's leaked into this process.  */
      close (fd + 1);
      close (fd + 2);
      ASSERT (!is_open (fd + 1));
      ASSERT (!is_open (fd + 2));

      /* Assigning to self is invalid.  */
      errno = 0;
      ASSERT (dup3 (fd, fd, o_flags) == -1);
      ASSERT (errno == EINVAL);
      ASSERT (is_open (fd));

      /* If the source is not open, then the destination is unaffected.  */
      errno = 0;
      ASSERT (dup3 (fd + 1, fd + 2, o_flags) == -1);
      ASSERT (errno == EBADF);
      ASSERT (!is_open (fd + 2));
      errno = 0;
      ASSERT (dup3 (fd + 1, fd, o_flags) == -1);
      ASSERT (errno == EBADF);
      ASSERT (is_open (fd));

      /* The destination must be valid.  */
      errno = 0;
      ASSERT (dup3 (fd, -2, o_flags) == -1);
      ASSERT (errno == EBADF);
      errno = 0;
      ASSERT (dup3 (fd, 10000000, o_flags) == -1);
      ASSERT (errno == EBADF);

      /* Using dup3 can skip fds.  */
      ASSERT (dup3 (fd, fd + 2, o_flags) == fd + 2);
      ASSERT (is_open (fd));
      ASSERT (!is_open (fd + 1));
      ASSERT (is_open (fd + 2));
      if (use_cloexec)
        ASSERT (is_cloexec (fd + 2));
      else
        ASSERT (!is_cloexec (fd + 2));

      /* Verify that dup3 closes the previous occupant of a fd.  */
      ASSERT (open ("/dev/null", O_WRONLY, 0600) == fd + 1);
      ASSERT (dup3 (fd + 1, fd, o_flags) == fd);
      ASSERT (close (fd + 1) == 0);
      ASSERT (write (fd, "1", 1) == 1);
      ASSERT (dup3 (fd + 2, fd, o_flags) == fd);
      ASSERT (lseek (fd, 0, SEEK_END) == 0);
      ASSERT (write (fd + 2, "2", 1) == 1);
      ASSERT (lseek (fd, 0, SEEK_SET) == 0);
      ASSERT (read (fd, buffer, 1) == 1);
      ASSERT (*buffer == '2');

      /* Clean up.  */
      ASSERT (close (fd + 2) == 0);
      ASSERT (close (fd) == 0);
      ASSERT (unlink (file) == 0);
    }

  return 0;
}
  // Cancel all operations associated with the handle.
  boost::system::error_code cancel(implementation_type& impl,
      boost::system::error_code& ec)
  {
    if (!is_open(impl))
    {
      ec = boost::asio::error::bad_descriptor;
    }
    else if (FARPROC cancel_io_ex_ptr = ::GetProcAddress(
          ::GetModuleHandleA("KERNEL32"), "CancelIoEx"))
    {
      // The version of Windows supports cancellation from any thread.
      typedef BOOL (WINAPI* cancel_io_ex_t)(HANDLE, LPOVERLAPPED);
      cancel_io_ex_t cancel_io_ex = (cancel_io_ex_t)cancel_io_ex_ptr;
      if (!cancel_io_ex(impl.handle_, 0))
      {
        DWORD last_error = ::GetLastError();
        if (last_error == ERROR_NOT_FOUND)
        {
          // ERROR_NOT_FOUND means that there were no operations to be
          // cancelled. We swallow this error to match the behaviour on other
          // platforms.
          ec = boost::system::error_code();
        }
        else
        {
          ec = boost::system::error_code(last_error,
              boost::asio::error::get_system_category());
        }
      }
      else
      {
        ec = boost::system::error_code();
      }
    }
    else if (impl.safe_cancellation_thread_id_ == 0)
    {
      // No operations have been started, so there's nothing to cancel.
      ec = boost::system::error_code();
    }
    else if (impl.safe_cancellation_thread_id_ == ::GetCurrentThreadId())
    {
      // Asynchronous operations have been started from the current thread only,
      // so it is safe to try to cancel them using CancelIo.
      if (!::CancelIo(impl.handle_))
      {
        DWORD last_error = ::GetLastError();
        ec = boost::system::error_code(last_error,
            boost::asio::error::get_system_category());
      }
      else
      {
        ec = boost::system::error_code();
      }
    }
    else
    {
      // Asynchronous operations have been started from more than one thread,
      // so cancellation is not safe.
      ec = boost::asio::error::operation_not_supported;
    }

    return ec;
  }
Example #24
0
// Pass the given chars directly to _out.
void xmlStream::write(const char* s, size_t len) {
  if (!is_open())  return;

  out()->write(s, len);
  update_position(s, len);
}
  void async_read_some_at(implementation_type& impl, boost::uint64_t offset,
      const MutableBufferSequence& buffers, Handler handler)
  {
    if (!is_open(impl))
    {
      this->get_io_service().post(bind_handler(handler,
            boost::asio::error::bad_descriptor, 0));
      return;
    }

    // Update the ID of the thread from which cancellation is safe.
    if (impl.safe_cancellation_thread_id_ == 0)
      impl.safe_cancellation_thread_id_ = ::GetCurrentThreadId();
    else if (impl.safe_cancellation_thread_id_ != ::GetCurrentThreadId())
      impl.safe_cancellation_thread_id_ = ~DWORD(0);

    // Allocate and construct an operation to wrap the handler.
    typedef read_operation<MutableBufferSequence, Handler> value_type;
    typedef handler_alloc_traits<Handler, value_type> alloc_traits;
    raw_handler_ptr<alloc_traits> raw_ptr(handler);
    handler_ptr<alloc_traits> ptr(raw_ptr, iocp_service_, buffers, handler);

    // Find first buffer of non-zero length.
    boost::asio::mutable_buffer buffer;
    typename MutableBufferSequence::const_iterator iter = buffers.begin();
    typename MutableBufferSequence::const_iterator end = buffers.end();
    for (DWORD i = 0; iter != end; ++iter, ++i)
    {
      buffer = boost::asio::mutable_buffer(*iter);
      if (boost::asio::buffer_size(buffer) != 0)
        break;
    }

    // A request to receive 0 bytes on a stream handle is a no-op.
    if (boost::asio::buffer_size(buffer) == 0)
    {
      boost::asio::io_service::work work(this->get_io_service());
      ptr.reset();
      boost::system::error_code error;
      iocp_service_.post(bind_handler(handler, error, 0));
      return;
    }

    // Read some data.
    DWORD bytes_transferred = 0;
    ptr.get()->Offset = offset & 0xFFFFFFFF;
    ptr.get()->OffsetHigh = (offset >> 32) & 0xFFFFFFFF;
    BOOL ok = ::ReadFile(impl.handle_,
        boost::asio::buffer_cast<LPVOID>(buffer),
        static_cast<DWORD>(boost::asio::buffer_size(buffer)),
        &bytes_transferred, ptr.get());
    DWORD last_error = ::GetLastError();
    if (!ok && last_error != ERROR_IO_PENDING && last_error != ERROR_MORE_DATA)
    {
      boost::asio::io_service::work work(this->get_io_service());
      ptr.reset();
      boost::system::error_code ec(last_error,
          boost::asio::error::get_system_category());
      iocp_service_.post(bind_handler(handler, ec, bytes_transferred));
    }
    else
    {
      ptr.release();
    }
  }
Example #26
0
 File::~File() {
     if (is_open()) {
         ::close(_fd);
     }
     _fd = -1;
 }
Example #27
0
void Socket::WriteData(bamboo::protocol::MessageIf* message) {
  if (!is_open()) return;

  WriteData(message->Build());
}
Example #28
0
 File::~File() {
     if (is_open()) {
         CloseHandle(_handle);
     }
     _handle = INVALID_HANDLE_VALUE;
 }
Example #29
0
 void WalletDb::set_last_wallet_child_key_index( uint32_t key_index )
 { try {
     FC_ASSERT( is_open() ,"Wallet not open!");
     set_property( next_child_key_index, key_index );
 } FC_CAPTURE_AND_RETHROW( (key_index) ) }
void ProgressivePNGImageFileReader::read_canvas_properties(
    CanvasProperties&   props)
{
    assert(is_open());
    props = impl->m_image->properties();
}