Ejemplo n.º 1
0
int Database::Query::exec()
{
	sqlite3* db = getSqlite3();
	if (db == NULL)
		NIT_THROW_FMT(EX_INVALID_STATE, "can't exec : database closed");

	int pre = sqlite3_total_changes(db);
	while (step())
	{
	}

	return sqlite3_total_changes(db) - pre;;
}
Ejemplo n.º 2
0
int SQLiteDatabase::lastChanges()
{
    if (!m_db)
        return 0;

    return sqlite3_total_changes(m_db) - m_lastChangesCount;
}
Ejemplo n.º 3
0
void SQLiteDatabase::updateLastChangesCount()
{
    if (!m_db)
        return;

    m_lastChangesCount = sqlite3_total_changes(m_db);
}
Ejemplo n.º 4
0
/**
@SYMTestCaseID			SYSLIB-SQLITE3-UT-4001
@SYMTestCaseDesc		sqlite3_exec() tests.
						List of called SQLITE3 functions:
						 - sqlite3_exec;
						 - sqlite3_errcode;
						 - sqlite3_errmsg;
						 - sqlite3_last_insert_rowid;
						 - sqlite3_changes;
						 - sqlite3_total_changes;
						 - sqlite3_get_autocommit;
@SYMTestPriority		High
@SYMTestActions			sqlite3_exec() tests.
@SYMTestExpectedResults Test must not fail
@SYMREQ					REQ8782
*/
static void TestExec()
	{
	int err;
	sqlite_int64 lastrowid;
	int val;
	
	TEST(TheDb != 0);
	
	err = sqlite3_exec(TheDb, "CREATE TABLE A(F1 INTEGER, F2 BIGINT, F3 REAL, F4 TEXT, F5 BLOB)", &exec_callback, 0, 0);
	TEST2(err, SQLITE_OK);
	
	err = sqlite3_exec(TheDb, "INSERT INTO A VALUES(1, 1234567891234, 56.12, 'TEXT', x'313233343536')", &exec_callback, 0, 0);
	TEST2(err, SQLITE_OK);
	
	err = sqlite3_errcode(TheDb);
	TEST2(err, SQLITE_OK);
	
	(void)sqlite3_errmsg(TheDb);
	
	lastrowid = sqlite3_last_insert_rowid(TheDb);
	TEST(lastrowid > 0LL);
	
	val = sqlite3_changes(TheDb);
	TEST2(val, 1);
	
	val = sqlite3_total_changes(TheDb);
	TEST(val >= 1);
	
	val = sqlite3_get_autocommit(TheDb);
	TEST(val != 0);
	}
Ejemplo n.º 5
0
/* call-seq: total_changes
 *
 * Returns the total number of changes made to this database instance
 * since it was opened.
 */
