Exemplo n.º 1
0
stringer_t * imap_build_array_isliteral(placer_t data) {

	size_t length;
	chr_t *holder, buffer[32];

	if (pl_empty(data)) {
		return NULL;
	}

	length = pl_length_get(data);
	holder = pl_data_get(data);

	// Look for illegal characters.
	for (size_t i = 0; i < length; i++) {
		if ((*holder >= '*' && *holder <= '~') || *holder == ' ' || *holder == '_'	|| *holder == '!' || (*holder >= '#' && *holder <= '&')) {
			holder++;
		}
		else {
			snprintf(buffer, 32, "{%zu}\r\n", length);
			return st_merge("ns", buffer, &data);

		}
	}

	return NULL;
}
Exemplo n.º 2
0
/**
 * @brief	Truncate a placer to start before any of the specified characters, and update the placer accordingly.
 * @param	place		a pointer to a placer that will be updated to be truncated before any of the specified characters.
 * @param	shrinkchars	a pointer to a buffer containing bytes that will be skipped when they are found at the end of the placer.
 * @param	nchars		the number of characters to be tested in the collection in shrinkchars.
 * @return	true if the shrink operation completed before the end of the placer was reached, or false otherwise.
 */
bool_t pl_shrink_before_characters (placer_t *place, char *shrinkchars, size_t nchars) {

	char *ptr = pl_char_get(*place) + pl_length_get(*place) - 1;

	if (pl_empty(*place)) {
		return false;
	}

	for (int i = 0; i < place->length; i++, ptr--) {

		for (int j = 0; j <= nchars; j++) {

				// We went through all the skip characters without finding something... so this is where we return.
				if (j == nchars) {
					place->length -= i;
					return true;
				}

				if (*ptr == shrinkchars[j])
					break;

		}

	}

	return false;
}
Exemplo n.º 3
0
/**
 * @brief	Get a placer pointing to the text contained within a specified pair of opening and closing braces.
 * @param	str			a placer pointing to the string to be parsed.
 * @param	out			a pointer to a placer that will store the string between the braces on success.
 * @param	opening		the character to be the opening brace of the sequence.
 * @param	closing		the character to be the closing brace of the sequence.
 * @param	required	if true, fail if no data was found between the pair of braces.
 * @return	true if the brace sequence was complete, or false if either component could not be located.
 */
bool_t pl_get_embraced (placer_t str, placer_t *out, unsigned char opening, unsigned char closing, bool_t required) {

	char *ptr = pl_char_get(str);

	if (pl_empty(str)) {
		return false;
	}

	// Must have at least 2 characters for the opening and closing
	if (str.length < 2) {
		return false;
	} else if (*ptr != opening) {
		return false;
	}

	ptr++;

	for (int i = 1; i < str.length; i++, ptr++) {

		if (*ptr == closing) {

			if (required && i <= 1) {
				return false;
			}

			out->data = pl_char_get(str) + 1;
			out->length = i - 1;
			return true;
		}

	}

	// We hit the end without finding a closing character...
	return false;
}
Exemplo n.º 4
0
/**
 * @brief	Skip to the first instance of any of the specified characters in the placer, and update the placer accordingly.
 * @param	place		a pointer to a placer that will be updated to skip to any of the specified characters.
 * @param	skiptochars	a pointer to a buffer containing bytes that will be skipped to when they are first found in the placer.
 * @param	nchars		the number of characters to be tested in the collection in skiptochars.
 * @return	true if the skip operation completed before the end of the placer was reached, or false otherwise.
 */
bool_t pl_skip_to_characters (placer_t *place, char *skiptochars, size_t nchars) {

	char *ptr = pl_char_get(*place);

	if (pl_empty(*place)) {
		return false;
	}

	for (int i = 0; i < place->length; i++, ptr++) {

		for (int j = 0; j < nchars; j++) {

			// We went through all the skip characters without finding something... so this is where we return.
			if (*ptr == skiptochars[j]) {
				place->data = (char *) place->data + i;
				place->length -= i;
				return true;
			}

		}

	}

	return false;
}
Exemplo n.º 5
0
void test_random(int *score, int *maxtile) {
    printf("Playing random...\n");
    Game g = init_game(squaresum_heuristic);
    PointList pl = open_spaces(g->board);
    while (!pl_empty(pl)) {
        pl_free(pl);
        make_move(g, (Move)randint(4));
        pl = open_spaces(g->board);
    }
    pl_free(pl);
    *score = g->score;
    *maxtile = max_tile(g->board);
    game_free(g);
}
Exemplo n.º 6
0
/**
 * @brief	Count the number of instances of a boundary string inside a MIME body.
 * @note	The search is terminated if "--" is found right after the boundary string.
 * @param	body		a placer containing the body text to be parsed.
 * @param	boundary	a pointer to a managed string containing the boundary string for the MIME content.
 * @return	0 on failure, or the number of times the boundary string was located in the MIME body on success.
 */
