Пример #1
0
/**
 * Normalize a path, eg, foo//bar, foo/foo2/../bar, foo/./bar all become
 * foo/bar.
 *
 * If the path begins with either a forward slash or a dot *and* a forward
 * slash, they will be preserved.
 * @param path
 * Path to normalize.
 * @return
 * The normalized path; never NULL. Must be freed.
 */
char *path_normalize(const char *path)
{
    StringBuffer *sb;
    size_t pos, startsbpos;
    char component[MAX_BUF];
    ssize_t last_slash;

    TOOLKIT_PROTECT();

    if (string_isempty(path)) {
        return estrdup(".");
    }

    sb = stringbuffer_new();
    pos = 0;

    if (string_startswith(path, "/")) {
        stringbuffer_append_string(sb, "/");
    } else if (string_startswith(path, "./")) {
        stringbuffer_append_string(sb, "./");
    }

    startsbpos = stringbuffer_length(sb);

    while (string_get_word(path, &pos, '/', component, sizeof(component), 0)) {
        if (strcmp(component, ".") == 0) {
            continue;
        }

        if (strcmp(component, "..") == 0) {
            if (stringbuffer_length(sb) > startsbpos) {
                last_slash = stringbuffer_rindex(sb, '/');

                if (last_slash == -1) {
                    LOG(BUG, "Should have found a forward slash, but didn't: %s", path);
                    continue;
                }

                stringbuffer_seek(sb, last_slash);
            }
        } else {
            size_t len = stringbuffer_length(sb);
            if (len == 0 || stringbuffer_data(sb)[len - 1] != '/') {
                stringbuffer_append_string(sb, "/");
            }

            stringbuffer_append_string(sb, component);
        }
    }

    if (stringbuffer_length(sb) == 0) {
        stringbuffer_append_string(sb, ".");
    }

    return stringbuffer_finish(sb);
}
Пример #2
0
void path_cache_clear_except(const string& name, const set<string>& except)
{
	string dir = path_user_get("cache");

	if(path_exists(dir)) {
		directory_iterator it(dir), it_end;

		for(; it != it_end; ++it) {
			string filename = path_filename(it->path());

			if(string_startswith(filename, name.c_str()))
				if(except.find(filename) == except.end())
					path_remove(it->path());
		}
	}

}
Пример #3
0
string path_source_replace_includes(const string& source,
                                    const string& path,
                                    const string& source_filename)
{
	/* Our own little c preprocessor that replaces #includes with the file
	 * contents, to work around issue of opencl drivers not supporting
	 * include paths with spaces in them.
	 */

	string result = "";
	vector<string> lines;
	string_split(lines, source, "\n", false);

	for(size_t i = 0; i < lines.size(); ++i) {
		string line = lines[i];
		if(line[0] == '#') {
			string token = string_strip(line.substr(1, line.size() - 1));
			if(string_startswith(token, "include")) {
				token = string_strip(token.substr(7, token.size() - 7));
				if(token[0] == '"') {
					size_t n_start = 1;
					size_t n_end = token.find("\"", n_start);
					string filename = token.substr(n_start, n_end - n_start);
					string text, filepath = path_join(path, filename);
					if(path_read_text(filepath, text)) {
						/* Replace include directories with both current path
						 * and path extracted from the include file.
						 * Not totally robust, but works fine for Cycles kernel
						 * and avoids having list of include directories.x
						 */
						text = path_source_replace_includes(
						        text, path_dirname(filepath), filename);
						text = path_source_replace_includes(text, path, filename);
						/* Use line directives for better error messages. */
						line = line_directive(filepath, 1)
						     + token.replace(0, n_end + 1, "\n" + text + "\n")
						     + line_directive(path_join(path, source_filename), i);
					}
				}
			}
		}
		result += line + "\n";
	}

	return result;
}
Пример #4
0
  void tex_alloc(device_memory &mem)
  {
    VLOG(1) << "Texture allocate: " << mem.name << ", "
            << string_human_readable_number(mem.memory_size()) << " bytes. ("
            << string_human_readable_size(mem.memory_size()) << ")";

    if (mem.interpolation == INTERPOLATION_NONE) {
      /* Data texture. */
      kernel_tex_copy(&kernel_globals, mem.name, mem.host_pointer, mem.data_size);
    }
    else {
      /* Image Texture. */
      int flat_slot = 0;
      if (string_startswith(mem.name, "__tex_image")) {
        int pos = string(mem.name).rfind("_");
        flat_slot = atoi(mem.name + pos + 1);
      }
      else {
        assert(0);
      }

      if (flat_slot >= texture_info.size()) {
        /* Allocate some slots in advance, to reduce amount
         * of re-allocations. */
        texture_info.resize(flat_slot + 128);
      }

      TextureInfo &info = texture_info[flat_slot];
      info.data = (uint64_t)mem.host_pointer;
      info.cl_buffer = 0;
      info.interpolation = mem.interpolation;
      info.extension = mem.extension;
      info.width = mem.data_width;
      info.height = mem.data_height;
      info.depth = mem.data_depth;

      need_texture_info = true;
    }

    mem.device_pointer = (device_ptr)mem.host_pointer;
    mem.device_size = mem.memory_size();
    stats.mem_alloc(mem.device_size);
  }
