Beispiel #1
0
char *test_fuzzing()
{
	BSTree *store = BSTree_create(NULL);
	int i = 0;
	int j = 0;
	bstring numbers[100] = {NULL};
	bstring data[100] = {NULL};
	srand((unsigned int)time(NULL));

	for(i = 0; i < 100; i++) {
		int num = rand();
		numbers[i] = bformat("%d", num);
		data[i] = bformat("data %d", num);
		BSTree_set(store, numbers[i], data[i]);
	}

	for(i = 0; i < 100; i++) {
		bstring value = BSTree_delete(store, numbers[i]);
		mu_assert(value == data[i], "Failed to delete the right number.");

		mu_assert(BSTree_delete(store, numbers[i]) == NULL, "Should get nothing.");

		for(j = j+1; j < 99 - i; j++) {
			bstring value = BSTree_get(store, numbers[j]);
			mu_assert(value == data[j], "Failed to get the right number.");
		}

		bdestroy(value);
		bdestroy(numbers[i]);
	}

	BSTree_destroy(store);

	return NULL;
}
Beispiel #2
0
void Handler_notify_leave(Handler *handler, int id)
{
    void *socket = handler->send_socket;
    assert(socket && "Socket can't be NULL");
    bstring payload = NULL;

    if(handler->protocol == HANDLER_PROTO_TNET) {
        payload = bformat("%s %d @* %s%d:%s,",
                bdata(handler->send_ident), id,
                bdata(&LEAVE_HEADER_TNET),
                blength(&LEAVE_MSG), bdata(&LEAVE_MSG));
    } else {
        payload = bformat("%s %d @* %d:%s,%d:%s,",
                bdata(handler->send_ident), id,
                blength(&LEAVE_HEADER_JSON), bdata(&LEAVE_HEADER_JSON),
                blength(&LEAVE_MSG), bdata(&LEAVE_MSG));
    }

    check(payload != NULL, "Failed to make the payload for disconnect.");

    if(Handler_deliver(socket, bdata(payload), blength(payload)) == -1) {
        log_err("Can't tell handler %d died.", id);
    }

error: //fallthrough
    if(payload) free(payload);
}
Beispiel #3
0
char *test_Dir_serve_big_files(){

  struct stat less1gb;
  less1gb.st_size = 858993459; /* ~1.5GB */

  struct stat more1gb;
  more1gb.st_size = 399560397; /* ~4GB */
  
  char *LESS_1GB = "HTTP/1.1 200 OK\r\n"
    "Date: \r\n"
    "Content-Type: \r\n"
    "Content-Length: 858993459\r\n"
    "Last-Modified: \r\n"
    "ETag: \r\n"
    "Server: " VERSION
    "\r\n\r\n";
  
  char *MORE_1GB = "HTTP/1.1 200 OK\r\n"
    "Date: \r\n"
    "Content-Type: \r\n"
    "Content-Length: 399560397\r\n"
    "Last-Modified: \r\n"
    "ETag: \r\n"
    "Server: " VERSION
    "\r\n\r\n";

  bstring response_less_1gb = bformat(RESPONSE_FORMAT, "", "", less1gb.st_size, "", "");
  bstring response_more_1gb = bformat(RESPONSE_FORMAT, "", "", more1gb.st_size, "", "");

  mu_assert(bstrcmp(response_less_1gb, bfromcstr(LESS_1GB)) == 0, "Wrong response headers for <1GB files");
  debug("MORE_1GB=%s\n", MORE_1GB);
  debug("RESPONSE=%s\n", bdata(response_more_1gb));
  mu_assert(bstrcmp(response_more_1gb,  bfromcstr(MORE_1GB)) == 0, "Wrong response headers for >1GB files");
  return NULL;
}
static void
socks_accept_cb(struct evconnlistener *lis, evutil_socket_t fd,
	struct sockaddr *addr, int len, void *ptr)
{
	obfsproxyssh_client_t *client = ptr;
	obfsproxyssh_t *state = client->state;
	obfsproxyssh_client_session_t *session;
	struct sockaddr_in *sa;
	char addr_buf[INET_ADDRSTRLEN];
	uint32_t tmp;

	assert(lis == client->listener);