uint32_t mail_mime_count(placer_t body, stringer_t *boundary) {

	uint32_t result = 0;
	chr_t *stream, *bounddata;
	size_t increment = 0, length, boundlen;

	if (pl_empty(body) || st_empty(boundary)) {
		return 0;
	}

	// Figure out the lengths.
	if (!(length = st_length_get(&body))) {
		log_pedantic("Cannot count boundary marker in zero-length MIME body..");
		return 0;
	}
	else if (!(boundlen = st_length_get(boundary))) {
		log_pedantic("Cannot count zero-length MIME boundary.");
		return 0;
	}

	// Setup.
	stream = st_char_get(&body);
	bounddata = st_char_get(boundary);

	// Find the start of the first part.
	while (increment + boundlen <= length) {

		if (mm_cmp_cs_eq(stream, bounddata, boundlen) == 0) {
			stream += boundlen + 1;
			increment += boundlen + 1;

			// Two dashes indicate the end of this mime sections.
			if (increment + 1 <= length && mm_cmp_cs_eq(stream, "--", 2) == 0) {
				increment = length + 1;
			}
			else {
				result++;
			}
		}
		else {
			stream++;
			increment++;
		}
	}

	return result;
}
Exemplo n.º 7
0
stringer_t * imap_parse_address(stringer_t *address) {

	placer_t token;
	uint32_t part = 0;
	stringer_t *holder, *value, *output = NULL;

	if (address == NULL) {
		return NULL;
	}

	while (!pl_empty((token = imap_parse_address_breaker(address, part++)))) {

		holder = imap_parse_address_part(token);

		if (output != NULL) {
			if ((value = st_merge("sns", output, " ", holder)) != NULL) {
				st_free(holder);
				st_free(output);
				output = value;
			}
			else {
				st_free(holder);
			}
		}
		else {
			output = holder;
		}
	}

	if (output != NULL && (value = imap_build_array("a", output)) != NULL) {
		st_free(output);
		output = value;
	}

	return output;
}
Exemplo n.º 8
0
/**
 * @brief	Get a placer pointing to the specified child inside a MIME body.
 * @param	body		a placer containing the body text to be parsed.
 * @param	boundary	a pointer to a managed string containing the boundary string to split the MIME content.
 * @param	child		the zero-based index of the MIME child to be located in the body text.
 * @return	pl_null() on failure, or a placer containing the specified MIME child on success.
 */
placer_t mail_mime_child(placer_t body, stringer_t *boundary, uint32_t child) {

	uint32_t result = 0;
	chr_t *start, *stream, *bounddata;
	size_t increment = 0, length, boundlen;

	if (pl_empty(body) || st_empty(boundary)) {
		return pl_null();
	}

	// Figure out the lengths.
	if (!(length = st_length_get(&body))) {
		log_pedantic("Cannot parse children from zero-length MIME body..");
		return pl_null();
	}
	else if (!(boundlen = st_length_get(boundary))) {
		log_pedantic("Cannot parse children from MIME body with zero-length boundary.");
		return pl_null();;
	}

	// Setup.
	stream = st_char_get(&body);
	bounddata = st_char_get(boundary);

	// Find the start of the first part.
	while (increment + boundlen <= length && result < child) {

		if (mm_cmp_cs_eq(stream, bounddata, boundlen) == 0 && (increment + boundlen == length || *(stream + boundlen) < '!' || *(stream + boundlen) > '~')) {
			stream += boundlen;
			increment += boundlen;

			// Two dashes indicate the end of this mime sections.
			if (increment < length && mm_cmp_cs_eq(stream, "--", 2) == 0) {
				increment = length + 1;
			}
			else {
				result++;
			}

		}
		else {
			stream++;
			increment++;
		}

	}

	// The requested child wasn't found.
	if (increment + boundlen >= length) {
		return pl_null();
	}

	// This will skip a line break after the boundary marker.
	if (length - increment > 0 && *stream == '\r') {
		stream++;
		increment++;
	}

	if (length - increment > 0 && *stream == '\n') {
		stream++;
		increment++;
	}

	// Store the start position.
	start = stream;

	// Find the end.
	while (increment < length) {

		if (increment + boundlen < length && mm_cmp_cs_eq(stream, bounddata, boundlen) == 0) {
			increment = length;
		}
		else {
			stream++;
			increment++;
		}
	}

	// Make sure we advanced.
	if (stream == start) {
		return pl_null();
	}

	return pl_init(start, stream - start);
}
Exemplo n.º 9
0
/**
 * @brief	Perform client command processing on an established imap session.
 * @note	This function will read the next line of user input, parse the command, and then attempt to execute it with the appropriate handler.
 * @param	con		a pointer to the connection object underlying the imap session.
 * @return	This function returns no value.
 */
