Ejemplo n.º 1
0
int plugin_register(struct plugin_handle* plugin, const char* config)
{
	struct chat_history_data* data;
	PLUGIN_INITIALIZE(plugin, "SQLite chat history plugin", "1.0", "Provide a global chat history log.");

	plugin->funcs.on_user_chat_message = history_add;
	plugin->funcs.on_user_login = user_login;
	data = parse_config(config, plugin);
	
	if (!data)
		return -1;

	plugin->ptr = data;

	create_tables(plugin);

	data->command_history_handle = (struct plugin_command_handle*) hub_malloc(sizeof(struct plugin_command_handle));
	PLUGIN_COMMAND_INITIALIZE(data->command_history_handle, plugin, "history", "?N", auth_cred_guest, &command_history, "Show chat message history.");
	plugin->hub.command_add(plugin, data->command_history_handle);

	data->command_historycleanup_handle = (struct plugin_command_handle*) hub_malloc(sizeof(struct plugin_command_handle));
	PLUGIN_COMMAND_INITIALIZE(data->command_historycleanup_handle, plugin, "historycleanup", "", auth_cred_admin, &command_historycleanup, "Clean chat message history.");
	plugin->hub.command_add(plugin, data->command_historycleanup_handle);

	return 0;
}
Ejemplo n.º 2
0
/*
 * Builds arguments.
 */
PRIVATE addr_t buildargs
(void *stack, size_t size, const char **argv, const char **envp)
{
	int p;        /* Stack pointer. */
	int argc;     /* argv length.   */
	int envc;     /* envc length.   */
	
	/* Get argv count. */
	if ((argc = count(argv)) < 0)
		return (0);
		
	/* Get envp count. */
	if ((envc = count(envp)) < 0)
		return (0);
		
	/* Copy argv and envp to stack. */
	if ((p = copy_strings(envc, envp, stack, size - 1, 0)) < 0)
		return (0);
	if ((p = copy_strings(argc, argv, stack, p, 0)) < 0)
		return (0);
	if ((p = create_tables(stack, size, p, argc, envc)) == 0)
		return (0);
		
	return (p);
}
Ejemplo n.º 3
0
int plugin_register(struct plugin_handle* plugin, const char* config)
{
	PLUGIN_INITIALIZE(plugin, "SQLite logging plugin", "0.5", "Logs users entering and leaving the hub to SQLite database.");

	struct log_data* ldata;

	plugin->funcs.on_user_login = log_user_login;
	plugin->funcs.on_user_login_error = log_user_login_error;
	plugin->funcs.on_user_logout = log_user_logout;
	plugin->funcs.on_user_nick_change = log_change_nick;

	ldata = parse_config(config, plugin);

	if (!ldata)
		return -1;

	ldata->command_userlog_handle = (struct plugin_command_handle*) hub_malloc(sizeof(struct plugin_command_handle));
	PLUGIN_COMMAND_INITIALIZE(ldata->command_userlog_handle, plugin, "userlog", "?N?mm", auth_cred_operator, &command_userlog, "[<lines> [<column> <search pattern>]]", "Search in userlog for a value.");
	plugin->hub.command_add(plugin, ldata->command_userlog_handle);

	ldata->command_userlogcleanup_handle = (struct plugin_command_handle*) hub_malloc(sizeof(struct plugin_command_handle));
	PLUGIN_COMMAND_INITIALIZE(ldata->command_userlogcleanup_handle, plugin, "userlogcleanup", "N", auth_cred_admin, &command_userlogcleanup, "<days>", "Delete log entries.");
	plugin->hub.command_add(plugin, ldata->command_userlogcleanup_handle);

	plugin->ptr = ldata;

	create_tables(plugin);

	return 0;
}
Ejemplo n.º 4
0
sqlite3* db_open()
{
    sqlite3 *db;
    g_debug("Open db connection to "CONFIGDIR"gtkqq.db (%s, %d)"
                                        , __FILE__, __LINE__);
    gint retcode = sqlite3_open(CONFIGDIR"gtkqq.db", &db);
    if(retcode != SQLITE_OK){
        if(retcode == SQLITE_NOMEM){
            g_error("Open database error. no memory. (%s, %d)", __FILE__, __LINE__);
            return NULL;
        }
        g_error("Open database error. %s (%s, %d)", sqlite3_errmsg(db)
                                        , __FILE__, __LINE__);
        sqlite3_close(db);
        return NULL;
    }
    if(!test_table_exist(db)){
        if(create_tables(db) != SQLITE_OK){
            g_error("Create tables error! (%s, %d)", __FILE__, __LINE__);
            sqlite3_close(db);
            return NULL;
        }
    }
    return db;
}
Ejemplo n.º 5
0
int plugin_register(struct plugin_handle* plugin, const char* config)
{
	struct extras_data* extrasdata;
	PLUGIN_INITIALIZE(plugin, "Extras plugin", "0.1", "Plugin for extra features like hub news, releases, hublist.");

	extrasdata = parse_config(config, plugin);

	if (!extrasdata)
		return -1;
  
	extrasdata->command_hubadd_handle = (struct plugin_command_handle*) hub_malloc(sizeof(struct plugin_command_handle));
	PLUGIN_COMMAND_INITIALIZE(extrasdata->command_hubadd_handle, plugin, "hubadd", "m+m", auth_cred_admin, &command_hubadd, "<address> <hub name>", "Add hub to hublist.");
	plugin->hub.command_add(plugin, extrasdata->command_hubadd_handle);

	extrasdata->command_hubdel_handle = (struct plugin_command_handle*) hub_malloc(sizeof(struct plugin_command_handle));
	PLUGIN_COMMAND_INITIALIZE(extrasdata->command_hubdel_handle, plugin, "hubdel", "N", auth_cred_admin, &command_hubdel, "<hub id>", "Delete hub from hublist.");
	plugin->hub.command_add(plugin, extrasdata->command_hubdel_handle);

	extrasdata->command_hublist_handle = (struct plugin_command_handle*) hub_malloc(sizeof(struct plugin_command_handle));
	PLUGIN_COMMAND_INITIALIZE(extrasdata->command_hublist_handle, plugin, "hublist", "", auth_cred_user, &command_hublist, "", "List hubs in hublist.");
	plugin->hub.command_add(plugin, extrasdata->command_hublist_handle);

	extrasdata->command_newsadd_handle = (struct plugin_command_handle*) hub_malloc(sizeof(struct plugin_command_handle));
	PLUGIN_COMMAND_INITIALIZE(extrasdata->command_newsadd_handle, plugin, "newsadd", "+m", auth_cred_admin, &command_newsadd, "", "Add news item.");
	plugin->hub.command_add(plugin, extrasdata->command_newsadd_handle);

	extrasdata->command_newsdel_handle = (struct plugin_command_handle*) hub_malloc(sizeof(struct plugin_command_handle));
	PLUGIN_COMMAND_INITIALIZE(extrasdata->command_newsdel_handle, plugin, "newsdel", "N", auth_cred_admin, &command_newsdel, "<news id>", "Delete news item.");
	plugin->hub.command_add(plugin, extrasdata->command_newsdel_handle);

	extrasdata->command_news_handle = (struct plugin_command_handle*) hub_malloc(sizeof(struct plugin_command_handle));
	PLUGIN_COMMAND_INITIALIZE(extrasdata->command_news_handle, plugin, "news", "", auth_cred_user, &command_news, "", "Show hubnews.");
	plugin->hub.command_add(plugin, extrasdata->command_news_handle);

	extrasdata->command_releaseadd_handle = (struct plugin_command_handle*) hub_malloc(sizeof(struct plugin_command_handle));
	PLUGIN_COMMAND_INITIALIZE(extrasdata->command_releaseadd_handle, plugin, "releaseadd", "m+m", auth_cred_admin, &command_releaseadd, "<tth> <title>", "Add release.");
	plugin->hub.command_add(plugin, extrasdata->command_releaseadd_handle);

	extrasdata->command_releasedel_handle = (struct plugin_command_handle*) hub_malloc(sizeof(struct plugin_command_handle));
	PLUGIN_COMMAND_INITIALIZE(extrasdata->command_releasedel_handle, plugin, "releasedel", "N", auth_cred_admin, &command_releasedel, "<release id>", "Delete release.");
	plugin->hub.command_add(plugin, extrasdata->command_releasedel_handle);

	extrasdata->command_releases_handle = (struct plugin_command_handle*) hub_malloc(sizeof(struct plugin_command_handle));
	PLUGIN_COMMAND_INITIALIZE(extrasdata->command_releases_handle, plugin, "releases", "", auth_cred_user, &command_releases, "", "Show releases.");
	plugin->hub.command_add(plugin, extrasdata->command_releases_handle);

	plugin->ptr = extrasdata;
	
	create_tables(plugin);
	
	return 0;
}
Ejemplo n.º 6
0
connection::connection(std::string const& file_name)
    : db_connection_m(0)
{
    int error = SQLITE_OK;
    error = sqlite3_open_v2(file_name.c_str(), &db_connection_m, SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, 0);
 
    if (error != SQLITE_OK)
    {
        throw std::runtime_error(std::string("Could not estabilish database connection: ") + sqlite3_errmsg(db_connection_m));
    }

    create_tables();
}
Ejemplo n.º 7
0
void SQLiteStorage::connect()
{
    if (SQLITE_OK != sqlite3_open(db_name_.c_str(), &connection_))
    {
        throw sqlite3_errcode(connection_);
    }
    if (create_)
    {
        create_tables();
        return;
    }
    load();
}
QcOfflineCacheDatabase::QcOfflineCacheDatabase(QString sqlite_path)
{
  bool create = !QFile(sqlite_path).exists();

  m_database = QSqlDatabase::addDatabase(QStringLiteral("QSQLITE"), sqlite_path);
  m_database.setDatabaseName(sqlite_path);
  if (!m_database.open())
    qWarning() << m_database.lastError().text();

  if (create)
    create_tables();
  else
    init_cache();
}
Ejemplo n.º 9
0
int BC_FileBox::refresh()
{
	create_tables();
	listbox->set_master_column(column_of_type(FILEBOX_NAME), 0);
	listbox->update(list_column, 
		column_titles, 
		column_width,
		columns, 
		0, 
		0,
		-1, 
		1);

	return 0;
}
Ejemplo n.º 10
0
struct plugin_t * init(void)
{
    plugin = malloc(sizeof (struct plugin_t));
    memset(plugin, 0, sizeof *plugin);

