Exemple #1
0
bool
O2DatDB::
update(O2DatRec &in, bool is_origurl)
{
	sqlite3 *db = NULL;
	sqlite3_stmt* stmt;
	O2DatRec org;

	int err = sqlite3_open16(dbfilename.c_str(), &db);
	if (err != SQLITE_OK)
		goto error;
	sqlite3_busy_timeout(db, 5000);

	if (select(org, in.hash)) {
		wchar_t *sql =
			L"update or replace dat"
			L"   set size        = ?"
			L"     , disksize    = ?"
			L"     , url         = ?"
			L"     , res	     = ?"
			L"     , lastupdate  = ?"
			L"     , lastpublish = 0"
			L" where hash = ?;";

		err = sqlite3_prepare16_v2(db, sql, wcslen(sql)*2, &stmt, NULL);
		if (err != SQLITE_OK)
			goto error;

		if (!is_origurl)
			in.url = org.url;
		if (!bind(db, stmt, 1, in.size))
			goto error;
		if (!bind(db, stmt, 2, in.disksize))
			goto error;
		if (!bind(db, stmt, 3, in.url))
			goto error;
		if (!bind(db, stmt, 4, in.res))
			goto error;
		if (!bind(db, stmt, 5, time(NULL)))
			goto error;
		if (!bind(db, stmt, 6, in.hash))
			goto error;

		err = sqlite3_step(stmt);
		if (err != SQLITE_ROW && err != SQLITE_DONE)
			goto error;
		sqlite3_finalize(stmt);
		stmt = NULL;
	}
	else {
		wchar_t *sql =
			L"insert or replace into dat ("
			COLUMNS
			L") values ("
			L"?,?,?,?,?,?,?,?,?,?,?"
			L");";

		err = sqlite3_prepare16_v2(db, sql, wcslen(sql)*2, &stmt, NULL);
		if (err != SQLITE_OK)
			goto error;

		if (!bind(db, stmt, 1, in.hash))
			goto error;
		if (!bind(db, stmt, 2, in.domain))
			goto error;
		if (!bind(db, stmt, 3, in.bbsname))
			goto error;
		if (!bind(db, stmt, 4, in.datname))
			goto error;
		if (!bind(db, stmt, 5, in.size))
			goto error;
		if (!bind(db, stmt, 6, in.disksize))
			goto error;
		if (!bind(db, stmt, 7, in.url))
			goto error;
		if (!bind(db, stmt, 8, in.title))
			goto error;
		if (!bind(db, stmt, 9, in.res))
			goto error;
		if (!bind(db, stmt, 10, time(NULL)))
			goto error;
		if (!bind(db, stmt, 11, (uint64)0))
			goto error;

		err = sqlite3_step(stmt);
		if (err != SQLITE_ROW && err != SQLITE_DONE)
			goto error;
		sqlite3_finalize(stmt);
		stmt = NULL;
	}

	err = sqlite3_close(db);
	if (err != SQLITE_OK)
		goto error;

	return true;

error:
	log(db);
	if (stmt) sqlite3_finalize(stmt);
	if (db) sqlite3_close(db);
	return false;
}
Exemple #2
0
/*
 * Connect to the database.
 * If fails, program terminates.
 */