static VALUE total_changes(VALUE self)
{
  sqlite3RubyPtr ctx;
  Data_Get_Struct(self, sqlite3Ruby, ctx);
  REQUIRE_OPEN_DB(ctx);

  return INT2NUM((long)sqlite3_total_changes(ctx->db));
}
Ejemplo n.º 6
0
/*
** Implementation of the total_changes() SQL function.  The return value is
** the same as the sqlite3_total_changes() API function.
*/
static void total_changes(
  sqlite3_context *context,
  int arg,
  sqlite3_value **argv
){
  sqlite3 *db = sqlite3_user_data(context);
  sqlite3_result_int(context, sqlite3_total_changes(db));
}
Ejemplo n.º 7
0
int main(int argc, char **argv)
{
	sqlite3 *db;
	sqlite3_stmt *plineInfo = 0;
	char *line = NULL;
	size_t len = 0;
	ssize_t read;

	//  char *zErrMsg = 0;
	int rc, i;

	if (argc < 2) {
		fprintf(stderr, "Usage: %s DATABASE < SQL-STATEMENT(S)\n",
			argv[0]);
		exit(1);
	}

	if (sqlite3_open(argv[1], &db) != SQLITE_OK) {
		fprintf(stderr, "Can't open database: \n");
		sqlite3_close(db);
		exit(1);
	}







	while ((read = getline(&line, &len, stdin)) != -1) {

		rc = sqlite3_prepare(db, line, -1, &plineInfo, 0);
		if (rc == SQLITE_OK && plineInfo != NULL ) {
			while ((rc =
				sqlite3_step(plineInfo)) == SQLITE_ROW) {
				//
				for (i = 0;
				     i < sqlite3_column_count(plineInfo);
				     ++i)
					print_col(plineInfo, i);

				printf("\n");

			}
			rc = sqlite3_finalize(plineInfo);
		}


		fprintf(stderr, "Total Changes %d\n",
			sqlite3_total_changes(db));
	}
	if (line) {
		free(line);
	}
	sqlite3_close(db);
	return 0;
}
Ejemplo n.º 8
0
/*
** Implementation of the total_changes() SQL function.  The return value is
** the same as the sqlite3_total_changes() API function.
*/
static void total_changes(
  sqlite3_context *context,
  int NotUsed,
  sqlite3_value **NotUsed2
){
  sqlite3 *db = sqlite3_context_db_handle(context);
  UNUSED_PARAMETER2(NotUsed, NotUsed2);
  sqlite3_result_int(context, sqlite3_total_changes(db));
}
Ejemplo n.º 9
0
/*
** Implementation of the total_changes() SQL function.  The return value is
** the same as the sqlite3_total_changes() API function.
*/
static void total_changes(
  sqlite3_context *context,
  int NotUsed,
  sqlite3_value **NotUsed2
){
  sqlite3 *db = sqlite3_context_db_handle(context);
  UNUSED_PARAMETER2(NotUsed, NotUsed2);
  /* IMP: R-52756-41993 This function is a wrapper around the
  ** sqlite3_total_changes() C/C++ interface. */
  sqlite3_result_int(context, sqlite3_total_changes(db));
}
SWIGEXPORT jint JNICALL Java_com_almworks_sqlite4java__1SQLiteSwiggedJNI_sqlite3_1total_1changes(JNIEnv *jenv, jclass jcls, jlong jarg1) {
  jint jresult = 0 ;
  sqlite3 *arg1 = (sqlite3 *) 0 ;
  int result;
  
  (void)jenv;
  (void)jcls;
  arg1 = *(sqlite3 **)&jarg1; 
  result = (int)sqlite3_total_changes(arg1);
  jresult = (jint)result; 
  return jresult;
}
Ejemplo n.º 11
0
static void
_exec_statement (struct oio_sqlx_client_LOCAL_s *s,
		GPtrArray *in, struct oio_sqlx_statement_result_s *out)
{
	sqlite3_stmt *stmt = NULL;

	/* prepare the query and bind the parameters */
	int rc = sqlite3_prepare (s->db, in->pdata[0], -1, &stmt, NULL);
	if (rc != SQLITE_OK) {
		out->err = NEWERROR(CODE_INTERNAL_ERROR, "DB ERROR (prepare): (%d) %s",
				rc, sqlite3_errmsg(s->db));
		goto out;
	}

	const guint max = in->len;
	for (guint i=1; i<max; ++i) {
		rc = sqlite3_bind_text (stmt, i, in->pdata[i], -1, NULL);
		if (SQLITE_OK != rc) {
			out->err = NEWERROR(CODE_INTERNAL_ERROR, "DB ERROR (bind): (%d) %s",
					rc, sqlite3_errmsg(s->db));
			goto out;
		}
	}

	/* pack the output */
	do {
		rc = sqlite3_step (stmt);
		if (rc == SQLITE_ROW) {
			g_ptr_array_add (out->rows, _pack_record (stmt));
		}
	} while (rc == SQLITE_ROW);

	if (rc != SQLITE_OK && rc != SQLITE_DONE) {
		out->err = NEWERROR(CODE_INTERNAL_ERROR, "DB ERROR (step): (%d) %s",
				rc, sqlite3_errmsg(s->db));
		goto out;
	}

out:
	if (SQLITE_OK != (rc = sqlite3_finalize (stmt))) {
		if (!out->err) {
			out->err = NEWERROR(CODE_INTERNAL_ERROR, "DB ERROR (finalize): "
					"(%d) %s", rc, sqlite3_errmsg(s->db));
		}
	}

	/* fill the context */
	out->ctx.changes = sqlite3_changes (s->db);
	out->ctx.total_changes = sqlite3_total_changes (s->db);
	out->ctx.last_rowid = sqlite3_last_insert_rowid (s->db);

}
Ejemplo n.º 12
0
void test(int newdb)
{
    const char * sSQL;
    char * pErrMsg = 0;
    int ret = 0;
    sqlite3 * db = 0;

    if(newdb) {
        ::DeleteFileA("encrypt.db");
    }

    //创建数据库
    ret = sqlite3_open("encrypt.db", &db);
    //添加密码
    if(newdb) {
        ret = sqlite3_key( db, "dcg", 3 );
    } else {
        ret = sqlite3_key(db, "abc", 3);
    }

    //在内存数据库中创建表
    sSQL = "create table files(path TEXT PRIMARY KEY, content BLOB, time INTEGER);";
    sqlite3_exec( db, sSQL, _callback_exec, 0, &pErrMsg );
    if(newdb) {
        //插入数据
        sSQL = "insert into files values(?,?,?);";
        sqlite3_stmt* stmt;
        int src;
        src = sqlite3_prepare_v2(db, sSQL, strlen(sSQL), &stmt, NULL);
        src = sqlite3_bind_text(stmt,1, "/global.dat", -1, SQLITE_STATIC);
        src = sqlite3_bind_blob(stmt,2, "zhaoyun", 7, SQLITE_STATIC);
        src = sqlite3_bind_int(stmt, 3, 100);
        src = sqlite3_step(stmt);
        src = sqlite3_total_changes(db);
        sqlite3_finalize(stmt);
        // sqlite3_exec( db, sSQL, _callback_exec, 0, &pErrMsg );
    }

    if(newdb) {
        ret = sqlite3_rekey( db, "abc", 3);
    }

    //取得数据并显示
    sSQL = "select * from files;";
    sqlite3_exec( db, sSQL, _callback_exec, 0, &pErrMsg );

    //关闭数据库
    sqlite3_close(db);

    db = 0;
}
Ejemplo n.º 13
0
UINT SQLiteDB::Excute(const char *Query)
{
    if(!isConnected())
        return NULL;
    m_strLastError="";

    char* err="";

    if(sqlite3_exec(pSQLiteConn->pCon, Query, NULL, 0, &err) != SQLITE_OK)
    {
        m_strLastError=sqlite3_errmsg(pSQLiteConn->pCon);
        return 0;
    }
    return sqlite3_total_changes(pSQLiteConn->pCon);
}
Ejemplo n.º 14
0
 bool SqliteDatabase::isDirty()
 {
   return (sqlite3_total_changes(dbPtr.get()) != changeCounter_reset);
 }