    plugin->run        = run;
    plugin->name       = "seen";
    plugin->type       = PLUGIN_TYPE_COMMAND | PLUGIN_TYPE_GREP;
    plugin->keywords   = keywords;

    create_tables();

    return plugin;

}
Ejemplo n.º 11
0
/* GNUCASH_RESAVE_VERSION indicates the earliest database version
 * compatible with this version of Gnucash; the stored value is the
 * earliest version of Gnucash conpatible with the database. If the
 * GNUCASH_RESAVE_VERSION for this Gnucash is newer than the Gnucash
 * version which created the database, a resave is offered. If the
 * version of this Gnucash is older than the saved resave version,
 * then the database will be loaded read-only. A resave will update
 * both values to match this version of Gnucash.
 */
void
gnc_dbi_load (QofBackend* qbe,  QofBook* book, QofBackendLoadType loadType)
{
    GncDbiBackend* be = (GncDbiBackend*)qbe;

    g_return_if_fail (qbe != nullptr);
    g_return_if_fail (book != nullptr);

    ENTER ("be=%p, book=%p", be, book);

    if (loadType == LOAD_TYPE_INITIAL_LOAD)
    {

        // Set up table version information
        be->init_version_info ();
        assert (be->m_book == nullptr);

        // Call all object backends to create any required tables
        auto registry = gnc_sql_get_backend_registry();
        for (auto entry : registry)
            create_tables(entry, be);
    }

    gnc_sql_load (be, book, loadType);

    if (GNUCASH_RESAVE_VERSION > be->get_table_version("Gnucash"))
    {
        /* The database was loaded with an older database schema or
         * data semantics. In order to ensure consistency, the whole
         * thing needs to be saved anew. */
        qof_backend_set_error (qbe, ERR_SQL_DB_TOO_OLD);
    }
    else if (GNUCASH_RESAVE_VERSION < be->get_table_version("Gnucash-Resave"))
    {
        /* Worse, the database was created with a newer version. We
         * can't safely write to this database, so the user will have
         * to do a "save as" to make one that we can write to.
         */
        qof_backend_set_error (qbe, ERR_SQL_DB_TOO_NEW);
    }


    LEAVE ("");
}
Ejemplo n.º 12
0
gboolean
almanah_storage_manager_connect (AlmanahStorageManager *self, GError **error)
{
	/* Our beautiful SQLite VFS */
	almanah_vfs_init(self->priv->settings);

	/* Open the plain database */
	if (sqlite3_open_v2 (self->priv->filename, &(self->priv->connection), SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, "almanah") != SQLITE_OK) {
		g_set_error (error, ALMANAH_STORAGE_MANAGER_ERROR, ALMANAH_STORAGE_MANAGER_ERROR_OPENING_FILE,
		             _("Could not open database \"%s\". SQLite provided the following error message: %s"),
		             self->priv->filename, sqlite3_errmsg (self->priv->connection));
		return FALSE;
	}

	/* Can't hurt to create the tables now */
	create_tables (self);

	return TRUE;
}
Ejemplo n.º 13
0
MetadataStorage::MetadataStorage(const char* db, aku_logger_cb_t logger)
    : pool_(nullptr, &delete_apr_pool)
    , driver_(nullptr)
    , handle_(nullptr, AprHandleDeleter(nullptr))
    , logger_(logger)
{
    apr_pool_t *pool = nullptr;
    auto status = apr_pool_create(&pool, NULL);
    if (status != APR_SUCCESS) {
        // report error (can't return error from c-tor)
        throw std::runtime_error("Can't create memory pool");
    }
    pool_.reset(pool);

    status = apr_dbd_get_driver(pool, "sqlite3", &driver_);
    if (status != APR_SUCCESS) {
        (*logger_)(AKU_LOG_ERROR, "Can't load driver, maybe libaprutil1-dbd-sqlite3 isn't installed");
        throw std::runtime_error("Can't load sqlite3 dirver");
    }

    apr_dbd_t *handle = nullptr;
    status = apr_dbd_open(driver_, pool, db, &handle);
    if (status != APR_SUCCESS) {
        (*logger_)(AKU_LOG_ERROR, "Can't open database, check file path");
        throw std::runtime_error("Can't open database");
    }
    handle_ = HandleT(handle, AprHandleDeleter(driver_));

    auto sqlite_handle = apr_dbd_native_handle(driver_, handle);
    sqlite3_trace((sqlite3*)sqlite_handle, callback_adapter, (void*)logger_);

    create_tables();

    // Create prepared statement
    const char* query = "INSERT INTO akumuli_series (series_id, keyslist, storage_id) VALUES (%s, %s, %d)";
    status = apr_dbd_prepare(driver_, pool_.get(), handle_.get(), query, "INSERT_SERIES_NAME", &insert_);
    if (status != 0) {
        (*logger_)(AKU_LOG_ERROR, "Error creating prepared statement");
        throw std::runtime_error(apr_dbd_error(driver_, handle_.get(), status));
    }
}
Ejemplo n.º 14
0
static gboolean create_database_connection() {
	gchar *path;
	int rc;

	if(_db)
		return TRUE;

	/* build the path */
	path = g_build_filename(purple_user_dir(), "cap.db", (gchar *)NULL);

	/* make database connection here */
	rc = sqlite3_open(path, &_db);
	g_free(path);
	if(rc != SQLITE_OK)
		return FALSE;

	/* Add tables here */
	create_tables();
	purple_debug_info("cap", "Database connection successfully made.\n");
	return TRUE;
}
Ejemplo n.º 15
0
int dbfile_create(char *filename)
{
	int ret;
	sqlite3 *db = NULL;

	ret = unlink(filename);
	if (ret && errno != ENOENT) {
		ret = errno;
		fprintf(stderr,
			"Error %d while unlinking old db file \"%s\": %s",
			ret, filename, strerror(ret));
		return ret;
	}

#define OPEN_FLAGS	(SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|SQLITE_OPEN_NOMUTEX)
	ret = sqlite3_open_v2(filename, &db, OPEN_FLAGS, NULL);
	if (ret) {
		perror_sqlite_open(db, filename);
		return ret;
	}

	ret = create_tables(db);
	if (ret) {
		perror_sqlite(ret, "creating tables");
		sqlite3_close(db);
		return ret;
	}

	ret = dbfile_set_modes(db);
	if (ret) {
		perror_sqlite(ret, "setting journal modes");
		sqlite3_close(db);
		return ret;
	}

	gdb = db;
	return 0;
}
Ejemplo n.º 16
0
/* GNUCASH_RESAVE_VERSION indicates the earliest database version
 * compatible with this version of Gnucash; the stored value is the
 * earliest version of Gnucash conpatible with the database. If the
 * GNUCASH_RESAVE_VERSION for this Gnucash is newer than the Gnucash
 * version which created the database, a resave is offered. If the
 * version of this Gnucash is older than the saved resave version,
 * then the database will be loaded read-only. A resave will update
 * both values to match this version of Gnucash.
 */