int	zbx_db_connect(char *host, char *user, char *password, char *dbname, char *dbsocket, int port)
{
	int	ret = ZBX_DB_OK;
#ifdef	HAVE_SQLITE3
	char	*p, *path;
#endif /* HAVE_SQLITE3 */

#ifdef	HAVE_MYSQL
	/* For MySQL >3.22.00 */
	/*	if( ! mysql_connect( conn, NULL, dbuser, dbpassword ) )*/

	conn = mysql_init(NULL);

	if (!mysql_real_connect(conn, host, user, password, dbname, port, dbsocket, CLIENT_MULTI_STATEMENTS))
	{
		zabbix_errlog(ERR_Z3001, dbname, mysql_errno(conn), mysql_error(conn));
		ret = ZBX_DB_FAIL;
	}

	if (ZBX_DB_OK == ret)
	{
		if (0 != mysql_select_db(conn, dbname))
		{
			zabbix_errlog(ERR_Z3001, dbname, mysql_errno(conn), mysql_error(conn));
			ret = ZBX_DB_FAIL;
		}
	}

	if (ZBX_DB_OK == ret)
		DBexecute("SET CHARACTER SET utf8");

	if (ZBX_DB_FAIL == ret)
	{
		switch (mysql_errno(conn)) {
		case CR_CONN_HOST_ERROR:
		case CR_SERVER_GONE_ERROR:
		case CR_CONNECTION_ERROR:
		case CR_SERVER_LOST:
		case ER_SERVER_SHUTDOWN:
		case ER_UNKNOWN_ERROR:
			ret = ZBX_DB_DOWN;
			break;
		default:
			break;
		}
	}

	return ret;
#endif
#ifdef	HAVE_POSTGRESQL
	char		*cport = NULL;
	DB_RESULT	result;
	DB_ROW		row;
	int		sversion;

	if( port )	cport = zbx_dsprintf(cport, "%i", port);

	conn = PQsetdbLogin(host, cport, NULL, NULL, dbname, user, password );

	zbx_free(cport);

	/* check to see that the backend connection was successfully made */
	if (PQstatus(conn) != CONNECTION_OK)
	{
		zabbix_errlog(ERR_Z3001, dbname, 0, PQerrorMessage(conn));
		ret = ZBX_DB_FAIL;
	}

	result = DBselect("select oid from pg_type where typname = 'bytea'");
	row = DBfetch(result);
	if(row)
	{
		ZBX_PG_BYTEAOID = atoi(row[0]);
	}
	DBfree_result(result);

#ifdef	HAVE_FUNCTION_PQSERVERVERSION
	sversion = PQserverVersion(conn);
	zabbix_log(LOG_LEVEL_DEBUG, "PostgreSQL Server version: %d", sversion);
#else
	sversion = 0;
#endif	/* HAVE_FUNCTION_PQSERVERVERSION */

	if (sversion >= 80100)
	{
		/* disable "nonstandard use of \' in a string literal" warning */
		DBexecute("set escape_string_warning to off");
	}

	return ret;
#endif
#ifdef	HAVE_ORACLE
	char	connect[MAX_STRING_LEN];

	zbx_strlcpy(connect, user, sizeof(connect));

	if (password && *password) {
		zbx_strlcat(connect, "/", sizeof(connect));
		zbx_strlcat(connect, password, sizeof(connect));

		if (dbname && *dbname) {
			zbx_strlcat(connect, "@", sizeof(connect));
			zbx_strlcat(connect, dbname, sizeof(connect));
		}
	}

	if (SQLO_SUCCESS != sqlo_init(SQLO_OFF, 1, 100)) {
		zabbix_errlog(ERR_Z3001, connect, 0, "Failed to init libsqlora8");
		ret = ZBX_DB_FAIL;
	}

	if (ZBX_DB_OK == ret) {
		/* login */ /* TODO: how to use port??? */
		if (SQLO_SUCCESS != sqlo_connect(&oracle, connect)) {
			zabbix_errlog(ERR_Z3001, connect, 0, "sqlo_connect");
			ret = ZBX_DB_FAIL;
		}
	}

	if (ZBX_DB_OK == ret)
		sqlo_autocommit_off(oracle);

	return ret;
#endif
#ifdef	HAVE_SQLITE3
	/* check to see that the backend connection was successfully made */
	if (SQLITE_OK != (ret = sqlite3_open(dbname, &conn))) {
		zabbix_errlog(ERR_Z3001, dbname, 0, sqlite3_errmsg(conn));
		exit(FAIL);
	}

	/* Do not return SQLITE_BUSY immediately, wait for N ms */
	sqlite3_busy_timeout(conn, 60*1000);

	sqlite_transaction_started = 0;

	path = strdup(dbname);
	if (NULL != (p = strrchr(path, '/')))
		*++p = '\0';
	else
		*path = '\0';

	DBexecute("PRAGMA synchronous = 0"); /* OFF */
	DBexecute("PRAGMA temp_store = 2"); /* MEMORY */
	DBexecute("PRAGMA temp_store_directory = '%s'", path);

	zbx_free(path);

	return ret;
#endif
}
Exemple #3
0
int detail_report(int id)
{
	int running = 0;
	int rows = 0;
	int oerow = 1;
	int OK = 0;
	char select[4096];
	char tmp[BUFSIZ];
	char header[BUFSIZ];
	char css_buffer[BUFSIZ];
	FILE *css_file;
	time_t current_time;
	struct tm *t;
	sqlite3 *db;
	sqlite3_stmt *statement;

	if(sqlite3_open(option.sessiondb, &db))
	{
		fprintf(stderr, "sqlite3_open: %.100s", sqlite3_errmsg(db));
		return(-1);
	}

	strncpy(select, "SELECT id,real_uid,real_gid,effective_uid,effective_gid,original_uid,original_gid,port,duration,real_pw_name,real_gr_name,effective_pw_name,effective_gr_name,original_pw_name,original_gr_name,terminal,ip,status,stype,method,cipher,sysname,nodename,release,version,machine,file_session,hash_session,remote_command,pid,created,modified FROM USER WHERE id=?;", sizeof(select) - 1);

	sqlite3_busy_timeout(db, 2000);

	if(sqlite3_prepare(db, select, -1, &statement, NULL) != SQLITE_OK)
	{
		fprintf(stderr, "sqlite3_prepare: %.100s\n", sqlite3_errmsg(db));
		sqlite3_close(db);
		return(-1);
	}

	sqlite3_bind_int(statement, 1, id);

	if((css_file = fopen(css ? css : "/etc/eas/css/detailed.css", "r")) == (FILE *) 0)
	{
		fprintf(stderr, "%.63s: %.127s: %.100s (%i)\n", basename(progname), css ? css : "/etc/eas/css/detailed.css", strerror(errno), errno);
		sqlite3_close(db);
		exit(EXIT_FAILURE);
	}

	current_time = time(0);
	t = localtime(&current_time);

	/* ISO8601 */
	strftime(header, sizeof(header) - 1, "%Y-%m-%d %H:%M:%S", t);
	
	fprintf(stdout, "<!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.01//EN\">\n");
	fprintf(stdout, "<html>\n");
	fprintf(stdout, "<head>\n");
	fprintf(stdout, "<title> %.63s %.127s</title>\n", client.cid.original_pw_name, header);
	fprintf(stdout, "<meta http-equiv=\"Content-Type\" content=\"text/html; charset=iso-8859-1\">\n");

	memset(css_buffer, '\0', sizeof(css_buffer));
	while(fgets(css_buffer, sizeof(css_buffer) - 1, css_file))
	{
		fprintf(stdout, css_buffer);
		memset(css_buffer, '\0', sizeof(css_buffer));
	}
	fclose(css_file);

	fprintf(stdout, "</head>\n");
	fprintf(stdout, "<body>\n");
	fprintf(stdout, "<h2>Enterprise Audit Shell Detailed Report</h2>\n");
	fprintf(stdout, "<h3>%.127s</h3>\n", header);
	fprintf(stdout, "<table cellspacing=\"0\" summary=\"Enterprise Audit Shell Report - %s\">\n", header);
	fprintf(stdout, "<tr>\n");

	running = 1;

	while(running)
	{
		switch(sqlite3_step(statement))
		{
			case SQLITE_DONE:
				running = 0;
				break;
			case SQLITE_ROW:
				/*
				 * 0 id
				 * 1 real_uid
				 * 2 real_gid
				 * 3 effective_uid
				 * 4 effective_gid
				 * 5 original_uid
				 * 6 original_gid
				 * 7 port
				 * 8 duration
				 * 9 real_pw_name
				 * 10 real_gr_name
				 * 11 effective_pw_name
				 * 12 effective_gr_name
				 * 13 original_pw_name
				 * 14 original_gr_name
				 * 15 terminal
				 * 16 ip
				 * 17 status
				 * 18 stype
				 * 19 method
				 * 20 cipher
				 * 21 sysname
				 * 22 nodename
				 * 23 release
				 * 24 version
				 * 25 machine
				 * 26 file_session
				 * 27 hash_session
				 * 28 remote_command
				 * 29 pid
				 * 30 created
				 * 31 modified
				*/

				rows++;

				client.cid.rowid = -1;
				client.cid.real_uid = -1;
				client.cid.real_gid = -1;
				client.cid.effective_uid = -1;
				client.cid.effective_gid = -1;
				client.cid.original_uid = -1;
				client.cid.original_gid = -1;
				client.cid.port = -1;
				client.cid.duration = -1;
				client.cid.pid = -1;

				memset(client.cid.real_pw_name, '\0', sizeof(client.cid.real_pw_name));
				memset(client.cid.real_gr_name, '\0', sizeof(client.cid.real_gr_name));
				memset(client.cid.effective_pw_name, '\0', sizeof(client.cid.effective_pw_name));
				memset(client.cid.effective_gr_name, '\0', sizeof(client.cid.effective_gr_name));
				memset(client.cid.original_pw_name, '\0', sizeof(client.cid.original_pw_name));
				memset(client.cid.original_gr_name, '\0', sizeof(client.cid.original_gr_name));
				memset(client.cid.terminal, '\0', sizeof(client.cid.terminal));
				memset(client.cid.ip, '\0', sizeof(client.cid.ip));
				memset(client.cid.status, '\0', sizeof(client.cid.status));
				memset(client.cid.stype, '\0', sizeof(client.cid.stype));
				memset(client.cid.method, '\0', sizeof(client.cid.method));
				memset(client.cid.cipher, '\0', sizeof(client.cid.cipher));
				memset(client.sysname, '\0', sizeof(client.sysname));
				memset(client.nodename, '\0', sizeof(client.nodename));
				memset(client.release, '\0', sizeof(client.release));
				memset(client.version, '\0', sizeof(client.version));
				memset(client.machine, '\0', sizeof(client.machine));
				memset(client.cid.file_session, '\0', sizeof(client.cid.file_session));
				memset(client.cid.hash_session, '\0', sizeof(client.cid.hash_session));
				memset(client.cid.remote_command, '\0', sizeof(client.cid.remote_command));
				memset(client.cid.created, '\0', sizeof(client.cid.created));
				memset(client.cid.modified, '\0', sizeof(client.cid.modified));

				client.cid.rowid = sqlite3_column_int(statement, 0);
				client.cid.real_uid = sqlite3_column_int(statement, 1);
				client.cid.real_gid = sqlite3_column_int(statement, 2);
				client.cid.effective_uid = sqlite3_column_int(statement, 3);
				client.cid.effective_gid = sqlite3_column_int(statement, 4);
				client.cid.original_uid = sqlite3_column_int(statement, 5);
				client.cid.original_gid = sqlite3_column_int(statement, 6);
				client.cid.port = sqlite3_column_int(statement, 7);
				client.cid.duration = sqlite3_column_int(statement, 8);

				if(sqlite3_column_text(statement, 9))
					strncpy(client.cid.real_pw_name, (char *) sqlite3_column_text(statement, 9),
						sizeof(client.cid.real_pw_name) - 1); 
				if(sqlite3_column_text(statement, 10))
					strncpy(client.cid.real_gr_name, (char *) sqlite3_column_text(statement, 10),
						sizeof(client.cid.real_gr_name) - 1); 
				if(sqlite3_column_text(statement, 11))
					strncpy(client.cid.effective_pw_name, (char *) sqlite3_column_text(statement, 11),
						sizeof(client.cid.effective_pw_name) - 1); 
				if(sqlite3_column_text(statement, 12))
					strncpy(client.cid.effective_gr_name, (char *) sqlite3_column_text(statement, 12),
						sizeof(client.cid.effective_gr_name) - 1); 
				if(sqlite3_column_text(statement, 13))
					strncpy(client.cid.original_pw_name, (char *) sqlite3_column_text(statement, 13),
						sizeof(client.cid.original_pw_name) - 1); 
				if(sqlite3_column_text(statement, 14))
					strncpy(client.cid.original_gr_name, (char *) sqlite3_column_text(statement, 14),
						sizeof(client.cid.original_gr_name) - 1); 
				if(sqlite3_column_text(statement, 15))
					strncpy(client.cid.terminal, (char *) sqlite3_column_text(statement, 15),
						sizeof(client.cid.terminal) - 1); 
				if(sqlite3_column_text(statement, 16))
					strncpy(client.cid.ip, (char *) sqlite3_column_text(statement, 16),
						sizeof(client.cid.ip) - 1); 
				if(sqlite3_column_text(statement, 17))
					strncpy(client.cid.status, (char *) sqlite3_column_text(statement, 17),
						sizeof(client.cid.status) - 1); 
				if(sqlite3_column_text(statement, 18))
					strncpy(client.cid.stype, (char *) sqlite3_column_text(statement, 18),
						sizeof(client.cid.stype) - 1); 
				if(sqlite3_column_text(statement, 19))
					strncpy(client.cid.method, (char *) sqlite3_column_text(statement, 19),
						sizeof(client.cid.method) - 1); 
				if(sqlite3_column_text(statement, 20))
					strncpy(client.cid.cipher, (char *) sqlite3_column_text(statement, 20),
						sizeof(client.cid.cipher) - 1); 
				if(sqlite3_column_text(statement, 21))
					strncpy(client.sysname, (char *) sqlite3_column_text(statement, 21),
						sizeof(client.sysname) - 1); 
				if(sqlite3_column_text(statement, 22))
					strncpy(client.nodename, (char *) sqlite3_column_text(statement, 22),
						sizeof(client.nodename) - 1); 
				if(sqlite3_column_text(statement, 23))
					strncpy(client.release, (char *) sqlite3_column_text(statement, 23),
						sizeof(client.release) - 1); 
				if(sqlite3_column_text(statement, 24))
					strncpy(client.version, (char *) sqlite3_column_text(statement, 24),
						sizeof(client.version) - 1); 
				if(sqlite3_column_text(statement, 25))
					strncpy(client.machine, (char *) sqlite3_column_text(statement, 25),
						sizeof(client.machine) - 1); 
				if(sqlite3_column_text(statement, 26))
					strncpy(client.cid.file_session, (char *) sqlite3_column_text(statement, 26),
						sizeof(client.cid.file_session) - 1); 
				if(sqlite3_column_text(statement, 27))
					strncpy(client.cid.hash_session, (char *) sqlite3_column_text(statement, 27),
						sizeof(client.cid.hash_session) - 1); 
				if(sqlite3_column_text(statement, 28))
					strncpy(client.cid.remote_command, (char *) sqlite3_column_text(statement, 28),
						sizeof(client.cid.remote_command) - 1); 

				client.cid.pid = sqlite3_column_int(statement, 29);

				if(sqlite3_column_text(statement, 30))
					strncpy(client.cid.created, (char *) sqlite3_column_text(statement, 30),
						sizeof(client.cid.created) - 1); 
				if(sqlite3_column_text(statement, 31))
					strncpy(client.cid.modified, (char *) sqlite3_column_text(statement, 31),
						sizeof(client.cid.modified) - 1); 
				break;
			default:
				running = 0;
				fprintf(stderr, "sqlite3_step: %.100s\n", sqlite3_errmsg(db));
				break;
		}
	}

	sqlite3_finalize(statement);
	sqlite3_close(db);

	if(rows == 0)
	{
		fprintf(stdout, "<tr>\n");
		fprintf(stdout, "\t<td>No session found for the criteria.</td>\n");
		fprintf(stdout, "</tr>\n");
		fprintf(stdout, "</table>\n");
		fprintf(stdout, "</body>\n");
		fprintf(stdout, "</html>\n");
		return(-1);
	}

	fprintf(stdout, "<tr class=\"%.63s\">\n", oerow++ % 2 ? "odd" : "even");
	fprintf(stdout, "\t<th class=\"rowid\">ID</th>\n");
	fprintf(stdout, "\t<td>%-.6i</td>\n", client.cid.rowid);
	fprintf(stdout, "</tr>\n");

	fprintf(stdout, "<tr class=\"%.63s\">\n", oerow++ % 2 ? "odd" : "even");
	fprintf(stdout, "\t<th class=\"type\">Type</th>\n");
	fprintf(stdout, "\t<td>%.63s</td>\n", client.cid.stype);
	fprintf(stdout, "</tr>\n");

	fprintf(stdout, "<tr class=\"%.63s\">\n", oerow++ % 2 ? "odd" : "even");
	fprintf(stdout, "\t<th class=\"status\">Status</th>\n");
	fprintf(stdout, "\t<td>%.63s</td>\n", client.cid.status);
	fprintf(stdout, "</tr>\n");

	fprintf(stdout, "<tr class=\"%.63s\">\n", oerow++ % 2 ? "odd" : "even");
	fprintf(stdout, "\t<th class=\"duration\">Duration</th>\n");
	fprintf(stdout, "\t<td>%i seconds.</td>\n", client.cid.duration);
	fprintf(stdout, "</tr>\n");

	fprintf(stdout, "<tr class=\"%.63s\">\n", oerow++ % 2 ? "odd" : "even");
	fprintf(stdout, "\t<th class=\"created\">Created</th>\n");
	fprintf(stdout, "\t<td>%.63s</td>\n", client.cid.created);
	fprintf(stdout, "</tr>\n");

	fprintf(stdout, "<tr class=\"%.63s\">\n", oerow++ % 2 ? "odd" : "even");
	fprintf(stdout, "\t<th class=\"modified\">Last modified</th>\n");
	fprintf(stdout, "\t<td>%.63s</td>\n", client.cid.modified);
	fprintf(stdout, "</tr>\n");

	fprintf(stdout, "<tr class=\"%.63s\">\n", oerow++ % 2 ? "odd" : "even");
	fprintf(stdout, "\t<th class=\"ip\">IP</th>\n");
	fprintf(stdout, "\t<td>%.15s:%i</td>\n", client.cid.ip, client.cid.port);
	fprintf(stdout, "</tr>\n");

	fprintf(stdout, "<tr class=\"%.63s\">\n", oerow++ % 2 ? "odd" : "even");
	fprintf(stdout, "\t<th class=\"method\">SSL Method</th>\n");
	fprintf(stdout, "\t<td>%.63s</td>\n", client.cid.method);
	fprintf(stdout, "</tr>\n");

	fprintf(stdout, "<tr class=\"%.63s\">\n", oerow++ % 2 ? "odd" : "even");
	fprintf(stdout, "\t<th class=\"cipher\">SSL Cipher</th>\n");
	fprintf(stdout, "\t<td>%.63s</td>\n", client.cid.cipher);
	fprintf(stdout, "</tr>\n");

	fprintf(stdout, "<tr class=\"%.63s\">\n", oerow++ % 2 ? "odd" : "even");
	fprintf(stdout, "\t<th class=\"system\">System</th>\n");
	fprintf(stdout, "\t<td>%.63s %.63s (%.63s)</td>\n", client.sysname, client.release, client.version);
	fprintf(stdout, "</tr>\n");

	fprintf(stdout, "<tr class=\"%.63s\">\n", oerow++ % 2 ? "odd" : "even");
	fprintf(stdout, "\t<th class=\"pid\">PID</th>\n");
	fprintf(stdout, "\t<td>%i</td>\n", client.cid.pid);
	fprintf(stdout, "</tr>\n");

	fprintf(stdout, "<tr class=\"%.63s\">\n", oerow++ % 2 ? "odd" : "even");
	fprintf(stdout, "\t<th class=\"terminal\">Terminal</th>\n");
	fprintf(stdout, "\t<td>%.63s</td>\n", client.cid.terminal);
	fprintf(stdout, "</tr>\n");

	if(!strcmp(client.cid.stype, "COMMAND"))
	{
		fprintf(stdout, "<tr class=\"%.63s\">\n", oerow++ % 2 ? "odd" : "even");
		fprintf(stdout, "\t<th class=\"command\">Command</th>\n");
		fprintf(stdout, "\t<td>%.63s</td>\n", client.cid.remote_command);
		fprintf(stdout, "</tr>\n");
	}

	fprintf(stdout, "<tr class=\"%.63s\">\n", oerow++ % 2 ? "odd" : "even");
	fprintf(stdout, "\t<th class=\"original_pw_name\">Original user</th>\n");
	fprintf(stdout, "\t<td>uid=%i(%.63s) gid=%i(%.63s)</td>\n", client.cid.original_uid, client.cid.original_pw_name, client.cid.original_gid, client.cid.original_gr_name);
	fprintf(stdout, "</tr>\n");

	fprintf(stdout, "<tr class=\"%.63s\">\n", oerow++ % 2 ? "odd" : "even");
	fprintf(stdout, "\t<th class=\"real_pw_name\">Real user</th>\n");
	fprintf(stdout, "\t<td>uid=%i(%.63s) gid=%i(%.63s)</td>\n", client.cid.real_uid, client.cid.real_pw_name, client.cid.real_gid, client.cid.real_gr_name);
	fprintf(stdout, "</tr>\n");

	fprintf(stdout, "<tr class=\"%.63s\">\n", oerow++ % 2 ? "odd" : "even");
	fprintf(stdout, "\t<th class=\"effective_pw_name\">Effective user</th>\n");
	fprintf(stdout, "\t<td>uid=%i(%.63s) gid=%i(%.63s)</td>\n", client.cid.effective_uid, client.cid.effective_pw_name, client.cid.effective_gid, client.cid.effective_gr_name);
	fprintf(stdout, "</tr>\n");

	fprintf(stdout, "<tr class=\"%.63s\">\n", oerow++ % 2 ? "odd" : "even");
	fprintf(stdout, "\t<th class=\"session\">Session</th>\n");
	fprintf(stdout, "\t<td>%.127s</td>\n", client.cid.file_session);
	fprintf(stdout, "</tr>\n");

	memset(tmp, '\0', sizeof(tmp));
	if(create_SHA1(client.cid.file_session, option.strict_inode, option.strict_mode, option.strict_owner, option.strict_ctime, option.strict_mtime))
	{
		strncpy(tmp, create_SHA1(client.cid.file_session, option.strict_inode, option.strict_mode, option.strict_owner, option.strict_ctime, option.strict_mtime), sizeof(tmp) - 1);
		if(!strcmp(tmp, client.cid.hash_session))
		{
			memset(tmp, '\0', sizeof(tmp));
			snprintf(tmp, sizeof(tmp) - 1, "%.63s (signature verified)", client.cid.hash_session);
			OK = 1;
		}
		else
		{
			memset(tmp, '\0', sizeof(tmp));
			snprintf(tmp, sizeof(tmp) - 1, "%.63s (signature INVALID)", client.cid.hash_session);
			OK = 0;
		}
	}
	else
	{
		memset(tmp, '\0', sizeof(tmp));
		strncpy(tmp, "??? (signature INVALID)", sizeof(tmp) - 1);
		OK = 0;
	}

	fprintf(stdout, "<tr class=\"%.63s\">\n", oerow++ % 2 ? "odd" : "even");
	fprintf(stdout, "\t<th class=\"signature\">Signature</th>\n");
	fprintf(stdout, "\t<td class=\"%.63s\">%.127s</td>\n", OK ? "verified" : "invalid", tmp);
	fprintf(stdout, "</tr>\n");

	fprintf(stdout, "</table>\n");
	fprintf(stdout, "</body>\n");
	fprintf(stdout, "</html>\n");

	return(0);
}
Exemple #4
0
int
main (int argc, char *argv[])
{
  int verbosity = 0;
  const char *scenario_db_name = NULL;
  const char *output_dir = NULL;
  double fixed_rng_value = -1;
  int seed = -1;
  int starting_iteration_number = -1;
  gboolean dry_run = FALSE;
  GError *option_error = NULL;
  GOptionContext *context;
  GOptionEntry options[] = {
    { "verbosity", 'V', 0, G_OPTION_ARG_INT, &verbosity, "Message verbosity level (0 = simulation output only, 1 = all debugging output)", NULL },
    { "output-dir", 'o', 0, G_OPTION_ARG_FILENAME, &output_dir, "Output directory", NULL },
    { "fixed-random-value", 'r', 0, G_OPTION_ARG_DOUBLE, &fixed_rng_value, "Fixed number to use instead of random numbers", NULL },
    { "rng-seed", 's', 0, G_OPTION_ARG_INT, &seed, "Seed used to initialize the random number generator", NULL },
    { "iteration-number", 'i', 0, G_OPTION_ARG_INT, &starting_iteration_number, "Number of the first iteration", NULL },
    { "dry-run", 'n', 0, G_OPTION_ARG_NONE, &dry_run, "Check the parameters but do not actually run the simulation", NULL },
    { NULL }
  };
  int sqlerr;
  sqlite3 *scenario_db;
  GError *error = NULL;
  int exit_status = EXIT_SUCCESS;

  clear_adsm_fns ();

#ifdef USE_SC_GUILIB
  _scenario.scenarioId = NULL;
  _scenario.description = NULL;
  _scenario.nruns = 0;
  _scenario.random_seed = 0;
  _scenario.start_time = _scenario.end_time = 0;

  _iteration.susceptible_units = NULL;
  _iteration.infectious_units = NULL;
  _iteration._unitsInZones = NULL;
  _iteration.zoneFociCreated = FALSE;
  _iteration.diseaseEndDay = -1;
  _iteration.outbreakEndDay = -1;
  _iteration.first_detection = FALSE;
#endif

  init_MAIN_structs();

  context = g_option_context_new ("- Runs epidemiological simulations for animal populations");
  g_option_context_add_main_entries (context, options, /* translation = */ NULL);
  if (!g_option_context_parse (context, &argc, &argv, &option_error))
    {
      g_error ("option parsing failed: %s\n", option_error->message);
    }
  if (argc >= 1)
    scenario_db_name = argv[1];
  else
    {
      g_error ("Need name of scenario database");
    }
  g_option_context_free (context);

  /* If an output directory was specified, and that directory does not exist,
   * create the directory. */
  {
    /* There will be a "Map" directory inside the output directory too. We can
     * make the output directory and the subdirectory inside with one call to
     * g_mkdir_with_parents. */
    gint errcode;
    gchar *map_output_dir;
    if (output_dir == NULL)
      map_output_dir = g_strdup ("Map");
    else
      map_output_dir = g_build_filename (output_dir, "Map", NULL);
    errcode = g_mkdir_with_parents (map_output_dir, S_IRUSR + S_IWUSR + S_IXUSR);
    if (errcode != 0)
      {
        g_error ("could not create output directory \"%s\": %s",
                 map_output_dir, strerror(errno));
      }
    g_free (map_output_dir);
  }

  sqlerr = sqlite3_open_v2 (scenario_db_name, &scenario_db, SQLITE_OPEN_READWRITE, NULL);
  if (sqlerr !=  SQLITE_OK)
    {
      g_error ("Error opening scenario database: %s", sqlite3_errmsg (scenario_db));
    }
  sqlite3_busy_timeout (scenario_db, 30 * 60 * 1000 /* 30 minutes, given in milliseconds */);

  run_sim_main (scenario_db,
                (char *)output_dir,
                fixed_rng_value,
                verbosity,
                seed,
                starting_iteration_number,
                dry_run,
                &error);

  sqlite3_close (scenario_db);
  
  if (error)
    {
      g_warning ("%s", error->message);
      g_clear_error (&error);
      exit_status = EXIT_FAILURE;
    }

  return exit_status;
}
int pysqlite_connection_init(pysqlite_Connection* self, PyObject* args, PyObject* kwargs)
{
    static char *kwlist[] = {"database", "timeout", "detect_types", "isolation_level", "check_same_thread", "factory", "cached_statements", NULL, NULL};

    PyObject* database;
    int detect_types = 0;
    PyObject* isolation_level = NULL;
    PyObject* factory = NULL;
    int check_same_thread = 1;
    int cached_statements = 100;
    double timeout = 5.0;
    int rc;
    PyObject* class_attr = NULL;
    PyObject* class_attr_str = NULL;
    int is_apsw_connection = 0;
    PyObject* database_utf8;

    if (!PyArg_ParseTupleAndKeywords(args, kwargs, "O|diOiOi", kwlist,
                                     &database, &timeout, &detect_types, &isolation_level, &check_same_thread, &factory, &cached_statements))
    {
        return -1;
    }

    self->initialized = 1;

    self->begin_statement = NULL;

    self->statement_cache = NULL;
    self->statements = NULL;
    self->cursors = NULL;

    Py_INCREF(Py_None);
    self->row_factory = Py_None;

    Py_INCREF(&PyUnicode_Type);
    self->text_factory = (PyObject*)&PyUnicode_Type;

    if (PyString_Check(database) || PyUnicode_Check(database)) {
        if (PyString_Check(database)) {
            database_utf8 = database;
            Py_INCREF(database_utf8);
        } else {
            database_utf8 = PyUnicode_AsUTF8String(database);
            if (!database_utf8) {
                return -1;
            }
        }

        Py_BEGIN_ALLOW_THREADS
        rc = sqlite3_open(PyString_AsString(database_utf8), &self->db);
        Py_END_ALLOW_THREADS

        Py_DECREF(database_utf8);

        if (rc != SQLITE_OK) {
            _pysqlite_seterror(self->db, NULL);
            return -1;
        }
    } else {
        /* Create a pysqlite connection from a APSW connection */
        class_attr = PyObject_GetAttrString(database, "__class__");
        if (class_attr) {
            class_attr_str = PyObject_Str(class_attr);
            if (class_attr_str) {
                if (strcmp(PyString_AsString(class_attr_str), "<type 'apsw.Connection'>") == 0) {
                    /* In the APSW Connection object, the first entry after
                     * PyObject_HEAD is the sqlite3* we want to get hold of.
                     * Luckily, this is the same layout as we have in our
                     * pysqlite_Connection */
                    self->db = ((pysqlite_Connection*)database)->db;

                    Py_INCREF(database);
                    self->apsw_connection = database;
                    is_apsw_connection = 1;
                }
            }
        }
        Py_XDECREF(class_attr_str);
        Py_XDECREF(class_attr);

        if (!is_apsw_connection) {
            PyErr_SetString(PyExc_ValueError, "database parameter must be string or APSW Connection object");
            return -1;
        }
    }

    if (!isolation_level) {
        isolation_level = PyString_FromString("");
        if (!isolation_level) {
            return -1;
        }
    } else {
        Py_INCREF(isolation_level);
    }
    self->isolation_level = NULL;
    pysqlite_connection_set_isolation_level(self, isolation_level);
    Py_DECREF(isolation_level);

    self->statement_cache = (pysqlite_Cache*)PyObject_CallFunction((PyObject*)&pysqlite_CacheType, "Oi", self, cached_statements);
    if (PyErr_Occurred()) {
        return -1;
    }

    self->created_statements = 0;
    self->created_cursors = 0;

    /* Create lists of weak references to statements/cursors */
    self->statements = PyList_New(0);
    self->cursors = PyList_New(0);
    if (!self->statements || !self->cursors) {
        return -1;
    }

    /* By default, the Cache class INCREFs the factory in its initializer, and
     * decrefs it in its deallocator method. Since this would create a circular
     * reference here, we're breaking it by decrementing self, and telling the
     * cache class to not decref the factory (self) in its deallocator.
     */
    self->statement_cache->decref_factory = 0;
    Py_DECREF(self);

    self->inTransaction = 0;
    self->detect_types = detect_types;
    self->timeout = timeout;
    (void)sqlite3_busy_timeout(self->db, (int)(timeout*1000));
#ifdef WITH_THREAD
    self->thread_ident = PyThread_get_thread_ident();
#endif
    self->check_same_thread = check_same_thread;

    self->function_pinboard = PyDict_New();
    if (!self->function_pinboard) {
        return -1;
    }

    self->collations = PyDict_New();
    if (!self->collations) {
        return -1;
    }

    self->Warning               = pysqlite_Warning;
    self->Error                 = pysqlite_Error;
    self->InterfaceError        = pysqlite_InterfaceError;
    self->DatabaseError         = pysqlite_DatabaseError;
    self->DataError             = pysqlite_DataError;
    self->OperationalError      = pysqlite_OperationalError;
    self->IntegrityError        = pysqlite_IntegrityError;
    self->InternalError         = pysqlite_InternalError;
    self->ProgrammingError      = pysqlite_ProgrammingError;
    self->NotSupportedError     = pysqlite_NotSupportedError;

    return 0;
}
void SqlDatabase::setBusyTimeout(int nMillisecs) {
	mnBusyTimeoutMs = nMillisecs;
	sqlite3_busy_timeout(mpDB, mnBusyTimeoutMs);
}
Exemple #7
0
/**
 * @brief Set a busy handler that sleeps for a specified amount of time when a table is locked.
 *
 *  This is useful in multithreaded program to handle case where a table is locked for writting by a thread.
 * Any other thread cannot access the table and will receive a SQLITE_BUSY error:
 * setting a timeout will wait and retry up to the time specified before returning this SQLITE_BUSY error.
 *  Reading the value of timeout for current connection can be done with SQL query "PRAGMA busy_timeout;".
 *  Default busy timeout is 0ms.
 *
 * @param[in] aBusyTimeoutMs    Amount of milliseconds to wait before returning SQLITE_BUSY
 *
 * @throw SQLite::Exception in case of error
 */