void imap_process(connection_t *con) {

	int_t state;
	command_t *command, client = { .function = NULL };

	// If the connection indicates an error occurred, or the socket was closed by the client we send the connection to the logout function.
	if (((state = con_read_line(con, false)) < 0) || (state == -2)) {
		con->command = NULL;
		enqueue(&imap_logout, con);
		return;
	}
	else if (pl_empty(con->network.line) && ((con->protocol.spins++) + con->protocol.violations) > con->server->violations.cutoff) {
		con->command = NULL;
		enqueue(&imap_logout, con);
		return;
	}
	else if (pl_empty(con->network.line)) {
		con->command = NULL;
		enqueue(&imap_process, con);
		return;
	}

	// Parse the line into its tag and command elements.
	if ((state = imap_command_parser(con)) < 0) {

		// Try to be helpful about the parsing error.
		if (state == -1) {
			con_write_bl(con, "* BAD Unable to parse the command tag.\r\n", 40);
		}
		else if (state == -2) {
			con_print(con, "%.*s BAD Unable to parse the command.\r\n", st_length_int(con->imap.tag), st_char_get(con->imap.tag));
		}
		else {
			con_print(con, "%.*s BAD The command arguments were submitted using an invalid syntax.\r\n", st_length_int(con->imap.tag), st_char_get(con->imap.tag));
		}

		// If the client keeps breaking rules drop them.
		if (((con->protocol.spins++) + con->protocol.violations) > con->server->violations.cutoff) {
			con->command = NULL;
			enqueue(&imap_logout, con);
			return;
		}

		// Requeue and hope the next line of data is useful.
		con->command = NULL;
		enqueue(&imap_process, con);
		return;

	}

	client.string = st_char_get(con->imap.command);
	client.length = st_length_get(con->imap.command);

	if ((command = bsearch(&client, imap_commands, sizeof(imap_commands) / sizeof(imap_commands[0]), sizeof(command_t), imap_compare))) {

		con->command = command;
		con->protocol.spins = 0;

		if (command->function == &imap_logout) {
			enqueue(command->function, con);
		}
		else {
			requeue(command->function, &imap_requeue, con);
		}
	}
	else {
		con->command = NULL;
		requeue(&imap_invalid, &imap_requeue, con);
	}
	return;
}
Exemplo n.º 10
0
Arquivo: read.c Projeto: lavabit/magma
/**
 * @brief	Read a line of input from a network connection.
 * @note	This function handles reading data from both regular and ssl connections.
 * 			This function continually attempts to read incoming data from the specified connection until a \n terminated line of input is received.
 * 			If a new line is read, the length of that line is returned to the caller, including the trailing \n.
 * 			If the read returns -1 and wasn't caused by a syscall interruption or blocking error, -1 is returned, and the connection status is set to -1.
 * 			If the read returns 0 and wasn't caused by a syscall interruption or blocking error, -2 is returned, and the connection status is set to 2.
 * 			Once a \n character is reached, the length of the current line of input is returned to the user, and the connection status is set to 1.
 * @param	con		the network connection across which the line of data will be read.
 * @return	-1 on general failure, -2 if the connection was reset, or the length of the current line of input, including the trailing new line character.
 */