template <DbType Type> void
GncDbiBackend<Type>::load (QofBook* book, QofBackendLoadType loadType)
{
    g_return_if_fail (book != nullptr);

    ENTER ("dbi_be=%p, book=%p", this, book);

    if (loadType == LOAD_TYPE_INITIAL_LOAD)
    {

        // Set up table version information
        init_version_info ();
        assert (m_book == nullptr);
        create_tables();
    }

    GncSqlBackend::load(book, loadType);

    if (GNUCASH_RESAVE_VERSION > get_table_version("Gnucash"))
    {
        /* The database was loaded with an older database schema or
         * data semantics. In order to ensure consistency, the whole
         * thing needs to be saved anew. */
        set_error(ERR_SQL_DB_TOO_OLD);
    }
    else if (GNUCASH_RESAVE_VERSION < get_table_version("Gnucash-Resave"))
    {
        /* Worse, the database was created with a newer version. We
         * can't safely write to this database, so the user will have
         * to do a "save as" to make one that we can write to.
         */
        set_error(ERR_SQL_DB_TOO_NEW);
    }


    LEAVE ("");
}
Ejemplo n.º 17
0
static void
main_window_prepare (GstUsersTool *tool)
{
	GtkWidget *uid_entry;
	GtkWidget *passwd_label;
	int width;

	uid_entry = gst_dialog_get_widget (GST_TOOL (tool)->main_dialog, "user_settings_uid");
	gtk_spin_button_set_range (GTK_SPIN_BUTTON (uid_entry), 0, OOBS_MAX_UID);

	create_tables (tool);

	gtk_window_set_default_size (GTK_WINDOW (GST_TOOL (tool)->main_dialog),
	                             650, 400);

	/* Ensure dialog won't change size when selecting another user */
	passwd_label = gst_dialog_get_widget (GST_TOOL (tool)->main_dialog,
	                                        "user_settings_passwd");
	width = MAX (strlen (_("Not asked on login")), strlen (_("Asked on login")));
	gtk_label_set_width_chars (GTK_LABEL (passwd_label), width);

	/* For random password generation. */
	srand (time (NULL));
}
Ejemplo n.º 18
0
int 
main(int argc, const char *argv[])
{
    const char* host = "127.0.0.1:2181";
    zhandle_t* zkhandle;
    int timeout = 5000;
    char node[512] = {0};
    char tables[][64] = {
        {"employee_info_tab"},
        {"boss_info_tab"}
    };
    
    zoo_set_debug_level(ZOO_LOG_LEVEL_WARN);
    zkhandle = zookeeper_init(host, NULL, timeout, 
                              0, "Zookeeper examples: config center services", 0);
    if (zkhandle == NULL) {
        fprintf(stderr, "Connecting to zookeeper servers error...\n");
        exit(EXIT_FAILURE);
    }

    /* join the election group */
    struct watch_func_para_t para;
    int ret = join_the_election(zkhandle, node, &para);
    if (zkhandle == NULL) {
        fprintf(stderr, "join the election error...\n");
        exit(EXIT_FAILURE);
    }

    /* leader election */
    if (is_leader(zkhandle, node)) {
        i_am_leader = true;
        printf("This is [%s], i am a leader\n", node);
        (void)create_tables(zkhandle, tables, sizeof(tables)/sizeof(tables[0]));
    } else {
        i_am_leader = false;
        printf("This is [%s], i am a follower\n", node);
    }

    /* start the trigger listen thread */
    pthread_attr_t attr1;
    ret = pthread_attr_init(&attr1);
    if (ret != 0) {
        fprintf(stderr, "pthread_attr_init error...\n");
        exit(EXIT_FAILURE);
    }

    pthread_t trigger_listen_thr;
    ret = pthread_create(&trigger_listen_thr, &attr1, trigger_listen_thread, zkhandle);
    if (ret != 0) {
        fprintf(stderr, "pthread_create error...\n");
        exit(EXIT_FAILURE);
    }

    ret = pthread_attr_destroy(&attr1);
    if (ret != 0) {
        fprintf(stderr, "pthread_attr_destroy error...\n");
        exit(EXIT_FAILURE);
    }
    
    /* start the item expire thread */
    pthread_attr_t attr2;
    ret = pthread_attr_init(&attr2);
    if (ret != 0) {
        fprintf(stderr, "pthread_attr_init error...\n");
        exit(EXIT_FAILURE);
    }

    pthread_t expire_thr;
    ret = pthread_create(&expire_thr, &attr2, item_expire_thread, zkhandle);
    if (ret != 0) {
        fprintf(stderr, "pthread_create error...\n");
        exit(EXIT_FAILURE);
    }

    ret = pthread_attr_destroy(&attr2);
    if (ret != 0) {
        fprintf(stderr, "pthread_attr_destroy error...\n");
        exit(EXIT_FAILURE);
    }

    void *res;
    ret = pthread_join(trigger_listen_thr, (void**)&res);
    if (ret != 0) {
        fprintf(stderr, "pthread_join error...\n");
        exit(EXIT_FAILURE);
    }

    ret = pthread_join(expire_thr, (void**)&res);
    if (ret != 0) {
        fprintf(stderr, "pthread_join error...\n");
        exit(EXIT_FAILURE);
    }

    zookeeper_close(zkhandle);
}
Ejemplo n.º 19
0
void
GncSqlBackend::sync_all(QofBook* book)
{
    g_return_if_fail (book != NULL);

    reset_version_info();
    ENTER ("book=%p, sql_be->book=%p", book, m_book);
    update_progress();

    /* Create new tables */
    m_is_pristine_db = true;
    create_tables();

    /* Save all contents */
    m_book = book;
    auto is_ok = m_conn->begin_transaction();

    // FIXME: should write the set of commodities that are used
    // write_commodities(sql_be, book);
    if (is_ok)
    {
        auto obe = m_backend_registry.get_object_backend(GNC_ID_BOOK);
        is_ok = obe->commit (this, QOF_INSTANCE (book));
    }
    if (is_ok)
    {
        is_ok = write_accounts();
    }
    if (is_ok)
    {
        is_ok = write_transactions();
    }
    if (is_ok)
    {
        is_ok = write_template_transactions();
    }
    if (is_ok)
    {
        is_ok = write_schedXactions();
    }
    if (is_ok)
    {
        for (auto entry : m_backend_registry)
            std::get<1>(entry)->write (this);
    }
    if (is_ok)
    {
        is_ok = m_conn->commit_transaction();
    }
    if (is_ok)
    {
        m_is_pristine_db = false;

        /* Mark the session as clean -- though it shouldn't ever get
         * marked dirty with this backend
         */
        qof_book_mark_session_saved(book);
    }
    else
    {
        if (!qof_backend_check_error (&qof_be))
            qof_backend_set_error (&qof_be, ERR_BACKEND_SERVER_ERR);
        is_ok = m_conn->rollback_transaction ();
    }
    finish_progress();
    LEAVE ("book=%p", book);
}
Ejemplo n.º 20
0
Archivo: db.c Proyecto: EEEden/chat
void init_db(){
    sqlite3 *db = connect_db();
    create_tables(&db);
    sqlite3_close(db);
}
Ejemplo n.º 21
0
int register_files_from_stdin(char* build, char* project, char* path) {
	int res = 0;
	int loaded = 0;
	char *line;
	size_t size;

	create_tables();
	
	if (SQL("BEGIN")) { return -1; }
	
	prune_old_entries(build, project);

	//
	// Enumerate the files in the path (DSTROOT) and associate them
	// with the project name and version in the sqlite database.
	//
	// Skip the first result, since that is . of the DSTROOT itself.
        while ((line = fgetln(stdin, &size)) != NULL) {
		char filename[MAXPATHLEN+1];
		char fullpath[MAXPATHLEN+1];
		char symlink[MAXPATHLEN+1];
		ssize_t len;
		struct stat sb;
		char *lastpathcomp = NULL;

		if (size > 0 && line[size-1] == '\n') line[--size] = 0; // chomp newline
		if (size > 0 && line[size-1] == '/') line[--size] = 0; // chomp trailing slash

		if(0 == strcmp(line, "."))
		  continue;

		// Filename
		filename[0] = 0;
		strcpy(filename, line+1); /* skip over leading "." */

		lastpathcomp = strrchr(filename, '/');
		if(lastpathcomp && 0 == strncmp(lastpathcomp+1, "._", 2))
		  continue;


		sprintf(fullpath, "%s/%s", path, filename);
		res = lstat(fullpath, &sb);
		if(res != 0) {
		  perror(fullpath);
		  return -1;
		}
		  
		// Symlinks
		symlink[0] = 0;
		if (S_ISLNK(sb.st_mode)) {
			len = readlink(fullpath, symlink, MAXPATHLEN);
			if (len >= 0) symlink[len] = 0;
		}
		
		// Default to empty SHA-1 checksum
		char* checksum = strdup("                                        ");
		
		// Checksum regular files
		if (S_ISREG(sb.st_mode)) {
			int fd = open(fullpath, O_RDONLY);
			if (fd == -1) {
				perror(filename);
				return -1;
			}
			res = register_libraries(fd, build, project, filename, NULL);
			/* For -stdin mode, we don't calculate checksums
			lseek(fd, (off_t)0, SEEK_SET);
			checksum = calculate_digest(fd);
			*/
			close(fd);
		}

		// register regular files and symlinks in the DB
		if (S_ISREG(sb.st_mode) || S_ISLNK(sb.st_mode)) {
			res = SQL("INSERT INTO files (build,project, path) VALUES (%Q,%Q,%Q)",
				build, project, filename);
			++loaded;
		}
		
		// add all regular files, directories, and symlinks to the manifest
		if (S_ISREG(sb.st_mode) || S_ISLNK(sb.st_mode) || S_ISDIR(sb.st_mode)) {
			fprintf(stdout, "%s %o %d %d %lld .%s%s%s\n",
				checksum,
				sb.st_mode,
				sb.st_uid,
				sb.st_gid,
				!S_ISDIR(sb.st_mode) ? sb.st_size : (off_t)0,
				filename,
				symlink[0] ? " -> " : "",
				symlink[0] ? symlink : "");
		}
		free(checksum);
	}
	
	if (SQL("COMMIT")) { return -1; }

	fprintf(stderr, "%s - %d files registered.\n", project, loaded);
	
	return res;
}
Ejemplo n.º 22
0
/**
 * @brief Start the storage server.
 *
 * This is the main entry point for the storage server.  It reads the
 * configuration file, starts listening on a port, and proccesses
 * commands from clients.
 */