	/*
	 * It is possible to defer allocating the session object till after the
	 * SOCKS protocol handling is done, but there isn't much point in doing
	 * so.
	 */

	session = calloc(1, sizeof(obfsproxyssh_client_session_t));
	if (NULL == session) {
		log_f(state, "SOCKS: Error: Failed to allocate session");
		goto out_close;
	}

	session->socks_ev = bufferevent_socket_new(state->base, fd,
					BEV_OPT_CLOSE_ON_FREE);
	if (NULL == session->socks_ev) {
		log_f(state, "SOCKS: Error: Failed to allocate bev");
		free(session);
		goto out_close;
	}
	bufferevent_setcb(session->socks_ev, socks_read_cb, NULL,
			socks_event_cb, session);
	bufferevent_enable(session->socks_ev, EV_READ | EV_WRITE);

	sa = (struct sockaddr_in *) addr;
	if (0 == state->unsafe_logging) {
		tmp = ntohl(sa->sin_addr.s_addr);
		tmp &= 0x000000ff;
		session->socks_addr = bformat("xxx.xxx.xxx.%d:%d", tmp,
			ntohs(sa->sin_port));
	} else {
		evutil_inet_ntop(AF_INET, &sa->sin_addr, addr_buf,
				INET_ADDRSTRLEN);
		session->socks_addr = bformat("%s:%d", addr_buf,
				ntohs(sa->sin_port));
	}
	/* TODO: Set the timeout */

	LIST_INSERT_HEAD(&client->sessions, session, entries);
	session->client = client;

	log_f(state, "SOCKS: %s Connect", bdata(session->socks_addr));