int64_t con_read_line(connection_t *con, bool_t block) {

	ssize_t bytes = 0;
	int_t counter = 0;
	bool_t line = false;

	if (!con || con->network.sockd == -1 || con_status(con) < 0) {
		if (con) con->network.status = -1;
		return -1;
	}

	// Check for an existing network buffer. If there isn't one, try creating it.
	else if (!con->network.buffer && !con_init_network_buffer(con)) {
		con->network.status = -1;
		return -1;
	}

	// Check if we have received more data than just what is in the current line of input.
	else if (pl_length_get(con->network.line) && st_length_get(con->network.buffer) > pl_length_get(con->network.line)) {

		// If so, move the unused "new" data after the current line marker to the front of the buffer.
		mm_move(st_data_get(con->network.buffer), st_data_get(con->network.buffer) + pl_length_get(con->network.line),
			st_length_get(con->network.buffer) - pl_length_get(con->network.line));

		// Update the buffer length.
		st_length_set(con->network.buffer, st_length_get(con->network.buffer) - pl_length_get(con->network.line));

		// Check whether the data we just moved contains a complete line.
		if (!pl_empty((con->network.line = line_pl_st(con->network.buffer, 0)))) {
			con->network.status = 1;
			return pl_length_get(con->network.line);
		}

	}
	// Otherwise reset the buffer and line lengths to zero.
	else {
		st_length_set(con->network.buffer, 0);
		con->network.line = pl_null();
	}

	// Loop until we get a complete line, an error, or the buffer is filled.
	do {
//		blocking = st_length_get(con->network.buffer) ? false : true;
		block = true;

		if (con->network.tls) {
			bytes = tls_read(con->network.tls, st_char_get(con->network.buffer) + st_length_get(con->network.buffer),
				st_avail_get(con->network.buffer) - st_length_get(con->network.buffer), block);
		}
		else {
			bytes = tcp_read(con->network.sockd, st_char_get(con->network.buffer) + st_length_get(con->network.buffer),
				st_avail_get(con->network.buffer) - st_length_get(con->network.buffer), block);
		}

		// We actually read in data, so we need to update the buffer to reflect the amount of unprocessed data it currently holds.
		if (bytes > 0) {
			st_length_set(con->network.buffer, st_length_get(con->network.buffer) + bytes);
		}
		else if (bytes == 0) {
			usleep(1000);
		}
		else {
			con->network.status = -1;
			return -1;
		}

		// Check whether we have a complete line before checking whether the connection was closed.
		if (!st_empty(con->network.buffer) && !pl_empty((con->network.line = line_pl_st(con->network.buffer, 0)))) {
			line = true;
		}

	} while (!line && block && counter++ < 128 && st_length_get(con->network.buffer) != st_avail_get(con->network.buffer) && status());

	if (st_length_get(con->network.buffer) > 0) {
		con->network.status = 1;
	}

	return pl_length_get(con->network.line);
}
Exemplo n.º 11
0
Arquivo: read.c Projeto: lavabit/magma
/**
 * @brief	Read a line of input from a network client session.
 * @return	-1 on general failure, -2 if the connection was reset, or the length of the current line of input, including the trailing new line character.
 */
int64_t client_read_line(client_t *client) {

	ssize_t bytes = 0;
	int_t counter = 0;
	stringer_t *error = NULL;
	bool_t blocking = true, line = false;

#ifdef MAGMA_PEDANTIC
	int_t local = 0;
	stringer_t *ip = NULL, *cipher = NULL;
#endif

	if (!client || client->sockd == -1) {
		if (client) client->status = 1;
		return -1;
	}

	// Check for data past the current line buffer.
	else if (pl_length_get(client->line) && st_length_get(client->buffer) > pl_length_get(client->line)) {

		// Move the unused data to the front of the buffer.
		mm_move(st_data_get(client->buffer), st_data_get(client->buffer) + pl_length_get(client->line), st_length_get(client->buffer) - pl_length_get(client->line));

		// Update the length.
		st_length_set(client->buffer, st_length_get(client->buffer) - pl_length_get(client->line));

		// Check whether the data we just moved contains a complete line.
		if (!pl_empty((client->line = line_pl_st(client->buffer, 0)))) {
			client->status = 1;
			return pl_length_get(client->line);
		}
	}
	// Otherwise reset the buffer and line lengths to zero.
	else {
		st_length_set(client->buffer, 0);
		client->line = pl_null();
	}

	// Loop until we get a complete line, an error, or the buffer is filled.
	do {

		// Read bytes off the network. Skip past any existing data in the buffer.
		if (client->tls) {

			// If bytes is zero or below and the library isn't asking for another read, then an error occurred.
			bytes = tls_read(client->tls, st_char_get(client->buffer) + st_length_get(client->buffer),
				st_avail_get(client->buffer) - st_length_get(client->buffer), blocking);

			// If zero bytes were read, or a negative value was returned to indicate an error, call tls_erorr(), which will return
			// NULL if the error can be safely ignored. Otherwise log the output for debug purposes.
			if (bytes <= 0 && (error = tls_error(client->tls, bytes, MANAGEDBUF(512)))) {
#ifdef MAGMA_PEDANTIC
				cipher = tls_cipher(client->tls, MANAGEDBUF(128));
				ip = ip_presentation(client->ip, MANAGEDBUF(INET6_ADDRSTRLEN));

				log_pedantic("TLS client read operation failed. { ip = %.*s / %.*s / result = %zi%s%.*s }",
					st_length_int(ip), st_char_get(ip), st_length_int(cipher), st_char_get(cipher),
					bytes, (error ? " / " : ""), st_length_int(error), st_char_get(error));
#endif
				client->status = -1;
				return -1;
			}
			// This will occur when the read operation results in a 0, or negative value, but TLS error returns NULL to
			// indicate it was a transient error. For transient errors we simply set bytes equal to 0 so the read call gets retried.
			else if (bytes <= 0) {
				bytes = 0;
			}
		}
		else {

			errno = 0;

			bytes = recv(client->sockd, st_char_get(client->buffer) + st_length_get(client->buffer),
				st_avail_get(client->buffer) - st_length_get(client->buffer), (blocking ? 0 : MSG_DONTWAIT));

			// Check for errors on non-SSL reads in the traditional way.
			if (bytes <= 0 && tcp_status(client->sockd)) {
#ifdef MAGMA_PEDANTIC
				local = errno;
				ip = ip_presentation(client->ip, MANAGEDBUF(INET6_ADDRSTRLEN));

				log_pedantic("TCP client read operation failed. { ip = %.*s / result = %zi / error = %i / message = %s }",
					st_length_int(ip), st_char_get(ip), bytes, local, strerror_r(local, MEMORYBUF(1024), 1024));
#endif
				client->status = -1;
				return -1;
			}

		}

		// We actually read in data, so we need to update the buffer to reflect the amount of data it currently holds.
		if (bytes > 0) {
			st_length_set(client->buffer, st_length_get(client->buffer) + bytes);
		}

		// Check whether we have a complete line before checking whether the connection was closed.
		if (!st_empty(client->buffer) && !pl_empty((client->line = line_pl_st(client->buffer, 0)))) {
			line = true;
		}

	} while (!line && counter++ < 128 && st_length_get(client->buffer) != st_avail_get(client->buffer) && status());

	if (st_length_get(client->buffer) > 0) {
		client->status = 1;
	}

	return pl_length_get(client->line);
}
Exemplo n.º 12
0
/**
 * @brief	Extract the contents of a literal string and advance the position of the parser stream.
 * @note	This function expects as input a string beginning with '{' and followed by a numerical string, an optional '+', and a closing '}'.
 	 	 	After reading in the numerical size parameter, it then attempts to read in that many bytes of input from the network stream.
 * @param	con		the client IMAP connection passing the literal string as input to the server.
 * @param	output	the address of a managed string that will receive a copy of the literal string's contents on success, or NULL on failure or if it is zero length.
 * @param	start	the address of a pointer to the start of the buffer to be parsed (beginning with '{'), that will also be updated to
 * 					point to the next argument in the sequence on success.
 * @param	length	a pointer to a size_t variable that contains the length of the string to be parsed, and that will be updated to reflect
 * 					the length of the remainder of the input string that follows the parsed literal string.
 * @return	-1 on general or parse error or if an enclosing pair of double quotes was not found, or 1 if the supplied quoted string was valid.
 */