int main(int argc, char *argv[])
{
    char file_name[MAX_LOG_NAME] = "Server";
    server_time_log = fopen("server_times.log", "a");

    switch (LOGGING)
    {
        case 0:
            server_log = NULL;
            break;
            
        case 1:
            server_log = stdout;
            break;
            
        case 2:
            server_log = fopen(generate_logfile(file_name), "w");
            break;
    }
    
    // Process command line arguments.
    // This program expects exactly one argument: the config file name.
    assert(argc > 0);
    if (argc != 2)
    {
        printf("Usage %s <config_file>\n", argv[0]);
        exit(EXIT_FAILURE);
    }
    char *config_file = argv[1];
    
    // Read the config file.
    
    int status = read_config(config_file, &params);
    if (status != 0)
    {
        printf("Error processing config file.\n");
        exit(EXIT_FAILURE);
    }
    
    
    sprintf(log_buffer, "server main: Server on %s:%d\n", params.server_host, params.server_port);
    logger(server_log, log_buffer);
    
    // Create a socket.
    int listensock = socket(PF_INET, SOCK_STREAM, 0);
    if (listensock < 0)
    {
        printf("Error creating socket.\n");
        exit(EXIT_FAILURE);
    }
    
    // Allow listening port to be reused if defunct.
    int yes = 1;
    status = setsockopt(listensock, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof yes);
    if (status != 0)
    {
        printf("Error configuring socket.\n");
        exit(EXIT_FAILURE);
    }
    
    // Bind it to the listening port.
    struct sockaddr_in listenaddr;
    memset(&listenaddr, 0, sizeof listenaddr);
    listenaddr.sin_family = AF_INET;
    listenaddr.sin_port = htons(params.server_port);
    inet_pton(AF_INET, params.server_host, &(listenaddr.sin_addr)); // bind to local IP address
    status = bind(listensock, (struct sockaddr*) &listenaddr, sizeof listenaddr);
    if (status != 0)
    {
        printf("Error binding socket.\n");
        exit(EXIT_FAILURE);
    }
    
    // Listen for connections.
    status = listen(listensock, MAX_LISTENQUEUELEN);
    if (status != 0)
    {
        printf("Error listening on socket.\n");
        exit(EXIT_FAILURE);
    }

    status = create_tables();
    if (status != 0)
    {
        printf("Error creating tables.\n");
        delete_tables();
        exit(EXIT_FAILURE);
    }

    int i;
    if(strcmp(params.table_names[0], "census") == 0)
        for(i = 0; i < params.num_tables; i++)
        {
            status = populate_database(params.table_names[i]);
            if(status != 0)
            {
                printf("Error populating tables.\n");
                delete_tables();
                exit(EXIT_FAILURE);
            }
        }

    // Listen loop.
    int wait_for_connections = 1;
    while (wait_for_connections)
    {
        // Wait for a connection.
        struct sockaddr_in clientaddr;
        socklen_t clientaddrlen = sizeof clientaddr;
        int clientsock = accept(listensock, (struct sockaddr*)&clientaddr, &clientaddrlen);
        if (clientsock < 0)
        {
            printf("Error accepting a connection.\n");
            delete_tables();
            exit(EXIT_FAILURE);
        }
        
        
        sprintf(log_buffer, "server main: Got a connection from %s:%d.\n", inet_ntoa(clientaddr.sin_addr), clientaddr.sin_port);
        logger(server_log, log_buffer);
        
        // Get commands from client.
        int wait_for_commands = 1;
        do
        {
            // Read a line from the client.
            char cmd[MAX_CMD_LEN] = {0};
            int status = recvline(clientsock, cmd, MAX_CMD_LEN);
            if (status != 0)
            {
                // Either an error occurred or the client closed the connection.
                wait_for_commands = 0;
            }
            else
            {
                // Handle the command from the client.
                int status = handle_command(clientsock, cmd);
                if (status != 0)
                    wait_for_commands = 0; // Oops.  An error occured.
            }
        }
        while (wait_for_commands);
        
        // Close the connection with the client.
        close(clientsock);
        
        
        sprintf(log_buffer, "server main: Closed connection from %s:%d.\n", inet_ntoa(clientaddr.sin_addr), clientaddr.sin_port);
        logger(server_log, log_buffer);
    }
    
    // Stop listening for connections.
    close(listensock);
 
    fprintf(server_time_log, "Total %d gets performed in %ld microseconds\n", n_gets, get_processing_time.tv_usec);
    fprintf(server_time_log, "Total %d sets performed in %ld microseconds\n", n_sets, set_processing_time.tv_usec);
    fclose(server_time_log);
 
    delete_tables();
    fclose(server_log);
    
    return EXIT_SUCCESS;
}
Ejemplo n.º 23
0
int BC_FileBox::create_objects()
{
	int x = 10, y = 10;
	BC_Resources *resources = BC_WindowBase::get_resources();
	int directory_title_margin = MAX(20,
		resources->filebox_text_images[0]->get_h());

// Create recent dir list
	create_history();

// Directories aren't filtered in FileSystem so skip this
	if(!want_directory)
	{
		filter_list.append(new BC_ListBoxItem("*"));
		filter_list.append(new BC_ListBoxItem("[*.ifo][*.vob]"));
		filter_list.append(new BC_ListBoxItem("[*.mp2][*.mp3][*.wav]"));
		filter_list.append(new BC_ListBoxItem("[*.avi][*.mpg][*.m2v][*.m1v][*.mov]"));
		filter_list.append(new BC_ListBoxItem("heroine*"));
		filter_list.append(new BC_ListBoxItem("*.xml"));
		fs->set_filter(get_resources()->filebox_filter);
	}

	fs->update(directory);
	create_icons();
	create_tables();

	add_subwindow(ok_button = new BC_FileBoxOK(this));
	if(want_directory)
		add_subwindow(usethis_button = new BC_FileBoxUseThis(this));
	add_subwindow(cancel_button = new BC_FileBoxCancel(this));

	add_subwindow(new BC_Title(x, y, caption));

	x = get_w() - resources->filebox_icons_images[0]->get_w() - 10;
	add_subwindow(icon_button = new BC_FileBoxIcons(x, y, this));
	x -= resources->filebox_text_images[0]->get_w() + 5;
	add_subwindow(text_button = new BC_FileBoxText(x, y, this));
	x -= resources->filebox_newfolder_images[0]->get_w() + 5;
	add_subwindow(folder_button = new BC_FileBoxNewfolder(x, y, this));
	x -= resources->filebox_delete_images[0]->get_w() + 5;
	add_subwindow(delete_button = new BC_FileBoxDelete(x, y, this));
	x -= resources->filebox_reload_images[0]->get_w() + 5;
	add_subwindow(reload_button = new BC_FileBoxReload(x, y, this));
	x -= resources->filebox_updir_images[0]->get_w() + 5;
	add_subwindow(updir_button = new BC_FileBoxUpdir(x, y, this));

	x = 10;
	y += directory_title_margin + 3;

	add_subwindow(recent_popup = new BC_FileBoxRecent(this, 
		x, 
		y));
	add_subwindow(directory_title = new BC_FileBoxDirectoryText(x, y, this));
	directory_title->reposition_window(
		x,
		y,
		get_w() - recent_popup->get_w() -  20,
		1);
	recent_popup->reposition_window(
		x + directory_title->get_w(),
		y,
		directory_title->get_w(),
		200);

	x = 10;
	y += directory_title->get_h() + 5;
	listbox = 0;

	create_listbox(x, y, get_display_mode());
	y += listbox->get_h() + 10;
	add_subwindow(textbox = new BC_FileBoxTextBox(x, y, this));
	y += textbox->get_h() + 10;


	if(!want_directory)
	{
		add_subwindow(filter_text = new BC_FileBoxFilterText(x, y, this));
		add_subwindow(filter_popup = 
			new BC_FileBoxFilterMenu(x + filter_text->get_w(), y, this));;
	}

// listbox has to be active because refresh might be called from newfolder_thread
 	listbox->activate();
	newfolder_thread = new BC_NewFolderThread(this);
	
	show_window();
	return 0;
}
Ejemplo n.º 24
0
/**
 * Attaches a registry database to the registry object. Prior to calling this,
 * the registry object is not actually connected to the registry. This function
 * attaches it so it can be queried and manipulated.
 *
 * @param [in] reg     the registry to attach to
 * @param [in] path    path to the registry db on disk
 * @param [out] errPtr on error, a description of the error that occurred
 * @return             true if success; false if failure
 */