	return;

out_close:
	evutil_closesocket(fd);
}
Beispiel #5
0
FileRecord *Dir_resolve_file(Dir *dir, bstring path)
{
    FileRecord *file = NULL;
    bstring target = NULL;

    check(Dir_lazy_normalize_base(dir) == 0, "Failed to normalize base path when requesting %s",
            bdata(path));

    check(bstrncmp(path, dir->prefix, blength(dir->prefix)) == 0, 
            "Request for path %s does not start with %s prefix.", 
            bdata(path), bdata(dir->prefix));

    file = FileRecord_cache_check(dir, path);

    if(file) {
        // TODO: double check this gives the right users count
        file->users++;
        return file;
    }

    // We subtract one from the blengths below, because dir->prefix includes
    // a trailing '/'.  If we skip over this in path->data, we drop the '/'
    // from the URI, breaking the target path
    if(bchar(path, blength(path) - 1) == '/') {
        target = bformat("%s%s%s",
                    bdata(dir->normalized_base),
                    path->data + blength(dir->prefix) - 1,
                    bdata(dir->index_file));
    } else {
        target = bformat("%s%s",
                bdata(dir->normalized_base),
                path->data + blength(dir->prefix) - 1);
    }

    check(target, "Couldn't construct target path for %s", bdata(path));

    check_debug(normalize_path(target) == 0, "Failed to normalize target path.");
   
    check_debug(bstrncmp(target, dir->normalized_base, blength(dir->normalized_base)) == 0, 
            "Request for path %s does not start with %s base after normalizing.", 
            bdata(target), bdata(dir->base));

    // the FileRecord now owns the target
    file = Dir_find_file(target, dir->default_ctype);
    check_debug(file, "Error opening file: %s", bdata(target));

    // Increment the user count because we're adding it to the cache
    file->users++;
    file->request_path = bstrcpy(path);
    Cache_add(dir->fr_cache, file);


    return file;

error:
    bdestroy(target);
    FileRecord_release(file);
    return NULL;
}
Beispiel #6
0
void InsetCaption::updateBuffer(ParIterator const & it, UpdateType utype)
{
	Buffer const & master = *buffer().masterBuffer();
	DocumentClass const & tclass = master.params().documentClass();
	string const & lang = it.paragraph().getParLanguage(master.params())->code();
	Counters & cnts = tclass.counters();
	string const & type = cnts.current_float();
	if (utype == OutputUpdate) {
		// counters are local to the caption
		cnts.saveLastCounter();
	}
	// Memorize type for addToToc().
	floattype_ = type;
	if (type.empty() || type == "senseless")
		full_label_ = master.B_("Senseless!!! ");
	else {
		// FIXME: life would be _much_ simpler if listings was
		// listed in Floating.
		docstring name;
		if (type == "listing")
			name = master.B_("Listing");
		else
			name = master.B_(tclass.floats().getType(type).name());
		docstring counter = from_utf8(type);
		is_subfloat_ = cnts.isSubfloat();
		if (is_subfloat_) {
			// only standard captions allowed in subfloats
			type_ = "Standard";
			counter = "sub-" + from_utf8(type);
			name = bformat(_("Sub-%1$s"),
				       master.B_(tclass.floats().getType(type).name()));
		}
		docstring sec;
		docstring const lstring = getLayout().labelstring();
		docstring const labelstring = isAscii(lstring) ?
				master.B_(to_ascii(lstring)) : lstring;
		if (cnts.hasCounter(counter)) {
			// for longtables, we step the counter upstream
			if (!cnts.isLongtable())
				cnts.step(counter, utype);
			sec = cnts.theCounter(counter, lang);
		}
		if (labelstring != master.B_("standard")) {
			if (!sec.empty())
				sec += from_ascii(" ");
			sec += bformat(from_ascii("(%1$s)"), labelstring);
		}
		if (!sec.empty())
			full_label_ = bformat(from_ascii("%1$s %2$s: "), name, sec);
		else
			full_label_ = bformat(from_ascii("%1$s #: "), name);
	}

	// Do the real work now.
	InsetText::updateBuffer(it, utype);
	if (utype == OutputUpdate)
		cnts.restoreLastCounter();
}
Beispiel #7
0
// Recursively copies a directory.
//
// src  - The path of the file or directory to copy.
// dest - The path where the copy should be placed.
//
// Returns 0 if successful, otherwise returns -1.
int sky_file_cp_r(bstring src, bstring dest)
{
    int rc;
    bstring ent_src = NULL;
    bstring ent_dest = NULL;
    check(src != NULL, "Source path required");
    check(dest != NULL, "Destination path required");
    check(sky_file_exists(src), "Source file does not exist");

    // If this is a directory then create a new dest directory and copy the
    // contents.
    if(sky_file_is_dir(src)) {
        // Create destination directory if it doesn't exist.
        if(!sky_file_exists(dest)) {
            struct stat st;
            rc = stat(bdata(src), &st);
            check(rc == 0, "Unable to stat source directory: %s", bdata(src));
            rc = mkdir(bdata(dest), st.st_mode);
            check(rc == 0, "Unable to create directory: %s", bdata(dest));
        }
        
        // Open directory.
        DIR *dir = opendir(bdata(src));
        check(dir != NULL, "Unable to open directory: %s", bdata(src));
        
        // Copy over contents of directory.
        struct dirent *ent;
        while((ent = readdir(dir))) {
            if(strcmp(ent->d_name, ".") != 0 && strcmp(ent->d_name, "..") != 0) {
                ent_src  = bformat("%s/%s", bdata(src), ent->d_name); check_mem(ent_src);
                ent_dest = bformat("%s/%s", bdata(dest), ent->d_name); check_mem(ent_dest);

                rc = sky_file_cp_r(ent_src, ent_dest);
                check(rc == 0, "Unable to copy: %s", bdata(ent_src));

                bdestroy(ent_src);
                bdestroy(ent_dest);
            }
        }
        
        // Close directory.
        closedir(dir);
    }
    // If this is a file then copy its contents.
    else {
        rc = sky_file_cp(src, dest);
        check(rc == 0, "Unable to copy file: %s", bdata(src));
    }
    
    return 0;

error:
    bdestroy(ent_src);
    bdestroy(ent_dest);
    return -1;
}
Beispiel #8
0
FileRecord *Dir_find_file(bstring path, bstring default_type)
{
    FileRecord *fr = calloc(sizeof(FileRecord), 1);
    const char *p = bdata(path);

    check_mem(fr);

    // We set the number of users here.  If we cache it, we can add one later
    fr->users = 1;

    int rc = stat(p, &fr->sb);
    check(rc == 0, "File stat failed: %s", bdata(path));

    if(S_ISDIR(fr->sb.st_mode)) {
        fr->full_path = path;
        fr->is_dir = 1;
        return fr;
    }
    
    fr->fd = open(p, O_RDONLY);
    check(fr->fd >= 0, "Failed to open file but stat worked: %s", bdata(path));

    fr->loaded = time(NULL);

    fr->last_mod = bStrfTime(RFC_822_TIME, gmtime(&fr->sb.st_mtime));
    check(fr->last_mod, "Failed to format last modified time.");

    // TODO: get this from a configuration
    fr->content_type = MIME_match_ext(path, default_type);
    check(fr->content_type, "Should always get a content type back.");

    // we own this now, not the caller
    fr->full_path = path;

    time_t now = time(NULL);

    fr->date = bStrfTime(RFC_822_TIME, gmtime(&now));

    fr->etag = bformat("%x-%x", fr->sb.st_mtime, fr->sb.st_size);

    fr->header = bformat(RESPONSE_FORMAT,
        bdata(fr->date),
        bdata(fr->content_type),
        fr->sb.st_size,
        bdata(fr->last_mod),
        bdata(fr->etag));

    check(fr->header != NULL, "Failed to create response header.");

    return fr;

error:
    FileRecord_destroy(fr);
    return NULL;
}
Beispiel #9
0
docstring const Font::stateText(BufferParams * params) const
{
	odocstringstream os;
	os << lyx::stateText(bits_);
	if (!params || (language() != params->language))
		os << bformat(_("Language: %1$s, "),
			      _(language()->display()));
	if (bits_.number() != FONT_OFF)
		os << "  " << bformat(_("Number %1$s"),
			      _(GUIMiscNames[bits_.number()]));
	return rtrim(os.str(), ", ");
}
Beispiel #10
0
void irc_init(void)
{
    /*****************************************
     * Now connected, start sending commands *
     *****************************************/
        irc_write(bformat("PASS %s", bdata(config.password))); /* PASS password */
        irc_write(bformat("NICK %s", bdata(config.nickname))); /* NICK nickname */
        irc_write(bformat("USER %s %s %s :%s", bdata(config.ident), bdata(config.host), bdata(config.server_address), bdata(config.name))); /* USER ident host server :name */
    /**********************************
     * Read socket and stay connected *
     **********************************/
    irc_read();
}
Beispiel #11
0
/* ----------------------------------------------------------
 * FUNCTION     : init_identification
 * DESCRIPTION  : This function will read the signature file
 *              : into the signature data structure.
 * INPUT        : 0 - Data Structure
 * RETURN       : -1 - Error
 *              : 0 - Normal Return
 * ---------------------------------------------------------- */
