Ejemplo n.º 1
0
Archivo: mct.c Proyecto: elominp/zappy
bool
mct(t_cli *c, t_msg *msg)
{
  int64_t	x;
  int64_t	y;
  int64_t	xmax;
  int64_t	ymax;
  t_list	*params;

  (void)msg;
  x = 0;
  y = 0;
  xmax = c->servptr->map.width;
  ymax = c->servptr->map.height;
  if ((params = new_list()) == NULL || init_list(params) == false)
    return (ERR(RED"Omg malloc failed, BAIL OUT BAIL OUT\n"WHITE), false);
  while (y <= xmax)
    {
      while (x <= ymax)
	{
	  prepare_message(params, x, y);
	  bct(c, &(t_msg){NULL, "bct", params, 0});
	  x++;
	}
      x = 0;
      y++;
    }
  return (list_destruct(&params, &free), true);
}
Ejemplo n.º 2
0
Archivo: log.c Proyecto: dstam/core
void log_entry(LogLevel level, char *format, ...)
{
    if (level > CURRENT_LEVEL)
    {
        return;
    }

    va_list ap;
    va_start(ap, format);
    char *message = prepare_message(format, ap);
    va_end(ap);

    switch (level)
    {
    case LogCritical:
    case LogNormal:
    case LogVerbose:
        write_console_log_entry(message);
        write_file_log_entry(message);
        break;
    case LogDebug:
        write_file_log_entry(message);
        break;
    }

    free(message);
}
Ejemplo n.º 3
0
BOOST_FIXTURE_TEST_CASE(test_connection_closed_when_illegal_message, F)
{
	int ret = alloc_websocket_peer(connection);
	BOOST_REQUIRE_MESSAGE(ret == 0, "alloc_websocket_peer did not return 0");

	struct websocket *socket = (struct websocket *)connection->parser.data;
	socket->upgrade_complete = true;

	uint8_t mask[4] = {0xaa, 0x55, 0xcc, 0x11};
	prepare_message(WS_OPCODE_ILLEGAL, NULL, 0, true, mask);
	ws_get_header(socket, read_buffer_ptr++, read_buffer_length);

	BOOST_CHECK_MESSAGE(num_close_called == 1, "Close of buffered_reader was not called when receiving an illegal frame!");
	BOOST_CHECK_MESSAGE(is_close_frame(WS_CLOSE_UNSUPPORTED), "No close frame sent when receiving an illegal frame!");
}
void print_string(const char *string, int num_lines, int freq_min, int freq_max, int col_time_ms)
{
    Context context;
    Pa_Initialize();
    context_init(&context, num_lines, freq_min, freq_max, col_time_ms);
    start_playback(&context);
    int num_cols = 0;
    const char *message = prepare_message(string, &num_cols);
    for (int col = 0; col < num_cols; col++) {
        const char *col_start = message + col*ROWS_PER_LETTER;
        print_text_column(&context, col_start, ROWS_PER_LETTER);
    }
    free((void*)message);
    stop_playback(&context);
    Pa_Terminate();
    context_dealloc(&context);
}
Ejemplo n.º 5
0
/* Prepare DHCPv4 Message request and send it to peer */
static void send_request(struct net_if *iface, bool renewal)
{
	struct net_buf *buf;

	buf = prepare_message(iface, DHCPV4_MSG_TYPE_REQUEST);
	if (!buf) {
		goto fail;
	}

	if (!add_server_id(buf) ||
	    !add_req_ipaddr(buf) ||
	    !add_end(buf)) {
		goto fail;
	}

	setup_header(buf);

	if (net_send_data(buf) < 0) {
		goto fail;
	}

	if (renewal) {
		iface->dhcpv4.state = NET_DHCPV4_RENEWAL;
	} else {
		iface->dhcpv4.state = NET_DHCPV4_REQUEST;
	}

	iface->dhcpv4.attempts++;

	k_delayed_work_init(&iface->dhcpv4_timeout, dhcpv4_timeout);
	k_delayed_work_submit(&iface->dhcpv4_timeout, get_dhcpv4_timeout());

	return;

fail:
	NET_DBG("Message preparation failed");

	if (!buf) {
		net_nbuf_unref(buf);
	}
}
Ejemplo n.º 6
0
/* Prepare DHCPv4 Discover message and broadcast it */
static void send_discover(struct net_if *iface)
{
	struct net_buf *buf;

	iface->dhcpv4.xid++;

	buf = prepare_message(iface, DHCPV4_MSG_TYPE_DISCOVER);
	if (!buf) {
		goto fail;
	}

	if (!add_req_options(buf) ||
	    !add_end(buf)) {
		goto fail;
	}

	setup_header(buf);

	if (net_send_data(buf) < 0) {
		goto fail;
	}

	iface->dhcpv4.state = NET_DHCPV4_DISCOVER;

	k_delayed_work_init(&iface->dhcpv4_timeout, dhcpv4_timeout);
	k_delayed_work_submit(&iface->dhcpv4_timeout, get_dhcpv4_timeout());

	return;

fail:
	NET_DBG("Message preparation failed");

	if (!buf) {
		net_nbuf_unref(buf);
	}
}
Ejemplo n.º 7
0
/*
 * The entry point in C.
 *
 * The bootstrap routine has to load the kickstart at 0x01000000, with RO sections growing up the memory and 
 * RW sections stored beneath the 0x01000000 address. It is supposed to transfer the GRUB information further 
 * into the 64-bit kickstart.
 *
 * The kickstart is assembled from modules which have been loaded by GRUB. The modules may be loaded separately,
 * or as a collection in PKG file. If some file is specified in both PKG file and list of separate modules, the
 * copy in PKG will be skipped.
*/
static void __bootstrap(unsigned int magic, void *mb)
{
    struct mb_mmap *mmap = NULL;
    unsigned long len = 0;
    unsigned long ro_size = 0;
    unsigned long rw_size = 0;
    unsigned long ksize;
    unsigned long mod_end = 0;
    unsigned long kbase = 0;
    unsigned long kstart = 0;
    void *kend = NULL;
    kernel_entry_fun_t kentry = NULL;
    struct ELF_ModuleInfo *kdebug = NULL;
#ifdef DEBUG_MEM
    struct mb_mmap *mm2;
#endif

    /*
     * This will set fb_Mirror address to start of our working memory.
     * We don't know its size yet, we will allocate it later.
     */
    fb_Mirror = __bs_malloc(0);

#ifdef MULTIBOOT_64BIT
    /*
     * tell the CPU that we will support SSE. We do it here because x86-64 compiler
     * with -m32 switch will use SSE for operations on long longs.
     */                                                                                    
    wrcr(cr4, rdcr(cr4) | (3 << 9));                                                                                               
    /* Clear the EM and MP flags of CR0 */                                                                                         
    wrcr(cr0, rdcr(cr0) & ~6);
#endif

    switch(magic)
    {
    case MB_STARTUP_MAGIC:
	/* Parse multiboot v1 information */
	mod_end = mb1_parse(mb, &mmap, &len);
	break;

    case MB2_STARTUP_MAGIC:
    	/* Parse multiboot v2 information */
    	mod_end = mb2_parse(mb, &mmap, &len);
	break;

    default:
    	/* What to do here? We have no console... Die silently... */
    	return;
    }

#ifdef DEBUG_MEM
    ksize = len;
    mm2   = mmap;

    kprintf("[BOOT] Memory map contents:\n", mmap);
    while (ksize >= sizeof(struct mb_mmap))
    {
#ifdef DEBUG_MEM_TYPE
        if (mm2->type == DEBUG_MEM_TYPE)
#endif
	    kprintf("[BOOT] Type %lu addr %p len %p\n", mm2->type, mm2->addr, mm2->len);

        ksize -= mm2->size+4;
        mm2 = (struct mb_mmap *)(mm2->size + (unsigned long)mm2 + 4);
    }
#endif

    D(kprintf("[BOOT] Modules end at 0x%p\n", mod_end));
    if (!firstMod)
    {
    	panic("No kickstart modules found, nothing to run");
    }

    tag->ti_Tag = KRN_MMAPAddress;
    tag->ti_Data = KERNEL_OFFSET | (unsigned long)mmap;
    tag++;

    tag->ti_Tag = KRN_MMAPLength;
    tag->ti_Data = len;
    tag++;

    /* Setup stage - prepare the environment */
    setup_mmu();

    /* Count kickstart size */
    if (!GetKernelSize(firstMod, &ro_size, &rw_size, NULL))
    {
    	panic("Failed to determine kickstart size");
    }

    D(kprintf("[BOOT] Code %u, data %u\n", ro_size, rw_size));

    /*
     * Total kickstart size + alignment window (page size - 1) + some free space (512KB) for
     * boot-time memory allocator.
     * TODO: This is a temporary thing. Currently our kernel expects that it can use addresses beyond
     * KRN_KernelHighest to store boot-time private data, supervisor stack, segment descriptors, MMU stuff, etc.
     * The area is joined with read-only section because it's accessed only by supervisor-mode code
     * and can safely be marked as read-only for users.
     * Boot-time allocator needs to be smarter.
     */
    ksize = ro_size + rw_size + PAGE_SIZE - 1 + 0x80000;

    /* Now locate the highest appropriate region */
    while (len >= sizeof(struct mb_mmap))
    {
        if (mmap->type == MMAP_TYPE_RAM)
        {
            unsigned long long start = mmap->addr;
            unsigned long long end = mmap->addr + mmap->len;

	    /*
	     * The region must be located in 32-bit memory and must not overlap
	     * our modules.
	     * Here we assume the following:
	     * 1. Multiboot data from GRUB is placed in low memory.
	     * 2. At least one module is placed in upper memory, above ourselves.
	     * 3. There's no usable space below our modules.
	     */
	    if ((start <= 0x100000000ULL - ksize) && (end >= mod_end + ksize))
	    {
		unsigned long size;

	    	if (start < mod_end)
	    	    start = mod_end;

	    	if (end > 0x100000000ULL)
	    	    end = 0x100000000ULL;

		/* Remember the region if it fits in */
		size = end - start;
		if (size >= ksize)
		{
		    /*
		     * We place .data section at the start of the region, followed by .code section
		     * at page-aligned 'kbase' address.
		     * There must be a space beyond kickstart's read-only section, because the kickstart
		     * will extend it in order to store boot-time configuration and own private data.
		     */
		    kstart = start;
		    kbase = start + rw_size;
		    kbase = (kbase + PAGE_SIZE - 1) & ~(PAGE_SIZE - 1);
	    	}
	    }
	}

        len -= mmap->size+4;
        mmap = (struct mb_mmap *)(mmap->size + (unsigned long)mmap+4);
    }

    if (!kbase)
    {
    	panic("Failed to find %u bytes for the kickstart.\n"
    	      "Your system doesn't have enough memory.");
    }

    kprintf("[BOOT] Loading kickstart, data 0x%p, code 0x%p...\n", kstart, kbase);

    if (!LoadKernel(firstMod, (void *)kbase, (void *)kstart, (char *)__bss_track, DEF_SYSBASE, &kend, &kentry, &kdebug))
    {
        panic("Failed to load the kickstart");
    }

    /* Prepare the rest of boot taglist */
    prepare_message(kstart, kbase, kend, kdebug);

#ifdef DEBUG_TAGLIST
    kprintf("[BOOT] Boot taglist:\n");
    for (tag = km; tag->ti_Tag != TAG_DONE; tag++)
    	kprintf("[BOOT] 0x%llp 0x%llp\n", tag->ti_Tag, tag->ti_Data);
#endif

    /* Jump to the kickstart */
    kick(kentry, km);

    panic("Failed to run the kickstart");
}
Ejemplo n.º 8
0
static void prepare_message_string(uint8_t type, const char *message, bool shall_mask, uint8_t mask[4])
{
	prepare_message(type, (uint8_t *)message, ::strlen(message), shall_mask, mask);
}
Ejemplo n.º 9
0
	void net_process() {
		while (true) {
			struct bitcoin_msg_header header;
			if (read_all(sock, (char*)&header, sizeof(header)) != sizeof(header))
				return disconnect("failed to read message header");

			if (header.magic != BITCOIN_MAGIC)
				return disconnect("invalid magic bytes");

			struct timeval start_read;
			gettimeofday(&start_read, NULL);

			header.length = le32toh(header.length);
			if (header.length > 5000000)
				return disconnect("got message too large");

			auto msg = std::make_shared<std::vector<unsigned char> > (sizeof(struct bitcoin_msg_header) + uint32_t(header.length));
			if (read_all(sock, (char*)&(*msg)[sizeof(struct bitcoin_msg_header)], header.length) != int(header.length))
				return disconnect("failed to read message");

			unsigned char fullhash[32];
			CSHA256 hash;
			hash.Write(&(*msg)[sizeof(struct bitcoin_msg_header)], header.length).Finalize(fullhash);
			hash.Reset().Write(fullhash, sizeof(fullhash)).Finalize(fullhash);
			if (memcmp((char*)fullhash, header.checksum, sizeof(header.checksum)))
				return disconnect("got invalid message checksum");

			if (!strncmp(header.command, "version", strlen("version"))) {
				if (connected != 0)
					return disconnect("got invalid version");
				connected = 1;

				if (header.length < sizeof(struct bitcoin_version_start))
					return disconnect("got short version");
				struct bitcoin_version_start *their_version = (struct bitcoin_version_start*) &(*msg)[sizeof(struct bitcoin_msg_header)];

				printf("%s Protocol version %u\n", host.c_str(), le32toh(their_version->protocol_version));

				struct bitcoin_version_with_header version_msg;
				version_msg.version.start.timestamp = htole64(time(0));
				memcpy(((char*)&version_msg.version.end.user_agent) + 27, location, 7);
				static_assert(BITCOIN_UA_LENGTH == 27 + 7 + 2 /* 27 + 7 + '/' + '\0' */, "BITCOIN_UA changed in header but file not updated");

				prepare_message("version", (unsigned char*)&version_msg, sizeof(struct bitcoin_version));
				if (send_all(sock, (char*)&version_msg, sizeof(struct bitcoin_version_with_header)) != sizeof(struct bitcoin_version_with_header))
					return disconnect("failed to send version message");

				struct bitcoin_msg_header verack_header;
				prepare_message("verack", (unsigned char*)&verack_header, 0);
				if (send_all(sock, (char*)&verack_header, sizeof(struct bitcoin_msg_header)) != sizeof(struct bitcoin_msg_header))
					return disconnect("failed to send verack");

				continue;
			} else if (!strncmp(header.command, "verack", strlen("verack"))) {
				if (connected != 1)
					return disconnect("got invalid verack");
				connected = 2;
				send_mutex.unlock();

				continue;
			}

			if (connected != 2)
				return disconnect("got non-version, non-verack before version+verack");

			if (!strncmp(header.command, "ping", strlen("ping"))) {
				memcpy(&header.command, "pong", sizeof("pong"));
				memcpy(&(*msg)[0], &header, sizeof(struct bitcoin_msg_header));
				std::lock_guard<std::mutex> lock(send_mutex);
				if (send_all(sock, (char*)&(*msg)[0], sizeof(struct bitcoin_msg_header) + header.length) != int64_t(sizeof(struct bitcoin_msg_header) + header.length))
					return disconnect("failed to send pong");
				continue;
			} else if (!strncmp(header.command, "inv", strlen("inv"))) {
				std::lock_guard<std::mutex> lock(send_mutex);

				try {
					std::set<std::vector<unsigned char> > setRequestBlocks;
					std::set<std::vector<unsigned char> > setRequestTxn;

					std::vector<unsigned char>::const_iterator it = msg->begin();
					it += sizeof(struct bitcoin_msg_header);
					uint64_t count = read_varint(it, msg->end());
					if (count > 50000)
						return disconnect("inv count > MAX_INV_SZ");

					uint32_t MSG_TX = htole32(1);
					uint32_t MSG_BLOCK = htole32(2);

					for (uint64_t i = 0; i < count; i++) {
						move_forward(it, 4 + 32, msg->end());
						std::vector<unsigned char> hash(it-32, it);

						const uint32_t type = (*(it-(1+32)) << 24) | (*(it-(2+32)) << 16) | (*(it-(3+32)) << 8) | *(it-(4+32));
						if (type == MSG_TX) {
							if (!txnAlreadySeen.insert(hash).second)
								continue;
							setRequestTxn.insert(hash);
						} else if (type == MSG_BLOCK) {
							if (!blocksAlreadySeen.insert(hash).second)
								continue;
							setRequestBlocks.insert(hash);
						} else
							return disconnect("unknown inv type");
					}

					if (setRequestBlocks.size()) {
						std::vector<unsigned char> getdataMsg;
						std::vector<unsigned char> invCount = varint(setRequestBlocks.size());
						getdataMsg.reserve(sizeof(struct bitcoin_msg_header) + invCount.size() + setRequestBlocks.size()*36);

						getdataMsg.insert(getdataMsg.end(), sizeof(struct bitcoin_msg_header), 0);
						getdataMsg.insert(getdataMsg.end(), invCount.begin(), invCount.end());

						for (auto& hash : setRequestBlocks) {
							getdataMsg.insert(getdataMsg.end(), (unsigned char*)&MSG_BLOCK, ((unsigned char*)&MSG_BLOCK) + 4);
							getdataMsg.insert(getdataMsg.end(), hash.begin(), hash.end());
						}

						prepare_message("getdata", (unsigned char*)&getdataMsg[0], invCount.size() + setRequestBlocks.size()*36);
						if (send_all(sock, (char*)&getdataMsg[0], sizeof(struct bitcoin_msg_header) + invCount.size() + setRequestBlocks.size()*36) !=
								int(sizeof(struct bitcoin_msg_header) + invCount.size() + setRequestBlocks.size()*36))
							return disconnect("error sending getdata");

						for (auto& hash : setRequestBlocks) {
							struct timeval tv;
							gettimeofday(&tv, NULL);
							for (unsigned int i = 0; i < hash.size(); i++)
								printf("%02x", hash[hash.size() - i - 1]);
							printf(" requested from %s at %lu\n", host.c_str(), uint64_t(tv.tv_sec) * 1000 + uint64_t(tv.tv_usec) / 1000);
						}
					}

					if (setRequestTxn.size()) {
						std::vector<unsigned char> getdataMsg;
						std::vector<unsigned char> invCount = varint(setRequestTxn.size());
						getdataMsg.reserve(sizeof(struct bitcoin_msg_header) + invCount.size() + setRequestTxn.size()*36);

						getdataMsg.insert(getdataMsg.end(), sizeof(struct bitcoin_msg_header), 0);
						getdataMsg.insert(getdataMsg.end(), invCount.begin(), invCount.end());

						for (const std::vector<unsigned char>& hash : setRequestTxn) {
							getdataMsg.insert(getdataMsg.end(), (unsigned char*)&MSG_TX, ((unsigned char*)&MSG_TX) + 4);
							getdataMsg.insert(getdataMsg.end(), hash.begin(), hash.end());
						}

						prepare_message("getdata", (unsigned char*)&getdataMsg[0], invCount.size() + setRequestTxn.size()*36);
						if (send_all(sock, (char*)&getdataMsg[0], sizeof(struct bitcoin_msg_header) + invCount.size() + setRequestTxn.size()*36) !=
								int(sizeof(struct bitcoin_msg_header) + invCount.size() + setRequestTxn.size()*36))
							return disconnect("error sending getdata");
					}
				} catch (read_exception) {
					return disconnect("failed to process inv");
				}
				continue;
			}

			memcpy(&(*msg)[0], &header, sizeof(struct bitcoin_msg_header));
			if (!strncmp(header.command, "block", strlen("block"))) {
				provide_block(this, msg, start_read);
			} else if (!strncmp(header.command, "tx", strlen("tx"))) {
				provide_transaction(this, msg);
			}
		}
	}