void Database::setBusyTimeout ( const int aBusyTimeoutMs ) noexcept { // nothrow
    const int ret = sqlite3_busy_timeout ( mpSQLite, aBusyTimeoutMs );
    check ( ret );
}
/* public native void dbopen(String path, int flags, String locale); */
void dbopen(JNIEnv* env, jobject object, jstring pathString, jint flags)
{
    int err;
    sqlite3 * handle = NULL;
    sqlite3_stmt * statement = NULL;
    char const * path8 = env->GetStringUTFChars(pathString, NULL);
    int sqliteFlags;

    // register the logging func on sqlite. needs to be done BEFORE any sqlite3 func is called.
    registerLoggingFunc(path8);

    // convert our flags into the sqlite flags
    if (flags & CREATE_IF_NECESSARY) {
        sqliteFlags = SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE;
    } else if (flags & OPEN_READONLY) {
        sqliteFlags = SQLITE_OPEN_READONLY;
    } else {
        sqliteFlags = SQLITE_OPEN_READWRITE;
    }

    err = sqlite3_open_v2(path8, &handle, sqliteFlags, NULL);
    if (err != SQLITE_OK) {
        LOGE("sqlite3_open_v2(\"%s\", &handle, %d, NULL) failed\n", path8, sqliteFlags);
        throw_sqlite3_exception_errcode(env, err, "Could not open database");
        goto done;
    }

    // Check that the database is really read/write when that is what we asked for.
    if ((sqliteFlags & SQLITE_OPEN_READWRITE) && sqlite3_db_readonly(handle, NULL)) {
        throw_sqlite3_exception(env, handle, "Could not open the database in read/write mode.");
        goto done;
    }

    // The soft heap limit prevents the page cache allocations from growing
    // beyond the given limit, no matter what the max page cache sizes are
    // set to. The limit does not, as of 3.5.0, affect any other allocations.
    sqlite3_soft_heap_limit(SQLITE_SOFT_HEAP_LIMIT);

    // Set the default busy handler to retry for 1000ms and then return SQLITE_BUSY
    err = sqlite3_busy_timeout(handle, 1000 /* ms */);
    if (err != SQLITE_OK) {
        LOGE("sqlite3_busy_timeout(handle, 1000) failed for \"%s\"\n", path8);
        throw_sqlite3_exception(env, handle, "Could not set busy timeout");
        goto done;
    }

#ifdef DB_INTEGRITY_CHECK
    static const char* integritySql = "pragma integrity_check(1);";
    err = sqlite3_prepare_v2(handle, integritySql, -1, &statement, NULL);
    if (err != SQLITE_OK) {
        LOGE("sqlite_prepare_v2(handle, \"%s\") failed for \"%s\"\n", integritySql, path8);
        throw_sqlite3_exception(env, handle, "sqlite_prepare_v2(handle, \"pragma integrity_check(1);\") failed");
        goto done;
    }

    // first is OK or error message
    err = sqlite3_step(statement);
    if (err != SQLITE_ROW) {
        LOGE("integrity check failed for \"%s\"\n", integritySql, path8);
        throw_sqlite3_exception(env, handle);
        goto done;
    } else {
        const char *text = (const char*)sqlite3_column_text(statement, 0);
        if (strcmp(text, "ok") != 0) {
            LOGE("integrity check failed for \"%s\": %s\n", integritySql, path8, text);
            jniThrowException(env, "net/sqlcipher/database/SQLiteDatabaseCorruptException", text);
            goto done;
        }
    }
#endif

    err = register_android_functions(handle, UTF16_STORAGE);
    if (err) {
        throw_sqlite3_exception(env, handle, "Could not register Android SQL functions.");
        goto done;
    }

    sqlite3_enable_load_extension(handle, 1);
    
    LOGV("Opened '%s' - %p\n", path8, handle);
    env->SetIntField(object, offset_db_handle, (int) handle);
    handle = NULL;  // The caller owns the handle now.

done:
    // Release allocated resources
    if (path8 != NULL) env->ReleaseStringUTFChars(pathString, path8);
    if (statement != NULL) sqlite3_finalize(statement);
    if (handle != NULL) sqlite3_close(handle);
}
Exemple #9
0
	void Database::SetBusyTimeout(int millis)
	{
		ASSERT(m_db);
		sqlite3_busy_timeout(m_db, millis);
	}
Exemple #10
0
/******************************************************************************
 *                                                                            *
 * Function: zbx_db_connect                                                   *
 *                                                                            *
 * Purpose: connect to the database                                           *
 *                                                                            *
 * Return value: ZBX_DB_OK - succefully connected                             *
 *               ZBX_DB_DOWN - database is down                               *
 *               ZBX_DB_FAIL - failed to connect                              *
 *                                                                            *
 ******************************************************************************/