int_t imap_parse_literal(connection_t *con, stringer_t **output, chr_t **start, size_t *length) {

	chr_t *holder;
	int_t plus = 0;
	stringer_t *result;
	size_t characters, left;
	ssize_t nread;
	uint64_t literal, number;

	// Get setup.
	holder = *start;
	left = *length;
	*output = NULL;

	// Skip the opening bracket.
	if (*holder != '{' || !left) {
		return -1;
	}
	else {
		holder++;
		left--;
	}

	// Advance until we have a break character.
	while (left && *holder >= '0' && *holder <= '9') {
		holder++;
		left--;
	}

	// Store the length.
	characters = holder - *start - 1;

	if (left && *holder == '+') {
		plus = 1;
		holder++;
		left--;
	}

	if (*holder != '}' || !characters) {
		return -1;
	}

	// Convert to a number. Make sure the number is positive.
	if (!uint64_conv_bl(*start + 1, characters, &number)) {
		return -1;
	}

	literal = (size_t)number;

	// If the number is larger than 128 megabytes, then reject it.
	if (!plus && number > 134217728) {
		return -1;
	}
	// They client is already transmitting, so read the entire file, then reject it.
	else if (number > 134217728) {

		while (number > 0) {

			// Read the data.
			if ((nread = con_read(con)) <= 0) {
				log_pedantic("The connection was dropped while reading the literal.");
				return -1;
			}

			// Deal with signedness problem.
			characters = nread;

			if (number > (uint64_t)characters) {
				number -= characters;
			}
			else {

				// If we have any extra characters in the buffer, move them to the beginning.
				if ((uint64_t)characters > number) {
					mm_move(st_char_get(con->network.buffer), st_char_get(con->network.buffer) + number, characters - number);
					st_length_set(con->network.buffer, characters - number);
					con->network.line = line_pl_st(con->network.buffer, 0);
				}
				else {
					st_length_set(con->network.buffer, 0);
					con->network.line = pl_null();
				}

				// Make sure we have a full line.
				if (pl_empty(con->network.line) && con_read_line(con, true) <= 0) {
					log_pedantic("The connection was dropped while reading the literal.");
					return -1;
				}

				number = 0;
			}

		}

		return -1;
	}

	// If this is not a plus literal, output the proceed statement.
	if (!plus) {
		con_write_bl(con, "+ GO\r\n", 6);
	}

	// Handle the special case of a zero length literal.
	if (literal == 0) {

		// Read the next line.
		if (con_read_line(con, true) <= 0) {
			log_pedantic("The connection was dropped while reading the literal.");
			return -1;
		}

		*start = st_char_get(con->network.buffer);
		*length = pl_length_get(con->network.line);

		// There should be a space before the next argument.
		if (*length && **start == ' ') {
			(*start)++;
			(*length)--;
		}

		return 1;
	}

	// Allocate a stringer for the buffer.
	if (!(result = st_alloc(literal))) {
		log_pedantic("Unable to allocate a buffer of %lu bytes for the literal argument.", literal);
		return -1;
	}

	// So we know how many more characters to read.
	left = literal;

	// Where we put the data.
	holder = st_char_get(result);

	// Keep looping until we run out of data.
	while (left) {

		// Read the data.
		if ((nread = con_read(con)) <= 0) {
			log_pedantic("The connection was dropped while reading the literal.");
			st_free(result);
			return -1;
		}

		characters = nread;

		// If we have a buffer, copy the data into the buffer.
		mm_copy(holder, st_char_get(con->network.buffer), (left > characters) ? characters : left);

		if (left > characters) {
			holder += characters;
			left -= characters;
		}
		else {
		 	st_length_set(result, literal);

			// If we have any extra characters in the buffer, move them to the beginning.
			if (characters > left) {
				mm_move(st_char_get(con->network.buffer), st_char_get(con->network.buffer) + left, characters - left);
				st_length_set(con->network.buffer, characters - left);
				con->network.line = line_pl_st(con->network.buffer, 0);
			}
			else {
					st_length_set(con->network.buffer, 0);
					con->network.line = pl_null();
			}

			// Make sure we have a full line.
			if (pl_empty(con->network.line) && con_read_line(con, true) <= 0) {
				log_pedantic("The connection was dropped while reading the literal.");
				st_free(result);
				return -1;
			}
			left = 0;
		}
	}

	*start = st_char_get(con->network.buffer);
	*length = pl_length_get(con->network.line);

	// There should be a space before the next argument.
	if (*length && **start == ' ') {
		(*start)++;
		(*length)--;
	}

	if (result != NULL) {
		*output = result;
	}
	else {
		return -1;
	}

	return 1;
}
Exemplo n.º 13
0
/**
 * @brief	Return a zero-length placer pointing to NULL data.
 * @return	a zero-length placer pointing to NULL data.
 */