Ejemplo n.º 15
0
/* process HTTP or SSDP requests */
int
main(int argc, char * * argv)
{
	int i;
	int sudp = -1, shttpl = -1;
	int snotify[MAX_LAN_ADDR];
	LIST_HEAD(httplisthead, upnphttp) upnphttphead;
	struct upnphttp * e = 0;
	struct upnphttp * next;
	fd_set readset;	/* for select() */
	fd_set writeset;
	struct timeval timeout, timeofday, lastnotifytime = {0, 0};
	time_t lastupdatetime = 0;
	int max_fd = -1;
	int last_changecnt = 0;
	pid_t scanner_pid = 0;
	pthread_t inotify_thread = 0;
	struct media_dir_s *media_path, *last_path;
	struct album_art_name_s *art_names, *last_name;
#ifdef TIVO_SUPPORT
	unsigned short int beacon_interval = 5;
	int sbeacon = -1;
	struct sockaddr_in tivo_bcast;
	struct timeval lastbeacontime = {0, 0};
#endif

	for (i = 0; i < L_MAX; i++)
		log_level[i] = E_WARN;
#ifdef ENABLE_NLS
	setlocale(LC_MESSAGES, "");
	setlocale(LC_CTYPE, "en_US.utf8");
	DPRINTF(E_DEBUG, L_GENERAL, "Using locale dir %s\n", bindtextdomain("minidlna", getenv("TEXTDOMAINDIR")));
	textdomain("minidlna");
#endif

	if (init(argc, argv) != 0)
		return 1;

#ifdef READYNAS
	DPRINTF(E_WARN, L_GENERAL, "Starting " SERVER_NAME " version " MINIDLNA_VERSION ".\n");
	unlink("/ramfs/.upnp-av_scan");
#else
	DPRINTF(E_WARN, L_GENERAL, "Starting " SERVER_NAME " version " MINIDLNA_VERSION " [SQLite %s].\n", sqlite3_libversion());
	if( !sqlite3_threadsafe() )
	{
		DPRINTF(E_ERROR, L_GENERAL, "SQLite library is not threadsafe!  "
		                            "Scanning must be finished before file serving can begin, "
		                            "and inotify will be disabled.\n");
	}
	if( sqlite3_libversion_number() < 3005001 )
	{
		DPRINTF(E_WARN, L_GENERAL, "SQLite library is old.  Please use version 3.5.1 or newer.\n");
	}
#endif
	LIST_INIT(&upnphttphead);

	if( open_db() == 0 )
	{
		updateID = sql_get_int_field(db, "SELECT UPDATE_ID from SETTINGS");
	}
	i = db_upgrade(db);
	if( i != 0 )
	{
		if( i < 0 )
		{
			DPRINTF(E_WARN, L_GENERAL, "Creating new database...\n");
		}
		else
		{
			DPRINTF(E_WARN, L_GENERAL, "Database version mismatch; need to recreate...\n");
		}
		sqlite3_close(db);
		char *cmd;
		i = asprintf(&cmd, "rm -rf %s/files.db %s/art_cache", db_path, db_path);
		if( i > 0 )
			i = system(cmd);
		else
			cmd = NULL;
		if( i != 0 )
		{
			DPRINTF(E_WARN, L_GENERAL, "Failed to clean old file cache.\n");
		}
		free(cmd);
		open_db();
		if( CreateDatabase() != 0 )
		{
			DPRINTF(E_FATAL, L_GENERAL, "ERROR: Failed to create sqlite database!  Exiting...\n");
		}
#if USE_FORK
		scanning = 1;
		sqlite3_close(db);
		scanner_pid = fork();
		open_db();
		if( !scanner_pid ) // child (scanner) process
		{
			start_scanner();
			sqlite3_close(db);
			media_path = media_dirs;
			art_names = album_art_names;
			while( media_path )
			{
				free(media_path->path);
				last_path = media_path;
				media_path = media_path->next;
				free(last_path);
			}
			while( art_names )
			{
				free(art_names->name);
				last_name = art_names;
				art_names = art_names->next;
				free(last_name);
			}
			freeoptions();
			exit(EXIT_SUCCESS);
		}
#else
		start_scanner();
#endif
	}
	signal(SIGCHLD, SIG_IGN);
	if( sqlite3_threadsafe() && sqlite3_libversion_number() >= 3005001 &&
	    GETFLAG(INOTIFY_MASK) && pthread_create(&inotify_thread, NULL, start_inotify, NULL) )
	{
		DPRINTF(E_FATAL, L_GENERAL, "ERROR: pthread_create() failed for start_inotify.\n");
	}

	sudp = OpenAndConfSSDPReceiveSocket(n_lan_addr, lan_addr);
	if(sudp < 0)
	{
		DPRINTF(E_INFO, L_GENERAL, "Failed to open socket for receiving SSDP. Trying to use MiniSSDPd\n");
		if(SubmitServicesToMiniSSDPD(lan_addr[0].str, runtime_vars.port) < 0) {
			DPRINTF(E_FATAL, L_GENERAL, "Failed to connect to MiniSSDPd. EXITING");
			return 1;
		}
	}
	/* open socket for HTTP connections. Listen on the 1st LAN address */
	shttpl = OpenAndConfHTTPSocket(runtime_vars.port);
	if(shttpl < 0)
	{
		DPRINTF(E_FATAL, L_GENERAL, "Failed to open socket for HTTP. EXITING\n");
	}
	DPRINTF(E_WARN, L_GENERAL, "HTTP listening on port %d\n", runtime_vars.port);

	/* open socket for sending notifications */
	if(OpenAndConfSSDPNotifySockets(snotify) < 0)
	{
		DPRINTF(E_FATAL, L_GENERAL, "Failed to open sockets for sending SSDP notify "
	                "messages. EXITING\n");
	}

#ifdef TIVO_SUPPORT
	if( GETFLAG(TIVO_MASK) )
	{
		DPRINTF(E_WARN, L_GENERAL, "TiVo support is enabled.\n");
		/* Add TiVo-specific randomize function to sqlite */
		if( sqlite3_create_function(db, "tivorandom", 1, SQLITE_UTF8, NULL, &TiVoRandomSeedFunc, NULL, NULL) != SQLITE_OK )
		{
			DPRINTF(E_ERROR, L_TIVO, "ERROR: Failed to add sqlite randomize function for TiVo!\n");
		}
		/* open socket for sending Tivo notifications */
		sbeacon = OpenAndConfTivoBeaconSocket();
		if(sbeacon < 0)
		{
			DPRINTF(E_FATAL, L_GENERAL, "Failed to open sockets for sending Tivo beacon notify "
		                "messages. EXITING\n");
		}
		tivo_bcast.sin_family = AF_INET;
		tivo_bcast.sin_addr.s_addr = htonl(getBcastAddress());
		tivo_bcast.sin_port = htons(2190);
	}
	else
	{
		sbeacon = -1;
	}
#endif

	SendSSDPGoodbye(snotify, n_lan_addr);

	/* main loop */
	while(!quitting)
	{
		/* Check if we need to send SSDP NOTIFY messages and do it if
		 * needed */
		if(gettimeofday(&timeofday, 0) < 0)
		{
			DPRINTF(E_ERROR, L_GENERAL, "gettimeofday(): %s\n", strerror(errno));
			timeout.tv_sec = runtime_vars.notify_interval;
			timeout.tv_usec = 0;
		}
		else
		{
			/* the comparaison is not very precise but who cares ? */
			if(timeofday.tv_sec >= (lastnotifytime.tv_sec + runtime_vars.notify_interval))
			{
				SendSSDPNotifies2(snotify,
			                  (unsigned short)runtime_vars.port,
			                  (runtime_vars.notify_interval << 1)+10);
				memcpy(&lastnotifytime, &timeofday, sizeof(struct timeval));
				timeout.tv_sec = runtime_vars.notify_interval;
				timeout.tv_usec = 0;
			}
			else
			{
				timeout.tv_sec = lastnotifytime.tv_sec + runtime_vars.notify_interval
				                 - timeofday.tv_sec;
				if(timeofday.tv_usec > lastnotifytime.tv_usec)
				{
					timeout.tv_usec = 1000000 + lastnotifytime.tv_usec
					                  - timeofday.tv_usec;
					timeout.tv_sec--;
				}
				else
				{
					timeout.tv_usec = lastnotifytime.tv_usec - timeofday.tv_usec;
				}
			}
#ifdef TIVO_SUPPORT
			if( GETFLAG(TIVO_MASK) )
			{
				if(timeofday.tv_sec >= (lastbeacontime.tv_sec + beacon_interval))
				{
   					sendBeaconMessage(sbeacon, &tivo_bcast, sizeof(struct sockaddr_in), 1);
					memcpy(&lastbeacontime, &timeofday, sizeof(struct timeval));
					if( timeout.tv_sec > beacon_interval )
					{
						timeout.tv_sec = beacon_interval;
						timeout.tv_usec = 0;
					}
					/* Beacons should be sent every 5 seconds or so for the first minute,
					 * then every minute or so thereafter. */
					if( beacon_interval == 5 && (timeofday.tv_sec - startup_time) > 60 )
					{
						beacon_interval = 60;
					}
				}
				else if( timeout.tv_sec > (lastbeacontime.tv_sec + beacon_interval + 1 - timeofday.tv_sec) )
				{
					timeout.tv_sec = lastbeacontime.tv_sec + beacon_interval - timeofday.tv_sec;
				}
			}
#endif
		}

		if( scanning )
		{
			if( !scanner_pid || kill(scanner_pid, 0) )
			{
				scanning = 0;
				updateID++;
			}
		}

		/* select open sockets (SSDP, HTTP listen, and all HTTP soap sockets) */
		FD_ZERO(&readset);

		if (sudp >= 0) 
		{
			FD_SET(sudp, &readset);
			max_fd = MAX(max_fd, sudp);
		}
		
		if (shttpl >= 0) 
		{
			FD_SET(shttpl, &readset);
			max_fd = MAX(max_fd, shttpl);
		}
#ifdef TIVO_SUPPORT
		if (sbeacon >= 0) 
		{
			FD_SET(sbeacon, &readset);
			max_fd = MAX(max_fd, sbeacon);
		}
#endif
		i = 0;	/* active HTTP connections count */
		for(e = upnphttphead.lh_first; e != NULL; e = e->entries.le_next)
		{
			if((e->socket >= 0) && (e->state <= 2))
			{
				FD_SET(e->socket, &readset);
				max_fd = MAX(max_fd, e->socket);
				i++;
			}
		}
#ifdef DEBUG
		/* for debug */
		if(i > 1)
		{
			DPRINTF(E_DEBUG, L_GENERAL, "%d active incoming HTTP connections\n", i);
		}
#endif
		FD_ZERO(&writeset);
		upnpevents_selectfds(&readset, &writeset, &max_fd);

		if(select(max_fd+1, &readset, &writeset, 0, &timeout) < 0)
		{
			if(quitting) goto shutdown;
			DPRINTF(E_ERROR, L_GENERAL, "select(all): %s\n", strerror(errno));
			DPRINTF(E_FATAL, L_GENERAL, "Failed to select open sockets. EXITING\n");
		}
		upnpevents_processfds(&readset, &writeset);
		/* process SSDP packets */
		if(sudp >= 0 && FD_ISSET(sudp, &readset))
		{
			/*DPRINTF(E_DEBUG, L_GENERAL, "Received UDP Packet\n");*/
			ProcessSSDPRequest(sudp, (unsigned short)runtime_vars.port);
		}
#ifdef TIVO_SUPPORT
		if(sbeacon >= 0 && FD_ISSET(sbeacon, &readset))
		{
			/*DPRINTF(E_DEBUG, L_GENERAL, "Received UDP Packet\n");*/
			ProcessTiVoBeacon(sbeacon);
		}
#endif
		/* increment SystemUpdateID if the content database has changed,
		 * and if there is an active HTTP connection, at most once every 2 seconds */
		if( i && (timeofday.tv_sec >= (lastupdatetime + 2)) )
		{
			if( scanning || sqlite3_total_changes(db) != last_changecnt )
			{
				updateID++;
				last_changecnt = sqlite3_total_changes(db);
				upnp_event_var_change_notify(EContentDirectory);
				lastupdatetime = timeofday.tv_sec;
			}
		}
		/* process active HTTP connections */
		for(e = upnphttphead.lh_first; e != NULL; e = e->entries.le_next)
		{
			if(  (e->socket >= 0) && (e->state <= 2)
				&&(FD_ISSET(e->socket, &readset)) )
			{
				Process_upnphttp(e);
			}
		}
		/* process incoming HTTP connections */
		if(shttpl >= 0 && FD_ISSET(shttpl, &readset))
		{
			int shttp;
			socklen_t clientnamelen;
			struct sockaddr_in clientname;
			clientnamelen = sizeof(struct sockaddr_in);
			shttp = accept(shttpl, (struct sockaddr *)&clientname, &clientnamelen);
			if(shttp<0)
			{
				DPRINTF(E_ERROR, L_GENERAL, "accept(http): %s\n", strerror(errno));
			}
			else
			{
				struct upnphttp * tmp = 0;
				DPRINTF(E_DEBUG, L_GENERAL, "HTTP connection from %s:%d\n",
					inet_ntoa(clientname.sin_addr),
					ntohs(clientname.sin_port) );
				/*if (fcntl(shttp, F_SETFL, O_NONBLOCK) < 0) {
					DPRINTF(E_ERROR, L_GENERAL, "fcntl F_SETFL, O_NONBLOCK\n");
				}*/
				/* Create a new upnphttp object and add it to
				 * the active upnphttp object list */
				tmp = New_upnphttp(shttp);
				if(tmp)
				{
					tmp->clientaddr = clientname.sin_addr;
					LIST_INSERT_HEAD(&upnphttphead, tmp, entries);
				}
				else
				{
					DPRINTF(E_ERROR, L_GENERAL, "New_upnphttp() failed\n");
					close(shttp);
				}
			}
		}
		/* delete finished HTTP connections */
		for(e = upnphttphead.lh_first; e != NULL; )
		{
			next = e->entries.le_next;
			if(e->state >= 100)
			{
				LIST_REMOVE(e, entries);
				Delete_upnphttp(e);
			}
			e = next;
		}
	}

shutdown:
	/* kill the scanner */
	if( scanning && scanner_pid )
	{
		kill(scanner_pid, 9);
	}
	/* close out open sockets */
	while(upnphttphead.lh_first != NULL)
	{
		e = upnphttphead.lh_first;
		LIST_REMOVE(e, entries);
		Delete_upnphttp(e);
	}

	if (sudp >= 0) close(sudp);
	if (shttpl >= 0) close(shttpl);
	#ifdef TIVO_SUPPORT
	if (sbeacon >= 0) close(sbeacon);
	#endif
	
	if(SendSSDPGoodbye(snotify, n_lan_addr) < 0)
	{
		DPRINTF(E_ERROR, L_GENERAL, "Failed to broadcast good-bye notifications\n");
	}
	for(i=0; i<n_lan_addr; i++)
		close(snotify[i]);

	if( inotify_thread )
		pthread_join(inotify_thread, NULL);

	sql_exec(db, "UPDATE SETTINGS set UPDATE_ID = %u", updateID);
	sqlite3_close(db);

	upnpevents_removeSubscribers();

	media_path = media_dirs;
	art_names = album_art_names;
	while( media_path )
	{
		free(media_path->path);
		last_path = media_path;
		media_path = media_path->next;
		free(last_path);
	}
	while( art_names )
	{
		free(art_names->name);
		last_name = art_names;
		art_names = art_names->next;
		free(last_name);
	}

	if(unlink(pidfilename) < 0)
	{
		DPRINTF(E_ERROR, L_GENERAL, "Failed to remove pidfile %s: %s\n", pidfilename, strerror(errno));
	}

	freeoptions();

	exit(EXIT_SUCCESS);
}
Ejemplo n.º 16
0
int main(int argc, char **argv)
{
	sqlite3 *db;
	sqlite3_stmt *plineInfo = 0;
	char *line = NULL;
	size_t len = 0;
	ssize_t mread;

	int fd, n;
	long buflen = 0, totread = 0;
	char *buf = NULL, *pbuf = NULL;

	//  char *zErrMsg = 0;
	int rc, i;

	if (argc < 3) {
		fprintf(stderr,
			"Usage: %s <DATABASE> <BINARYFILE> < sqlcommands \n\n"
			"Or, the following:\n\n"
			"  $%s test3.db test.png \n"

                        "   eatblob:0> create table blobtest (des varchar(80), b blob);\n"
                        "   eatblob:0> insert into blobtest (des,b) values ('A test file: test.png',?);\n"
                        "   eatblob:1> select * from blobtest;\n"
                        "    A test file: test.png\n"
                        "   eatblob:1>\n\n"
			" Note output.0.png will contain a copy of test.png\n\n"
			"Or, do everything on the command prompt:\n\n"
			" $ ./eatblob test3.db test.png \"create table blobtest (des varchar(80),b blob);\"\n"
			" $ ./eatblob test3.db test.png \"insert into blobtest (des,b) values ('A test file: test.png',?);\"\n"
                        "\n\n",
			argv[0], argv[0]);
		exit(1);
	}

	if (sqlite3_open(argv[1], &db) != SQLITE_OK) {
		fprintf(stderr, "Can't open database: \n");
		sqlite3_close(db);
		exit(1);
	}

	if ((fd = open(argv[2], O_RDWR | O_CREAT, 0600)) == -1) {
		fprintf(stderr, "Can't open data: %s\n", strerror(errno));
		return 1;
	}

	while (buflen - totread - 1 < 1024)
		buflen = addmem(&buf, buflen);
	pbuf = buf;
	totread = 0;
	while ((n = read(fd, pbuf, 1024)) > 0) {
		totread += n;
		pbuf[n] = '\0';	// This is for printing test
		while (buflen - totread - 1 < 1024)
			buflen = addmem(&buf, buflen);

		pbuf = &buf[totread];

	}
	close(fd);


	if (argc == 4) {
		rc = sqlite3_prepare(db, argv[3], -1, &plineInfo, 0);
		if (rc == SQLITE_OK && plineInfo != NULL) {
			//fprintf(stderr, "SQLITE_OK\n");
			sqlite3_bind_blob(plineInfo, 1, buf, totread,
					  free);
			while ((rc =
				sqlite3_step(plineInfo)) == SQLITE_ROW) {
				//
				for (i = 0;
				     i < sqlite3_column_count(plineInfo);
				     ++i)
					print_col(plineInfo, i);

				printf("\n");

			}
			rc = sqlite3_finalize(plineInfo);
		}
		fprintf(stderr, "eatblob:%d> ", sqlite3_total_changes(db));

	} else {
		fprintf(stderr, "eatblob:0> ");
		while ((mread = mygetline(&line, &len, stdin)) > 0) {
			rc = sqlite3_prepare(db, line, -1, &plineInfo, 0);
			if (rc == SQLITE_OK && plineInfo != NULL) {
				//fprintf(stderr, "SQLITE_OK\n");
				sqlite3_bind_blob(plineInfo, 1, buf,
						  totread, free);
				while ((rc =
					sqlite3_step(plineInfo)) ==
				       SQLITE_ROW) {
					//
					for (i = 0;
					     i <
					     sqlite3_column_count
					     (plineInfo); ++i)
						print_col(plineInfo, i);

					printf("\n");

				}
				rc = sqlite3_finalize(plineInfo);
			}
			fprintf(stderr, "eatblob:%d> ",
				sqlite3_total_changes(db));
		}		/* end of while */

	}

	if (line) {
		free(line);
	}
	sqlite3_close(db);
	return 0;
}
Ejemplo n.º 17
0
/* Internal: */
void
dupin_attachment_db_disconnect (DupinAttachmentDB * attachment_db)
{
  g_return_if_fail (attachment_db != NULL);

#if DEBUG
  g_message("dupin_attachment_db_disconnect: total number of changes for '%s' attachments database: %d\n", attachment_db->name, (gint)sqlite3_total_changes (attachment_db->db));
#endif

  if (attachment_db->db)
    sqlite3_close (attachment_db->db);

  if (attachment_db->todelete == TRUE)
    g_unlink (attachment_db->path);

  if (attachment_db->name)
    g_free (attachment_db->name);

  if (attachment_db->path)
    g_free (attachment_db->path);

  if (attachment_db->parent)
    g_free (attachment_db->parent);

  if (attachment_db->rwlock)
    {
      g_rw_lock_clear (attachment_db->rwlock);
      g_free (attachment_db->rwlock);
    }

  if (attachment_db->error_msg)
    g_free (attachment_db->error_msg);

  if (attachment_db->warning_msg)
    g_free (attachment_db->warning_msg);

  g_free (attachment_db);
}
Ejemplo n.º 18
0
int sqlg_db_total_changes(sqlg_handle_t db)
{
  sqlite3 *mydb = HANDLE_TO_VP(db);

  return sqlite3_total_changes(mydb);
}
Ejemplo n.º 19
0
bool store_to_sqlite(
	sqlite3 *db,
	const char *tablename,
	const char *idcolumn,
	int64_t idvalue,
	const char *idvalue_str,
	const void *src,
	const struct field_desc *fields,
	size_t num_fields,
	GError **err_p)
{
	GString *sql = g_string_sized_new(32 + num_fields * 32);

	/* compose the update statement. */
	g_string_append_printf(sql, "UPDATE %s SET ", tablename);
	for(size_t i=0; i < num_fields; i++) {
		g_string_append_printf(sql, "%s%s = ?",
			i > 0 ? ", " : "", fields[i].column);
	}
	g_string_append_printf(sql, " WHERE %s = ?", idcolumn);

	sqlite3_stmt *stmt = NULL;
	int n = sqlite3_prepare_v2(db, sql->str, sql->len, &stmt, NULL);
	if(n != SQLITE_OK) goto fail;
	format_to_sqlite(stmt, src, fields, num_fields);
	bind_idvalue(stmt, num_fields, idvalue, idvalue_str);
	n = sqlite3_step(stmt);
	if(n != SQLITE_DONE) goto fail;
	/* sqlite3_total_changes() counts matched rows, not necessarily rows that
	 * got a different value. that's what we want here.
	 */
	if(sqlite3_total_changes(db) < 1) {
		sqlite3_finalize(stmt); stmt = NULL;

		/* compose an insert statement. */
		bool separate_id = true;
		for(size_t i=0; i < num_fields; i++) {
			if(strcmp(fields[i].column, idcolumn) == 0) {
				separate_id = false;
				break;
			}
		}

		g_string_truncate(sql, 0);
		g_string_append_printf(sql, "INSERT INTO %s (", tablename);
		for(size_t i=0; i < num_fields; i++) {
			g_string_append_printf(sql, "%s%s", i > 0 ? ", " : "",
				fields[i].column);
		}
		if(separate_id) {
			g_string_append_printf(sql, "%s%s", num_fields > 0 ? ", " : "",
				idcolumn);
		}
		g_string_append(sql, ") VALUES (");
		for(size_t i=0; i < num_fields; i++) {
			g_string_append_printf(sql, "%s?", i > 0 ? ", " : "");
		}
		if(separate_id) {
			g_string_append_printf(sql, "%s?", num_fields > 0 ? ", " : "");
		}
		g_string_append(sql, ")");

		n = sqlite3_prepare_v2(db, sql->str, sql->len, &stmt, NULL);
		if(n != SQLITE_OK) goto fail;
		format_to_sqlite(stmt, src, fields, num_fields);
		if(separate_id) bind_idvalue(stmt, num_fields, idvalue, idvalue_str);
		n = sqlite3_step(stmt);
		if(n != SQLITE_DONE) goto fail;
	}

	g_string_free(sql, TRUE);
	sqlite3_finalize(stmt);
	return true;

fail:
	g_set_error(err_p, 0, sqlite3_extended_errcode(db), "%s",
		sqlite3_errmsg(db));
	g_string_free(sql, TRUE);
	if(stmt != NULL) sqlite3_finalize(stmt);
	return false;
}
Ejemplo n.º 20
0
/* process HTTP or SSDP requests */
int
main(int argc, char **argv)
{
	int ret, i;
	int shttpl = -1;
	int smonitor = -1;
	LIST_HEAD(httplisthead, upnphttp) upnphttphead;
	struct upnphttp * e = 0;
	struct upnphttp * next;
	fd_set readset;	/* for select() */
	fd_set writeset;
	struct timeval timeout, timeofday, lastnotifytime = {0, 0};
	time_t lastupdatetime = 0;
	int max_fd = -1;
	int last_changecnt = 0;
	pid_t scanner_pid = 0;
	pthread_t inotify_thread = 0;
#ifdef TIVO_SUPPORT
	uint8_t beacon_interval = 5;
	int sbeacon = -1;
	struct sockaddr_in tivo_bcast;
	struct timeval lastbeacontime = {0, 0};
#endif

	for (i = 0; i < L_MAX; i++)
		log_level[i] = E_WARN;
	init_nls();

	ret = init(argc, argv);
	if (ret != 0)
		return 1;

#if (!defined(RTN66U) && !defined(RTN56U))
	init_icon(PATH_ICON_PNG_SM);
	init_icon(PATH_ICON_PNG_LRG);
	init_icon(PATH_ICON_JPEG_SM);
	init_icon(PATH_ICON_JPEG_LRG);
#endif

	DPRINTF(E_WARN, L_GENERAL, "Starting " SERVER_NAME " version " MINIDLNA_VERSION ".\n");
	if (sqlite3_libversion_number() < 3005001)
	{
		DPRINTF(E_WARN, L_GENERAL, "SQLite library is old.  Please use version 3.5.1 or newer.\n");
	}

	LIST_INIT(&upnphttphead);

	ret = open_db(NULL);
	if (ret == 0)
	{
		updateID = sql_get_int_field(db, "SELECT VALUE from SETTINGS where KEY = 'UPDATE_ID'");
		if (updateID == -1)
			ret = -1;
	}
	check_db(db, ret, &scanner_pid);
#ifdef HAVE_INOTIFY
	if( GETFLAG(INOTIFY_MASK) )
	{
		if (!sqlite3_threadsafe() || sqlite3_libversion_number() < 3005001)
			DPRINTF(E_ERROR, L_GENERAL, "SQLite library is not threadsafe!  "
			                            "Inotify will be disabled.\n");
		else if (pthread_create(&inotify_thread, NULL, start_inotify, NULL) != 0)
			DPRINTF(E_FATAL, L_GENERAL, "ERROR: pthread_create() failed for start_inotify. EXITING\n");
	}
#endif
	smonitor = OpenAndConfMonitorSocket();

	sssdp = OpenAndConfSSDPReceiveSocket();
	if (sssdp < 0)
	{
		DPRINTF(E_INFO, L_GENERAL, "Failed to open socket for receiving SSDP. Trying to use MiniSSDPd\n");
		if (SubmitServicesToMiniSSDPD(lan_addr[0].str, runtime_vars.port) < 0)
			DPRINTF(E_FATAL, L_GENERAL, "Failed to connect to MiniSSDPd. EXITING");
	}
	/* open socket for HTTP connections. */
	shttpl = OpenAndConfHTTPSocket(runtime_vars.port);
	if (shttpl < 0)
		DPRINTF(E_FATAL, L_GENERAL, "Failed to open socket for HTTP. EXITING\n");
	DPRINTF(E_WARN, L_GENERAL, "HTTP listening on port %d\n", runtime_vars.port);

#ifdef TIVO_SUPPORT
	if (GETFLAG(TIVO_MASK))
	{
		DPRINTF(E_WARN, L_GENERAL, "TiVo support is enabled.\n");
		/* Add TiVo-specific randomize function to sqlite */
		ret = sqlite3_create_function(db, "tivorandom", 1, SQLITE_UTF8, NULL, &TiVoRandomSeedFunc, NULL, NULL);
		if (ret != SQLITE_OK)
			DPRINTF(E_ERROR, L_TIVO, "ERROR: Failed to add sqlite randomize function for TiVo!\n");
		/* open socket for sending Tivo notifications */
		sbeacon = OpenAndConfTivoBeaconSocket();
		if(sbeacon < 0)
			DPRINTF(E_FATAL, L_GENERAL, "Failed to open sockets for sending Tivo beacon notify "
				"messages. EXITING\n");
		tivo_bcast.sin_family = AF_INET;
		tivo_bcast.sin_addr.s_addr = htonl(getBcastAddress());
		tivo_bcast.sin_port = htons(2190);
	}
#endif

	reload_ifaces(0);
	lastnotifytime.tv_sec = time(NULL) + runtime_vars.notify_interval;

	/* main loop */
	while (!quitting)
	{
		/* Check if we need to send SSDP NOTIFY messages and do it if
		 * needed */
		if (gettimeofday(&timeofday, 0) < 0)
		{
			DPRINTF(E_ERROR, L_GENERAL, "gettimeofday(): %s\n", strerror(errno));
			timeout.tv_sec = runtime_vars.notify_interval;
			timeout.tv_usec = 0;
		}
		else
		{
			/* the comparison is not very precise but who cares ? */
			if (timeofday.tv_sec >= (lastnotifytime.tv_sec + runtime_vars.notify_interval))
			{
				DPRINTF(E_DEBUG, L_SSDP, "Sending SSDP notifies\n");
				for (i = 0; i < n_lan_addr; i++)
				{
					SendSSDPNotifies(lan_addr[i].snotify, lan_addr[i].str,
						runtime_vars.port, runtime_vars.notify_interval);
				}
				memcpy(&lastnotifytime, &timeofday, sizeof(struct timeval));
				timeout.tv_sec = runtime_vars.notify_interval;
				timeout.tv_usec = 0;
			}
			else
			{
				timeout.tv_sec = lastnotifytime.tv_sec + runtime_vars.notify_interval
				                 - timeofday.tv_sec;
				if (timeofday.tv_usec > lastnotifytime.tv_usec)
				{
					timeout.tv_usec = 1000000 + lastnotifytime.tv_usec
					                  - timeofday.tv_usec;
					timeout.tv_sec--;
				}
				else
					timeout.tv_usec = lastnotifytime.tv_usec - timeofday.tv_usec;
			}
#ifdef TIVO_SUPPORT
			if (sbeacon >= 0)
			{
				if (timeofday.tv_sec >= (lastbeacontime.tv_sec + beacon_interval))
				{
					sendBeaconMessage(sbeacon, &tivo_bcast, sizeof(struct sockaddr_in), 1);
					memcpy(&lastbeacontime, &timeofday, sizeof(struct timeval));
					if (timeout.tv_sec > beacon_interval)
					{
						timeout.tv_sec = beacon_interval;
						timeout.tv_usec = 0;
					}
					/* Beacons should be sent every 5 seconds or so for the first minute,
					 * then every minute or so thereafter. */
					if (beacon_interval == 5 && (timeofday.tv_sec - startup_time) > 60)
						beacon_interval = 60;
				}
				else if (timeout.tv_sec > (lastbeacontime.tv_sec + beacon_interval + 1 - timeofday.tv_sec))
					timeout.tv_sec = lastbeacontime.tv_sec + beacon_interval - timeofday.tv_sec;
			}
#endif
		}

		if (scanning)
		{
			if (!scanner_pid || kill(scanner_pid, 0) != 0)
			{
				scanning = 0;
				updateID++;
			}
		}

		/* select open sockets (SSDP, HTTP listen, and all HTTP soap sockets) */
		FD_ZERO(&readset);

		if (sssdp >= 0) 
		{
			FD_SET(sssdp, &readset);
			max_fd = MAX(max_fd, sssdp);
		}
		
		if (shttpl >= 0) 
		{
			FD_SET(shttpl, &readset);
			max_fd = MAX(max_fd, shttpl);
		}
#ifdef TIVO_SUPPORT
		if (sbeacon >= 0) 
		{
			FD_SET(sbeacon, &readset);
			max_fd = MAX(max_fd, sbeacon);
		}
#endif
		if (smonitor >= 0) 
		{
			FD_SET(smonitor, &readset);
			max_fd = MAX(max_fd, smonitor);
		}

		i = 0;	/* active HTTP connections count */
		for (e = upnphttphead.lh_first; e != NULL; e = e->entries.le_next)
		{
			if ((e->socket >= 0) && (e->state <= 2))
			{
				FD_SET(e->socket, &readset);
				max_fd = MAX(max_fd, e->socket);
				i++;
			}
		}
		FD_ZERO(&writeset);
		upnpevents_selectfds(&readset, &writeset, &max_fd);

		ret = select(max_fd+1, &readset, &writeset, 0, &timeout);
		if (ret < 0)
		{
			if(quitting) goto shutdown;
			if(errno == EINTR) continue;
			DPRINTF(E_ERROR, L_GENERAL, "select(all): %s\n", strerror(errno));
			DPRINTF(E_FATAL, L_GENERAL, "Failed to select open sockets. EXITING\n");
		}
		upnpevents_processfds(&readset, &writeset);
		/* process SSDP packets */
		if (sssdp >= 0 && FD_ISSET(sssdp, &readset))
		{
			/*DPRINTF(E_DEBUG, L_GENERAL, "Received SSDP Packet\n");*/
			ProcessSSDPRequest(sssdp, (unsigned short)runtime_vars.port);
		}
#ifdef TIVO_SUPPORT
		if (sbeacon >= 0 && FD_ISSET(sbeacon, &readset))
		{
			/*DPRINTF(E_DEBUG, L_GENERAL, "Received UDP Packet\n");*/
			ProcessTiVoBeacon(sbeacon);
		}
#endif
		if (smonitor >= 0 && FD_ISSET(smonitor, &readset))
		{
			ProcessMonitorEvent(smonitor);
		}
		/* increment SystemUpdateID if the content database has changed,
		 * and if there is an active HTTP connection, at most once every 2 seconds */
		if (i && (timeofday.tv_sec >= (lastupdatetime + 2)))
		{
			if (scanning || sqlite3_total_changes(db) != last_changecnt)
			{
				updateID++;
				last_changecnt = sqlite3_total_changes(db);
				upnp_event_var_change_notify(EContentDirectory);
				lastupdatetime = timeofday.tv_sec;
			}
		}
		/* process active HTTP connections */
		for (e = upnphttphead.lh_first; e != NULL; e = e->entries.le_next)
		{
			if ((e->socket >= 0) && (e->state <= 2) && (FD_ISSET(e->socket, &readset)))
				Process_upnphttp(e);
		}
		/* process incoming HTTP connections */
		if (shttpl >= 0 && FD_ISSET(shttpl, &readset))
		{
			int shttp;
			socklen_t clientnamelen;
			struct sockaddr_in clientname;
			clientnamelen = sizeof(struct sockaddr_in);
			shttp = accept(shttpl, (struct sockaddr *)&clientname, &clientnamelen);
			if (shttp<0)
			{
				DPRINTF(E_ERROR, L_GENERAL, "accept(http): %s\n", strerror(errno));
			}
			else
			{
				struct upnphttp * tmp = 0;
				DPRINTF(E_DEBUG, L_GENERAL, "HTTP connection from %s:%d\n",
					inet_ntoa(clientname.sin_addr),
					ntohs(clientname.sin_port) );
				/*if (fcntl(shttp, F_SETFL, O_NONBLOCK) < 0) {
					DPRINTF(E_ERROR, L_GENERAL, "fcntl F_SETFL, O_NONBLOCK\n");
				}*/
				/* Create a new upnphttp object and add it to
				 * the active upnphttp object list */
				tmp = New_upnphttp(shttp);
				if (tmp)
				{
					tmp->clientaddr = clientname.sin_addr;
					LIST_INSERT_HEAD(&upnphttphead, tmp, entries);
				}
				else
				{
					DPRINTF(E_ERROR, L_GENERAL, "New_upnphttp() failed\n");
					close(shttp);
				}
			}
		}
		/* delete finished HTTP connections */
		for (e = upnphttphead.lh_first; e != NULL; e = next)
		{
			next = e->entries.le_next;
			if(e->state >= 100)
			{
				LIST_REMOVE(e, entries);
				Delete_upnphttp(e);
			}
		}
	}

shutdown:
	/* kill the scanner */
	if (scanning && scanner_pid)
		kill(scanner_pid, SIGKILL);

	/* kill other child processes */
	process_reap_children();
	free(children);

	/* close out open sockets */
	while (upnphttphead.lh_first != NULL)
	{
		e = upnphttphead.lh_first;
		LIST_REMOVE(e, entries);
		Delete_upnphttp(e);
	}
	if (sssdp >= 0)
		close(sssdp);
	if (shttpl >= 0)
		close(shttpl);
#ifdef TIVO_SUPPORT
	if (sbeacon >= 0)
		close(sbeacon);
#endif
	
	for (i = 0; i < n_lan_addr; i++)
	{
		SendSSDPGoodbyes(lan_addr[i].snotify);
		close(lan_addr[i].snotify);
	}

	if (inotify_thread)
		pthread_join(inotify_thread, NULL);

	sql_exec(db, "UPDATE SETTINGS set VALUE = '%u' where KEY = 'UPDATE_ID'", updateID);
	sqlite3_close(db);

	upnpevents_removeSubscribers();

	if (pidfilename && unlink(pidfilename) < 0)
		DPRINTF(E_ERROR, L_GENERAL, "Failed to remove pidfile %s: %s\n", pidfilename, strerror(errno));

	log_close();
	freeoptions();

	exit(EXIT_SUCCESS);
}
Ejemplo n.º 21
0
size_t session::total_changes() const
{
	return is_open()? sqlite3_total_changes(impl_) : 0;
}
Ejemplo n.º 22
0
 int Connection::total_changes()
 {
     return sqlite3_total_changes(_db);
 }