int	zbx_db_connect(char *host, char *user, char *password, char *dbname, char *dbschema, char *dbsocket, int port)
{
	int		ret = ZBX_DB_OK;
#if defined(HAVE_IBM_DB2)
	char		*connect = NULL;
#elif defined(HAVE_ORACLE)
	char		*connect = NULL;
	sword		err = OCI_SUCCESS;
#elif defined(HAVE_POSTGRESQL)
	char		*cport = NULL;
	DB_RESULT	result;
	DB_ROW		row;
#endif

	txn_init = 1;

#if defined(HAVE_IBM_DB2)
	connect = strdup("PROTOCOL=TCPIP;");
	if (NULL != dbname && '\0' != *dbname)
		connect = zbx_strdcatf(connect, "DATABASE=%s;", dbname);
	if (NULL != host && '\0' != *host)
		connect = zbx_strdcatf(connect, "HOSTNAME=%s;", host);
	if (0 != port)
		connect = zbx_strdcatf(connect, "PORT=%d;", port);
	if (NULL != user && '\0' != *user)
		connect = zbx_strdcatf(connect, "UID=%s;", user);
	if (NULL != password && '\0' != *password)
		connect = zbx_strdcatf(connect, "PWD=%s;", password);

	memset(&ibm_db2, 0, sizeof(ibm_db2));

	/* allocate an environment handle */
	if (SUCCEED != zbx_ibm_db2_success(SQLAllocHandle(SQL_HANDLE_ENV, SQL_NULL_HANDLE, &ibm_db2.henv)))
		ret = ZBX_DB_FAIL;

	/* set attribute to enable application to run as ODBC 3.0 application; recommended for pure IBM DB2 CLI, but not required */
	if (ZBX_DB_OK == ret && SUCCEED != zbx_ibm_db2_success(SQLSetEnvAttr(ibm_db2.henv, SQL_ATTR_ODBC_VERSION, (void *)SQL_OV_ODBC3, 0)))
		ret = ZBX_DB_FAIL;

	/* allocate a database connection handle */
	if (ZBX_DB_OK == ret && SUCCEED != zbx_ibm_db2_success(SQLAllocHandle(SQL_HANDLE_DBC, ibm_db2.henv, &ibm_db2.hdbc)))
		ret = ZBX_DB_FAIL;

	/* connect to the database */
	if (ZBX_DB_OK == ret && SUCCEED != zbx_ibm_db2_success(SQLDriverConnect(ibm_db2.hdbc, NULL, (SQLCHAR *)connect, SQL_NTS,
								NULL, 0, NULL, SQL_DRIVER_NOPROMPT)))
		ret = ZBX_DB_FAIL;

	/* set autocommit on */
  	if (ZBX_DB_OK == ret && SUCCEED != zbx_ibm_db2_success(SQLSetConnectAttr(ibm_db2.hdbc, SQL_ATTR_AUTOCOMMIT,
								(SQLPOINTER)SQL_AUTOCOMMIT_ON, SQL_NTS)))
		ret = ZBX_DB_DOWN;

	/* we do not generate vendor escape clause sequences */
  	if (ZBX_DB_OK == ret && SUCCEED != zbx_ibm_db2_success(SQLSetConnectAttr(ibm_db2.hdbc, SQL_ATTR_NOSCAN,
								(SQLPOINTER)SQL_NOSCAN_ON, SQL_NTS)))
		ret = ZBX_DB_DOWN;

	/* set current schema */
	if (NULL != dbschema && '\0' != *dbschema && ZBX_DB_OK == ret)
	{
		char	*dbschema_esc;

		dbschema_esc = DBdyn_escape_string(dbschema);
		DBexecute("set current schema='%s'", dbschema_esc);
		zbx_free(dbschema_esc);
	}

	/* output error information */
	if (ZBX_DB_OK != ret)
	{
		zbx_ibm_db2_log_errors(SQL_HANDLE_ENV, ibm_db2.henv);
		zbx_ibm_db2_log_errors(SQL_HANDLE_DBC, ibm_db2.hdbc);

		zbx_db_close();
	}

	zbx_free(connect);
#elif defined(HAVE_MYSQL)
	conn = mysql_init(NULL);

	if (!mysql_real_connect(conn, host, user, password, dbname, port, dbsocket, CLIENT_MULTI_STATEMENTS))
	{
		zabbix_errlog(ERR_Z3001, dbname, mysql_errno(conn), mysql_error(conn));
		ret = ZBX_DB_FAIL;
	}

	if (ZBX_DB_OK == ret)
	{
		if (0 != mysql_select_db(conn, dbname))
		{
			zabbix_errlog(ERR_Z3001, dbname, mysql_errno(conn), mysql_error(conn));
			ret = ZBX_DB_FAIL;
		}
	}

	if (ZBX_DB_OK == ret)
	{
		DBexecute("SET NAMES utf8");
	}

	if (ZBX_DB_FAIL == ret)
	{
		switch (mysql_errno(conn))
		{
			case CR_CONN_HOST_ERROR:
			case CR_SERVER_GONE_ERROR:
			case CR_CONNECTION_ERROR:
			case CR_SERVER_LOST:
			case ER_SERVER_SHUTDOWN:
			case ER_ACCESS_DENIED_ERROR:		/* wrong user or password */
			case ER_ILLEGAL_GRANT_FOR_TABLE:	/* user without any privileges */
			case ER_TABLEACCESS_DENIED_ERROR:	/* user without some privilege */
			case ER_UNKNOWN_ERROR:
				ret = ZBX_DB_DOWN;
				break;
			default:
				break;
		}
	}
#elif defined(HAVE_ORACLE)
#if defined(HAVE_GETENV) && defined(HAVE_PUTENV)
	if (NULL == getenv("NLS_LANG"))
		putenv("NLS_LANG=.UTF8");
#endif
	memset(&oracle, 0, sizeof(oracle));

	/* connection string format: [//]host[:port][/service name] */

	if (NULL != host && '\0' != *host)
	{
		connect = zbx_strdcatf(connect, "//%s", host);

		if (port)
			connect = zbx_strdcatf(connect, ":%d", port);

		if (dbname && *dbname)
			connect = zbx_strdcatf(connect, "/%s", dbname);
	}
	else
		ret = ZBX_DB_FAIL;

	if (ZBX_DB_OK == ret)
	{
		/* initialize environment */
		err = OCIEnvCreate((OCIEnv **)&oracle.envhp, (ub4)OCI_DEFAULT,
				(dvoid *)0, (dvoid * (*)(dvoid *,size_t))0,
				(dvoid * (*)(dvoid *, dvoid *, size_t))0,
				(void (*)(dvoid *, dvoid *))0, (size_t)0, (dvoid **)0);

		if (OCI_SUCCESS != err)
		{
			zabbix_errlog(ERR_Z3001, connect, err, zbx_oci_error(err));
			ret = ZBX_DB_FAIL;
		}
	}

	if (ZBX_DB_OK == ret)
	{
		/* allocate an error handle */
		(void)OCIHandleAlloc((dvoid *)oracle.envhp, (dvoid **)&oracle.errhp, OCI_HTYPE_ERROR,
				(size_t)0, (dvoid **)0);

		/* get the session */
		err = OCILogon2(oracle.envhp, oracle.errhp, &oracle.svchp,
				(text *)user, (ub4)(NULL != user ? strlen(user) : 0),
				(text *)password, (ub4)(NULL != password ? strlen(password) : 0),
				(text *)connect, (ub4)strlen(connect),
				OCI_DEFAULT);

		if (OCI_SUCCESS != err)
		{
			zabbix_errlog(ERR_Z3001, connect, err, zbx_oci_error(err));
			ret = ZBX_DB_DOWN;
		}
		else
		{
			err = OCIAttrGet((void *)oracle.svchp, OCI_HTYPE_SVCCTX, (void *)&oracle.srvhp, (ub4 *)0,
					OCI_ATTR_SERVER, oracle.errhp);

			if (OCI_SUCCESS != err)
			{
				zabbix_errlog(ERR_Z3001, connect, err, zbx_oci_error(err));
				ret = ZBX_DB_DOWN;
			}
		}
	}

	zbx_free(connect);

	if (ZBX_DB_OK != ret)
		zbx_db_close();
#elif defined(HAVE_POSTGRESQL)
	if (0 != port)
		cport = zbx_dsprintf(cport, "%d", port);

	conn = PQsetdbLogin(host, cport, NULL, NULL, dbname, user, password);

	zbx_free(cport);

	/* check to see that the backend connection was successfully made */
	if (CONNECTION_OK != PQstatus(conn))
	{
		zabbix_errlog(ERR_Z3001, dbname, 0, PQerrorMessage(conn));
		ret = ZBX_DB_DOWN;
	}
	else
	{
		result = DBselect("select oid from pg_type where typname='bytea'");
		if (NULL != (row = DBfetch(result)))
			ZBX_PG_BYTEAOID = atoi(row[0]);
		DBfree_result(result);
	}

#ifdef HAVE_FUNCTION_PQSERVERVERSION
	ZBX_PG_SVERSION = PQserverVersion(conn);
	zabbix_log(LOG_LEVEL_DEBUG, "PostgreSQL Server version: %d", ZBX_PG_SVERSION);
#endif

	if (80100 <= ZBX_PG_SVERSION)
	{
		/* disable "nonstandard use of \' in a string literal" warning */
		DBexecute("set escape_string_warning to off");
	}

	if (90000 <= ZBX_PG_SVERSION)
	{
		/* change the output format for values of type bytea from hex (the default) to escape */
		DBexecute("set bytea_output=escape");
	}
#elif defined(HAVE_SQLITE3)
#ifdef HAVE_FUNCTION_SQLITE3_OPEN_V2
	if (SQLITE_OK != sqlite3_open_v2(dbname, &conn, SQLITE_OPEN_READWRITE, NULL))
#else
	if (SQLITE_OK != sqlite3_open(dbname, &conn))
#endif
	{
		zabbix_errlog(ERR_Z3001, dbname, 0, sqlite3_errmsg(conn));
		sqlite3_close(conn);
		ret = ZBX_DB_DOWN;
	}
	else
	{
		char	*p, *path;

		/* do not return SQLITE_BUSY immediately, wait for N ms */
		sqlite3_busy_timeout(conn, SEC_PER_MIN * 1000);

		path = strdup(dbname);
		if (NULL != (p = strrchr(path, '/')))
			*++p = '\0';
		else
			*path = '\0';

		DBexecute("PRAGMA synchronous = 0"); /* OFF */
		DBexecute("PRAGMA temp_store = 2"); /* MEMORY */
		DBexecute("PRAGMA temp_store_directory = '%s'", path);

		zbx_free(path);
	}
#endif	/* HAVE_SQLITE3 */

	txn_init = 0;

	return ret;
}
Exemple #11
0
int
sqlitecmd(int argc, char **argv)
{
	sqlite3        *db;
	int		res;
	int		i;
	char		*query;
	char		*tmp;
	char		*dbdir;
	char		*dbfile;
	int		ret = 0;
	sqlite3_stmt   *stmt;
	char		*cp;

	const char journal_mode_sql[] = "PRAGMA journal_mode = MEMORY;";

	if ((cp = lookupvar("sqldelimer")) == NULL)
		delim = DEFSQLDELIMER;
	else
		delim = cp;

	if (argc < 3) {
		out1fmt("%s: format: %s <dbfile> <query>\n", nm(), nm());
		return 0;
	}

	if ( argv[1][0]!='/' ) {
		//search file in dbdir
		dbdir = lookupvar("dbdir");
		i = strlen(dbdir) + strlen(argv[1]);
		dbfile = calloc(strlen(dbdir) + strlen(argv[1]) + strlen(DBPOSTFIX) + 1, sizeof(char *));

		if (dbfile == NULL) {
			error("Out of memory!\n");
			return (1);
		}
		sprintf(dbfile, "%s/%s%s", dbdir, argv[1], DBPOSTFIX);
	} else {
		dbfile = calloc(strlen(argv[1]) + 1, sizeof(char *));
		sprintf(dbfile,"%s",argv[1]);
	}

	if (SQLITE_OK != (res = sqlite3_open(dbfile, &db))) {
		out1fmt("%s: Can't open database file: %s\n", nm(), dbfile);
		free(dbfile);
		return 1;
	}
	free(dbfile);

	sqlite3_busy_timeout(db, SQLITE_BUSY_TIMEOUT);

	res = 0;
	for (i = 2; i < argc; i++)
		res += strlen(argv[i]) + 1;
	if (res) {
		query = (char *)sqlite3_malloc(res);
		tmp = query;
		for (i = 2; i < argc; i++) {
			strcpy(tmp, argv[i]);
			tmp += strlen(tmp);
			*tmp = ' ';
			tmp++;
		}
		tmp[-1] = 0;
	}

	sqlite3_prepare_v2(db, journal_mode_sql, -1, &stmt, NULL);
	ret = 	sqlite3_prepare_v2(db, query, -1, &stmt, NULL);

	if (ret == SQLITE_OK) {
		ret = sqlite3_step(stmt);

		while ( ret == SQLITE_ROW ) {
			sqlCB(stmt);
			ret = sqlite3_step(stmt);
		}
	}

	sqlite3_finalize(stmt);
	sqlite3_free(query);
	sqlite3_close(db);

	return 0;
}
Exemple #12
0
int sql_init(struct rekey_session *sess) 
{
  sqlite3 *dbh;
  int dblock, rc, i;
  char *sql, *errmsg;

  if (sess->dbh)
    return 0;
  
  dblock = open(REKEY_DATABASE_LOCK, O_WRONLY | O_CREAT, 0644);
  if (dblock < 0) {
    prtmsg("Cannot create/open database lock: %s", strerror(errno));
    return 1;
  }

  if (flock(dblock, LOCK_EX)) {
    prtmsg("Cannot obtain database lock: %s", strerror(errno));
    close(dblock);
    return 1;
  }

#if SQLITE_VERSION_NUMBER >= 3005000
  rc = sqlite3_open_v2(REKEY_LOCAL_DATABASE, &dbh, SQLITE_OPEN_READWRITE, NULL);
  if (rc == SQLITE_OK) {
    sess->db_lock = dblock;
    sess->dbh = dbh;
    return 0;
  }
  
  if (rc != SQLITE_ERROR && rc != SQLITE_CANTOPEN) {
    prtmsg("Cannot open database: %d", rc);
    close(dblock);
    return 1;
  }

  rc = sqlite3_open_v2(REKEY_LOCAL_DATABASE, &dbh, SQLITE_OPEN_READWRITE | 
                       SQLITE_OPEN_CREATE, NULL);
  if (rc != SQLITE_OK) { 
    prtmsg("Cannot create/open database: %d", rc);
    close(dblock);
    return 1;
  }
#else
  rc = sqlite3_open(REKEY_LOCAL_DATABASE, &dbh);
  if (rc != SQLITE_OK) { 
    prtmsg("Cannot create/open database: %d", rc);
    close(dblock);
    return 1;
  }
#endif

  rc = sqlite3_busy_timeout(dbh, 30000);
  if (rc != SQLITE_OK) {
    prtmsg("Failed setting database busy handler: %d", rc);
    sqlite3_close(dbh);
    close(dblock);
    return 1;
  }
    
#if SQLITE_VERSION_NUMBER >= 3003007 /* need support for CREATE TRIGGER IF NOT EXIST */
  for (sql=sql_embeded_init[i=0]; sql;sql=sql_embeded_init[++i]) {
    rc = sqlite3_exec(dbh, sql, NULL, NULL, &errmsg);
    if (rc != SQLITE_OK) {
      if (errmsg) {
        prtmsg("SQL Initialization action %d failed: %s", i, errmsg);
        sqlite3_free(errmsg);
      } else {
        prtmsg("SQL Initialization action %d failed: %d", i, rc);
      }
      sqlite3_close(dbh);
      close(dblock);
      return 1;
    }
  }
#else
#warning Automatic database initialization not available
#endif
  sess->db_lock = dblock;
  sess->dbh = dbh;
  return 0;
}
Exemple #13
0
static svn_error_t *
internal_open(svn_sqlite__db_t *db, const char *path, svn_sqlite__mode_t mode,
              apr_int32_t timeout, apr_pool_t *scratch_pool)
{
  {
    int flags;

    if (mode == svn_sqlite__mode_readonly)
      flags = SQLITE_OPEN_READONLY;
    else if (mode == svn_sqlite__mode_readwrite)
      flags = SQLITE_OPEN_READWRITE;
    else if (mode == svn_sqlite__mode_rwcreate)
      flags = SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE;
    else
      SVN_ERR_MALFUNCTION();

    /* Turn off SQLite's mutexes. All svn objects are single-threaded,
       so we can already guarantee that our use of the SQLite handle
       will be serialized properly.

       Note: in 3.6.x, we've already config'd SQLite into MULTITHREAD mode,
       so this is probably redundant, but if we are running in a process where
       somebody initialized SQLite before us it is needed anyway.  */
    flags |= SQLITE_OPEN_NOMUTEX;

#if !defined(WIN32) && !defined(SVN_SQLITE_INLINE)
    if (mode == svn_sqlite__mode_rwcreate)
      {
        svn_node_kind_t kind;

        /* Create the file before SQLite to avoid any permissions
           problems with an SQLite build that uses the default
           SQLITE_DEFAULT_FILE_PERMISSIONS of 644 modified by umask.
           We simply want umask permissions. */
        SVN_ERR(svn_io_check_path(path, &kind, scratch_pool));
        if (kind == svn_node_none)
          {
            /* Another thread may have created the file, that's OK. */
            svn_error_t *err = svn_io_file_create_empty(path, scratch_pool);
            if (err && !APR_STATUS_IS_EEXIST(err->apr_err))
              return svn_error_trace(err);
            svn_error_clear(err);
          }
      }
#endif

    /* Open the database. Note that a handle is returned, even when an error
       occurs (except for out-of-memory); thus, we can safely use it to
       extract an error message and construct an svn_error_t.  SQLite always
       requires sqlite3_close() after sqlite3_open_v2() while Subversion
       typically does not require close() after an open() that returns an
       error.  So we must ensure we close the handle if this function, or
       the caller svn_sqlite__open, returns an error to the application. */
    {
      const char *vFs = NULL;

#if defined(WIN32) && SQLITE_VERSION_AT_LEAST(3, 8, 1)
      if (strlen(path) > 248)
        {
          WCHAR *win_path;
          vFs = "win32-longpath"; /* Enable long paths in sqlite */

          /* Long paths must be absolute */
          if (!svn_dirent_is_absolute(path))
            SVN_ERR(svn_dirent_get_absolute(&path, path, scratch_pool));

          /* Convert the path to a properly canonicalized \\?\C:\long\path */
          SVN_ERR(svn_io__utf8_to_unicode_longpath(&win_path, path,
                                                   scratch_pool));

          /* And convert it back to UTF-8 because there is no
              sqlite3_open16_v2() yet */
          SVN_ERR(svn_utf__win32_utf16_to_utf8(&path, win_path, NULL,
                                               scratch_pool));
        }
#endif

      /* ### SQLITE_CANTOPEN */
      SQLITE_ERR_CLOSE(sqlite3_open_v2(path, &db->db3, flags, vFs),
                       db, scratch_pool);
    }
  }

  if (timeout <= 0)
    timeout = BUSY_TIMEOUT;

  /* Retry until timeout when database is busy. */
  SQLITE_ERR_CLOSE(sqlite3_busy_timeout(db->db3, timeout),
                   db, scratch_pool);

  return SVN_NO_ERROR;
}
/*
 * This ist the Entry Function of this Mex-DLL
 */