placer_t pl_null(void) {

	return (placer_t){ .opts = PLACER_T | JOINTED | STACK | FOREIGNDATA, .data = NULL, .length = 0 };
}

/**
 * @brief	Return a placer wrapping a data buffer of given size.
 * @param	data	a pointer to the data to be wrapped.
 * @param	len		the length, in bytes, of the data.
 * @return	a placer pointing to the specified data.
 */
placer_t pl_init(void *data, size_t len) {

	return (placer_t){ .opts = PLACER_T | JOINTED | STACK | FOREIGNDATA, .data = data, .length = len };
}

placer_t pl_clone(placer_t place) {
	return (pl_init(place.data, place.length));
}

placer_t pl_set(placer_t place, placer_t set) {

	return (placer_t){ .opts = place.opts, .data = set.data, .length = set.length };
}

/**
 * @brief	Get a pointer to the data referenced by a placer.
 * @param	place	the input placer.
 * @return	NULL on failure or a pointer to the block of data associated with the specified placer on success.
 */
void * pl_data_get(placer_t place) {

	return st_data_get((stringer_t *)&place);
}

/**
 * @brief	Get a character pointer to the data referenced by a placer.
 * @param	place	the input placer.
 * @return	NULL on failure or a a character pointer to the block of data associated with the specified placer on success.
 */
chr_t * pl_char_get(placer_t place) {

	return st_char_get((stringer_t *)&place);
}

/**
 * @brief	Get the length, in bytes, of a placer as an integer.
 * @param	place	the input placer.
 * @return	the size, in bytes, of the specified placer.
 */
int_t pl_length_int(placer_t place) {

	return st_length_int((stringer_t *)&place);
}

/**
 * @brief	Get the length, in bytes, of a placer.
 * @param	place	the input placer.
 * @return	the size, in bytes, of the specified placer.
 */
size_t pl_length_get(placer_t place) {

	return st_length_get((stringer_t *)&place);
}

/**
 * @brief	Determine whether or not the specified placer is empty.
 * @param	place	the input placer.
 * @return	true if the placer is empty or zero-length, or false otherwise.
 */
bool_t pl_empty(placer_t place) {

	return st_empty((stringer_t *)&place);
}