Ejemplo n.º 23
0
DLL_FUNCTION(int32_t) BU_SQLite_Total_Changes(sqlite3* db) {
#pragma comment(linker, "/EXPORT:BU_SQLite_Total_Changes=_BU_SQLite_Total_Changes@4")
	return sqlite3_total_changes(db);
}
Ejemplo n.º 24
0
__declspec(dllexport) int WINAPI sqlite3_total_changes_interop(sqlite3 *db)
{
  return sqlite3_total_changes(db);
}
Ejemplo n.º 25
0
 int SqliteDatabase::getDirtyCounter()
 {
   return sqlite3_total_changes(dbPtr.get());
 }
Ejemplo n.º 26
0
int SqliteDatabaseBackend::totalChangesCount()
{
    return sqlite3_total_changes(sqliteDatabaseHandle());
}
Ejemplo n.º 27
0
// Get total number of rows modified by all INSERT, UPDATE or DELETE statement since connection.
int Database::getTotalChanges() const noexcept // nothrow
{
    return sqlite3_total_changes(mpSQLite);
}
Ejemplo n.º 28
0
 std::size_t
 Database::getTotalChanges ()
 {
   return sqlite3_total_changes (_connection->db ());
 }
Ejemplo n.º 29
0
 void SqliteDatabase::resetDirtyFlag()
 {
   changeCounter_reset = sqlite3_total_changes(dbPtr.get());
 }