int load_servicefp_file(char *sigfile, signature **db, int len)
{

    FILE *fp;
    bstring filename;
    bstring filedata;
    struct bstrList *lines;
    int i;
    (void)(len); // doesn't matter

    /*
     * Check for a PADS_SIGNATURE_LIST file within the current directory.  
     */
    if ((fp = fopen(TCP_SIGNATURE_LIST, "r")) != NULL) {
        filename = bformat("%s", sigfile);
        fclose(fp);
    } else {
        filename = bformat(sigfile);
    }

    /*
     * Open Signature File 
     */
    if ((fp = fopen(bdata(filename), "r")) == NULL) {
        printf("Unable to open signature file - %s\n", bdata(filename));
        return 1;
    }

    /*
     * Read file into 'filedata' and process it accordingly. 
     */
    filedata = bread((bNread) fread, fp);
    if ((lines = bsplit(filedata, '\n')) != NULL) {
        for (i = 0; i < lines->qty; i++) {
            parse_raw_signature(lines->entry[i], i + 1, db);
        }
    }

    /*
     * Clean Up 
     */
    bdestroy(filename);
    bdestroy(filedata);
    bstrListDestroy(lines);
    fclose(fp);

    return 0;
}
Beispiel #12
0
int attempt_chroot_drop(Server *srv)
{
    int rc = 0;

    if(Unixy_chroot(srv->chroot) == 0) {
        log_info("All loaded up, time to turn into a server.");
        log_info("-- Starting " VERSION ". Copyright (C) Zed A. Shaw. Licensed BSD.\n");
        log_info("-- Look in %s for startup messages and errors.", bdata(srv->error_log));

        check(access("/run", F_OK) == 0, "/run directory doesn't exist in %s or isn't owned right.", bdata(srv->chroot));
        check(access("/tmp", F_OK) == 0, "/tmp directory doesn't exist in %s or isn't owned right.", bdata(srv->chroot));

        rc = Unixy_daemonize();
        check(rc == 0, "Failed to daemonize, looks like you're hosed.");

        FILE *log = fopen(bdata(srv->error_log), "a+");
        check(log, "Couldn't open %s log file.", bdata(srv->error_log));
        setbuf(log, NULL);

        dbg_set_log(log);

        rc = Unixy_pid_file(srv->pid_file);
        check(rc == 0, "Failed to make the PID file %s", bdata(srv->pid_file));

        rc = Unixy_drop_priv(&PRIV_DIR);
        check(rc == 0, "Failed to drop priv to the owner of %s", bdata(&PRIV_DIR));

    } else {
        log_warn("Couldn't chroot too %s, assuming running in test mode.", bdata(srv->chroot));

        // rewrite the access log to be in the right location
        bstring temp = bformat("%s%s", bdata(srv->chroot), bdata(srv->access_log));
        bassign(srv->access_log, temp);
        bdestroy(temp);

        temp = bformat(".%s", bdata(srv->pid_file));
        bassign(srv->pid_file, temp);
        bdestroy(temp);

        rc = Unixy_pid_file(srv->pid_file);
        check(rc == 0, "Failed to make the PID file %s", bdata(srv->pid_file));
    }

    return 0;

error:
    return -1;
}
Beispiel #13
0
Datei: dht.c Projekt: nja/dumhet
bstring DataRGetPeersStr(Message *message)
{
    if (message->data.rgetpeers.nodes != NULL)
    {
        return DataRFindNodeStr(message);
    }

    bstring ftoken = Dht_FTokenStr(message->data.rgetpeers.token);

    bstring str = bformat("Token: %s", ftoken->data);

    bdestroy(ftoken);

    size_t i = 0;

    if (message->data.rgetpeers.values == NULL)
    {
        bformata(str, "\n(NULL rgetpeers.values)");
        return str;
    }

    for (i = 0; i < message->data.rgetpeers.count; i++)
    {
        bstring peer = Dht_PeerStr(message->data.rgetpeers.values + i);

        bformata(str, "\nPeer %03zd: %s", i, peer->data);

        bdestroy(peer);
    }

    return str;
}
Beispiel #14
0
Datei: dht.c Projekt: nja/dumhet
bstring Dht_HashStr(Hash *hash)
{
    if (hash == NULL)
        return bformat("%*s", HASH_BYTES * 2, "(NULL HASH)");

    return HexStr(hash->value, HASH_BYTES);
}
Beispiel #15
0
/**
 * Process a chat message or command
 *
 * @remarks Scope: private
 *
 * @param player Player List player pointer
 * @param message Chat message
 */