/**
 * @brief	Determine if a placer begins with a specified character.
 * @param	place	the input placer.
 * @param	c		the character to be compared with the first byte of the placer's data.
 * @return	true if the placer begins with the given character or false otherwise.
 */
bool_t pl_starts_with_char(placer_t place, chr_t c) {

	if (pl_empty(place)) {
		return false;
	}

	if (*(pl_char_get(place)) == c) {
		return true;
	}

	return false;
}

/**
 * @brief	Advance the placer one character forward beyond an expected character.
 * @param	place	the input placer.
 * @param	more	if true, the placer must contain more data, and vice versa.
 * @return	true if more was true and the placer contains more data, or if more was false and the placer ended; false otherwise.
 */
bool_t pl_inc(placer_t *place, bool_t more) {

	if (pl_empty(*place)) {
		return false;
	}

	place->length--;
	place->data = (chr_t *)place->data + 1;

	return (more == (place->length > 0));
}
Exemplo n.º 14
0
void human_game() {
    printf("Welcome to 2048!\n");
    print_commands();


    //char buf[MAXLINE];
    Game g = init_game(squaresum_heuristic);
    print_game(g);

    char in;
    int playing = 1;
    while (playing) {
        in = getc(stdin);
        if (in == '\033') {
            getc(stdin);
            switch (getc(stdin)) {
                case 'A':
                    in = 'u';
                    break;
                case 'B':
                    in = 'd';
                    break;
                case 'C':
                    in = 'r';
                    break;
                case 'D':
                    in = 'l';
                    break;
                default:
                    break;
            }
        }
        switch (in) {
            case 'q':
                playing = 0;
                break;
            case 'u':
                make_move(g, Up);
                print_game(g);
                break;
            case 'd':
                make_move(g, Down);
                print_game(g);
                break;
            case 'l':
                make_move(g, Left);
                print_game(g);
                break;
            case 'r':
                make_move(g, Right);
                print_game(g);
                break;
            case 'h':
                print_commands();
                break;
            default:
                break;
        }
        PointList pl = open_spaces(g->board);
        if (pl_empty(pl)) {
            playing = 0;
        }
        pl_free(pl);
    }
    print_game(g);
    printf("Game Over! Final Score: %d\n", g->score);
}
Exemplo n.º 15
0
/**
 * @brief	Read a line of input from a network connection.
 * @note	This function handles reading data from both regular and ssl connections.
 * 			This function continually attempts to read incoming data from the specified connection until a \n terminated line of input is received.
 * 			If a new line is read, the length of that line is returned to the caller, including the trailing \n.
 * 			If the read returns -1 and wasn't caused by a syscall interruption or blocking error, -1 is returned, and the connection status is set to -1.
 * 			If the read returns 0 and wasn't caused by a syscall interruption or blocking error, -2 is returned, and the connection status is set to 2.
 * 			Once a \n character is reached, the length of the current line of input is returned to the user, and the connection status is set to 1.
 * @param	con		the network connection across which the line of data will be read.
 * @return	-1 on general failure, -2 if the connection was reset, or the length of the current line of input, including the trailing \n.
 */
int64_t con_read_line(connection_t *con, bool_t block) {

	ssize_t bytes;
	bool_t line = false;

	if (!con || con->network.sockd == -1) {
		con->network.status = -1;
		return -1;
	}

	// Check for an existing network buffer. If there isn't one, try creating it.
	if (!con->network.buffer && !con_init_network_buffer(con)) {
		con->network.status = -1;
		return -1;
	}

	// Check if we have received more data than just what is in the current line of input.
	if (pl_length_get(con->network.line) && st_length_get(con->network.buffer) > pl_length_get(con->network.line)) {

		// If so, move the unused "new" data after the current line marker to the front of the buffer.
		mm_move(st_data_get(con->network.buffer), st_data_get(con->network.buffer) + pl_length_get(con->network.line),
			st_length_get(con->network.buffer) - pl_length_get(con->network.line));

		// Update the buffer length.
		st_length_set(con->network.buffer, st_length_get(con->network.buffer) - pl_length_get(con->network.line));

		// Check whether the data we just moved contains a complete line.
		if (!pl_empty((con->network.line = line_pl_st(con->network.buffer, 0)))) {
			con->network.status = 1;
			return pl_length_get(con->network.line);
		}

	}
	// Otherwise reset the buffer and line lengths to zero.
	else {
		st_length_set(con->network.buffer, 0);
		con->network.line = pl_null();
	}

	// Loop until we get a complete line, an error, or the buffer is filled.
	do {

		// Read bytes off the network. Skip past any existing data in the buffer.
		if (con->network.ssl) {

			// If bytes is zero or below and the library isn't asking for another read, then an error occurred.
			bytes = ssl_read(con->network.ssl, st_char_get(con->network.buffer) + st_length_get(con->network.buffer),
				st_avail_get(con->network.buffer) - st_length_get(con->network.buffer), block);

			if (bytes <= 0 && bytes != SSL_ERROR_WANT_READ) {
				con->network.status = -1;
				return -1;
			}
			else if (bytes <= 0) {
				return 0;
			}
		}
		else {
			bytes = recv(con->network.sockd, st_char_get(con->network.buffer) + st_length_get(con->network.buffer),
				st_avail_get(con->network.buffer) - st_length_get(con->network.buffer), (block ? 0 : MSG_DONTWAIT));

			// Check for errors on non-SSL reads in the traditional way.
			if (bytes <= 0 && errno != EINTR && errno != EAGAIN && errno != EWOULDBLOCK) {
				con->network.status = -1;
				return -1;
			}
			else if (!bytes) {
				con->network.status = 2;
				return -2;
			}

		}

		if (bytes > 0) {
			st_length_set(con->network.buffer, st_length_get(con->network.buffer) + bytes);
		}

		// Check whether we have a complete line before checking whether the connection was closed.
		if (!st_empty(con->network.buffer) && !pl_empty((con->network.line = line_pl_st(con->network.buffer, 0)))) {
			line = true;
		}

	} while (status() && !line && st_length_get(con->network.buffer) != st_avail_get(con->network.buffer));

	if (st_length_get(con->network.buffer) > 0) {
		con->network.status = 1;
	}

	return pl_length_get(con->network.line);
}
Exemplo n.º 16
0
/**
 * @brief	Read a line of input from a network client session.
 *
 *
 * @return
 *
 *
 */