int reg_attach(reg_registry* reg, const char* path, reg_error* errPtr) {
    struct stat sb;
    int initialized = 1; /* registry already exists */
    int can_write = 1; /* can write to this location */
    int result = 0;
    if (reg->status & reg_attached) {
        reg_throw(errPtr, REG_MISUSE, "a database is already attached to this "
                "registry");
        return 0;
    }
    if (stat(path, &sb) != 0) {
        initialized = 0;
        if (errno == ENOENT) {
            char *dirc, *dname;
            dirc = strdup(path);
            dname = dirname(dirc);
            if (stat(dname, &sb) != 0) {
                can_write = 0;
            }
            free(dirc);
        } else {
            can_write = 0;
        }
    }
    /* can_write is still true if one of the stat calls succeeded */
    if (initialized || can_write) {
        sqlite3_stmt* stmt = NULL;
        char* query = sqlite3_mprintf("ATTACH DATABASE '%q' AS registry", path);
        int r;
        do {
            r = sqlite3_prepare_v2(reg->db, query, -1, &stmt, NULL);
        } while (r == SQLITE_BUSY);
        if (r == SQLITE_OK) {
            /* XXX: Busy waiting, consider using sqlite3_busy_handler/timeout */
            do {
                sqlite3_step(stmt);
                r = sqlite3_reset(stmt);
                switch (r) {
                    case SQLITE_OK:
                        if (initialized || (create_tables(reg->db, errPtr))) {
                            Tcl_InitHashTable(&reg->open_entries,
                                    sizeof(sqlite_int64)/sizeof(int));
                            Tcl_InitHashTable(&reg->open_files,
                                    TCL_STRING_KEYS);
                            Tcl_InitHashTable(&reg->open_portgroups,
                                    sizeof(sqlite_int64)/sizeof(int));
                            reg->status |= reg_attached;
                            result = 1;
                        }
                        break;
                    case SQLITE_BUSY:
                        break;
                    default:
                        reg_sqlite_error(reg->db, errPtr, query);
                }
            } while (r == SQLITE_BUSY);

            sqlite3_finalize(stmt);
            stmt = NULL;

            if (result) {
                result &= update_db(reg->db, errPtr);
            }
        } else {
            reg_sqlite_error(reg->db, errPtr, query);
        }
        if (stmt) {
            sqlite3_finalize(stmt);
        }
        sqlite3_free(query);
    } else {
        reg_throw(errPtr, REG_CANNOT_INIT, "port registry doesn't exist at "
                "\"%q\" and couldn't write to this location", path);
    }
    return result;
}
Ejemplo n.º 25
0
int
main(int argc, char **argv)
{
	LOGINREC *login;
	DBPROCESS *dbproc;
	int i;
	char teststr[1024];
	DBINT testint;
	DBVARYBIN  testvbin;
	DBVARYCHAR testvstr;
	int failed = 0;
	int expected_error;

	set_malloc_options();

	read_login_info(argc, argv);

	fprintf(stdout, "Starting %s\n", argv[0]);

	dbinit();

	dberrhandle(syb_err_handler);
	dbmsghandle(syb_msg_handler);

	fprintf(stdout, "About to logon\n");

	login = dblogin();
	DBSETLPWD(login, PASSWORD);
	DBSETLUSER(login, USER);
	DBSETLAPP(login, "t0007");

	fprintf(stdout, "About to open\n");

	dbproc = dbopen(login, SERVER);
	if (strlen(DATABASE))
		dbuse(dbproc, DATABASE);
	dbloginfree(login);

	create_tables(dbproc, 10);

	if (!start_query(dbproc)) {
		fprintf(stderr, "%s:%d: start_query failed\n", __FILE__, __LINE__);
		failed = 1;
	}

	dbbind(dbproc, 1, INTBIND, 0, (BYTE *) & testint);
	dbbind(dbproc, 2, STRINGBIND, 0, (BYTE *) teststr);

	for (i = 1; i <= 2; i++) {
		char expected[1024];

		sprintf(expected, "row %07d", i);

		if (i % 5 == 0) {
			dbclrbuf(dbproc, 5);
		}

		testint = -1;
		strcpy(teststr, "bogus");

		if (REG_ROW != dbnextrow(dbproc)) {
			fprintf(stderr, "Failed.  Expected a row\n");
			abort();
		}
		if (testint != i) {
			fprintf(stderr, "Failed.  Expected i to be %d, was %d\n", i, (int) testint);
			abort();
		}
		if (0 != strncmp(teststr, expected, strlen(expected))) {
			fprintf(stdout, "Failed.  Expected s to be |%s|, was |%s|\n", expected, teststr);
			abort();
		}
		printf("Read a row of data -> %d %s\n", (int) testint, teststr);
	}


	fprintf(stdout, "second select.  Should fail.\n");

	expected_error = 20019;
	dbsetuserdata(dbproc, (BYTE*) &expected_error);

	if (start_query(dbproc)) {
		fprintf(stderr, "%s:%d: start_query should have failed but didn't\n", __FILE__, __LINE__);
		failed = 1;
	}

	dbcancel(dbproc);
	
	/* 
	 * Test Binary binding
	 */
	if (!start_query(dbproc)) {
		fprintf(stderr, "%s:%d: start_query failed\n", __FILE__, __LINE__);
		failed = 1;
	}

	dbbind(dbproc, 1, VARYBINBIND, sizeof(testvbin), (BYTE *) &testvbin);
	dbbind(dbproc, 2, VARYCHARBIND, sizeof(testvstr), (BYTE *) &testvstr);
	dbbind(dbproc, 3, BINARYBIND, sizeof(testint), (BYTE *) &testint);

	for (i = 1; i <= 2; i++) {
		char expected[1024];

		sprintf(expected, "row %07d ", i);

		testint = -1;
		memset(&testvbin, '*', sizeof(testvbin));
		memset(&testvstr, '*', sizeof(testvstr));

		if (REG_ROW != dbnextrow(dbproc)) {
			fprintf(stderr, "Failed.  Expected a row\n");
			abort();
		}
		if (testint != i) {
			fprintf(stderr, "Failed, line %d.  Expected i to be %d, was %d (0x%x)\n", __LINE__, i, (int) testint, (int) testint);
			abort();
		}
		if (testvbin.len != sizeof(testint)) {
			fprintf(stderr, "Failed, line %d.  Expected bin lenght to be %d, was %d\n", __LINE__, (int) sizeof(testint), (int) testvbin.len);
			abort();
		}
		memcpy(&testint, testvbin.array, sizeof(testint));
		if (testint != i) {
			fprintf(stderr, "Failed, line %d.  Expected i to be %d, was %d (0x%x)\n", __LINE__, i, (int) testint, (int) testint);
			abort();
		}
		if (testvstr.len != strlen(expected) || 0 != strncmp(testvstr.str, expected, strlen(expected))) {
			fprintf(stdout, "Failed, line %d.  Expected s to be |%s|, was |%s|\n", __LINE__, expected, testvstr.str);
			abort();
		}
		testvstr.str[testvstr.len] = 0;
		printf("Read a row of data -> %d %s\n", (int) testint, testvstr.str);
	}


	dbexit();

	fprintf(stdout, "%s %s\n", __FILE__, (failed ? "failed!" : "OK"));
	return failed ? 1 : 0;
}
Ejemplo n.º 26
0
Archivo: jess.c Proyecto: kunaldeo/JESS
void
jess_init (void)
{

  /*  quit_keyb = 0; */
  quit_renderer = 0;

  xres2 = resx/2;
  yres2 = resy/2;

  conteur.fullscreen = 0;
  conteur.blur_mode = 1;

  /******* ALLOCATION OF TABLES AND BUFFERS *****************/
  table1 = (unsigned int *) malloc (resx * resy * sizeof (int));
  if (!table1)
    {
      printf ("Not enought memory for allocating tables\n");
      exit (1);
    }
  table2 = (unsigned int *) malloc (resx * resy * sizeof (int));
  if (!table2)
    {
      printf ("Not enought memory for allocating tables\n");
      exit (1);
    }
  table3 = (unsigned int *) malloc (resx * resy * sizeof (int));
  if (!table3)
    {
      printf ("Not enought memory for allocating tables\n");
      exit (1);
    }
  table4 = (unsigned int *) malloc (resx * resy * sizeof (int));
  if (!table4)
    {
      printf ("Not enought memory for allocating tables\n");
      exit (1);
    }
  printf ("Tables created\n");

  printf("Video mode = %d*%d*%d bits\n", resx, resy, video);
  if (video == 8)
    buffer = (unsigned char *) malloc (resx * resy); 
  else
    {
      buffer = (unsigned char *) malloc (resx * resy * 4); 
      printf("Allocating memory done.\n");
    }
  if (!buffer)
    {
      printf ("Not enought memory for allocating buffer\n");
      exit (1);
    }

  printf ("Buffer created\n");
  /**********************************************************/

  /******* TABLES COMPUTATION *******************************/
  create_tables();
  printf("Table computation Ok\n");
  /***********************************************************/

  srand (343425);

  if (video == 8)
    init_video_8();
  else 
    init_video_32();
  


}
Ejemplo n.º 27
0
static int
load_object (struct linux_binprm * bprm, struct pt_regs *regs, int lib_ok)
{
    COFF_FILHDR  *coff_hdr = (COFF_FILHDR *) bprm->buf;	/* COFF Header */
    COFF_SCNHDR  *sect_bufr;	/* Pointer to section table            */
    COFF_SCNHDR  *text_sect;	/* Pointer to the text section         */
    COFF_SCNHDR  *data_sect;	/* Pointer to the data section         */
    COFF_SCNHDR  *bss_sect;	/* Pointer to the bss section          */
    int text_count;		/* Number of text sections             */
    int data_count;		/* Number of data sections             */
    int bss_count;		/* Number of bss sections              */
    int lib_count;		/* Number of lib sections              */
    unsigned int start_addr = 0;/* Starting location for program       */
    int status = 0;		/* Result status register              */
    int fd = -1;		/* Open file descriptor                */
    struct file *fp     = NULL;	/* Pointer to the file at "fd"         */
    short int sections  = 0;	/* Number of sections in the file      */
    short int aout_size = 0;	/* Size of the a.out header area       */
    short int flags;		/* Flag bits from the COFF header      */

#ifdef COFF_DEBUG
    printk ("binfmt_coff entry: %s\n", bprm->filename);
#endif

/*
 *  Validate the magic value for the object file.
 */
    do {
	if (COFF_I386BADMAG (*coff_hdr)) {
#ifdef COFF_DEBUG
	    printk ("bad filehdr magic\n");
#endif
	    status = -ENOEXEC;
	    break;
	}
/*
 *  The object file should have 32 BIT little endian format. Do not allow
 *  it to have the 16 bit object file flag set as Linux is not able to run
 *  on the 80286/80186/8086.
 */
	flags = COFF_SHORT (coff_hdr->f_flags);
	if ((flags & (COFF_F_AR32WR | COFF_F_AR16WR)) != COFF_F_AR32WR) {
#ifdef COFF_DEBUG
	    printk ("invalid f_flags bits\n");
#endif
	    status = -ENOEXEC;
	    break;
	}
/*
 *  Extract the header information which we need.
 */
	sections  = COFF_SHORT (coff_hdr->f_nscns);   /* Number of sections */
	aout_size = COFF_SHORT (coff_hdr->f_opthdr);  /* Size of opt. headr */
/*
 *  If the file is not executable then reject the execution. This means
 *  that there must not be external references.
 */
	if ((flags & COFF_F_EXEC) == 0) {
#ifdef COFF_DEBUG
	    printk ("not executable bit\n");
#endif
	    status = -ENOEXEC;
	    break;
	}
/*
 *  There must be at least one section.
 */
	if (sections == 0) {
#ifdef COFF_DEBUG
	    printk ("no sections\n");
#endif
	    status = -ENOEXEC;
	    break;
	}
/*
 *  Do some additional consistency checks.
 *  The system requires mapping for this loader. If you try
 *  to use a file system with no mapping, the format is not valid.
 */
	if (!bprm->inode->i_op ||
	    !bprm->inode->i_op->default_file_ops->mmap) {
#ifdef COFF_DEBUG
	    printk ("no mmap in fs\n");
#endif
	    status = -ENOEXEC;
	}
    }
    while (0);
/*
 *  Allocate a buffer to hold the entire coff section list.
 */
    if (status >= 0) {
	int nbytes = sections * COFF_SCNHSZ;

	sect_bufr = (COFF_SCNHDR *) kmalloc (nbytes, GFP_KERNEL);
	if (0 == sect_bufr) {
#ifdef COFF_DEBUG
	    printk ("kmalloc failed\n");
#endif
	    status = -ENOEXEC;
	}
/*
 *  Read the section list from the disk file.
 */
	else {
	     int old_fs = get_fs ();
	     set_fs (get_ds ());  /* Make it point to the proper location    */
	     status = read_exec (bprm->inode,	     /* INODE for file       */
			    aout_size + COFF_FILHSZ, /* Offset in the file   */
			    (char *) sect_bufr,      /* Buffer for read      */
			    nbytes);                 /* Byte count reqd.     */
	     set_fs (old_fs);	                     /* Restore the selector */
#ifdef COFF_DEBUG
	     if (status < 0)
	        printk ("read aout hdr, status = %d\n", status);
#endif
	 }
    }
    else
	sect_bufr = NULL;	/* Errors do not have a section buffer */
/*
 *  Count the number of sections for the required types and store the location
 *  of the last section for the three primary types.
 */
    text_count = 0;
    data_count = 0;
    bss_count  = 0;
    lib_count  = 0;

    text_sect = NULL;
    data_sect = NULL;
    bss_sect  = NULL;
/*
 *  Loop through the sections and find the various types
 */
    if (status >= 0) {
	int nIndex;
	COFF_SCNHDR *sect_ptr = sect_bufr;

	for (nIndex = 0; nIndex < sections; ++nIndex) {
	    long int sect_flags = COFF_LONG (sect_ptr->s_flags);

	    switch (sect_flags) {
	    case COFF_STYP_TEXT:
		text_sect = sect_ptr;
		++text_count;
		status = is_properly_aligned (sect_ptr);
		break;

	    case COFF_STYP_DATA:
		data_sect = sect_ptr;
		++data_count;
		status = is_properly_aligned (sect_ptr);
		break;

	    case COFF_STYP_BSS:
		bss_sect = sect_ptr;
		++bss_count;
		break;

	    case COFF_STYP_LIB:
#ifdef COFF_DEBUG
		printk (".lib section found\n");
#endif
		++lib_count;
		break;

	    default:
		break;
	    }
	    sect_ptr = (COFF_SCNHDR *) & ((char *) sect_ptr)[COFF_SCNHSZ];
	}
/*
 *  Ensure that there are the required sections. There must be one text
 *  sections and one each of the data and bss sections for an executable.
 *  A library may or may not have a data / bss section.
 */
	if (text_count != 1) {
	    status = -ENOEXEC;
#ifdef COFF_DEBUG
	    printk ("no text sections\n");
#endif
	}
	else {
	    if (lib_ok) {
		if (data_count != 1 || bss_count != 1) {
		    status = -ENOEXEC;
#ifdef COFF_DEBUG
		    printk ("no .data nor .bss sections\n");
#endif
		}
	    }
	}
    }
/*
 *  If there is no additional header then assume the file starts at
 *  the first byte of the text section. This may not be the proper place,
 *  so the best solution is to include the optional header. A shared library
 *  __MUST__ have an optional header to indicate that it is a shared library.
 */
    if (status >= 0) {
	if (aout_size == 0) {
	    if (!lib_ok) {
		status = -ENOEXEC;
#ifdef COFF_DEBUG
		printk ("no header in library\n");
#endif
	    }
	    start_addr = COFF_LONG (text_sect->s_vaddr);
	}
/*
 *  There is some header. Ensure that it is sufficient.
 */
	else {
	    if (aout_size < COFF_AOUTSZ) {
		status = -ENOEXEC;
#ifdef COFF_DEBUG
		printk ("header too small\n");
#endif
	    }
	    else {
		COFF_AOUTHDR *aout_hdr =	/* Pointer to a.out header */
		(COFF_AOUTHDR *) & ((char *) coff_hdr)[COFF_FILHSZ];
		short int aout_magic = COFF_SHORT (aout_hdr->magic); /* id */
/*
 *  Validate the magic number in the a.out header. If it is valid then
 *  update the starting symbol location. Do not accept these file formats
 *  when loading a shared library.
 */
		switch (aout_magic) {
		case COFF_OMAGIC:
		case COFF_ZMAGIC:
		case COFF_STMAGIC:
		    if (!lib_ok) {
			status = -ENOEXEC;
#ifdef COFF_DEBUG
			printk ("wrong a.out header magic\n");
#endif
		    }
		    start_addr = (unsigned int) COFF_LONG (aout_hdr->entry);
		    break;
/*
 *  Magic value for a shared library. This is valid only when loading a
 *  shared library. (There is no need for a start_addr. It won't be used.)
 */
		case COFF_SHMAGIC:
		    if (lib_ok) {
#ifdef COFF_DEBUG
			printk ("wrong a.out header magic\n");
#endif
			status = -ENOEXEC;
		    }
		    break;

		default:
#ifdef COFF_DEBUG
		    printk ("wrong a.out header magic\n");
#endif
		    status = -ENOEXEC;
		    break;
		}
	    }
	}
    }
/*
 *  Fetch a file pointer to the executable.
 */
    if (status >= 0) {
	fd = open_inode (bprm->inode, O_RDONLY);
	if (fd < 0) {
#ifdef COFF_DEBUG
	    printk ("can not open inode, result = %d\n", fd);
#endif
	    status = fd;
	}
	else
	    fp = current->files->fd[fd];
    }
    else
	fd = -1;		/* Invalidate the open file descriptor */
/*
 *  Generate the proper values for the text fields
 *
 *  THIS IS THE POINT OF NO RETURN. THE NEW PROCESS WILL TRAP OUT SHOULD
 *  SOMETHING FAIL IN THE LOAD SEQUENCE FROM THIS POINT ONWARD.
 */
    if (status >= 0) {
	long text_scnptr = COFF_LONG (text_sect->s_scnptr);
	long text_size   = COFF_LONG (text_sect->s_size);
	long text_vaddr  = COFF_LONG (text_sect->s_vaddr);

	long data_scnptr;
	long data_size;
	long data_vaddr;

	long bss_size;
	long bss_vaddr;
/*
 *  Generate the proper values for the data fields
 */
	if (data_sect != NULL) {
	    data_scnptr = COFF_LONG (data_sect->s_scnptr);
	    data_size   = COFF_LONG (data_sect->s_size);
	    data_vaddr  = COFF_LONG (data_sect->s_vaddr);
	}
	else {
	    data_scnptr = 0;
	    data_size   = 0;
	    data_vaddr  = 0;
	}
/*
 *  Generate the proper values for the bss fields
 */
	if (bss_sect != NULL) {
	    bss_size  = COFF_LONG (bss_sect->s_size);
	    bss_vaddr = COFF_LONG (bss_sect->s_vaddr);
	}
	else {
	    bss_size  = 0;
	    bss_vaddr = 0;
	}
/*
 *  Flush the executable from memory. At this point the executable is
 *  committed to being defined or a segmentation violation will occur.
 */
	if (lib_ok) {
#ifdef COFF_DEBUG
	    printk ("flushing executable\n");
#endif
	    flush_old_exec (bprm);
/*
 *  Define the initial locations for the various items in the new process
 */
	    current->mm->mmap        = NULL;
	    current->mm->rss         = 0;
/*
 *  Construct the parameter and environment string table entries.
 */
	    bprm->p += change_ldt (0, bprm->page);
	    bprm->p -= MAX_ARG_PAGES*PAGE_SIZE;
	    bprm->p  = (unsigned long) create_tables ((char *) bprm->p,
						      bprm->argc,
						      bprm->envc,
						      1);
/*
 *  Do the end processing once the stack has been constructed
 */
	    current->mm->start_code  = text_vaddr & PAGE_MASK;
	    current->mm->end_code    = text_vaddr + text_size;
	    current->mm->end_data    = data_vaddr + data_size;
	    current->mm->start_brk   =
	    current->mm->brk         = bss_vaddr + bss_size;
	    current->suid            =
	    current->euid            = bprm->e_uid;
	    current->sgid            =
	    current->egid            = bprm->e_gid;
	    current->executable      = bprm->inode; /* Store inode for file  */
	    ++bprm->inode->i_count;             /* Count the open inode  */
	    regs->eip                = start_addr;  /* Current EIP register  */
	    regs->esp                =
	    current->mm->start_stack = bprm->p;
	}
/*
 *   Map the text pages
 */

#ifdef COFF_DEBUG
	printk (".text: vaddr = %d, size = %d, scnptr = %d\n",
		 text_vaddr,
		 text_size,
		 text_scnptr);
#endif
	status = do_mmap (fp,
			  text_vaddr & PAGE_MASK,
			  text_size + (text_vaddr & ~PAGE_MASK),
			  PROT_READ | PROT_EXEC,
			  MAP_FIXED | MAP_SHARED,
			  text_scnptr & PAGE_MASK);

	status = (status == (text_vaddr & PAGE_MASK)) ? 0 : -ENOEXEC;
/*
 *   Map the data pages
 */
	if (status >= 0 && data_size != 0) {
#ifdef COFF_DEBUG
	    printk (".data: vaddr = %d, size = %d, scnptr = %d\n",
		     data_vaddr,
		     data_size,
		     data_scnptr);
#endif
	    status = do_mmap (fp,
			      data_vaddr & PAGE_MASK,
			      data_size + (data_vaddr & ~PAGE_MASK),
			      PROT_READ | PROT_WRITE | PROT_EXEC,
			      MAP_FIXED | MAP_PRIVATE,
			      data_scnptr & PAGE_MASK);

	    status = (status == (data_vaddr & PAGE_MASK)) ? 0 : -ENOEXEC;
	}
/*
 *   Construct the bss data for the process. The bss ranges from the
 *   end of the data (which may not be on a page boundary) to the end
 *   of the bss section. Allocate any necessary pages for the data.
 */
	if (status >= 0 && bss_size != 0) {
#ifdef COFF_DEBUG
	    printk (".bss: vaddr = %d, size = %d\n",
		     bss_vaddr,
		     bss_size);
#endif
	    zeromap_page_range (PAGE_ALIGN (bss_vaddr),
				PAGE_ALIGN (bss_size),
				PAGE_COPY);

	    status = clear_memory (bss_vaddr, bss_size);
	}
/*
 *  Load any shared library for the executable.
 */
	if (status >= 0 && lib_ok && lib_count != 0) {
	    int nIndex;
	    COFF_SCNHDR *sect_ptr = sect_bufr;
/*
 *  Find the library sections. (There should be at least one. It was counted
 *  earlier.) This will eventually recurse to our code and load the shared
 *  library with our own procedures.
 */
	    for (nIndex = 0; nIndex < sections; ++nIndex) {
		long int sect_flags = COFF_LONG (sect_ptr->s_flags);
		if (sect_flags == COFF_STYP_LIB) {
		    status = preload_library (bprm, sect_ptr, fp);
		    if (status != 0)
			break;
		}
	    sect_ptr = (COFF_SCNHDR *) &((char *) sect_ptr) [COFF_SCNHSZ];
	    }
	}
/*
 *   Generate any needed trap for this process. If an error occurred then
 *   generate a segmentation violation. If the process is being debugged
 *   then generate the load trap. (Note: If this is a library load then
 *   do not generate the trap here. Pass the error to the caller who
 *   will do it for the process in the outer lay of this procedure call.)
 */
	if (lib_ok) {
	    if (status < 0)
		send_sig (SIGSEGV, current, 0);	/* Generate the error trap  */
	    else {
		if (current->flags & PF_PTRACED)
		    send_sig (SIGTRAP, current, 0);
	    }
	    status = 0;		/* We are committed. It can't fail */
	}
    }
/*
 *  Do any cleanup processing
 */
    if (fd >= 0)
	sys_close (fd);		/* Close unused code file      */

    if (sect_bufr != NULL)
	kfree (sect_bufr);	/* Release section list buffer */
/*
 *  Return the completion status.
 */
#ifdef COFF_DEBUG
    printk ("binfmt_coff: result = %d\n", status);
#endif
    return (status);
}
Ejemplo n.º 28
0
int register_files(char* build, char* project, char* path) {
	ssize_t res = 0;
	int loaded = 0;
	
	create_tables();

	if (SQL("BEGIN")) { return -1; }

	prune_old_entries(build, project);
	
	

	//
	// Enumerate the files in the path (DSTROOT) and associate them
	// with the project name and version in the sqlite database.
	// Uses ent->fts_number to mark which files we have and have
	// not seen before.
	//
	// Skip the first result, since that is . of the DSTROOT itself.
	char* path_argv[] = { path, NULL };
	FTS* fts = fts_open(path_argv, FTS_PHYSICAL | FTS_COMFOLLOW | FTS_XDEV, compare);
	FTSENT* ent = fts_read(fts); // throw away the entry for the DSTROOT itself
	while ((ent = fts_read(fts)) != NULL) {
		char filename[MAXPATHLEN+1];
		char symlink[MAXPATHLEN+1];
		ssize_t len;
		
		// Filename
		filename[0] = 0;
		ent_filename(ent, filename, MAXPATHLEN);

		// Symlinks
		symlink[0] = 0;
		if (ent->fts_info == FTS_SL || ent->fts_info == FTS_SLNONE) {
			len = readlink(ent->fts_accpath, symlink, MAXPATHLEN);
			if (len >= 0) symlink[len] = 0;
		}
		
		// Default to empty SHA-1 checksum
		char* checksum = strdup("                                        ");
		
		// Checksum regular files
		if (ent->fts_info == FTS_F) {
			int fd = open(ent->fts_accpath, O_RDONLY);
			if (fd == -1) {
				perror(filename);
				return -1;
			}
			int isMachO;
			res = register_libraries(fd, build, project, filename, &isMachO);
			lseek(fd, (off_t)0, SEEK_SET);
			if (isMachO && have_undo_prebinding() == 0) {
				checksum = calculate_unprebound_digest(ent->fts_accpath);
			} else {
				checksum = calculate_digest(fd);
			}
			close(fd);
		}

		// register regular files and symlinks in the DB
		if (ent->fts_info == FTS_F || ent->fts_info == FTS_SL || ent->fts_info == FTS_SLNONE) {
			res = SQL("INSERT INTO files (build, project, path) VALUES (%Q,%Q,%Q)",
				build, project, filename);
			++loaded;
		}
		
		// add all regular files, directories, and symlinks to the manifest
		if (ent->fts_info == FTS_F || ent->fts_info == FTS_D ||
			ent->fts_info == FTS_SL || ent->fts_info == FTS_SLNONE) {
			fprintf(stdout, "%s %o %d %d %lld .%s%s%s\n",
				checksum,
				ent->fts_statp->st_mode,
				ent->fts_statp->st_uid,
				ent->fts_statp->st_gid,
				(ent->fts_info != FTS_D) ? ent->fts_statp->st_size : (off_t)0,
				filename,
				symlink[0] ? " -> " : "",
				symlink[0] ? symlink : "");
		}
		free(checksum);
	}
	fts_close(fts);
	
	if (SQL("COMMIT")) { return -1; }

	fprintf(stderr, "%s - %d files registered.\n", project, loaded);
	
	return (int)res;
}