Пример #5
0
/**
 * Analyze /cmd type commands the player has typed in the console or bound to a
 * key.
 * Sort out the "client intern" commands and expand or pre process them for the
 * server.
 * @param cmd
 * Command to check
 * @return
 * 0 to send command to server, 1 to not send it
 */
int client_command_check(const char *cmd)
{
    if (cmd_aliases_handle(cmd)) {
        return 1;
    } else if (strncasecmp(cmd, "/ready_spell", 12) == 0) {
        cmd = strchr(cmd, ' ');

        if (!cmd || *++cmd == '\0') {
            draw_info(COLOR_RED, "Usage: /ready_spell <spell name>");
            return 1;
        } else {
            object *tmp;

            for (tmp = cpl.ob->inv; tmp; tmp = tmp->next) {
                if (tmp->itype == TYPE_SPELL && strncasecmp(tmp->s_name, cmd, strlen(cmd)) == 0) {
                    if (!(tmp->flags & CS_FLAG_APPLIED)) {
                        client_send_apply(tmp);
                    }

                    return 1;
                }
            }
        }

        draw_info(COLOR_RED, "Unknown spell.");
        return 1;
    } else if (strncasecmp(cmd, "/ready_skill", 12) == 0) {
        cmd = strchr(cmd, ' ');

        if (!cmd || *++cmd == '\0') {
            draw_info(COLOR_RED, "Usage: /ready_skill <skill name>");
            return 1;
        } else {
            object *tmp;

            for (tmp = cpl.ob->inv; tmp; tmp = tmp->next) {
                if (tmp->itype == TYPE_SKILL && strncasecmp(tmp->s_name, cmd, strlen(cmd)) == 0) {
                    if (!(tmp->flags & CS_FLAG_APPLIED)) {
                        client_send_apply(tmp);
                    }

                    return 1;
                }
            }
        }

        draw_info(COLOR_RED, "Unknown skill.");
        return 1;
    } else if (!strncmp(cmd, "/help", 5)) {
        cmd += 5;

        if (*cmd == '\0') {
            help_show("main");
        } else {
            help_show(cmd + 1);
        }

        return 1;
    } else if (!strncmp(cmd, "/resetwidgets", 13)) {
        widgets_reset();
        return 1;
    } else if (!strncmp(cmd, "/effect ", 8)) {
        if (!strcmp(cmd + 8, "none")) {
            effect_stop();
            draw_info(COLOR_GREEN, "Stopped effect.");
            return 1;
        }

        if (effect_start(cmd + 8)) {
            draw_info_format(COLOR_GREEN, "Started effect %s.", cmd + 8);
        } else {
            draw_info_format(COLOR_RED, "No such effect %s.", cmd + 8);
        }

        return 1;
    } else if (!strncmp(cmd, "/d_effect ", 10)) {
        effect_debug(cmd + 10);
        return 1;
    } else if (!strncmp(cmd, "/music_pause", 12)) {
        sound_pause_music();
        return 1;
    } else if (!strncmp(cmd, "/music_resume", 13)) {
        sound_resume_music();
        return 1;
    } else if (!strncmp(cmd, "/party joinpassword ", 20)) {
        cmd += 20;

        if (cpl.partyjoin[0] != '\0') {
            char buf[MAX_BUF];

            snprintf(VS(buf), "/party join %s\t%s", cpl.partyjoin, cmd);
            send_command(buf);
        }

        return 1;
    } else if (!strncmp(cmd, "/invfilter ", 11)) {
        inventory_filter_set_names(cmd + 11);
        return 1;
    } else if (!strncasecmp(cmd, "/screenshot", 11)) {
        SDL_Surface *surface_save;

        cmd += 11;

        if (!strncasecmp(cmd, " map", 4)) {
            surface_save = cur_widget[MAP_ID]->surface;
        } else {
            surface_save = ScreenSurface;
        }

        if (!surface_save) {
            draw_info(COLOR_RED, "No surface to save.");
            return 1;
        }

        screenshot_create(surface_save);
        return 1;
    } else if (!strncasecmp(cmd, "/console-load ", 14)) {
        FILE *fp;
        char path[HUGE_BUF], buf[HUGE_BUF * 4], *cp;
        StringBuffer *sb;

        cmd += 14;

        snprintf(path, sizeof(path), "%s/.atrinik/console/%s", get_config_dir(), cmd);

        fp = fopen(path, "r");

        if (!fp) {
            draw_info_format(COLOR_RED, "Could not read %s.", path);
            return 1;
        }

        send_command("/console noinf::");

        while (fgets(buf, sizeof(buf) - 1, fp)) {
            cp = strchr(buf, '\n');

            if (cp) {
                *cp = '\0';
            }

            sb = stringbuffer_new();
            stringbuffer_append_string(sb, "/console noinf::");
            stringbuffer_append_string(sb, buf);
            cp = stringbuffer_finish(sb);
            send_command(cp);
            efree(cp);
        }

        send_command("/console noinf::");

        fclose(fp);

        return 1;
    } else if (strncasecmp(cmd, "/console-obj", 11) == 0) {
        menu_inventory_loadtoconsole(cpl.inventory_focus, NULL, NULL);
        return 1;
    } else if (strncasecmp(cmd, "/patch-obj", 11) == 0) {
        menu_inventory_patch(cpl.inventory_focus, NULL, NULL);
        return 1;
    } else if (string_startswith(cmd, "/cast ") || string_startswith(cmd, "/use_skill ")) {
        object *tmp;
        uint8_t type;

        type = string_startswith(cmd, "/cast ") ? TYPE_SPELL : TYPE_SKILL;
        cmd = strchr(cmd, ' ') + 1;

        if (string_isempty(cmd)) {
            return 1;
        }

        for (tmp = cpl.ob->inv; tmp; tmp = tmp->next) {
            if (tmp->itype == type && strncasecmp(tmp->s_name, cmd, strlen(cmd)) == 0) {
                client_send_fire(5, tmp->tag);
                return 1;
            }
        }

        draw_info_format(COLOR_RED, "Unknown %s.", type == TYPE_SPELL ? "spell" : "skill");
        return 1;
    } else if (strncasecmp(cmd, "/clearcache", 11) == 0) {
        cmd += 12;

        if (string_isempty(cmd)) {
            return 1;
        }

        if (strcasecmp(cmd, "sound") == 0) {
            sound_clear_cache();
            draw_info(COLOR_GREEN, "Sound cache cleared.");
        } else if (strcasecmp(cmd, "textures") == 0) {
            texture_reload();
            draw_info(COLOR_GREEN, "Textures reloaded.");
        }

        return 1;
    } else if (string_startswith(cmd, "/droptag ") ||
            string_startswith(cmd, "/gettag ")) {
        char *cps[3];
        unsigned long int loc, tag, num;

        if (string_split(strchr(cmd, ' ') + 1, cps, arraysize(cps), ' ') !=
                arraysize(cps)) {
            return 1;
        }

        loc = strtoul(cps[0], NULL, 10);
        tag = strtoul(cps[1], NULL, 10);
        num = strtoul(cps[2], NULL, 10);
        client_send_move(loc, tag, num);

        if (string_startswith(cmd, "/gettag ")) {
            sound_play_effect("get.ogg", 100);
        } else {
            sound_play_effect("drop.ogg", 100);
        }

        return 1;
    } else if (string_startswith(cmd, "/talk")) {
        char type[MAX_BUF], npc_name[MAX_BUF];
        size_t pos;
        uint8_t type_num;
        packet_struct *packet;

        pos = 5;

        if (!string_get_word(cmd, &pos, ' ', type, sizeof(type), 0) || string_isempty(cmd + pos)) {
            return 1;
        }

        type_num = atoi(type);

        if (type_num == CMD_TALK_NPC_NAME && (!string_get_word(cmd, &pos, ' ', npc_name, sizeof(npc_name), '"') || string_isempty(cmd + pos))) {
            return 1;
        }

        packet = packet_new(SERVER_CMD_TALK, 64, 64);
        packet_append_uint8(packet, type_num);

        if (type_num == CMD_TALK_NPC || type_num == CMD_TALK_NPC_NAME) {
            if (type_num == CMD_TALK_NPC_NAME) {
                packet_append_string_terminated(packet, npc_name);
            }

            packet_append_string_terminated(packet, cmd + pos);
        } else {
            char tag[MAX_BUF];

            if (!string_get_word(cmd, &pos, ' ', tag, sizeof(tag), 0) || string_isempty(cmd + pos)) {
                packet_free(packet);
                return 1;
            }

            packet_append_uint32(packet, atoi(tag));
            packet_append_string_terminated(packet, cmd + pos);
        }

        socket_send_packet(packet);

        return 1;
    } else if (string_startswith(cmd, "/widget_toggle")) {
        size_t pos;
        char word[MAX_BUF], *cps[2];
        int widget_id;

        pos = 14;

        while (string_get_word(cmd, &pos, ' ', word, sizeof(word), 0)) {
            if (string_split(word, cps, arraysize(cps), ':') < 1) {
                continue;
            }

            widget_id = widget_id_from_name(cps[0]);

            /* Invalid widget ID */
            if (widget_id == -1) {
                continue;
            }

            /* Redraw all or a specific one identified by its UID */
            if (cps[1] == NULL) {
                WIDGET_SHOW_TOGGLE_ALL(widget_id);
            } else {
                widgetdata *widget;

                widget = widget_find(NULL, widget_id, cps[1], NULL);

                if (widget) {
                    WIDGET_SHOW_TOGGLE(widget);
                }
            }
        }

        return 1;
    } else if (string_startswith(cmd, "/widget_focus")) {
        size_t pos;
        char word[MAX_BUF], *cps[2];
        int widget_id;

        pos = 14;

        while (string_get_word(cmd, &pos, ' ', word, sizeof(word), 0)) {
            if (string_split(word, cps, arraysize(cps), ':') < 1) {
                continue;
            }

            widget_id = widget_id_from_name(cps[0]);
            if (widget_id == -1) {
                /* Invalid widget ID */
                continue;
            }

            widget_switch_focus(widget_id, cps[1]);
        }

        return 1;
    } else if (string_startswith(cmd, "/ping")) {
        keepalive_ping_stats();
        return 1;
    } else if (string_startswith(cmd, "/region_map")) {
        region_map_open();
        return 1;
    }

    return 0;
}
Пример #6
0
void parser(_map *mem, const char *statement) {
	/*
	 * there're three occasions:
	 * (1) variable declaration
	 * (2) variable printing
	 * (3) variable assignment
	 */

	_vector *vec_statement = vector_new(8);
	int count = string_split(vec_statement, statement, ';');

	char *current_statement = (char *)malloc(sizeof(char));

	for (int i = 0; i < count; ++i) {

		size_t len = strlen((char *)*vector_get(vec_statement, i));
		current_statement = (char *)realloc(current_statement, sizeof(char) * (len + 1));
		strcpy(current_statement, (char *)*vector_get(vec_statement, i));

		if (!strcmp(current_statement, "")) {
			break;
		}

		bool is_assignment = true;

		// variable declaration
		char temp_str[1005]; // TODO(twd2): enough?
		const char double_declare[] = "double ";
		const char int_declare[] = "int ";
		const size_t double_declare_len = strlen(double_declare);
		const size_t int_declare_len = strlen(int_declare);

		int str_int_start_pos = string_startswith(current_statement, int_declare);
		int str_double_start_pos = string_startswith(current_statement, double_declare);

		if (str_double_start_pos != -1) {
			// variable declared as a double
			is_assignment = false;

			size_t j;
			for (j = str_double_start_pos + double_declare_len; j < len; ++j) {
				if (current_statement[j] != ' ') {
					break;
				}
			}
			string_sub(temp_str, current_statement, j, len);
			_vector *vec_declare = vector_new(8);
			int count = string_split(vec_declare, temp_str, ',');
			for (j = 0; j < count; ++j) {
				char *name_purified = string_purify((char *)(*vector_get(vec_declare, j)));
				add_double_variable(mem, name_purified, 0);
				free(name_purified);
			}
			vector_deepfree(vec_declare);
		}

		if (str_int_start_pos != -1) {
			// variable declared as a int
			is_assignment = false;

			size_t j;
			for (j = str_int_start_pos + int_declare_len; j < len; ++j) {
				if (current_statement[j] != ' ') {
					break;
				}
			}
			string_sub(temp_str, current_statement, j, len);
			_vector *vec_declare = vector_new(8);
			int count = string_split(vec_declare, temp_str, ',');
			for (j = 0; j < count; ++j) {
				char *name_purified = string_purify((char *)(*vector_get(vec_declare, j)));
				add_int_variable(mem, name_purified, 0);
				free(name_purified);
			}
			vector_deepfree(vec_declare);
		}

		// variable printing
		const char print_declare1[] = "print ";
		const char print_declare2[] = "print(";
		const size_t print_declare_len = strlen(print_declare1);

		if (string_startswith(current_statement, print_declare1) != -1 ||
			string_startswith(current_statement, print_declare2) != -1) {
			// print statement
			is_assignment = false;

			int j;
			for (j = print_declare_len - 1; j < len; ++j) {
				if (current_statement[j] == ')') {
					break;
				}
			}
			string_sub(temp_str, current_statement, print_declare_len, j - print_declare_len);
			string_clearspace(temp_str);
			parse(temp_str);
			convert(temp_str);
			_variable var = calculate(mem, temp_str);
			if (var.type == ERRORVALUE) {
				catch_error(var.int_value);
				break;
			}
			print_variable(&var);
		}

		// variable assignment
		if (is_assignment) {
			strcpy(temp_str, current_statement);
			string_clearspace(temp_str);
			parse(temp_str);
			convert(temp_str);
			_variable var = calculate(mem, temp_str);
			if (var.type == ERRORVALUE) {
				catch_error(var.int_value);
				break;
			}
		}

	}

	free(current_statement);
	vector_deepfree(vec_statement);
	return;
}
Пример #7
0
HttpMessage RequestHandler :: handleRequest( HttpMessage& request ){
	HttpMessage response;
	std::string body, path, ckey;
	handler_function func = NULL;
	size_t pattern_length = 0;
	uint64_t cache_key;
	std::unordered_map<uint64_t, CachedEntry>::iterator cache_it;
	
	path = request.get_path();
	response.set_version( "HTTP/1.1" );
	response.set_header_field( "Server", SERVER_VERSION );
	response.set_header_field( "Content-Type", "text/html" );
	response.set_header_field( "Date", get_gmt_time(0) );
	
	/*
	ckey = request.get_method() + ":" + path;
	cache_key = fnv1a_hash( ckey );
	*/
	cache_key = compute_hash( request );
	
	pthread_rwlock_rdlock( &RequestHandler::cache_lock );
	cache_it = cache.find( cache_key );
	if( cache_it != cache.end() ){
		if( (cache_it->second).is_valid() ){
			pthread_rwlock_unlock( &RequestHandler::cache_lock );
			//std::cerr << "Found @ cache" << std::endl;
			return (cache_it->second).get_content();
			}
		}
	pthread_rwlock_unlock( &RequestHandler::cache_lock );
					
	for( std::map< std::string, handler_function >::iterator it = handlers.begin() ; it != handlers.end() ; it++ ){
		if( string_startswith( it->first, path ) ){
			if( (it->first).size() > pattern_length ){
				pattern_length = (it->first).size();
				func = it->second;
				}
			}
		}
	
	if( func == NULL ){
		response.set_code( 404 );
		response.set_code_string( "Not found." );
		response.set_version( "HTTP/1.1" );
		response.set_header_field( "Connection", "close" );
		response.set_header_field( "Date", get_gmt_time(0) );
		response.set_header_field( "Server", SERVER_VERSION );
		response.set_header_field( "Last-Modified", get_gmt_time(0) );
		response.set_header_field( "Content-Type", "text/plain" );
		response.set_body( "Error 404 - Not found!\n" );
		}
	else{
		response_options_t result;
		try{
			result = func( request, response );
			} catch( std::string error ){
				response.set_code( 500 );
				response.set_code_string( "Internal server error." );
				
				}
		if( !result.ok ){
			response.set_code( 404 );
			response.set_code_string( "Not found." );
			response.set_version( "HTTP/1.1" );
			response.set_header_field( "Connection", "close" );
			response.set_header_field( "Date", get_gmt_time(0) );
			response.set_header_field( "Server", SERVER_VERSION );
			response.set_header_field( "Last-Modified", get_gmt_time(0) );
			response.set_header_field( "Content-Type", "text/plain" );
			response.set_body( "Error 404 - Not found!\n" );
			}
		else{
			if( request.has_header_field( "Accept-Encoding" ) ){
				if( request.get_header_field( "Accept-Encoding" ).find( "gzip" ) != std::string::npos ){
					response.set_body( zlib_gzip_deflate( response.get_body() ) );
					response.set_header_field( "Content-Encoding", "gzip" );
					} 
				else{
					if( request.get_header_field( "Accept-Encoding" ).find( "deflate" ) != std::string::npos ){
						response.set_body( zlib_deflate( response.get_body() ) );
						response.set_header_field( "Content-Encoding", "deflate" );
						}
					}
				}
			
			if( result.cached ){
				add_cache( cache_key, response, result.expires );
				}
			
			}
		}
	
	return response;
	}