void
process_chat(struct PL_entry *player, bstring message)
{
  if (message->data[0] == '/')
  {
    LOG(LOG_INFO, "Command: %s", message->data);
    send_directchat(player, message);
    
    // TODO: temporary who cmd
    bstring whocmd = bfromcstr("/who");
    bstring lcmd = bfromcstr("/login");
    if (binstrr(message, (whocmd->slen), whocmd) != BSTR_ERR)
    {
      pthread_rwlock_rdlock(&PL_rwlock);
      bstring whomsg = bformat("There are %d players online", PL_count);
      send_directchat(player, whomsg);
      pthread_rwlock_unlock(&PL_rwlock);
      bstrFree(whomsg);
    } else if(binstrr(message, (lcmd->slen), lcmd) != BSTR_ERR)
    {
      send_loginresp(player);
    }
  }
  else
  {
    send_chat(player, message);
  }
}
Beispiel #16
0
// Generates a special header to allow LuaJIT and Sky to interact and then
// initializes the script.
//
// source     - The script source code.
// table      - The table used to generate the header.
// descriptor - The descriptor to initialize with the script.
// L          - A reference to where the new Lua state should be returned.
//
// Returns 0 if successful, otherwise returns -1.
int sky_lua_initscript_with_table(bstring source, sky_table *table,
                                  sky_data_descriptor *descriptor,
                                  lua_State **L)
{
    int rc;
    bstring header = NULL;
    bstring new_source = NULL;
    assert(source != NULL);
    assert(table != NULL);
    assert(descriptor != NULL);
    assert(L != NULL);
    
    // Generate header.
    rc = sky_lua_generate_header(source, table, &header);
    check(rc == 0, "Unable to generate header");
    new_source = bformat("%s%s", bdata(header), bdata(source)); check_mem(new_source);
    
    // Initialize script.
    rc = sky_lua_initscript(new_source, L);
    check(rc == 0, "Unable to initialize Lua script");

    // Initialize data descriptor.
    lua_getglobal(*L, "sky_init_descriptor");
    lua_pushlightuserdata(*L, descriptor);
    rc = lua_pcall(*L, 1, 0, 0);
    check(rc == 0, "Lua error while initializing descriptor: %s", lua_tostring(*L, -1));

    return 0;

error:
    *L = NULL;
    bdestroy(new_source);
    return -1;
}
Beispiel #17
0
// Unlocks an table.
//
// table - The table to unlock.
//
// Returns 0 if successful, otherwise returns -1.
int sky_table_unlock(sky_table *table)
{
    check(table != NULL, "Table required to unlock");

    // Generate lock file path.
    bstring path = NULL;

    // Only attempt to remove the lock if one has been obtained.
    if(table->lock_file != NULL) {
        // Close the lock file descriptor.
        fclose(table->lock_file);

        // Remove the lock file. We don't necessarily care if it gets cleaned
        // up so don't check for an error. The write lock is the more
        // important piece.
        path = bformat("%s/%s", bdata(table->path), SKY_LOCK_NAME);
        check_mem(path);
        unlink(bdata(path));
    }

    bdestroy(path);
    return 0;

error:
    bdestroy(path);
    return -1;
}
Beispiel #18
0
SkObject *sk_message_dispatch_simple(SkObject *self) {
    SkObject *result = NULL;
    bstring name = sk_string_get_bstring(sk_message_get_name(self));
    /* is a string */
    if(bchar(name, 0) == '"' && bchar(name, name->slen - 1) == '"') {
        return sk_string_from_bstring(self->vm, bmidstr(name, 1, name->slen - 2));
    } 
    /* is a number */
    else if(is_number(name)) {
        return sk_number_create(self->vm, atoi(bstr2cstr(name, '\0')));
    }
    /* is a command terminator. */
    else if(biseqcstr(name, ";") == 1) {
        return NULL;
    }
    /* a message. */
    else {
        int i;
        SkObjectList *callstack = sk_vm_callstack(SK_VM);
        for(i = kv_size(*callstack) - 1; i >= 0; i--) {
            SkObject *object = kv_A(*callstack, i);
            result = sk_object_dispatch_message(object, self);
            if(result) {
                return result;
            }
        }
        sk_printf("name: %s\n", name->data);
        sk_printf("thread: 0x%x\n", (unsigned int)pthread_self());
        sk_exc_raise(SK_VM, sk_exception_create_lazy(SK_VM, "MessageError",
                    bformat("Nobody is answering to the message '%s'.", name->data)));
        return NULL;
    }
}
Beispiel #19
0
int Upload_notify(Connection *conn, Handler *handler, const char *stage, bstring tmp_name)
{
    bstring key = bformat("x-mongrel2-upload-%s", stage);
    Request_set(conn->req, key, bstrcpy(tmp_name), 1);

    return Connection_send_to_handler(conn, handler, "", 0, NULL);
}
Beispiel #20
0
// Parses a timestamp from a C string. The return value is the number of
// microseconds before or after the epoch (Jan 1, 1970).
//
// NOTE: Parsing seems to only work back to around the first decade of the
//       1900's. Need to investigate further why this is.
//
// str - The string containing an ISO 8601 formatted date.
int sky_timestamp_parse(bstring str, sky_timestamp_t *ret)
{
    // Validate string.
    if(str == NULL) {
        return -1;
    }

    // Append "GMT" to end of string so that strptime will parse in UTC.
    bstring str2 = bformat("%s GMT", bdata(str));
    check_mem(str2);

    // Parse date.
    struct tm tp;
    char *ch;
    ch = strptime(bdata(str2), "%Y-%m-%dT%H:%M:%SZ %Z", &tp);
    check(ch != NULL, "Unable to parse timestamp");

    // Convert to microseconds since epoch in UTC.
    char buffer[100];
    strftime(buffer, 100, "%s", &tp);
    sky_timestamp_t value = atoll(buffer);
    *ret = value * 1000000;

    return 0;

error:
    bdestroy(str2);
    return -1;
}
Beispiel #21
0
bool LyXVC::file_not_found_hook(FileName const & fn)
{
	// Check if file is under RCS.
	// This happens if we are trying to load non existent
	// file on disk, but existent in ,v version.
	bool foundRCS = !RCS::findFile(fn).empty();
	bool foundCVS = foundRCS ? false : !CVS::findFile(fn).empty();
	bool foundSVN = (foundRCS || foundCVS) ? false : !SVN::findFile(fn).empty();
	bool foundGIT = (foundRCS || foundCVS || foundSVN) ? false : !GIT::findFile(fn).empty();
	if (foundRCS || foundCVS || foundSVN || foundGIT) {
		docstring const file = makeDisplayPath(fn.absFileName(), 20);
		docstring const text =
			bformat(_("Do you want to retrieve the document"
						   " %1$s from version control?"), file);
		int const ret = Alert::prompt(_("Retrieve from version control?"),
			text, 0, 1, _("&Retrieve"), _("&Cancel"));

		if (ret == 0) {
			// Since the retrieve commands are implemented using
			// more general update commands we need to ensure that
			// we do not change an existing file by accident.
			if (fn.exists())
				return false;
			if (foundRCS)
				return RCS::retrieve(fn);
			else if (foundCVS)
				return CVS::retrieve(fn);
			else if (foundSVN)
				return SVN::retrieve(fn);
			else
				return GIT::retrieve(fn);
		}
	}
	return false;
}
Beispiel #22
0
char *test_bformat() {
    bstring bstr = bformat("%s %s", "hello", "world");

    mu_assert(biseqStatic(bstr, "hello world") == 1, "bformat failed");
    
    bdestroy(bstr);
    return NULL;
}
Beispiel #23
0
void Handler_notify_credits(Handler *handler, int id, int credits)
{
    void *socket = handler->send_socket;
    assert(socket && "Socket can't be NULL");
    tns_outbuf outbuf = {.buffer = NULL};
    bstring payload = NULL;

    if(handler->protocol == HANDLER_PROTO_TNET) {
        int header_start = tns_render_request_start(&outbuf);
        bstring creditsstr = bformat("%d", credits);
        tns_render_hash_pair(&outbuf, &HTTP_METHOD, &JSON_METHOD);
        tns_render_hash_pair(&outbuf, &DOWNLOAD_CREDITS, creditsstr);
        bdestroy(creditsstr);
        tns_outbuf_clamp(&outbuf, header_start);

        payload = bformat("%s %d @* %s%d:%s,",
                bdata(handler->send_ident), id,
                bdata(tns_outbuf_to_bstring(&outbuf)),
                blength(&CREDITS_MSG), bdata(&CREDITS_MSG));
    } else {
        bstring headers = bfromcstralloc(PAYLOAD_GUESS, "{");

        bcatcstr(headers, "\"METHOD\":\"JSON\",\"");
        bconcat(headers, &DOWNLOAD_CREDITS);
        bcatcstr(headers, "\":\"");
        bformata(headers, "%d", credits);
        bcatcstr(headers, "\"}");

        payload = bformat("%s %d @* %d:%s,%d:%s,",
                bdata(handler->send_ident), id,
                blength(headers), bdata(headers),
                blength(&CREDITS_MSG), bdata(&CREDITS_MSG));

        bdestroy(headers);
    }

    check(payload != NULL, "Failed to make the payload for credits.");

    if(Handler_deliver(socket, bdata(payload), blength(payload)) == -1) {
        log_err("Can't tell handler %d giving credits.", id);
    }

error: //fallthrough
    if(payload) free(payload);
    if(outbuf.buffer) free(outbuf.buffer);
}
Beispiel #24
0
int Proxy_listen(Proxy *conn, ProxyClientType type, bstring name)
{
  switch(type) {
    case PROXY_CLIENT_DOMAIN:
      check(name, "DOMAIN client IO specified but NULL given for the name.");
      log(INFO, "Attaching to listener server socket on %s.", bdata(name));
      conn->client.read_fd = conn->client.write_fd =  unix_client(name);
      break;
    case PROXY_CLIENT_FIFO:
      check(name, "FIFO client IO specified but NULL given for the name.");
      bstring in_file = bformat("%s.in", bdata(name));
      bstring out_file = bformat("%s.out", bdata(name));
      check(!mkfifo((const char *)in_file->data, 0600), "Failed to create input fifo.");
      check(!mkfifo((const char *)out_file->data, 0600), "Failed to create output fifo.");

      log(INFO, "Opening %s for the read FIFO end.", bdata(in_file));
      conn->client.read_fd = open((const char *)in_file->data, O_RDONLY);
      check(conn->client.read_fd >= 0, "Failed to open read end of FIFO.");

      log(INFO, "Opening %s for the write FIFO end.", bdata(out_file));
      conn->client.write_fd = open((const char *)out_file->data, O_WRONLY);
      check(conn->client.write_fd >= 0, "Failed to open write end of FIFO.");

      bdestroy(in_file);
      bdestroy(out_file);
      break;
    case PROXY_CLIENT_STDIO:
      log(INFO, "Listening on stdin/stdout.");
      conn->client.read_fd = 0;
      conn->client.write_fd = 1;
      break;
    case PROXY_CLIENT_NONE:
      fail("You did not set a client connection type.");
      break;
    default:
      fail("Invalid proxy client type given.");
  }

  check_err(conn->client.read_fd >= 0, LISTENER_IO, "Failed to start listener read side.");
  check_err(conn->client.write_fd >= 0, LISTENER_IO, "Failed to start listener write side.");

  dbg("Client listening on read_fd %d and write_fd %d", conn->client.read_fd, conn->client.write_fd);

  return 1;
  on_fail(return 0);
}
Beispiel #25
0
docstring LyXVC::vcstatus() const
{
	if (!vcs)
		return docstring();
	if (locking())
		return bformat(_("%1$s lock"), from_ascii(vcs->vcname()));
	else
		return from_ascii(vcs->vcname());
}
Beispiel #26
0
char *test_bformat(void)
{
	bstring b = bformat("Hello %s, %d", "peter", 12345);
	mu_assert(b != NULL, "Failed to bformat().");
	mu_assert(strcmp((const char *)b->data, "Hello peter, 12345") == 0, "Wrong bformat() data.");
	
	mu_assert(bdestroy(b) == BSTR_OK, "Failed to bdestroy() afetr bformat().");
	return NULL;
}
Beispiel #27
0
void irc_write(bstring message)
{
    int n;

    n = write(sockfd, bdata(bformat("%s\r\n", bdata(message))), blength(message)+2);
    if (n < 0)
        perror("ERROR writing to socket");
    printf("%s\n", bdata(message));
}
Beispiel #28
0
int nodestr_to_nodelist(char* nodestr, int* nodes, int length)
{
    int ret = 0;
    bstring prefix = bformat("M");
    bstring bnodestr = bfromcstr(nodestr);
    ret = cpuexpr_to_list(bnodestr, prefix, nodes, length);
    bdestroy(bnodestr);
    return ret;
}
Beispiel #29
0
int sockstr_to_socklist(char* sockstr, int* sockets, int length)
{
    int ret = 0;
    bstring prefix = bformat("S");
    bstring bsockstr = bfromcstr(sockstr);
    ret = cpuexpr_to_list(bsockstr, prefix, sockets, length);
    bdestroy(bsockstr);
    return ret;
}
Beispiel #30
0
int headers_complete_cb (http_parser *p)
{
    assert(p == parser);
    Request *req = (Request*)p->data;

    req->request_method = bfromcstr(http_method_str(p->method));
    req->version = bformat("%d.%d", p->http_major, p->http_minor);

    return 0;
}