int64_t client_read_line(client_t *client) {

	ssize_t bytes;
	bool_t line = false;
	int sslerr;

	if (!client || client->sockd == -1) {
		client->status = 1;
		return -1;
	}

	// Check for data past the current line buffer.
	if (pl_length_get(client->line) && st_length_get(client->buffer) > pl_length_get(client->line)) {

		// Move the unused data to the front of the buffer.
		mm_move(st_data_get(client->buffer), st_data_get(client->buffer) + pl_length_get(client->line), st_length_get(client->buffer) - pl_length_get(client->line));

		// Update the length.
		st_length_set(client->buffer, st_length_get(client->buffer) - pl_length_get(client->line));

		// Check whether the data we just moved contains a complete line.
		if (!pl_empty((client->line = line_pl_st(client->buffer, 0)))) {
			client->status = 1;
			return pl_length_get(client->line);
		}
	}
	// Otherwise reset the buffer and line lengths to zero.
	else {
		st_length_set(client->buffer, 0);
		client->line = pl_null();
	}

	// Loop until we get a complete line, an error, or the buffer is filled.
	do {

		// Read bytes off the network. Skip past any existing data in the buffer.
		if (client->ssl) {
			bytes = ssl_read(client->ssl, st_char_get(client->buffer) + st_length_get(client->buffer), st_avail_get(client->buffer) - st_length_get(client->buffer), true);
			sslerr = SSL_get_error_d(client->ssl, bytes);
		}
		else {
			bytes = recv(client->sockd, st_char_get(client->buffer) + st_length_get(client->buffer), st_avail_get(client->buffer) - st_length_get(client->buffer), 0);
		}

		// Check for errors on SSL reads.
		if (client->ssl) {

			// If 0 bytes were read, and it wasn't related to a shutdown, or if < 0 was returned and there was no more data waiting, it's an error.
			if ((!bytes && sslerr != SSL_ERROR_NONE && sslerr != SSL_ERROR_ZERO_RETURN) ||
				((bytes < 0) && sslerr != SSL_ERROR_WANT_READ)) {
				client->status = -1;
				return -1;
			}
		}

		// Check for errors on non-SSL reads in the traditional way.
		else if (bytes < 0 && errno != EINTR && errno != EAGAIN && errno != EWOULDBLOCK) {
			client->status = -1;
			return -1;
		}

		if (bytes > 0) {
			st_length_set(client->buffer, st_length_get(client->buffer) + bytes);
		}

		// Check whether we have a complete line before checking whether the connection was closed.
		if (!st_empty(client->buffer) && !pl_empty((client->line = line_pl_st(client->buffer, 0)))) {
			line = true;
		}
		// Otherwise if the connection has been closed (as indicated by a return value of 0) the line will never terminate. As such
		// the best course of action is to return an error code up the stack to indicate the disconnect.
		else if (!bytes) {
			client->status = 2;
			return -2;
		}

	} while (status() && !line && st_length_get(client->buffer) != st_avail_get(client->buffer));

	if (st_length_get(client->buffer) > 0) {
		client->status = 1;
	}

	return pl_length_get(client->line);
}