void mexFunction(int nlhs, mxArray*plhs[], int nrhs, const mxArray*prhs[])
{
    mexAtExit(CloseDBs);
    
    /*
     * Get the current Language
     */
    if (Language == -1)
    {
#ifdef _WIN32        
        switch(PRIMARYLANGID(GetUserDefaultLangID()))
        {
            case LANG_GERMAN:
                Language = 1;
                break;
                
            default:
                Language = 0;
        }
#else
        Language = 0;
#endif
    }
    
	/*
	 * Print Version Information
	 */
	if (! FirstStart)
    {
    	FirstStart = true;

        mexPrintf (MSG_HELLO, sqlite3_libversion());
    }
    
    int db_id = 0;
    int CommandPos = 0;
    int NumArgs = nrhs;
    int i;
    
    /*
     * Check if the first argument is a number, then we have to use
	 * this number as an database id.
     */
    if (nrhs >= 1 && mxIsNumeric(prhs[0]))
    {
        db_id = getinteger(prhs[0]);
        if (db_id < 0 || db_id > MaxNumOfDbs)
        {
            mexPrintf(MSG_INVALIDDBHANDLE);
            mexErrMsgTxt(MSG_IMPOSSIBLE);
        }
        db_id --;
        CommandPos ++;
        NumArgs --;
    }

    /*
     * no argument -> fail
     */
    if (NumArgs < 1)
    {
        mexPrintf(MSG_USAGE);
        mexErrMsgTxt(MSG_INVALIDARG);
    }
    
    /*
     * The next (or first if no db number available) is the command,
     * it has to be a string.
     * This fails also, if the first arg is a db-id and there is no 
     * further argument
     */
    if (! mxIsChar(prhs[CommandPos]))
    {
        mexPrintf(MSG_USAGE);
        mexErrMsgTxt(MSG_INVALIDARG);
    }
    
	/*
	 * Get the command string
	 */
    char *command = getstring(prhs[CommandPos]);
    
    /*
     * Adjust the Argument pointer and counter
     */
    int FirstArg = CommandPos +1;
    NumArgs --;
    
    if (! strcmp(command, "open"))
    {
		/*
		 * open a database. There has to be one string argument,
		 * the database filename
		 */
        if (NumArgs != 1 || !mxIsChar(prhs[FirstArg]))
        {
            mexPrintf(MSG_NOOPENARG, mexFunctionName());
			mxFree(command);
            mexErrMsgTxt(MSG_INVALIDARG);
        }
        
		// TODO: possible Memoryleak 'command not freed' when getstring fails
        char* dbname = getstring(prhs[FirstArg]);

		/*
		 * Is there an database ID? The close the database with the same id 
		 */
        if (db_id > 0 && g_dbs[db_id])
        {
            sqlite3_close(g_dbs[db_id]);
            g_dbs[db_id] = 0;
        }

		/*
		 * If there isn't an database id, then try to get one
		 */
        if (db_id < 0)
        {
            for (i = 0; i < MaxNumOfDbs; i++)
            {
                if (g_dbs[i] == 0)
                {
                    db_id = i;
                    break;
                }
            }
        }
		/*
		 * no database id? sorry, database id table full
		 */
        if (db_id < 0)
        {
            plhs[0] = mxCreateDoubleScalar((double) 0);
            mexPrintf(MSG_NOFREESLOT);
			mxFree(command);
        	mxFree(dbname);
            mexErrMsgTxt(MSG_IMPOSSIBLE);
        }
       
		/*
		 * Open the database
		 */
        int rc = sqlite3_open(dbname, &g_dbs[db_id]);
        
        if (rc)
        {
			/*
			 * Anything wrong? free the database id and inform the user
			 */
            mexPrintf(MSG_CANTOPEN, sqlite3_errmsg(g_dbs[db_id]));
            sqlite3_close(g_dbs[db_id]);

            g_dbs[db_id] = 0;
            plhs[0] = mxCreateDoubleScalar((double) 0);
            
			mxFree(command);
	        mxFree(dbname);
            mexErrMsgTxt(MSG_IMPOSSIBLE);
        }
        
        /*
         * Set Default Busytimeout
         */
        rc = sqlite3_busy_timeout(g_dbs[db_id], DEFAULT_BUSYTIMEOUT);
        if (rc)
        {
			/*
			 * Anything wrong? free the database id and inform the user
			 */
            mexPrintf(MSG_CANTOPEN, sqlite3_errmsg(g_dbs[db_id]));
            sqlite3_close(g_dbs[db_id]);

            g_dbs[db_id] = 0;
            plhs[0] = mxCreateDoubleScalar((double) 0);
            
			mxFree(command);
	        mxFree(dbname);
            mexErrMsgTxt(MSG_BUSYTIMEOUTFAIL);
        }
        
		/*
		 * return value will be the used database id
		 */
        plhs[0] = mxCreateDoubleScalar((double) db_id +1);
        mxFree(dbname);
    }
    else if (! strcmp(command, "close"))
    {
		/*
		 * close a database
		 */

        /*
         * There should be no Argument to close
         */
        if (NumArgs > 0)
        {
			mxFree(command);
            mexErrMsgTxt(MSG_INVALIDARG);
        }
        
		/*
		 * if the database id is < 0 than close all open databases
		 */
        if (db_id < 0)
        {
            for (i = 0; i < MaxNumOfDbs; i++)
            {
                if (g_dbs[i])
                {
                    sqlite3_close(g_dbs[i]);
                    g_dbs[i] = 0;
                }
            }
        }
        else
        {
			/*
			 * If the database is open, then close it. Otherwise
			 * inform the user
			 */
            if (! g_dbs[db_id])
            {
				mxFree(command);
                mexErrMsgTxt(MSG_DBNOTOPEN);
            }
            else
            {
                sqlite3_close(g_dbs[db_id]);
                g_dbs[db_id] = 0;
            }
        }
    }
    else if (! strcmp(command, "status"))
    {
        /*
         * There should be no Argument to status
         */
        if (NumArgs > 0)
        {
			mxFree(command);
            mexErrMsgTxt(MSG_INVALIDARG);
        }
        
    	for (i = 0; i < MaxNumOfDbs; i++)
        {
            mexPrintf("DB Handle %d: %s\n", i, g_dbs[i] ? "OPEN" : "CLOSED");
        }
    }
    else if (! _strcmpi(command, "setbusytimeout"))
    {
        /*
         * There should be one Argument, the Timeout in ms
         */
        if (NumArgs != 1 || !mxIsNumeric(prhs[FirstArg]))
        {
			mxFree(command);
            mexErrMsgTxt(MSG_INVALIDARG);
        }

        if (! g_dbs[db_id])
        {
            mxFree(command);
            mexErrMsgTxt(MSG_DBNOTOPEN);
        }
        else
        {
            /*
             * Set Busytimeout
             */
            int TimeoutValue = getinteger(prhs[FirstArg]);
    
            int rc = sqlite3_busy_timeout(g_dbs[db_id], TimeoutValue);
            if (rc)
            {
                /*
                 * Anything wrong? free the database id and inform the user
                 */
                mexPrintf(MSG_CANTOPEN, sqlite3_errmsg(g_dbs[db_id]));
                sqlite3_close(g_dbs[db_id]);

                g_dbs[db_id] = 0;
                plhs[0] = mxCreateDoubleScalar((double) 0);

                mxFree(command);
                mexErrMsgTxt(MSG_BUSYTIMEOUTFAIL);
            }
        }
    }
    else
    {
		/*
		 * database id < 0? Thats an error...
		 */
        if (db_id < 0)
        {
            mexPrintf(MSG_INVALIDDBHANDLE);
			mxFree(command);
            mexErrMsgTxt(MSG_IMPOSSIBLE);
        }
        
		/*
		 * database not open? -> error
		 */
        if (!g_dbs[db_id])
        {
			mxFree(command);
            mexErrMsgTxt(MSG_DBNOTOPEN);
        }
        
		/*
		 * Every unknown command is treated as an sql query string
		 */
		const char* query = command;

        /*
         * a query shuld have no arguments
         */
        if (NumArgs > 0)
        {
			mxFree(command);
            mexErrMsgTxt(MSG_INVALIDARG);
        }
        
		/*
		 * emulate the "show tables" sql query
		 */
        if (! _strcmpi(query, "show tables"))
        {
            query = "SELECT name as tablename FROM sqlite_master "
                    "WHERE type IN ('table','view') AND name NOT LIKE 'sqlite_%' "
                    "UNION ALL "
                    "SELECT name as tablename FROM sqlite_temp_master "
                    "WHERE type IN ('table','view') "
                    "ORDER BY 1";
        }

		/*
		 * complete the query
		 */
        if (sqlite3_complete(query))
        {
			mxFree(command);
            mexErrMsgTxt(MSG_INVQUERY);
        }
        
        sqlite3_stmt *st;
        
		/*
		 * and prepare it
		 * if anything is wrong with the query, than complain about it.
		 */
        if (sqlite3_prepare_v2(g_dbs[db_id], query, -1, &st, 0))
        {
            if (st)
                sqlite3_finalize(st);
            
			mxFree(command);
            mexErrMsgIdAndTxt(TransErrToIdent(g_dbs[db_id]), sqlite3_errmsg(g_dbs[db_id]));
        }

		/*
		 * Any results?
		 */
        int ncol = sqlite3_column_count(st);
        if (ncol > 0)
        {
            char **fieldnames = new char *[ncol];   /* Column names */
            Values* allrows = 0;                    /* All query results */
            Values* lastrow = 0;					/* pointer to the last result row */
            int rowcount = 0;						/* number of result rows */
            
			/*
			 * Get the column names of the result set
			 */
            for(i=0; i<ncol; i++)
            {
                const char *cname = sqlite3_column_name(st, i);
                
                fieldnames[i] = new char [strlen(cname) +1];
                strcpy (fieldnames[i], cname);
				/*
				 * replace invalid chars by '_', so we can build
				 * valid MATLAB structs
				 */
                char *mk_c = fieldnames[i];
                while (*mk_c)
                {
                	if ((*mk_c == ' ') || (*mk_c == '*') || (*mk_c == '?'))
                    	*mk_c = '_';
                    mk_c++;
                }
            }
            
            /*
			 * get the result rows from the engine
			 *
			 * We cannot get the number of result lines, so we must
			 * read them in a loop and save them into an temporary list.
			 * Later, we can transfer this List into an MATLAB array of structs.
			 * This way, we must allocate enough memory for two result sets,
			 * but we save time by allocating the MATLAB Array at once.
			 */
            for(;;)
            {
				/*
				 * Advance to teh next row
				 */
                int step_res = sqlite3_step(st);

				/*
				 * no row left? break out of the loop
				 */
                if (step_res != SQLITE_ROW)
                    break;

				/*
				 * get new memory for the result
				 */
                Values* RecordValues = new Values(ncol);
                
                Value *v = RecordValues->m_Values;
                for (int j = 0; j < ncol; j++, v++)
                {
                     int fieldtype = sqlite3_column_type(st,j);

                     v->m_Type = fieldtype;
                     v->m_Size = 0;
                     
                     switch (fieldtype)
                     {
                         case SQLITE_NULL:      v->m_NumericValue = g_NaN;                                   break;
                         case SQLITE_INTEGER:	v->m_NumericValue = (double) sqlite3_column_int(st, j);      break;
                         case SQLITE_FLOAT:     v->m_NumericValue = (double) sqlite3_column_double(st, j);	 break;
                         case SQLITE_TEXT:      v->m_StringValue  = strnewdup((const char*) sqlite3_column_text(st, j));   break;
                         case SQLITE_BLOB:      
                            {
                                v->m_Size = sqlite3_column_bytes(st,j);
                                if (v->m_Size > 0)
                                {
                                    v->m_StringValue = new char[v->m_Size];
                                    memcpy(v->m_StringValue, sqlite3_column_blob(st,j), v->m_Size);
                                }
                                else
                                {
                                    v->m_Size = 0;
                                }
                            }
                            break;
                         default:	
							mxFree(command);
							mexErrMsgTxt(MSG_UNKNWNDBTYPE);
                     }
                }
				/*
				 * and add this row to the list of all result rows
				 */
                if (! lastrow)
                {
                    allrows = lastrow = RecordValues;
                }
                else
                {
                    lastrow->m_NextValues = RecordValues;
                    lastrow = lastrow->m_NextValues;
                }
				/*
				 * we have one more...
				 */
                rowcount ++;
            }
            
			/*
			 * end the sql engine
			 */
            sqlite3_finalize(st);

			/*
			 * got nothing? return an empty result to MATLAB
			 */
            if (rowcount == 0 || ! allrows)
            {
                if (!( plhs[0] = mxCreateDoubleMatrix(0,0,mxREAL) ))
				{
					mxFree(command);
                    mexErrMsgTxt(MSG_CANTCREATEOUTPUT);
				}
            }
            else
            {
				/*
				 * Allocate an array of MATLAB structs to return as result
				 */
                int ndims[2];
                
                ndims[0] = rowcount;
                ndims[1] = 1;
                
                if (( plhs[0] = mxCreateStructArray (2, ndims, ncol, (const char**)fieldnames)) == 0)
                {
					mxFree(command);
                    mexErrMsgTxt(MSG_CANTCREATEOUTPUT);
                }
                
				/*
				 * transfer the result rows from the temporary list into the result array
				 */
                lastrow = allrows;
                i = 0;
                while(lastrow)
                {
                    Value* recordvalue = lastrow->m_Values;
                    
                    for (int j = 0; j < ncol; j++, recordvalue++)
                    {
                        if (recordvalue -> m_Type == SQLITE_TEXT)
                        {
                            mxArray* c = mxCreateString(recordvalue->m_StringValue);
                            mxSetFieldByNumber(plhs[0], i, j, c);
                        }
                        else if (recordvalue -> m_Type == SQLITE_NULL && !NULLasNaN)
                        {
                            mxArray* out_double = mxCreateDoubleMatrix(0,0,mxREAL);
                            mxSetFieldByNumber(plhs[0], i, j, out_double);
                        }
                        else if (recordvalue -> m_Type == SQLITE_BLOB)
                        {
                            if (recordvalue->m_Size > 0)
                            {
                                int BytePos;
                                int NumDims[2]={1,1};
                                NumDims[1]=recordvalue->m_Size;
                                mxArray*out_uchar8=mxCreateNumericArray(2, NumDims, mxUINT8_CLASS, mxREAL);
                                unsigned char *v = (unsigned char *) mxGetData(out_uchar8);
                                
                                memcpy(v, recordvalue->m_StringValue, recordvalue->m_Size);
                                    
                                mxSetFieldByNumber(plhs[0], i, j, out_uchar8);
                            }
                            else
                            {
                                // empty BLOB
                                mxArray* out_double = mxCreateDoubleMatrix(0,0,mxREAL);
                                mxSetFieldByNumber(plhs[0], i, j, out_double);
                            }
                        }
                        else
                        {
                            mxArray* out_double = mxCreateDoubleScalar(recordvalue->m_NumericValue);
                            mxSetFieldByNumber(plhs[0], i, j, out_double);
                        }
                    }
                    allrows = lastrow;
                    lastrow = lastrow->m_NextValues;
                    delete allrows;
                    i++;
                }
            }
            for(int i=0; i<ncol; i++)
                delete [] fieldnames[i];
            delete [] fieldnames;
        }
        else
        {
			/*
			 * no result, cleanup the sqlite engine
			 */
            int res = sqlite3_step(st);
            sqlite3_finalize(st);

			if (!( plhs[0] = mxCreateDoubleMatrix(0, 0, mxREAL) )) 
			{
                mexErrMsgTxt(MSG_CANTCREATEOUTPUT);
            }

            if (res != SQLITE_DONE)
            {
				mxFree(command);
                mexErrMsgIdAndTxt(TransErrToIdent(g_dbs[db_id]), sqlite3_errmsg(g_dbs[db_id]));
            }            
        }
    }
	mxFree(command);
}
Exemple #15
0
int main(int argc, char **argv) { 

	int i;
	pthread_t p_thread;
	int thr_id;
	int status;

	int rc;

	void *socket_fd;
	//int socket_fd;
	struct sockaddr_in servaddr; //server addr

	// wifi
	struct termios tio, old_tio;
	int ret;
	//sleep(2);

	/******************** DB connect ***********************/
	//char	*szErrMsg;

	// DB Open
	rc = el1000_sqlite3_open( DBPATH, &pSQLite3 );
	if( rc != 0 )
	{
		writeLog( "error DB Open" );
		return -1;
	}
	else
		printf("%s OPEN!!\n", DBPATH);


	//sqlite3_busy_handler( pSQLite3, busy, NULL);
	sqlite3_busy_timeout( pSQLite3, 1000);
	//sqlite3_busy_timeout( pSQLite3, 5000);

	// DB Customize
	rc = el1000_sqlite3_customize( &pSQLite3 );
	if( rc != 0 )
	{
		writeLog( "error DB Customize" );
		return -1;
	}


	/*******************************************************/
	// wifi
	/*
	wifi = open( "/dev/ttyUSB0", O_RDWR, 0);
	if(wifi == -1) {
		perror("open()\n");
		writeLog( "error open /dev/ttyUSB0" );
		return -1;
	}
	memset(&tio, 0, sizeof(tio)); 
	tio.c_iflag = IGNPAR; 
	//tio.c_cflag = B57600 | HUPCL | CS8 | CLOCAL | CREAD; 
	tio.c_cflag = B115200 | HUPCL | CS8 | CLOCAL | CREAD; 
	tio.c_cc[VTIME] = 1;
	tio.c_cc[VMIN] = 0;
	tcgetattr(wifi, &old_tio);
	tcsetattr(wifi, TCSANOW, &tio);
	*/

	/***************** Server Connect **********************/
	if( -1 == ( m2mid = msgget( (key_t)2222, IPC_CREAT | 0666)))
	{
		writeLog( "error msgget() m2mid" );
		//perror( "msgget() 실패");
		return -1;
	}

	if( -1 == ( eventid = msgget( (key_t)3333, IPC_CREAT | 0666)))
	{
		writeLog( "error msgget() eventid" );
		//perror( "msgget() 실패");
		return -1;
	}


	Connect_Manager();

	/*
	while(1) 
	{

		ReadMsgSize = read(wifi, DataBuf, BUFFER_SIZE); 
		if( ReadMsgSize > 0 )
		{
			if( receiveSize >= BUFFER_SIZE )
				continue;

			memcpy( receiveBuffer+receiveSize, DataBuf, ReadMsgSize );
			receiveSize += ReadMsgSize;

			parsingSize = ParsingReceiveValue(receiveBuffer, receiveSize, remainder, parsingSize);
			memset( receiveBuffer, 0 , sizeof(BUFFER_SIZE) );
			receiveSize = 0;
			memcpy( receiveBuffer, remainder, parsingSize );
			receiveSize = parsingSize;

			memset( remainder, 0 , sizeof(BUFFER_SIZE) );
		}			
		else
		{
			//printf("Serial timeout %d\n", ReadMsgSize);
			sleep(1);
		}

	}
	*/


	/*******************************************************/
	el1000_sqlite3_close( &pSQLite3 );

	printf("[M2MManager] end of main loop \n");
	return 0; 
} 
Exemple #16
0
int csync_statedb_load(CSYNC *ctx, const char *statedb, sqlite3 **pdb) {
  int rc = -1;
  c_strlist_t *result = NULL;
  sqlite3 *db = NULL;

  if( !ctx ) {
      return -1;
  }

  if (ctx->statedb.db) {
      CSYNC_LOG(CSYNC_LOG_PRIORITY_NOTICE, "ERR: DB already open");
      ctx->status_code = CSYNC_STATUS_PARAM_ERROR;
      return -1;
  }

  ctx->statedb.lastReturnValue = SQLITE_OK;

  /* Openthe database */
  if (sqlite_open(statedb, &db) != SQLITE_OK) {
    const char *errmsg= sqlite3_errmsg(ctx->statedb.db);
    CSYNC_LOG(CSYNC_LOG_PRIORITY_NOTICE, "ERR: Failed to sqlite3 open statedb - bail out: %s.",
              errmsg ? errmsg : "<no sqlite3 errormsg>");

    rc = -1;
    ctx->status_code = CSYNC_STATUS_STATEDB_LOAD_ERROR;
    goto out;
  }

  if (_csync_check_db_integrity(db) != 0) {
      const char *errmsg= sqlite3_errmsg(db);
      CSYNC_LOG(CSYNC_LOG_PRIORITY_NOTICE, "ERR: sqlite3 integrity check failed - bail out: %s.",
                errmsg ? errmsg : "<no sqlite3 errormsg>");
      rc = -1;
      ctx->status_code = CSYNC_STATUS_STATEDB_CORRUPTED;
      goto out;
  }

  if (_csync_statedb_is_empty(db)) {
    CSYNC_LOG(CSYNC_LOG_PRIORITY_NOTICE, "statedb contents doesn't exist");
    csync_set_statedb_exists(ctx, 0);
  } else {
    csync_set_statedb_exists(ctx, 1);
  }

  /* Print out the version */
  //
  result = csync_statedb_query(db, "SELECT sqlite_version();");
  if (result && result->count >= 1) {
      CSYNC_LOG(CSYNC_LOG_PRIORITY_NOTICE, "sqlite3 version \"%s\"", *result->vector);
  }
  c_strlist_destroy(result);

  /* optimization for speeding up SQLite */
  result = csync_statedb_query(db, "PRAGMA synchronous = NORMAL;");
  c_strlist_destroy(result);
  result = csync_statedb_query(db, "PRAGMA case_sensitive_like = ON;");
  c_strlist_destroy(result);

  /* set a busy handler with 5 seconds timeout */
  sqlite3_busy_timeout(db, 5000);

#ifndef NDEBUG
  sqlite3_profile(db, sqlite_profile, 0 );
#endif
  *pdb = db;

   CSYNC_LOG(CSYNC_LOG_PRIORITY_NOTICE, "Success");

  return 0;
out:
  sqlite3_close(db);
  return rc;
}
Exemple #17
0
/*
   SQLite dbs have no user name, passwords, hosts or ports.
   just file names.
*/
bool QSQLiteDriver::open(const QString & db, const QString &, const QString &, const QString &, int, const QString &conOpts)
{
    if (isOpen())
        close();

    if (db.isEmpty())
        return false;
    bool sharedCache = false;
    int openMode = SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, timeOut=5000;
    QStringList opts=QString(conOpts).remove(QLatin1Char(' ')).split(QLatin1Char(';'));
    foreach(const QString &option, opts) {
        if (option.startsWith(QLatin1String("QSQLITE_BUSY_TIMEOUT="))) {
            bool ok;
            int nt = option.mid(21).toInt(&ok);
            if (ok)
                timeOut = nt;
        }
        if (option == QLatin1String("QSQLITE_OPEN_READONLY"))
            openMode = SQLITE_OPEN_READONLY;
        if (option == QLatin1String("QSQLITE_ENABLE_SHARED_CACHE"))
            sharedCache = true;
    }

    sqlite3_enable_shared_cache(sharedCache);

#ifndef QT_WEBOS
    if (sqlite3_open_v2(db.toUtf8().constData(), &d->access, openMode, NULL) == SQLITE_OK) {
#else // QT_WEBOS
#if SQLITE_VERSION_NUMBER >= 3005000
    if (sqlite3_open_v2(db.toUtf8().constData(), &d->access, openMode, NULL) == SQLITE_OK) {
#else
	if (sqlite3_open(db.toUtf8().constData(), &d->access) == SQLITE_OK) {
#endif
#endif // QT_WEBOS
        sqlite3_busy_timeout(d->access, timeOut);
        setOpen(true);
        setOpenError(false);
        return true;
    } else {
        setLastError(qMakeError(d->access, tr("Error opening database"),
                     QSqlError::ConnectionError));
        setOpenError(true);
        return false;
    }
}

void QSQLiteDriver::close()
{
    if (isOpen()) {
        foreach (QSQLiteResult *result, d->results)
            result->d->finalize();

        if (sqlite3_close(d->access) != SQLITE_OK)
            setLastError(qMakeError(d->access, tr("Error closing database"),
                                    QSqlError::ConnectionError));
        d->access = 0;
        setOpen(false);
        setOpenError(false);
    }
}

QSqlResult *QSQLiteDriver::createResult() const
{
    return new QSQLiteResult(this);
}

bool QSQLiteDriver::beginTransaction()
{
    if (!isOpen() || isOpenError())
        return false;

    QSqlQuery q(createResult());
    if (!q.exec(QLatin1String("BEGIN"))) {
        setLastError(QSqlError(tr("Unable to begin transaction"),
                               q.lastError().databaseText(), QSqlError::TransactionError));
        return false;
    }

    return true;
}

bool QSQLiteDriver::commitTransaction()
{
    if (!isOpen() || isOpenError())
        return false;

    QSqlQuery q(createResult());
    if (!q.exec(QLatin1String("COMMIT"))) {
        setLastError(QSqlError(tr("Unable to commit transaction"),
                               q.lastError().databaseText(), QSqlError::TransactionError));
        return false;
    }

    return true;
}

bool QSQLiteDriver::rollbackTransaction()
{
    if (!isOpen() || isOpenError())
        return false;

    QSqlQuery q(createResult());
    if (!q.exec(QLatin1String("ROLLBACK"))) {
        setLastError(QSqlError(tr("Unable to rollback transaction"),
                               q.lastError().databaseText(), QSqlError::TransactionError));
        return false;
    }

    return true;
}

QStringList QSQLiteDriver::tables(QSql::TableType type) const
{
    QStringList res;
    if (!isOpen())
        return res;

    QSqlQuery q(createResult());
    q.setForwardOnly(true);

    QString sql = QLatin1String("SELECT name FROM sqlite_master WHERE %1 "
                                "UNION ALL SELECT name FROM sqlite_temp_master WHERE %1");
    if ((type & QSql::Tables) && (type & QSql::Views))
        sql = sql.arg(QLatin1String("type='table' OR type='view'"));
    else if (type & QSql::Tables)
        sql = sql.arg(QLatin1String("type='table'"));
    else if (type & QSql::Views)
        sql = sql.arg(QLatin1String("type='view'"));
    else
        sql.clear();

    if (!sql.isEmpty() && q.exec(sql)) {
        while(q.next())
            res.append(q.value(0).toString());
    }

    if (type & QSql::SystemTables) {
        // there are no internal tables beside this one:
        res.append(QLatin1String("sqlite_master"));
    }

    return res;
}

static QSqlIndex qGetTableInfo(QSqlQuery &q, const QString &tableName, bool onlyPIndex = false)
{
    QString schema;
    QString table(tableName);
    int indexOfSeparator = tableName.indexOf(QLatin1Char('.'));
    if (indexOfSeparator > -1) {
        schema = tableName.left(indexOfSeparator).append(QLatin1Char('.'));
        table = tableName.mid(indexOfSeparator + 1);
    }
    q.exec(QLatin1String("PRAGMA ") + schema + QLatin1String("table_info (") + _q_escapeIdentifier(table) + QLatin1String(")"));

    QSqlIndex ind;
    while (q.next()) {
        bool isPk = q.value(5).toInt();
        if (onlyPIndex && !isPk)
            continue;
        QString typeName = q.value(2).toString().toLower();
        QSqlField fld(q.value(1).toString(), qGetColumnType(typeName));
        if (isPk && (typeName == QLatin1String("integer")))
            // INTEGER PRIMARY KEY fields are auto-generated in sqlite
            // INT PRIMARY KEY is not the same as INTEGER PRIMARY KEY!
            fld.setAutoValue(true);
        fld.setRequired(q.value(3).toInt() != 0);
        fld.setDefaultValue(q.value(4));
        ind.append(fld);
    }
    return ind;
}
Exemple #18
0
int
_ds_init_storage (DSPAM_CTX * CTX, void *dbh)
{
  struct _sqlite_drv_storage *s;
  FILE *file;
  char buff[1024];
  char filename[MAX_FILENAME_LENGTH];
  char *err=NULL;
  struct stat st;
  int noexist;

  buff[0] = 0;

  if (CTX == NULL)
    return EINVAL;

  if (CTX->flags & DSF_MERGED) {
    LOG(LOG_ERR, ERR_DRV_NO_MERGED);
    return EINVAL;
  }

  /* don't init if we're already initted */
  if (CTX->storage != NULL)
  {
    LOGDEBUG ("_ds_init_storage: storage already initialized");
    return EINVAL;
  }

  s = malloc (sizeof (struct _sqlite_drv_storage));
  if (s == NULL)
  {
    LOG (LOG_CRIT, ERR_MEM_ALLOC);
    return EUNKNOWN;
  }

  s->dbh = NULL;
  s->control_token = 0;
  s->iter_token = NULL;
  s->iter_sig = NULL;
  s->control_token = 0;
  s->control_sh = 0;
  s->control_ih = 0;
  s->dbh_attached = (dbh) ? 1 : 0;

  if (CTX->group == NULL || CTX->group[0] == 0)
    _ds_userdir_path (filename, CTX->home, CTX->username, "sdb");
  else
    _ds_userdir_path (filename, CTX->home, CTX->group, "sdb");

  _ds_prepare_path_for (filename);

  noexist = stat(filename, &st);

  if (dbh)
    s->dbh = dbh;
  else
    if ((sqlite3_open(filename, &s->dbh))!=SQLITE_OK)
      s->dbh = NULL;
                                                                                
  if (s->dbh == NULL)
  {
    LOGDEBUG
      ("_ds_init_storage: sqlite3_open: unable to initialize database: %s", err);    return EUNKNOWN;
  }

  /* Commit timeout of 20 minutes */
  sqlite3_busy_timeout(s->dbh, 1000 * 60 * 20);

  /* Create database objects */

  if (noexist) {

    sqlite3_exec(s->dbh, 
                "create table dspam_token_data (token char(20) primary key, "
                "spam_hits int, innocent_hits int, last_hit date)",
                NULL,
                NULL,
                &err);

    sqlite3_exec(s->dbh,
                "create index id_token_data_02 on dspam_token_data"
                "(innocent_hits)",
                NULL,
                NULL,
                &err);

    sqlite3_exec(s->dbh,
                "create table dspam_signature_data ("
                "signature char(128) primary key, data blob, created_on date)",
                NULL,
                NULL,
                &err);
                                                                                
    sqlite3_exec(s->dbh,
                "create table dspam_stats (dspam_stat_id int primary key, "
                "spam_learned int, innocent_learned int, "
                "spam_misclassified int, innocent_misclassified int, "
                "spam_corpusfed int, innocent_corpusfed int, "
                "spam_classified int, innocent_classified int)",
                NULL,
                NULL,
                &err);
  }

  if (_ds_read_attribute(CTX->config->attributes, "SQLitePragma")) {
    char pragma[1024];
    attribute_t t = _ds_find_attribute(CTX->config->attributes, "SQLitePragma");
    while(t != NULL) {
      snprintf(pragma, sizeof(pragma), "PRAGMA %s", t->value);
      if ((sqlite3_exec(s->dbh, pragma, NULL, NULL, &err))!=SQLITE_OK)
      {
        LOG(LOG_WARNING, "sqlite.pragma function error: %s: %s", err, pragma);
        _sqlite_drv_query_error (err, pragma);
      }
      t = t->next;
    } 
  } else {
    snprintf(filename, MAX_FILENAME_LENGTH, "%s/sqlite.pragma", CTX->home);
    file = fopen(filename, "r");
    if (file != NULL) {
      while((fgets(buff, sizeof(buff), file))!=NULL) {
        chomp(buff);
        if ((sqlite3_exec(s->dbh, buff, NULL, NULL, &err))!=SQLITE_OK)
        {
          LOG(LOG_WARNING, "sqlite.pragma function error: %s: %s", err, buff);
          _sqlite_drv_query_error (err, buff);
        }
      }
      fclose(file);
    }
  }

  CTX->storage = s;
  s->dir_handles = nt_create (NT_INDEX);

  s->control_token = 0;
  s->control_ih = 0;
  s->control_sh = 0; 

  /* get spam totals on successful init */
  if (CTX->username != NULL)
  {
      if (_sqlite_drv_get_spamtotals (CTX))
      {
        LOGDEBUG ("unable to load totals.  using zero values.");
      }
  }
  else
  {
    memset (&CTX->totals, 0, sizeof (struct _ds_spam_totals));
    memset (&s->control_totals, 0, sizeof (struct _ds_spam_totals));
  }

  return 0;
}
int bwl_init_database(const char *szDatabaseFilePath)
{
    if (SQLITE_OK != sqlite3_config(SQLITE_CONFIG_SERIALIZED))
    {
        LOG("Configure Sqlite3 error:%s.", sqlite3_errmsg(db));
        return BWLIST_ERROR;
    }

    if (SQLITE_OK != sqlite3_open(szDatabaseFilePath, &db))
    {
        LOG("Can't open database:%s.", sqlite3_errmsg(db));
        sqlite3_close(db);
        return BWLIST_ERROR;
    }

    sqlite3_busy_timeout(db, 1);

    //sqlite3_update_hook(db, db_change_hook, NULL);

    if (NULL == (db_mutex = sqlite3_db_mutex(db)))
    {
        LOG("SQLITE IS NOT IN SERIALIZED MOD");
        sqlite3_close(db);
        return BWLIST_ERROR;
    }

    sqlite3_mutex_enter(db_mutex);
    if (SQLITE_OK != sqlite3_exec(db, "PRAGMA page_size=4096;", 0, 0, NULL))
    {
        LOG("Can't set page_size:%s.", sqlite3_errmsg(db));
        sqlite3_mutex_leave(db_mutex);
        sqlite3_close(db);
        return BWLIST_ERROR;
    }

    if (SQLITE_OK != sqlite3_exec(db, "PRAGMA cache_size=8000;", 0, 0, NULL))
    {
        LOG("Can't set cache_size:%s.", sqlite3_errmsg(db));
        sqlite3_mutex_leave(db_mutex);
        sqlite3_close(db);
        return BWLIST_ERROR;
    }

    // if blacklist not exists, create it
    char *sSqlCreateBlacklist = sqlite3_mprintf("CREATE TABLE IF NOT EXISTS %Q"
            "(PlateNumber TEXT NOT NULL PRIMARY KEY, PlateType INTEGER, Comment TEXT);", szBlackListTable);
    int rc_bl = sqlite3_exec(db, sSqlCreateBlacklist, 0, 0, NULL);
    sqlite3_free(sSqlCreateBlacklist);
    if (SQLITE_OK != rc_bl)
    {
        LOG("Create BlackList Error:%s", sqlite3_errmsg(db));
        sqlite3_mutex_leave(db_mutex);
        sqlite3_close(db);
        return BWLIST_ERROR;
    }

    // if whitelist not exists, create it
    char *sSqlCreateWhitelist = sqlite3_mprintf("CREATE TABLE IF NOT EXISTS %Q"
            "(PlateNumber TEXT NOT NULL PRIMARY KEY, PlateType INTEGER, Comment TEXT);", szWhiteListTable);
    int rc_wl = sqlite3_exec(db, sSqlCreateWhitelist, 0, 0, NULL);
    sqlite3_free(sSqlCreateWhitelist);
    if (SQLITE_OK != rc_wl)
    {
        LOG("Create WhiteList error:%s.", sqlite3_errmsg(db));
        sqlite3_mutex_leave(db_mutex);
        sqlite3_close(db);
        return BWLIST_ERROR;
    }

    sqlite3_mutex_leave(db_mutex);

    if (0 != pthread_create(&query_tid, NULL, query_thread, NULL))
    {
        LOG("%s", strerror(errno));
        sqlite3_close(db);
        return BWLIST_ERROR;
    }

    return BWLIST_OK;
}
static jlong nativeOpen(JNIEnv* env, jclass clazz, jstring pathStr, jint openFlags,
        jstring labelStr, jboolean enableTrace, jboolean enableProfile) {
    int sqliteFlags;
    if (openFlags & SQLiteConnection::CREATE_IF_NECESSARY) {
        sqliteFlags = SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE;
    } else if (openFlags & SQLiteConnection::OPEN_READONLY) {
        sqliteFlags = SQLITE_OPEN_READONLY;
    } else {
        sqliteFlags = SQLITE_OPEN_READWRITE;
    }

    const char* pathChars = env->GetStringUTFChars(pathStr, NULL);
    String8 path(pathChars);
    env->ReleaseStringUTFChars(pathStr, pathChars);

    const char* labelChars = env->GetStringUTFChars(labelStr, NULL);
    String8 label(labelChars);
    env->ReleaseStringUTFChars(labelStr, labelChars);

    sqlite3* db;
    int err = sqlite3_open_v2(path.string(), &db, sqliteFlags, NULL);
    if (err != SQLITE_OK) {
        throw_sqlite3_exception_errcode(env, err, "Could not open database");
        return 0;
    }

    // Check that the database is really read/write when that is what we asked for.
    if ((sqliteFlags & SQLITE_OPEN_READWRITE) && sqlite3_db_readonly(db, NULL)) {
        throw_sqlite3_exception(env, db, "Could not open the database in read/write mode.");
        sqlite3_close(db);
        return 0;
    }

    // Set the default busy handler to retry automatically before returning SQLITE_BUSY.
    err = sqlite3_busy_timeout(db, BUSY_TIMEOUT_MS);
    if (err != SQLITE_OK) {
        throw_sqlite3_exception(env, db, "Could not set busy timeout");
        sqlite3_close(db);
        return 0;
    }

    // Register custom Android functions.
    err = register_android_functions(db, UTF16_STORAGE);
    if (err) {
        throw_sqlite3_exception(env, db, "Could not register Android SQL functions.");
        sqlite3_close(db);
        return 0;
    }

    // Create wrapper object.
    SQLiteConnection* connection = new SQLiteConnection(db, openFlags, path, label);

    // Enable tracing and profiling if requested.
    if (enableTrace) {
        sqlite3_trace(db, &sqliteTraceCallback, connection);
    }
    if (enableProfile) {
        sqlite3_profile(db, &sqliteProfileCallback, connection);
    }

    ALOGV("Opened connection %p with label '%s'", db, label.string());
    return reinterpret_cast<jlong>(connection);
}
Exemple #21
0
void CppSQLite3DB::setBusyTimeout(int nMillisecs)
{
    mnBusyTimeoutMs = nMillisecs;
    sqlite3_busy_timeout(mpDB, mnBusyTimeoutMs);
}
Exemple #22
0
DLL_FUNCTION(int32_t) BU_SQLite_Busy_Timeout(sqlite3* db, int32_t timeout) {
#pragma comment(linker, "/EXPORT:BU_SQLite_Busy_Timeout=_BU_SQLite_Busy_Timeout@8")
	return sqlite3_busy_timeout(db, timeout);
}
Exemple #23
0
 int database::set_busy_timeout(int ms)
 {
   return sqlite3_busy_timeout(db_, ms);
 }
Exemple #24
0
int main(void)
{
	printf("Open C DLL Test for sqlite!\n");
	printf("Sqlite Version %s!\n", sqlite3_libversion());
	
/*	FILE *fp = fopen("C:\\data\\redfivelabs\\temp\\test.txt", "a+b");
	if (fp != NULL)
		{
			printf("File opened.\n");
			char *test= "Hallo Welt";
			fwrite(test, strlen(test), 1, fp);
			fclose(fp);
			printf("File closed.\n");
		}
	else
		{
			printf("File cannot be opened.");
		}*/
	sqlite3 *db = NULL;
	int result = sqlite3_open("C:\\data\\redfivelabs\\temp\\test.sqlite", &db);
			
	printf("result = %d\n", result);

//	printf("result = %d\n", sqlite3_openTest("C:\\data\\redfivelabs\\temp\\test2.sqlite"));
	char tmp [512];
	char sql[512];
	char *ptr = tmp;
	result = sqlite3_exec(db, "pragma synchronous = off", NULL, NULL, &ptr);
	printf("result of sqlite3_exec = %d\n", result);

	strcpy(sql, "create table mytable (src_text, dst_float, time_float, value_float)");
	sqlite3_stmt *statement = NULL;
	result = sqlite3_prepare(db, (const char*)sql, (int)strlen(sql), &statement, (const char **)&ptr);
	printf("result of sqlite3_prepare = %d\n", result);
	result = sqlite3_busy_timeout(db, 60000);
	printf("result of sqlite3_busy_timeout = %d\n", result);
	result = sqlite3_step(statement);
	printf("result of sqlite3_step = %d\n", result);
	result = sqlite3_finalize(statement);
	printf("result of sqlite3_finalize = %d\n", result);

	result = sqlite3_exec(db, "begin transaction", NULL, NULL, &ptr);
	printf("result of sqlite3_exec = %d\n", result);

	strcpy(sql, "insert into mytable values ('Hallo Welt', 1, 2, 3)");
	result = sqlite3_prepare(db, (const char*)sql, (int)strlen(sql), &statement, (const char **)&ptr);
	printf("result of sqlite3_prepare = %d\n", result);
	result = sqlite3_busy_timeout(db, 60000);
	printf("result of sqlite3_busy_timeout = %d\n", result);
	result = sqlite3_step(statement);
	printf("result of sqlite3_step = %d\n", result);

	result = sqlite3_exec(db, "commit transaction", NULL, NULL, &ptr);
	printf("result of sqlite3_exec = %d\n", result);

	result = sqlite3_finalize(statement);
	printf("result of sqlite3_finalize = %d\n", result);

	result = sqlite3_close(db);
	printf("result of sqlite3_close = %d\n", result);

	printf("Press a character to exit!");
	int c = getchar();
	return 0;
}
Exemple #25
0
	void SQLiteDB::initialize() { 
		execute("pragma auto_vacuum = 1");
		execute("pragma encoding = \"UTF-8\"");
		sqlite3_busy_timeout(db_, 100);
	}
Exemple #26
0
/* public native void dbopen(String path, int flags, String locale); */
static void dbopen(JNIEnv* env, jobject object, jstring pathString, jint flags)
{
    int err;
    sqlite3 * handle = NULL;
    sqlite3_stmt * statement = NULL;
    char const * path8 = env->GetStringUTFChars(pathString, NULL);
    int sqliteFlags;
    // Error code handling for SQLite exec
    char* zErrMsg = NULL;

    // register the logging func on sqlite. needs to be done BEFORE any sqlite3 func is called.
    registerLoggingFunc(path8);

    // convert our flags into the sqlite flags
    if (flags & CREATE_IF_NECESSARY) {
        sqliteFlags = SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE;
    } else if (flags & OPEN_READONLY) {
        sqliteFlags = SQLITE_OPEN_READONLY;
    } else {
        sqliteFlags = SQLITE_OPEN_READWRITE;
    }

    err = sqlite3_open_v2(path8, &handle, sqliteFlags, NULL);
    if (err != SQLITE_OK) {
        LOGE("sqlite3_open_v2(\"%s\", &handle, %d, NULL) failed\n", path8, sqliteFlags);
        throw_sqlite3_exception(env, handle);
        goto done;
    }

    // WAL is a new rollback method available in SQLite v3.7+. WAL speeds up writes to
    // SQLite databases. WAL cannot be used with Read Only databases or databases opened
    // in read only mode.

    // Check if DB can use WAL mode; Open in WAL mode for non-ReadOnly DBs
    if(!(flags & OPEN_READONLY) && (use_wal_mode(path8))) {
        // Configure databases to run in WAL mode.
        err = sqlite3_exec(handle,"PRAGMA journal_mode = WAL;",
                           NULL, NULL,&zErrMsg);
        if (SQLITE_OK != err) {
           LOGE("sqlite3_exec - Failed to set WAL mode for [%s] \n", path8);
           err = sqlite3_exec(handle,"PRAGMA journal_mode = DELETE;",
                           NULL, NULL,&zErrMsg);
           if(SQLITE_OK != err) {
               LOGE("sqlite3_exec - Failed to set DELETE mode for [%s] \n", path8);
               throw_sqlite3_exception(env, handle);
               goto done;
           }
        }
        else {
            LOGI("WAL succesfuly enabled for [%s] \n", path8);
            // Set autocheckpoint = 100 pages
            err = sqlite3_wal_autocheckpoint(handle,
                                             100);
            if (SQLITE_OK != err) {
               LOGE("sqlite3_exec to set WAL autocheckpoint failed\n");
               throw_sqlite3_exception(env, handle);
               goto done;
            } else if (use_wal_mode(path8) == 2) {
                /* Try to disable fsyncs. We don't care if it fails */
                sqlite3_exec(handle,"PRAGMA synchronous = OFF;",
                           NULL, NULL,&zErrMsg);
            }
        }
    }

    // The soft heap limit prevents the page cache allocations from growing
    // beyond the given limit, no matter what the max page cache sizes are
    // set to. The limit does not, as of 3.5.0, affect any other allocations.
    sqlite3_soft_heap_limit(SQLITE_SOFT_HEAP_LIMIT);

    // Set the default busy handler to retry for 1000ms and then return SQLITE_BUSY
    err = sqlite3_busy_timeout(handle, 1000 /* ms */);
    if (err != SQLITE_OK) {
        LOGE("sqlite3_busy_timeout(handle, 1000) failed for \"%s\"\n", path8);
        throw_sqlite3_exception(env, handle);
        goto done;
    }

#ifdef DB_INTEGRITY_CHECK
    static const char* integritySql = "pragma integrity_check(1);";
    err = sqlite3_prepare_v2(handle, integritySql, -1, &statement, NULL);
    if (err != SQLITE_OK) {
        LOGE("sqlite_prepare_v2(handle, \"%s\") failed for \"%s\"\n", integritySql, path8);
        throw_sqlite3_exception(env, handle);
        goto done;
    }

    // first is OK or error message
    err = sqlite3_step(statement);
    if (err != SQLITE_ROW) {
        LOGE("integrity check failed for \"%s\"\n", integritySql, path8);
        throw_sqlite3_exception(env, handle);
        goto done;
    } else {
        const char *text = (const char*)sqlite3_column_text(statement, 0);
        if (strcmp(text, "ok") != 0) {
            LOGE("integrity check failed for \"%s\": %s\n", integritySql, path8, text);
            jniThrowException(env, "android/database/sqlite/SQLiteDatabaseCorruptException", text);
            goto done;
        }
    }
#endif

    err = register_android_functions(handle, UTF16_STORAGE);
    if (err) {
        throw_sqlite3_exception(env, handle);
        goto done;
    }

    LOGV("Opened '%s' - %p\n", path8, handle);
    env->SetIntField(object, offset_db_handle, (int) handle);
    handle = NULL;  // The caller owns the handle now.

done:
    // Release allocated resources
    if (path8 != NULL) env->ReleaseStringUTFChars(pathString, path8);
    if (statement != NULL) sqlite3_finalize(statement);
    if (handle != NULL) sqlite3_close(handle);
}
Exemple #27
0
/**
 * @brief Set a busy handler that sleeps for a specified amount of time when a table is locked.
 *
 *  This is useful in multithreaded program to handle case where a table is locked for writting by a thread.
 *  Any other thread cannot access the table and will receive a SQLITE_BUSY error:
 *  setting a timeout will wait and retry up to the time specified before returning this SQLITE_BUSY error.
 *  Reading the value of timeout for current connection can be done with SQL query "PRAGMA busy_timeout;".
 *  Default busy timeout is 0ms.
 *
 * @param[in] aBusyTimeoutMs    Amount of milliseconds to wait before returning SQLITE_BUSY
 *
 * @throw SQLite::Exception in case of error
 */
void Database::setBusyTimeout(const int aBusyTimeoutMs)
{
    const int ret = sqlite3_busy_timeout(mpSQLite, aBusyTimeoutMs);
    check(ret);
}
Exemple #28
0
int pysqlite_connection_init(pysqlite_Connection* self, PyObject* args, PyObject* kwargs)
{
    static char *kwlist[] = {
        "database", "timeout", "detect_types", "isolation_level",
        "check_same_thread", "factory", "cached_statements", "uri",
        NULL
    };

    char* database;
    int detect_types = 0;
    PyObject* isolation_level = NULL;
    PyObject* factory = NULL;
    int check_same_thread = 1;
    int cached_statements = 100;
    int uri = 0;
    double timeout = 5.0;
    int rc;

    if (!PyArg_ParseTupleAndKeywords(args, kwargs, "s|diOiOip", kwlist,
                                     &database, &timeout, &detect_types,
                                     &isolation_level, &check_same_thread,
                                     &factory, &cached_statements, &uri))
    {
        return -1;
    }

    self->initialized = 1;

    self->begin_statement = NULL;

    self->statement_cache = NULL;
    self->statements = NULL;
    self->cursors = NULL;

    Py_INCREF(Py_None);
    self->row_factory = Py_None;

    Py_INCREF(&PyUnicode_Type);
    self->text_factory = (PyObject*)&PyUnicode_Type;

#ifdef SQLITE_OPEN_URI
    Py_BEGIN_ALLOW_THREADS
    rc = sqlite3_open_v2(database, &self->db,
                         SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE |
                         (uri ? SQLITE_OPEN_URI : 0), NULL);
#else
    if (uri) {
        PyErr_SetString(pysqlite_NotSupportedError, "URIs not supported");
        return -1;
    }
    Py_BEGIN_ALLOW_THREADS
    rc = sqlite3_open(database, &self->db);
#endif
    Py_END_ALLOW_THREADS

    if (rc != SQLITE_OK) {
        _pysqlite_seterror(self->db, NULL);
        return -1;
    }

    if (!isolation_level) {
        isolation_level = PyUnicode_FromString("");
        if (!isolation_level) {
            return -1;
        }
    } else {
        Py_INCREF(isolation_level);
    }
    self->isolation_level = NULL;
    if (pysqlite_connection_set_isolation_level(self, isolation_level) < 0) {
        Py_DECREF(isolation_level);
        return -1;
    }
    Py_DECREF(isolation_level);

    self->statement_cache = (pysqlite_Cache*)PyObject_CallFunction((PyObject*)&pysqlite_CacheType, "Oi", self, cached_statements);
    if (PyErr_Occurred()) {
        return -1;
    }

    self->created_statements = 0;
    self->created_cursors = 0;

    /* Create lists of weak references to statements/cursors */
    self->statements = PyList_New(0);
    self->cursors = PyList_New(0);
    if (!self->statements || !self->cursors) {
        return -1;
    }

    /* By default, the Cache class INCREFs the factory in its initializer, and
     * decrefs it in its deallocator method. Since this would create a circular
     * reference here, we're breaking it by decrementing self, and telling the
     * cache class to not decref the factory (self) in its deallocator.
     */
    self->statement_cache->decref_factory = 0;
    Py_DECREF(self);

    self->inTransaction = 0;
    self->detect_types = detect_types;
    self->timeout = timeout;
    (void)sqlite3_busy_timeout(self->db, (int)(timeout*1000));
#ifdef WITH_THREAD
    self->thread_ident = PyThread_get_thread_ident();
#endif
    self->check_same_thread = check_same_thread;

    self->function_pinboard = PyDict_New();
    if (!self->function_pinboard) {
        return -1;
    }

    self->collations = PyDict_New();
    if (!self->collations) {
        return -1;
    }

    self->Warning               = pysqlite_Warning;
    self->Error                 = pysqlite_Error;
    self->InterfaceError        = pysqlite_InterfaceError;
    self->DatabaseError         = pysqlite_DatabaseError;
    self->DataError             = pysqlite_DataError;
    self->OperationalError      = pysqlite_OperationalError;
    self->IntegrityError        = pysqlite_IntegrityError;
    self->InternalError         = pysqlite_InternalError;
    self->ProgrammingError      = pysqlite_ProgrammingError;
    self->NotSupportedError     = pysqlite_NotSupportedError;

    return 0;
}
Exemple #29
0
int main(int argc, char **argv)
{
	extern int optind;
	int c = 0;
	int all = 0;
	int group = 0;
	int reverse = 0;
	int running = 0;
	int rows = 0;
	int col = 0;
	int limit = -1;
	char select[4096];
	char header[BUFSIZ];
	char css_buffer[BUFSIZ];
	char *ip = (char *) 0;
	char *from = (char *) 0;
	char *to = (char *) 0;
	time_t current_time;
	struct tm *t;
	FILE *css_file;

	sqlite3 *db;
	sqlite3_stmt *statement;

	memset(select, '\0', sizeof(select));
	strncpy(progname, argv[0], sizeof(progname) - 1);

	init_options();

	if(load_config(EASHD_CONFIG) < 0)
		exit(EXIT_FAILURE);

	if(sql_init_db(option.sessiondb) < 0)
		exit(EXIT_FAILURE);

	while((c = getopt(argc, argv, "ac:f:g?hi:l:t:rwvV")) != EOF)
	{
		switch(c)
		{
			case 'a':
				all = 1;
				break;
			case 'c':
				css = strdup(optarg);
				break;
			case 'f':
				from = strdup(optarg);
				break;
			case 'g':
				group = 1;
				break;
			case 'i':
				ip = strdup(optarg);
				break;
			case 'h':
			case '?':
				fprintf(stdout, "Usage: %.63s [-a] [-c css] [-f from] [-gh] [-i IP] [-l limit] [-t to] [-rwv]\n", basename(progname));
				fprintf(stdout, "Enterprise Audit Shell Report\n\n");
				fprintf(stdout, " -a\tshow all sessions.\n");
				fprintf(stdout, " -c\tpoint to another css file.\n");
				fprintf(stdout, " -f\tlimit records by the 'From' field.  E.g. `%.63s -f root'\n", basename(progname));
				fprintf(stdout, " -g\tgroup by username.\n");
				fprintf(stdout, " -h\tdisplay this help synopsis.\n");
				fprintf(stdout, " -i\tlimit records by the 'IP' field.  E.g. `%.63s -i 127.0.0.1'\n", basename(progname));
				fprintf(stdout, " -l\tlimit the number of records in general. E.g. `%.63s -l 10'\n", basename(progname));
				fprintf(stdout, " -t\tlimit records by the 'To' field.  E.g. `%.63s -t root'\n", basename(progname));
				fprintf(stdout, " -r\treverse sort.\n");
				fprintf(stdout, " -v\tdisplay version information.\n");
				exit(EXIT_SUCCESS);
				break;
			case 'l':
				limit = atoi(optarg);
				break;
			case 't':
				to = strdup(optarg);
				break;
			case 'r':
				reverse = 1;
				break;
			case 'v':
			case 'V':
				print_version(&option, *argv);
				exit(EXIT_SUCCESS);
				break;
			default:
				fprintf(stderr, "Try `%.63s -h' for more information.\n", basename(progname));
				exit(EXIT_FAILURE);
				break;
		}
	}

	argc -= optind;
	argv += optind;

	if(*argv)
	{
		exit(detail_report(atoi(*argv)));
	}

	if(sqlite3_open(option.sessiondb, &db))
	{
		fprintf(stderr, "sqlite3_open: %.100s", sqlite3_errmsg(db));
		exit(EXIT_FAILURE);
	}

	snprintf(select, sizeof(select) - 1,
		"SELECT created,real_pw_name,original_pw_name,ip,id,stype,status,file_session,hash_session FROM USER WHERE status != ? %.63s%.63s%.63s%.63s LIMIT ?;",
		ip ? "AND ip=? " : "",
		from ? "AND original_pw_name=? " : "",
		to ? "AND real_pw_name=? " : "",
		group ? 
			reverse ? 
				"ORDER BY original_pw_name DESC,created DESC,ip " : "ORDER BY original_pw_name ASC,created ASC,ip "
			:
			reverse ? 
				"ORDER BY created DESC,original_pw_name,ip " : "ORDER BY created ASC,original_pw_name,ip ");

	sqlite3_busy_timeout(db, 2000);

	if(sqlite3_prepare(db, select, -1, &statement, NULL) != SQLITE_OK)
	{
		fprintf(stderr, "sqlite3_prepare: %.100s\n", sqlite3_errmsg(db));
		sqlite3_close(db);
		exit(EXIT_FAILURE);
	}

	col = 1;

	sqlite3_bind_text(statement, col++, "R", -1, SQLITE_TRANSIENT);

	if(ip)
		sqlite3_bind_text(statement, col++, ip, -1, SQLITE_TRANSIENT);
	if(from)
		sqlite3_bind_text(statement, col++, from, -1, SQLITE_TRANSIENT);
	if(to)
		sqlite3_bind_text(statement, col++, to, -1, SQLITE_TRANSIENT);

	sqlite3_bind_int(statement, col++, limit);

	if((css_file = fopen(css ? css : "/etc/eas/css/report.css", "r")) == (FILE *) 0)
	{
		fprintf(stderr, "%.63s: %.127s: %.100s (%i)\n", basename(progname), css ? css : "/etc/eas/css/report.css", strerror(errno), errno);
		sqlite3_close(db);
		exit(EXIT_FAILURE);
	}

	current_time = time(0);
	t = localtime(&current_time);

	/* ISO8601 */
	strftime(header, sizeof(header) - 1, "%Y-%m-%d %H:%M:%S", t);
	
	fprintf(stdout, "<!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.01//EN\">\n");
	fprintf(stdout, "<html>\n");
	fprintf(stdout, "<head>\n");
	fprintf(stdout, "<title>%.127s</title>\n", header);
	fprintf(stdout, "<meta http-equiv=\"Content-Type\" content=\"text/html; charset=iso-8859-1\">\n");

	memset(css_buffer, '\0', sizeof(css_buffer));
	while(fgets(css_buffer, sizeof(css_buffer) - 1, css_file))
	{
		fprintf(stdout, css_buffer);
		memset(css_buffer, '\0', sizeof(css_buffer));
	}
	fclose(css_file);

	fprintf(stdout, "</head>\n");
	fprintf(stdout, "<body>\n");
	fprintf(stdout, "<h2>Enterprise Audit Shell Audit Report</h2>\n");
	fprintf(stdout, "<h3>%.127s</h3>\n", header);
	fprintf(stdout, "<table cellspacing=\"0\" summary=\"Enterprise Audit Shell Report - %s\">\n", header);
	fprintf(stdout, "<thead>\n");
	fprintf(stdout, "<tr>\n");
	fprintf(stdout, "\t<th class=\"hdate\">Date</th>\n");
	fprintf(stdout, "\t<th class=\"hfrom\">From</th>\n");
	fprintf(stdout, "\t<th class=\"hto\">To</th>\n");
	fprintf(stdout, "\t<th class=\"hip\">IP</th>\n");
	fprintf(stdout, "\t<th class=\"htype\">Type</th>\n");
	fprintf(stdout, "\t<th class=\"hsignature\">Signature</th>\n");
	fprintf(stdout, "\t<th class=\"hrowid\">ID</th>\n");
	fprintf(stdout, "</tr>\n");
	fprintf(stdout, "</thead>\n");
	fprintf(stdout, "<tbody>\n");

	running = 1;

	while(running)
	{
		int OK = 0;
		char type[BUFSIZ];

		memset(type, '\0', sizeof(type));

		switch(sqlite3_step(statement))
		{
			case SQLITE_DONE:
				running = 0;
				break;
			case SQLITE_ROW:
				rows++;
				/*
				 * 0 created
				 * 1 real_pw_name
				 * 2 original_pw_name
				 * 3 ip
				 * 4 id
				*/

				memset(client.cid.created, '\0', sizeof(client.cid.created));
				memset(client.cid.real_pw_name, '\0', sizeof(client.cid.real_pw_name));
				memset(client.cid.original_pw_name, '\0', sizeof(client.cid.original_pw_name));
				memset(client.cid.ip, '\0', sizeof(client.cid.ip));
				memset(client.cid.type, '\0', sizeof(client.cid.type));
				memset(client.cid.status, '\0', sizeof(client.cid.status));
				memset(client.cid.file_session, '\0', sizeof(client.cid.file_session));
				memset(client.cid.hash_session, '\0', sizeof(client.cid.hash_session));

				if(sqlite3_column_text(statement, 0))
					strncpy(client.cid.created, (char *) sqlite3_column_text(statement, 0),
						sizeof(client.cid.created) - 1);
				if(sqlite3_column_text(statement, 1))
					strncpy(client.cid.real_pw_name, (char *) sqlite3_column_text(statement, 1),
						sizeof(client.cid.real_pw_name) - 1);
				if(sqlite3_column_text(statement, 2))
					strncpy(client.cid.original_pw_name, (char *) sqlite3_column_text(statement, 2),
						sizeof(client.cid.original_pw_name) - 1);
				if(sqlite3_column_text(statement, 3))
					strncpy(client.cid.ip, (char *) sqlite3_column_text(statement, 3),
						sizeof(client.cid.ip) - 1);

				client.cid.rowid = sqlite3_column_int(statement, 4);

				if(sqlite3_column_text(statement, 5))
					strncpy(client.cid.type, (char *) sqlite3_column_text(statement, 5),
						sizeof(client.cid.type) - 1);
				if(sqlite3_column_text(statement, 6))
					strncpy(client.cid.status, (char *) sqlite3_column_text(statement, 6),
						sizeof(client.cid.status) - 1);
				if(sqlite3_column_text(statement, 7))
					strncpy(client.cid.file_session, (char *) sqlite3_column_text(statement, 7),
						sizeof(client.cid.file_session) - 1);
				if(sqlite3_column_text(statement, 8))
					strncpy(client.cid.hash_session, (char *) sqlite3_column_text(statement, 8),
						sizeof(client.cid.hash_session) - 1);

				if(create_SHA1(client.cid.file_session, option.strict_inode, option.strict_mode, option.strict_owner, option.strict_ctime, option.strict_mtime))
				{
					char a[BUFSIZ];

					strncpy(a, create_SHA1(client.cid.file_session, option.strict_inode, option.strict_mode, option.strict_owner, option.strict_ctime, option.strict_mtime), sizeof(a) - 1);

					if(!strcmp(a, client.cid.hash_session))
						OK = 1;
					else
						OK = 0;
				}
				else
				{
					OK = 0;
				}

				if(!strcmp(client.cid.type, "SESSION"))
					strcpy(type, "Session");
				else if(!strcmp(client.cid.type, "COMMAND"))
					strcpy(type, "Command");
				else if(!strcmp(client.cid.type, "LOGIN"))
					strcpy(type, "Login");
				else
					strcpy(type, "Unknown");

				fprintf(stdout, "<tr class=\"%.63s\">\n", rows % 2 ? "odd" : "even");
				fprintf(stdout, "\t<th class=\"date\">%.19s</th>\n", client.cid.created);
				fprintf(stdout, "\t<td class=\"from\">%.15s</td>\n", client.cid.original_pw_name);
				fprintf(stdout, "\t<td class=\"to\">%.15s</td>\n", client.cid.real_pw_name);
				fprintf(stdout, "\t<td class=\"ip\">%.15s</td>\n", client.cid.ip);
				fprintf(stdout, "\t<td class=\"type\">%.15s</td>\n", type);
				fprintf(stdout, "\t<td class=\"%.63s\">%.32s</td>\n", OK ? "verified" : "invalid", OK ? "Verified" : "Invalid");
				fprintf(stdout, "\t<td class=\"rowid\">%.9i</td>\n", client.cid.rowid);
				fprintf(stdout, "</tr>\n");
				break;
			default:
				running = 0;
				fprintf(stderr, "sqlite3_step: %.100s\n", sqlite3_errmsg(db));
				break;
		}
	}

	sqlite3_finalize(statement);
	sqlite3_close(db);

	if(rows == 0)
		fprintf(stdout, "<tr>\n\t<td class=\"norows\" colspan=7>No sessions found for the criteria.</td>\n</tr>");

	fprintf(stdout, "<tr>\n");
	fprintf(stdout, "\t<th class=\"empty\">&nbsp;</th>\n");
	fprintf(stdout, "\t<th class=\"total\" colspan=6>&nbsp;</th>\n");
	fprintf(stdout, "</tr>\n");
	fprintf(stdout, "<tbody>\n");
	fprintf(stdout, "</table>\n");
	fprintf(stdout, "</body>\n");
	fprintf(stdout, "</html>\n");

	exit(EXIT_SUCCESS);
}
Exemple #30
0
void
O2DatDB::
update(O2DatRecList &in)
{
#if TRACE_SQL_EXEC_TIME
	stopwatch sw("update by reclist");
#endif

	sqlite3 *db = NULL;
	sqlite3_stmt *stmt_insert = NULL;
	sqlite3_stmt *stmt_update = NULL;
	sqlite3_stmt *stmt_updatepublish = NULL;
	O2DatRec org;

	int err = sqlite3_open16(dbfilename.c_str(), &db);
	if (err != SQLITE_OK)
		goto error;
	sqlite3_busy_timeout(db, 5000);

	wchar_t *sql_insert =
		L"insert or replace into dat ("
		COLUMNS
		L") values ("
		L"?,?,?,?,?,?,?,?,?,?,?"
		L");";
	err = sqlite3_prepare16_v2(db, sql_insert, wcslen(sql_insert)*2, &stmt_insert, NULL);
	if (err != SQLITE_OK)
		goto error;

	wchar_t *sql_update =
		L"update or replace dat"
		L"   set size        = ?"
		L"     , disksize    = ?"
		L"     , url         = ?"
		L"     , res	     = ?"
		L"     , lastupdate  = ?"
//		L"     , lastpublish = 0"
		L" where hash = ?;";

	err = sqlite3_prepare16_v2(db, sql_update, wcslen(sql_update)*2, &stmt_update, NULL);
	if (err != SQLITE_OK)
		goto error;

	wchar_t *sql_updatepublish =
		L"update or replace dat"
		L"   set lastpublish = ?"
		L" where hash = ?;";

	err = sqlite3_prepare16_v2(db, sql_updatepublish, wcslen(sql_updatepublish)*2, &stmt_updatepublish, NULL);
	if (err != SQLITE_OK)
		goto error;

	//
	//	Loop
	//
	sqlite3_exec(db, "begin;", NULL, NULL, NULL);
	for (O2DatRecListIt it = in.begin(); it != in.end(); it++) {
		if (!select(org, it->hash)) {
			sqlite3_reset(stmt_insert);
			if (!bind(db, stmt_insert, 1, it->hash))
				goto error;
			if (!bind(db, stmt_insert, 2, it->domain))
				goto error;
			if (!bind(db, stmt_insert, 3, it->bbsname))
				goto error;
			if (!bind(db, stmt_insert, 4, it->datname))
				goto error;
			if (!bind(db, stmt_insert, 5, it->size))
				goto error;
			if (!bind(db, stmt_insert, 6, it->disksize))
				goto error;
			if (!bind(db, stmt_insert, 7, it->url))
				goto error;
			if (!bind(db, stmt_insert, 8, it->title))
				goto error;
			if (!bind(db, stmt_insert, 9, it->res))
				goto error;
			if (!bind(db, stmt_insert, 10, time(NULL)))
				goto error;
			if (!bind(db, stmt_insert, 11, (uint64)0))
				goto error;

			err = sqlite3_step(stmt_insert);
			if (err != SQLITE_ROW && err != SQLITE_DONE)
				goto error;
		}
		else if (it->userdata == 0) {
			sqlite3_reset(stmt_update);
			if (!bind(db, stmt_update, 1, it->size))
				goto error;
			if (!bind(db, stmt_update, 2, it->disksize))
				goto error;
			if (!bind(db, stmt_update, 3, (wcsstr(org.url.c_str(), L"xxx") == 0 ? it->url : org.url)))
				goto error;
			if (!bind(db, stmt_update, 4, it->res))
				goto error;
			if (!bind(db, stmt_update, 5, time(NULL)))
				goto error;
//			if (!bind(db, stmt_update, 6, (uint64)0))
//				goto error;

			err = sqlite3_step(stmt_update);
			if (err != SQLITE_ROW && err != SQLITE_DONE)
				goto error;
		}
		else {
			sqlite3_reset(stmt_updatepublish);
			if (!bind(db, stmt_updatepublish, 1, time(NULL)))
				goto error;
			if (!bind(db, stmt_updatepublish, 2, it->hash))
				goto error;

			err = sqlite3_step(stmt_updatepublish);
			if (err != SQLITE_ROW && err != SQLITE_DONE)
				goto error;
		}
		Sleep(1);
	}
	sqlite3_exec(db, "commit;", NULL, NULL, NULL);

	sqlite3_finalize(stmt_insert);
	sqlite3_finalize(stmt_update);
	sqlite3_finalize(stmt_updatepublish);
	stmt_insert = NULL;
	stmt_update = NULL;
	stmt_updatepublish = NULL;

	err = sqlite3_close(db);
	if (err != SQLITE_OK)
		goto error;

	return;

error:
	log(db);
	if (stmt_insert) sqlite3_finalize(stmt_insert);
	if (stmt_update) sqlite3_finalize(stmt_update);
	if (stmt_updatepublish) sqlite3_finalize(stmt_updatepublish);
	if (db) sqlite3_close(db);
	return;
}