int main (int argc, char **argv) { sqlite3 *db; // Definimos un puntero a la base de datos char *errMsg = 0; // Variable para el mensaje de error int rc; // Variable para el retorno de la sentencia sqlite3_stmt *result; // Puntero a la respuesta de la consulta // Abro la conexión con la base de datos rc = sqlite3_open("BDPrueba.sqlite", &db); // Compruebo que no hay error if (rc != SQLITE_OK) { fprintf(stderr, "No se puede acceder a la base de datos: %s.\n", sqlite3_errmsg(db)); sqlite3_close(db); return(1); } // Borro la tabla si no existe rc = sqlite3_exec(db, "DROP TABLE IF EXISTS Empresa", NULL, NULL, &errMsg); if (rc != SQLITE_OK) { fprintf(stderr, "Error al borrar la tabla: %s.\n", errMsg); sqlite3_free(errMsg); sqlite3_close(db); return(2); } // Creo la tabla Empresa rc = sqlite3_exec(db, "CREATE TABLE Empresa (IdEmpresa INTEGER PRIMARY KEY, Nombre CHAR[250])", NULL, NULL, &errMsg); if (rc != SQLITE_OK) { fprintf(stderr, "Error al crear la tabla: %s.\n", errMsg); sqlite3_free(errMsg); sqlite3_close(db); return(2); } // Inserto un par de registros rc = sqlite3_exec(db, "INSERT INTO Empresa VALUES( 1, 'Empresa A')", NULL, NULL, &errMsg); if (rc != SQLITE_OK) { fprintf(stderr, "Error al crear el primer registro: %s.\n", errMsg); sqlite3_free(errMsg); sqlite3_close(db); return(2); } rc = sqlite3_exec(db, "INSERT INTO Empresa VALUES( 2, 'Empresa B')", NULL, NULL, &errMsg); if (rc != SQLITE_OK) { fprintf(stderr, "Error al crear el segundo registro: %s.\n", errMsg); sqlite3_free(errMsg); sqlite3_close(db); return(2); } // Consulta a realizar sobre la tabla. // En este caso quiero los campos idEmpresa y Nombre de la tabla Empresa rc = sqlite3_prepare(db, "SELECT idEmpresa,Nombre FROM Empresa", -1, &result, NULL); // Compruebo que no hay error if (rc != SQLITE_OK) { fprintf(stderr, "Error en la consulta: %s.\n", sqlite3_errmsg(db)); sqlite3_close(db); return(3); } // Bucle de presentación en pantalla del resultado de la consulta while ( sqlite3_step(result) == SQLITE_ROW) { fprintf(stderr, "El Id y nombre de la empresa son: %i - %s.\n", sqlite3_column_int(result, 0) , sqlite3_column_text(result, 1)); } // Cierro la conexión sqlite3_close(db); return 0; }
int main(int argc, char **argv) { int addrtype = 0; int privtype = 128; int regex = 0; int caseinsensitive = 0; int opt; char pwbuf[128]; int platformidx = -1, deviceidx = -1; int prompt_password = 0; char *seedfile = NULL; char **patterns, *pend; int verbose = 1; int npatterns = 0; int nthreads = 0; int worksize = 0; int nrows = 0, ncols = 0; int invsize = 0; int remove_on_match = 1; int only_one = 0; int verify_mode = 0; int safe_mode = 0; vg_context_t *vcp = NULL; vg_ocl_context_t *vocp = NULL; EC_POINT *pubkey_base = NULL; const char *result_file = NULL; const char *key_password = NULL; char *devstrs[MAX_DEVS]; int ndevstrs = 0; int opened = 0; FILE *pattfp[MAX_FILE], *fp; int pattfpi[MAX_FILE]; int npattfp = 0; int pattstdin = 0; sqlite3 *db; int i; while ((opt = getopt(argc, argv, "vqik1NTX:eE:p:P:d:w:t:g:b:VSh?f:o:s:D:H")) != -1) { switch (opt) { case 'v': verbose = 2; break; case 'q': verbose = 0; break; case 'i': caseinsensitive = 1; break; case 'k': remove_on_match = 0; break; case '1': only_one = 1; break; case 'N': addrtype = 52; privtype = 180; break; case 'T': addrtype = 111; privtype = 239; break; case 'X': addrtype = atoi(optarg); privtype = 128 + addrtype; break; case 'e': prompt_password = 1; break; case 'E': key_password = optarg; break; case 'p': platformidx = atoi(optarg); break; case 'd': deviceidx = atoi(optarg); break; case 'w': worksize = atoi(optarg); if (worksize == 0) { fprintf(stderr, "Invalid work size '%s'\n", optarg); return 1; } break; case 't': nthreads = atoi(optarg); if (nthreads == 0) { fprintf(stderr, "Invalid thread count '%s'\n", optarg); return 1; } break; case 'g': nrows = 0; ncols = strtol(optarg, &pend, 0); if (pend && *pend == 'x') { nrows = strtol(pend+1, NULL, 0); } if (!nrows || !ncols) { fprintf(stderr, "Invalid grid size '%s'\n", optarg); return 1; } break; case 'b': invsize = atoi(optarg); if (!invsize) { fprintf(stderr, "Invalid modular inverse size '%s'\n", optarg); return 1; } if (invsize & (invsize - 1)) { fprintf(stderr, "Modular inverse size must be " "a power of 2\n"); return 1; } break; case 'V': verify_mode = 1; break; case 'S': safe_mode = 1; break; case 'D': if (ndevstrs >= MAX_DEVS) { fprintf(stderr, "Too many OpenCL devices (limit %d)\n", MAX_DEVS); return 1; } devstrs[ndevstrs++] = optarg; break; case 'P': { if (pubkey_base != NULL) { fprintf(stderr, "Multiple base pubkeys specified\n"); return 1; } EC_KEY *pkey = vg_exec_context_new_key(); pubkey_base = EC_POINT_hex2point( EC_KEY_get0_group(pkey), optarg, NULL, NULL); EC_KEY_free(pkey); if (pubkey_base == NULL) { fprintf(stderr, "Invalid base pubkey\n"); return 1; } break; } case 'f': if (npattfp >= MAX_FILE) { fprintf(stderr, "Too many input files specified\n"); return 1; } if (!strcmp(optarg, "-")) { if (pattstdin) { fprintf(stderr, "ERROR: stdin " "specified multiple times\n"); return 1; } fp = stdin; } else { fp = fopen(optarg, "r"); if (!fp) { fprintf(stderr, "Could not open %s: %s\n", optarg, strerror(errno)); return 1; } } pattfp[npattfp] = fp; pattfpi[npattfp] = caseinsensitive; npattfp++; break; case 'o': if (result_file) { fprintf(stderr, "Multiple output files specified\n"); return 1; } result_file = optarg; break; case 's': if (seedfile != NULL) { fprintf(stderr, "Multiple RNG seeds specified\n"); return 1; } seedfile = optarg; break; case 'H': fprintf(stderr, "Saving to database\n"); int rc; char* zErrMsg; char* sql; /* Open database */ rc = sqlite3_open("btc_dataBase.db", &db); if (rc) { fprintf(stderr, "Can't open database: %s\n", sqlite3_errmsg(db)); sqlite3_close(db); exit(EXIT_FAILURE); } else { fprintf(stdout, "Opened database successfully\n"); } /* Create Table */ sql = "CREATE TABLE BITCOIN(" \ "ADDRESS CHAR(50) PRIMARY KEY NOT NULL," \ "PRIVKEY CHAR(70) NOT NULL," \ "PATTERN CHAR(20) NOT NULL);"; /* Execute Create Table*/ rc = sqlite3_exec(db, sql, callback, NULL, &zErrMsg); if (rc != SQLITE_OK) { fprintf(stderr, "CREATE TABLE SQL error: %s\n", zErrMsg); sqlite3_free(zErrMsg); } else { fprintf(stdout, "CREATE TABLE successfully\n"); } sqlite3_close(db); break; default: usage(argv[0]); return 1; } } #if OPENSSL_VERSION_NUMBER < 0x10000000L /* Complain about older versions of OpenSSL */ if (verbose > 0) { fprintf(stderr, "WARNING: Built with " OPENSSL_VERSION_TEXT "\n" "WARNING: Use OpenSSL 1.0.0d+ for best performance\n"); } #endif if (caseinsensitive && regex) fprintf(stderr, "WARNING: case insensitive mode incompatible with " "regular expressions\n"); if (seedfile) { opt = -1; #if !defined(_WIN32) { struct stat st; if (!stat(seedfile, &st) && (st.st_mode & (S_IFBLK|S_IFCHR))) { opt = 32; } } #endif opt = RAND_load_file(seedfile, opt); if (!opt) { fprintf(stderr, "Could not load RNG seed %s\n", optarg); return 1; } if (verbose > 0) { fprintf(stderr, "Read %d bytes from RNG seed file\n", opt); } } if (regex) { vcp = vg_regex_context_new(addrtype, privtype); } else { vcp = vg_prefix_context_new(addrtype, privtype, caseinsensitive); } vcp->vc_verbose = verbose; vcp->vc_result_file = result_file; vcp->vc_remove_on_match = remove_on_match; vcp->vc_only_one = only_one; vcp->vc_pubkeytype = addrtype; vcp->vc_pubkey_base = pubkey_base; vcp->vc_output_match = vg_output_match_console; vcp->vc_output_timing = vg_output_timing_console; if (!npattfp) { if (optind >= argc) { usage(argv[0]); return 1; } patterns = &argv[optind]; npatterns = argc - optind; if (!vg_context_add_patterns(vcp, (const char ** const) patterns, npatterns)) return 1; } for (i = 0; i < npattfp; i++) { fp = pattfp[i]; if (!vg_read_file(fp, &patterns, &npatterns)) { fprintf(stderr, "Failed to load pattern file\n"); return 1; } if (fp != stdin) fclose(fp); if (!regex) vg_prefix_context_set_case_insensitive(vcp, pattfpi[i]); if (!vg_context_add_patterns(vcp, (const char ** const) patterns, npatterns)) return 1; } if (!vcp->vc_npatterns) { fprintf(stderr, "No patterns to search\n"); return 1; } if (prompt_password) { if (!vg_read_password(pwbuf, sizeof(pwbuf))) return 1; key_password = pwbuf; } vcp->vc_key_protect_pass = key_password; if (key_password) { if (!vg_check_password_complexity(key_password, verbose)) fprintf(stderr, "WARNING: Protecting private keys with " "weak password\n"); } if ((verbose > 0) && regex && (vcp->vc_npatterns > 1)) fprintf(stderr, "Regular expressions: %ld\n", vcp->vc_npatterns); if (ndevstrs) { for (opt = 0; opt < ndevstrs; opt++) { vocp = vg_ocl_context_new_from_devstr(vcp, devstrs[opt], safe_mode, verify_mode); if (!vocp) { fprintf(stderr, "Could not open device '%s', ignoring\n", devstrs[opt]); } else { opened++; } } } else { vocp = vg_ocl_context_new(vcp, platformidx, deviceidx, safe_mode, verify_mode, worksize, nthreads, nrows, ncols, invsize); if (vocp) opened++; } if (!opened) { vg_ocl_enumerate_devices(); return 1; } opt = vg_context_start_threads(vcp); if (opt) return 1; vg_context_wait_for_completion(vcp); vg_ocl_context_free(vocp); return 0; }
static int try_to_open_db(const char *filename, struct memblock *mem, struct dive_table *table) { sqlite3 *handle; char dm4_test[] = "select count(*) from sqlite_master where type='table' and name='Dive' and sql like '%ProfileBlob%'"; char dm5_test[] = "select count(*) from sqlite_master where type='table' and name='Dive' and sql like '%SampleBlob%'"; char shearwater_test[] = "select count(*) from sqlite_master where type='table' and name='system' and sql like '%dbVersion%'"; char cobalt_test[] = "select count(*) from sqlite_master where type='table' and name='TrackPoints' and sql like '%DepthPressure%'"; char divinglog_test[] = "select count(*) from sqlite_master where type='table' and name='DBInfo' and sql like '%PrgName%'"; int retval; retval = sqlite3_open(filename, &handle); if (retval) { fprintf(stderr, "Database connection failed '%s'.\n", filename); return 1; } /* Testing if DB schema resembles Suunto DM5 database format */ retval = sqlite3_exec(handle, dm5_test, &db_test_func, 0, NULL); if (!retval) { retval = parse_dm5_buffer(handle, filename, mem->buffer, mem->size, table); sqlite3_close(handle); return retval; } /* Testing if DB schema resembles Suunto DM4 database format */ retval = sqlite3_exec(handle, dm4_test, &db_test_func, 0, NULL); if (!retval) { retval = parse_dm4_buffer(handle, filename, mem->buffer, mem->size, table); sqlite3_close(handle); return retval; } /* Testing if DB schema resembles Shearwater database format */ retval = sqlite3_exec(handle, shearwater_test, &db_test_func, 0, NULL); if (!retval) { retval = parse_shearwater_buffer(handle, filename, mem->buffer, mem->size, table); sqlite3_close(handle); return retval; } /* Testing if DB schema resembles Atomic Cobalt database format */ retval = sqlite3_exec(handle, cobalt_test, &db_test_func, 0, NULL); if (!retval) { retval = parse_cobalt_buffer(handle, filename, mem->buffer, mem->size, table); sqlite3_close(handle); return retval; } /* Testing if DB schema resembles Divinglog database format */ retval = sqlite3_exec(handle, divinglog_test, &db_test_func, 0, NULL); if (!retval) { retval = parse_divinglog_buffer(handle, filename, mem->buffer, mem->size, table); sqlite3_close(handle); return retval; } sqlite3_close(handle); return retval; }
// opens a new sqlite database DBInterface::DBInterface(std::string db_path) { sqlite3_open(db_path.c_str(), &database); }
gboolean gc_db_init(gboolean disable_database_) { #ifdef USE_SQLITE disable_database = disable_database_; SUPPORT_OR_RETURN(FALSE); gboolean creation = FALSE; char *zErrMsg; char **result; int rc; int nrow; int ncolumn; GcomprisProperties *properties = gc_prop_get(); if (!g_file_test(properties->database, G_FILE_TEST_EXISTS)) creation = TRUE; rc = sqlite3_open(properties->database, &gcompris_db); if( rc ){ g_message("Can't open database %s : %s\n", properties->database, sqlite3_errmsg(gcompris_db)); sqlite3_close(gcompris_db); disable_database = TRUE; return FALSE; } g_message("Database %s opened", properties->database); if (creation){ _create_db(); } else { if ( ! _check_db_integrity() || _gc_boards_count() == 0 ) { // We failed to load the database, let's // backup it and re create it. sqlite3_close(gcompris_db); gchar *backup = g_strdup_printf("%s.broken", properties->database); if ( g_rename(properties->database, backup) < 0 ) { // Obviously, we cannot write the backup file either g_message("Failed to write the backup database %s", backup); disable_database = TRUE; return FALSE; } else g_message("Database is broken, it is copyed in %s", backup); g_free(backup); rc = sqlite3_open(properties->database, &gcompris_db); if( rc ){ g_message("Can't open database %s : %s\n", properties->database, sqlite3_errmsg(gcompris_db)); sqlite3_close(gcompris_db); disable_database = TRUE; return FALSE; } _create_db(); if ( ! _check_db_integrity() ) { disable_database = TRUE; return FALSE; } } g_message("Database Integrity ok"); rc = sqlite3_get_table(gcompris_db, CHECK_VERSION, &result, &nrow, &ncolumn, &zErrMsg ); if( rc!=SQLITE_OK ){ g_error("SQL error: %s\n", zErrMsg); } if (strcmp(result[1],VERSION)!=0) g_message("Running GCompris is %s, but database version is %s", VERSION, result[1]); sqlite3_free_table(result); /* Schema upgrade */ rc = sqlite3_get_table(gcompris_db, PRAGMA_SCHEMA_VERSION, &result, &nrow, &ncolumn, &zErrMsg ); if( rc!=SQLITE_OK ){ g_error("SQL error: %s\n", zErrMsg); } int version = atoi(result[1]); sqlite3_free_table(result); if(version <= 16) { g_message("Upgrading from <16 schema version\n"); rc = sqlite3_exec(gcompris_db,CREATE_TABLE_LOGS, NULL, 0, &zErrMsg); if( rc!=SQLITE_OK ) { g_error("SQL error: %s\n", zErrMsg); } } if ( _get_user_version() == 0) { g_message("Upgrading schema based on user version = 0\n"); rc = sqlite3_exec(gcompris_db,"DROP TABLE boards;", NULL, 0, &zErrMsg); if( rc!=SQLITE_OK ) { g_error("SQL error: %s\n", zErrMsg); } rc = sqlite3_exec(gcompris_db,CREATE_TABLE_BOARDS, NULL, 0, &zErrMsg); if( rc!=SQLITE_OK ) { g_error("SQL error: %s\n", zErrMsg); } // We just dropped the boards table, force a reread properties->reread_menu = TRUE; _set_user_version(1); } } return TRUE; #else return FALSE; #endif }
int main(int argc, char **argv){ const char *zDb; int rc = 0; char *zErr = 0; int i; int iVerbose = 1; /* -verbose option */ sqlite3 *db = 0; sqlite3expert *p = 0; if( argc<2 ) usage(argv); zDb = argv[argc-1]; if( zDb[0]=='-' ) usage(argv); rc = sqlite3_open(zDb, &db); if( rc!=SQLITE_OK ){ fprintf(stderr, "Cannot open db file: %s - %s\n", zDb, sqlite3_errmsg(db)); exit(-2); } p = sqlite3_expert_new(db, &zErr); if( p==0 ){ fprintf(stderr, "Cannot run analysis: %s\n", zErr); rc = 1; }else{ for(i=1; i<(argc-1); i++){ char *zArg = argv[i]; int nArg; if( zArg[0]=='-' && zArg[1]=='-' && zArg[2]!=0 ) zArg++; nArg = (int)strlen(zArg); if( nArg>=2 && 0==sqlite3_strnicmp(zArg, "-file", nArg) ){ if( ++i==(argc-1) ) option_requires_argument("-file"); rc = readSqlFromFile(p, argv[i], &zErr); } else if( nArg>=3 && 0==sqlite3_strnicmp(zArg, "-sql", nArg) ){ if( ++i==(argc-1) ) option_requires_argument("-sql"); rc = sqlite3_expert_sql(p, argv[i], &zErr); } else if( nArg>=3 && 0==sqlite3_strnicmp(zArg, "-sample", nArg) ){ int iSample; if( ++i==(argc-1) ) option_requires_argument("-sample"); iSample = option_integer_arg(argv[i]); sqlite3_expert_config(p, EXPERT_CONFIG_SAMPLE, iSample); } else if( nArg>=2 && 0==sqlite3_strnicmp(zArg, "-verbose", nArg) ){ if( ++i==(argc-1) ) option_requires_argument("-verbose"); iVerbose = option_integer_arg(argv[i]); } else{ usage(argv); } } } if( rc==SQLITE_OK ){ rc = sqlite3_expert_analyze(p, &zErr); } if( rc==SQLITE_OK ){ int nQuery = sqlite3_expert_count(p); if( iVerbose>0 ){ const char *zCand = sqlite3_expert_report(p,0,EXPERT_REPORT_CANDIDATES); fprintf(stdout, "-- Candidates -------------------------------\n"); fprintf(stdout, "%s\n", zCand); } for(i=0; i<nQuery; i++){ const char *zSql = sqlite3_expert_report(p, i, EXPERT_REPORT_SQL); const char *zIdx = sqlite3_expert_report(p, i, EXPERT_REPORT_INDEXES); const char *zEQP = sqlite3_expert_report(p, i, EXPERT_REPORT_PLAN); if( zIdx==0 ) zIdx = "(no new indexes)\n"; if( iVerbose>0 ){ fprintf(stdout, "-- Query %d ----------------------------------\n",i+1); fprintf(stdout, "%s\n\n", zSql); } fprintf(stdout, "%s\n%s\n", zIdx, zEQP); } }else{ fprintf(stderr, "Error: %s\n", zErr ? zErr : "?"); } sqlite3_expert_destroy(p); sqlite3_free(zErr); return rc; }
int main(int argc, char **argv) { sqlite3_int64 iBegin; /* Start time of this program */ int quietFlag = 0; /* True if --quiet or -q */ int verboseFlag = 0; /* True if --verbose or -v */ char *zInsSql = 0; /* SQL statement for --load-db or --load-sql */ int iFirstInsArg = 0; /* First argv[] to use for --load-db or --load-sql */ sqlite3 *db = 0; /* The open database connection */ sqlite3_stmt *pStmt; /* A prepared statement */ int rc; /* Result code from SQLite interface calls */ Blob *pSql; /* For looping over SQL scripts */ Blob *pDb; /* For looping over template databases */ int i; /* Loop index for the argv[] loop */ int onlySqlid = -1; /* --sqlid */ int onlyDbid = -1; /* --dbid */ int nativeFlag = 0; /* --native-vfs */ int rebuildFlag = 0; /* --rebuild */ int vdbeLimitFlag = 0; /* --limit-vdbe */ int timeoutTest = 0; /* undocumented --timeout-test flag */ int runFlags = 0; /* Flags sent to runSql() */ char *zMsg = 0; /* Add this message */ int nSrcDb = 0; /* Number of source databases */ char **azSrcDb = 0; /* Array of source database names */ int iSrcDb; /* Loop over all source databases */ int nTest = 0; /* Total number of tests performed */ char *zDbName = ""; /* Appreviated name of a source database */ const char *zFailCode = 0; /* Value of the TEST_FAILURE environment variable */ int cellSzCkFlag = 0; /* --cell-size-check */ int sqlFuzz = 0; /* True for SQL fuzz testing. False for DB fuzz */ int iTimeout = 120; /* Default 120-second timeout */ int nMem = 0; /* Memory limit */ char *zExpDb = 0; /* Write Databases to files in this directory */ char *zExpSql = 0; /* Write SQL to files in this directory */ void *pHeap = 0; /* Heap for use by SQLite */ iBegin = timeOfDay(); #ifdef __unix__ signal(SIGALRM, timeoutHandler); #endif g.zArgv0 = argv[0]; zFailCode = getenv("TEST_FAILURE"); for(i=1; i<argc; i++) { const char *z = argv[i]; if( z[0]=='-' ) { z++; if( z[0]=='-' ) z++; if( strcmp(z,"cell-size-check")==0 ) { cellSzCkFlag = 1; } else if( strcmp(z,"dbid")==0 ) { if( i>=argc-1 ) fatalError("missing arguments on %s", argv[i]); onlyDbid = integerValue(argv[++i]); } else if( strcmp(z,"export-db")==0 ) { if( i>=argc-1 ) fatalError("missing arguments on %s", argv[i]); zExpDb = argv[++i]; } else if( strcmp(z,"export-sql")==0 ) { if( i>=argc-1 ) fatalError("missing arguments on %s", argv[i]); zExpSql = argv[++i]; } else if( strcmp(z,"help")==0 ) { showHelp(); return 0; } else if( strcmp(z,"limit-mem")==0 ) { #if !defined(SQLITE_ENABLE_MEMSYS3) && !defined(SQLITE_ENABLE_MEMSYS5) fatalError("the %s option requires -DSQLITE_ENABLE_MEMSYS5 or _MEMSYS3", argv[i]); #else if( i>=argc-1 ) fatalError("missing arguments on %s", argv[i]); nMem = integerValue(argv[++i]); #endif } else if( strcmp(z,"limit-vdbe")==0 ) { vdbeLimitFlag = 1; } else if( strcmp(z,"load-sql")==0 ) { zInsSql = "INSERT INTO xsql(sqltext) VALUES(CAST(readfile(?1) AS text))"; iFirstInsArg = i+1; break; } else if( strcmp(z,"load-db")==0 ) { zInsSql = "INSERT INTO db(dbcontent) VALUES(readfile(?1))"; iFirstInsArg = i+1; break; } else if( strcmp(z,"m")==0 ) { if( i>=argc-1 ) fatalError("missing arguments on %s", argv[i]); zMsg = argv[++i]; } else if( strcmp(z,"native-vfs")==0 ) { nativeFlag = 1; } else if( strcmp(z,"quiet")==0 || strcmp(z,"q")==0 ) { quietFlag = 1; verboseFlag = 0; } else if( strcmp(z,"rebuild")==0 ) { rebuildFlag = 1; } else if( strcmp(z,"result-trace")==0 ) { runFlags |= SQL_OUTPUT; } else if( strcmp(z,"sqlid")==0 ) { if( i>=argc-1 ) fatalError("missing arguments on %s", argv[i]); onlySqlid = integerValue(argv[++i]); } else if( strcmp(z,"timeout")==0 ) { if( i>=argc-1 ) fatalError("missing arguments on %s", argv[i]); iTimeout = integerValue(argv[++i]); } else if( strcmp(z,"timeout-test")==0 ) { timeoutTest = 1; #ifndef __unix__ fatalError("timeout is not available on non-unix systems"); #endif } else if( strcmp(z,"verbose")==0 || strcmp(z,"v")==0 ) { quietFlag = 0; verboseFlag++; if( verboseFlag>1 ) runFlags |= SQL_TRACE; } else { fatalError("unknown option: %s", argv[i]); } } else { nSrcDb++; azSrcDb = safe_realloc(azSrcDb, nSrcDb*sizeof(azSrcDb[0])); azSrcDb[nSrcDb-1] = argv[i]; } } if( nSrcDb==0 ) fatalError("no source database specified"); if( nSrcDb>1 ) { if( zMsg ) { fatalError("cannot change the description of more than one database"); } if( zInsSql ) { fatalError("cannot import into more than one database"); } } /* Process each source database separately */ for(iSrcDb=0; iSrcDb<nSrcDb; iSrcDb++) { rc = sqlite3_open(azSrcDb[iSrcDb], &db); if( rc ) { fatalError("cannot open source database %s - %s", azSrcDb[iSrcDb], sqlite3_errmsg(db)); } rc = sqlite3_exec(db, "CREATE TABLE IF NOT EXISTS db(\n" " dbid INTEGER PRIMARY KEY, -- database id\n" " dbcontent BLOB -- database disk file image\n" ");\n" "CREATE TABLE IF NOT EXISTS xsql(\n" " sqlid INTEGER PRIMARY KEY, -- SQL script id\n" " sqltext TEXT -- Text of SQL statements to run\n" ");" "CREATE TABLE IF NOT EXISTS readme(\n" " msg TEXT -- Human-readable description of this file\n" ");", 0, 0, 0); if( rc ) fatalError("cannot create schema: %s", sqlite3_errmsg(db)); if( zMsg ) { char *zSql; zSql = sqlite3_mprintf( "DELETE FROM readme; INSERT INTO readme(msg) VALUES(%Q)", zMsg); rc = sqlite3_exec(db, zSql, 0, 0, 0); sqlite3_free(zSql); if( rc ) fatalError("cannot change description: %s", sqlite3_errmsg(db)); } if( zInsSql ) { sqlite3_create_function(db, "readfile", 1, SQLITE_UTF8, 0, readfileFunc, 0, 0); rc = sqlite3_prepare_v2(db, zInsSql, -1, &pStmt, 0); if( rc ) fatalError("cannot prepare statement [%s]: %s", zInsSql, sqlite3_errmsg(db)); rc = sqlite3_exec(db, "BEGIN", 0, 0, 0); if( rc ) fatalError("cannot start a transaction"); for(i=iFirstInsArg; i<argc; i++) { sqlite3_bind_text(pStmt, 1, argv[i], -1, SQLITE_STATIC); sqlite3_step(pStmt); rc = sqlite3_reset(pStmt); if( rc ) fatalError("insert failed for %s", argv[i]); } sqlite3_finalize(pStmt); rc = sqlite3_exec(db, "COMMIT", 0, 0, 0); if( rc ) fatalError("cannot commit the transaction: %s", sqlite3_errmsg(db)); rebuild_database(db); sqlite3_close(db); return 0; } if( zExpDb!=0 || zExpSql!=0 ) { sqlite3_create_function(db, "writefile", 2, SQLITE_UTF8, 0, writefileFunc, 0, 0); if( zExpDb!=0 ) { const char *zExDb = "SELECT writefile(printf('%s/db%06d.db',?1,dbid),dbcontent)," " dbid, printf('%s/db%06d.db',?1,dbid), length(dbcontent)" " FROM db WHERE ?2<0 OR dbid=?2;"; rc = sqlite3_prepare_v2(db, zExDb, -1, &pStmt, 0); if( rc ) fatalError("cannot prepare statement [%s]: %s", zExDb, sqlite3_errmsg(db)); sqlite3_bind_text64(pStmt, 1, zExpDb, strlen(zExpDb), SQLITE_STATIC, SQLITE_UTF8); sqlite3_bind_int(pStmt, 2, onlyDbid); while( sqlite3_step(pStmt)==SQLITE_ROW ) { printf("write db-%d (%d bytes) into %s\n", sqlite3_column_int(pStmt,1), sqlite3_column_int(pStmt,3), sqlite3_column_text(pStmt,2)); } sqlite3_finalize(pStmt); } if( zExpSql!=0 ) { const char *zExSql = "SELECT writefile(printf('%s/sql%06d.txt',?1,sqlid),sqltext)," " sqlid, printf('%s/sql%06d.txt',?1,sqlid), length(sqltext)" " FROM xsql WHERE ?2<0 OR sqlid=?2;"; rc = sqlite3_prepare_v2(db, zExSql, -1, &pStmt, 0); if( rc ) fatalError("cannot prepare statement [%s]: %s", zExSql, sqlite3_errmsg(db)); sqlite3_bind_text64(pStmt, 1, zExpSql, strlen(zExpSql), SQLITE_STATIC, SQLITE_UTF8); sqlite3_bind_int(pStmt, 2, onlySqlid); while( sqlite3_step(pStmt)==SQLITE_ROW ) { printf("write sql-%d (%d bytes) into %s\n", sqlite3_column_int(pStmt,1), sqlite3_column_int(pStmt,3), sqlite3_column_text(pStmt,2)); } sqlite3_finalize(pStmt); } sqlite3_close(db); return 0; } /* Load all SQL script content and all initial database images from the ** source db */ blobListLoadFromDb(db, "SELECT sqlid, sqltext FROM xsql", onlySqlid, &g.nSql, &g.pFirstSql); if( g.nSql==0 ) fatalError("need at least one SQL script"); blobListLoadFromDb(db, "SELECT dbid, dbcontent FROM db", onlyDbid, &g.nDb, &g.pFirstDb); if( g.nDb==0 ) { g.pFirstDb = safe_realloc(0, sizeof(Blob)); memset(g.pFirstDb, 0, sizeof(Blob)); g.pFirstDb->id = 1; g.pFirstDb->seq = 0; g.nDb = 1; sqlFuzz = 1; } /* Print the description, if there is one */ if( !quietFlag ) { zDbName = azSrcDb[iSrcDb]; i = (int)strlen(zDbName) - 1; while( i>0 && zDbName[i-1]!='/' && zDbName[i-1]!='\\' ) { i--; } zDbName += i; sqlite3_prepare_v2(db, "SELECT msg FROM readme", -1, &pStmt, 0); if( pStmt && sqlite3_step(pStmt)==SQLITE_ROW ) { printf("%s: %s\n", zDbName, sqlite3_column_text(pStmt,0)); } sqlite3_finalize(pStmt); } /* Rebuild the database, if requested */ if( rebuildFlag ) { if( !quietFlag ) { printf("%s: rebuilding... ", zDbName); fflush(stdout); } rebuild_database(db); if( !quietFlag ) printf("done\n"); } /* Close the source database. Verify that no SQLite memory allocations are ** outstanding. */ sqlite3_close(db); if( sqlite3_memory_used()>0 ) { fatalError("SQLite has memory in use before the start of testing"); } /* Limit available memory, if requested */ if( nMem>0 ) { sqlite3_shutdown(); pHeap = malloc(nMem); if( pHeap==0 ) { fatalError("failed to allocate %d bytes of heap memory", nMem); } sqlite3_config(SQLITE_CONFIG_HEAP, pHeap, nMem, 128); } /* Register the in-memory virtual filesystem */ formatVfs(); inmemVfsRegister(); /* Run a test using each SQL script against each database. */ if( !verboseFlag && !quietFlag ) printf("%s:", zDbName); for(pSql=g.pFirstSql; pSql; pSql=pSql->pNext) { for(pDb=g.pFirstDb; pDb; pDb=pDb->pNext) { int openFlags; const char *zVfs = "inmem"; sqlite3_snprintf(sizeof(g.zTestName), g.zTestName, "sqlid=%d,dbid=%d", pSql->id, pDb->id); if( verboseFlag ) { printf("%s\n", g.zTestName); fflush(stdout); } else if( !quietFlag ) { static int prevAmt = -1; int idx = pSql->seq*g.nDb + pDb->id - 1; int amt = idx*10/(g.nDb*g.nSql); if( amt!=prevAmt ) { printf(" %d%%", amt*10); fflush(stdout); prevAmt = amt; } } createVFile("main.db", pDb->sz, pDb->a); openFlags = SQLITE_OPEN_CREATE | SQLITE_OPEN_READWRITE; if( nativeFlag && pDb->sz==0 ) { openFlags |= SQLITE_OPEN_MEMORY; zVfs = 0; } rc = sqlite3_open_v2("main.db", &db, openFlags, zVfs); if( rc ) fatalError("cannot open inmem database"); if( cellSzCkFlag ) runSql(db, "PRAGMA cell_size_check=ON", runFlags); setAlarm(iTimeout); #ifndef SQLITE_OMIT_PROGRESS_CALLBACK if( sqlFuzz || vdbeLimitFlag ) { sqlite3_progress_handler(db, 100000, progressHandler, &vdbeLimitFlag); } #endif do { runSql(db, (char*)pSql->a, runFlags); } while( timeoutTest ); setAlarm(0); sqlite3_close(db); if( sqlite3_memory_used()>0 ) fatalError("memory leak"); reformatVfs(); nTest++; g.zTestName[0] = 0; /* Simulate an error if the TEST_FAILURE environment variable is "5". ** This is used to verify that automated test script really do spot ** errors that occur in this test program. */ if( zFailCode ) { if( zFailCode[0]=='5' && zFailCode[1]==0 ) { fatalError("simulated failure"); } else if( zFailCode[0]!=0 ) { /* If TEST_FAILURE is something other than 5, just exit the test ** early */ printf("\nExit early due to TEST_FAILURE being set\n"); iSrcDb = nSrcDb-1; goto sourcedb_cleanup; } } } } if( !quietFlag && !verboseFlag ) { printf(" 100%% - %d tests\n", g.nDb*g.nSql); } /* Clean up at the end of processing a single source database */ sourcedb_cleanup: blobListFree(g.pFirstSql); blobListFree(g.pFirstDb); reformatVfs(); } /* End loop over all source databases */ if( !quietFlag ) { sqlite3_int64 iElapse = timeOfDay() - iBegin; printf("fuzzcheck: 0 errors out of %d tests in %d.%03d seconds\n" "SQLite %s %s\n", nTest, (int)(iElapse/1000), (int)(iElapse%1000), sqlite3_libversion(), sqlite3_sourceid()); } free(azSrcDb); free(pHeap); return 0; }
extern void setup_sqlite() { int i; sqlite3_stmt *stmt = (sqlite3_stmt *)NULL; char *ztail = (char *)NULL; char *create[] = {"pragma foreign_keys=true", "create table decks" " (deckid integer primary key not null," " filename varchar(250) not null," " shortname varchar(30) not null," " constraint slides_uq unique(filename))", "create table slides" " (slideid integer primary key not null," " deckid int not null," " slidenum int not null," " constraint slides_uq unique(deckid," " slidenum)," " constraint slides_fk" " foreign key(deckid)" " references decks(deckid))", "create table words" " (word varchar(60) not null," " kw char(1) not null default 'N'," " slideid int not null," " counter int not null default 1," " origin char(1) not null," " stem varchar(30)," " constraint words_pk primary key(word," " slideid,origin)," " constraint words_fk" " foreign key(slideid)" " references slides(slideid))", "create index words_idx" " on words(slideid,word)", "create index words_idx2" " on words(stem)", NULL}; if (sqlite3_open(":memory:", &G_db) != SQLITE_OK) { fprintf(stderr, "sqlite3_open: %s\n", (char *)sqlite3_errmsg(G_db)); exit(1); } i = 0; while (create[i]) { if ((sqlite3_prepare(G_db, (const char *)create[i], -1, &stmt, (const char **)&ztail) != SQLITE_OK) || (sqlite3_step(stmt) != SQLITE_DONE)) { fprintf(stderr, "%s: %s\n", create[i], (char *)sqlite3_errmsg(G_db)); (void)sqlite3_close(G_db); exit(1); } (void)sqlite3_finalize(stmt); i++; } // Prepare statements that will be repeatedly executed if ((sqlite3_prepare(G_db, "insert into decks(filename,shortname)" "values(?,lower(?))", -1, &G_ins_deck, (const char **)&ztail) != SQLITE_OK) || (sqlite3_prepare(G_db, "insert or ignore into slides(deckid,slidenum)" "values(?,?)", -1, &G_ins_slide, (const char **)&ztail) != SQLITE_OK) || (sqlite3_prepare(G_db, "select slideid from slides" " where deckid=? and slidenum=?", -1, &G_sel_slide, (const char **)&ztail) != SQLITE_OK) || (sqlite3_prepare(G_db, "insert into words(word,slideid,origin,kw)" "values(lower(trim(?)),?,upper(char(?))," "case ? when 0 then 'N' else 'Y' end)", -1, &G_ins_word, (const char **)&ztail) != SQLITE_OK) || (sqlite3_prepare(G_db, "insert into words(word,slideid,origin,kw)" "values(trim(?),?,upper(char(?))," "case ? when 0 then 'N' else 'Y' end)", -1, &G_ins_word_as_is, (const char **)&ztail) != SQLITE_OK) || (sqlite3_prepare(G_db, "update words set counter=counter+1" " where word=lower(trim(?))" " and slideid=?" " and origin=upper(?)", -1, &G_upd_word, (const char **)&ztail) != SQLITE_OK) || (sqlite3_prepare(G_db, "update words set counter=counter+1" " where word=trim(?)" " and slideid=?" " and origin=upper(?)", -1, &G_upd_word_as_is, (const char **)&ztail) != SQLITE_OK)) { fprintf(stderr, "insert/update: %s\n", (char *)sqlite3_errmsg(G_db)); (void)sqlite3_close(G_db); exit(1); } atexit(finalize_sqlite); }
void initializeTags(void * mainCache) { MUTEX_CREATE(concurentColdUpdate); sqlite3 * coldDB = NULL; //Create the tables in the main cache createTagsTable(mainCache); if((!checkFileExist(TAG_DB) || sqlite3_open(TAG_DB , &coldDB) != SQLITE_OK) && (!checkFileExist(WIP_TAG_DB) || sqlite3_open(WIP_TAG_DB, &coldDB) != SQLITE_OK)) { //Error, we should reset it with the version we ship with then trigger an update resetTagsToLocal(); if(!checkFileExist(TAG_DB) || sqlite3_open(TAG_DB , &coldDB) != SQLITE_OK) { alertExit("We have significant issues setting up our environment, this may be caused by permission issues, please contact us at [email protected]"); } } sqlite3_stmt * requestRead, *requestWrite; //Build the tag base if((requestRead = createRequest(coldDB, "SELECT "DBNAMETOID(RDB_tagID)", "DBNAMETOID(RDB_tagName)" FROM "TABLE_TAGS)) != NULL) { requestWrite = tagUpdateQuery(mainCache, false); if(requestWrite != NULL) { while(sqlite3_step(requestRead) == SQLITE_ROW) { sqlite3_bind_int(requestWrite, 1, sqlite3_column_int(requestRead, 0)); sqlite3_bind_text(requestWrite, 2, (void *) sqlite3_column_text(requestRead, 1), -1, SQLITE_STATIC); if(sqlite3_step(requestWrite) != SQLITE_DONE) { #ifdef EXTENSIVE_LOGGING uint ID = (uint32_t) sqlite3_column_int(requestRead, 0); const unsigned char * text = sqlite3_column_text(requestRead, 1); if(text == NULL) logR("Error building the tag DB for ID %d: no text!", ID); else logR("Error building the tag DB for ID %d of text %s!", ID, text); #endif } sqlite3_reset(requestWrite); } destroyRequest(requestWrite); } destroyRequest(requestRead); } //Build the category base if((requestRead = createRequest(coldDB, "SELECT "DBNAMETOID(RDB_CAT_ID)", "DBNAMETOID(RDB_CAT_rootID)", "DBNAMETOID(RDB_CAT_name)" FROM "TABLE_CATEGORY)) != NULL) { requestWrite = catUpdateQuery(mainCache, false); if(requestWrite != NULL) { while(sqlite3_step(requestRead) == SQLITE_ROW) { sqlite3_bind_int(requestWrite, 1, sqlite3_column_int(requestRead, 0)); sqlite3_bind_int(requestWrite, 2, sqlite3_column_int(requestRead, 1)); sqlite3_bind_text(requestWrite, 3, (void *) sqlite3_column_text(requestRead, 2), -1, SQLITE_STATIC); for(byte i = 0; i < 32; i++) { sqlite3_bind_int(requestWrite, i + 4, sqlite3_column_int(requestRead, i + 3)); } if(sqlite3_step(requestWrite) != SQLITE_DONE) { #ifdef EXTENSIVE_LOGGING uint ID = (uint32_t) sqlite3_column_int(requestRead, 0); const unsigned char * text = sqlite3_column_text(requestRead, 2); if(text == NULL) logR("Error building the category DB for ID %d: no text!", ID); else logR("Error building the category DB for ID %d of text %s!", ID, text); #endif } sqlite3_reset(requestWrite); } destroyRequest(requestWrite); } destroyRequest(requestRead); } sqlite3_close(coldDB); }
int main( const int argc, const char const *argv[] ) { const char *rom1_filename; const char *rom2_filename; const char *db_filename; /**/ organization_s *organization; /**/ schedule_s *schedule; /**/ tsbrom_s *rom1; /**/ tsbrom_s *rom2; /**/ sqlite3 *db; /**/ char rom1_output_file [FILENAME_MAX + 1] = { 0 }; /**/ char rom2_output_file [FILENAME_MAX + 1] = { 0 }; /**/ char schedule_output_file [FILENAME_MAX + 1] = { 0 }; if ( argc < 4 ) { printf( "Usage %s <rom1> <rom2> <database> <output path>\n", argv[0] ); return EXIT_SUCCESS; } rom1_filename = argv[1]; rom2_filename = argv[2]; db_filename = argv[3]; sprintf( rom1_output_file, "%s/ncfo1.nes", argv[4] ); sprintf( rom2_output_file, "%s/ncfo2.nes", argv[4] ); sprintf( schedule_output_file, "%s/schedule.csv", argv[4] ); srand( time( NULL ) ); if ( (rom1 = readTsbRom( rom1_filename )) == NULL ) { printf( "Unable to open rom 1: %s\n", getFileUtilsError() ); return EXIT_FAILURE; } if ( (rom2 = readTsbRom( rom2_filename )) == NULL ) { printf( "Unable to open rom 2: %s\n", getFileUtilsError() ); free( rom1 ); return EXIT_FAILURE; } sqlite3_open( db_filename, &db ); if ( (organization = get_organization( db, 1 )) == NULL ) { printf( "Unable to retrieve organization data from database.\n" ); free( rom1 ); free( rom2 ); sqlite3_close( db ); return EXIT_FAILURE; } if ( ! populateRoms( rom1, rom2, organization ) ) { printf( "Error populating roms: %s\n", getPopulateRomsError() ); free( rom1 ); free( rom2 ); free_organization( organization ); sqlite3_close( db ); return EXIT_FAILURE; } injectSeason( rom1, organization->season ); injectSeason( rom2, organization->season ); if ( (schedule = generateSchedule( rom1, rom2 )) == NULL ) { printf( "Error generating schedule: %s\n", getGenerateScheduleError() ); free( rom1 ); free( rom2 ); free_organization( organization ); sqlite3_close( db ); return EXIT_FAILURE; } printf( "Creating TSB Rom File %s\n", rom1_output_file ); if ( ! writeTsbRom( rom1_output_file, rom1 ) ) { printf( "Unable to write to file %s: %s\n", rom1_output_file, getFileUtilsError() ); free( rom1 ); free( rom2 ); freeSchedule( schedule ); free_organization( organization ); sqlite3_close( db ); return EXIT_FAILURE; } printf( "Creating TSB Rom File %s\n", rom2_output_file ); if ( ! writeTsbRom( rom2_output_file, rom2 ) ) { printf( "Unable to write to file %s: %s\n", rom2_output_file, getFileUtilsError() ); free( rom1 ); free( rom2 ); freeSchedule( schedule ); free_organization( organization ); sqlite3_close( db ); return EXIT_FAILURE; } printf( "Creating Schedule File %s\n", schedule_output_file ); if ( ! writeSchedule( schedule_output_file, schedule ) ) { printf( "Unable to write to file %s: %s\n", schedule_output_file, getFileUtilsError() ); free( rom1 ); free( rom2 ); freeSchedule( schedule ); free_organization( organization ); sqlite3_close( db ); return EXIT_FAILURE; } free( rom1 ); free( rom2 ); freeSchedule( schedule ); free_organization( organization ); sqlite3_close( db ); return EXIT_SUCCESS; }
int main() { int ret; sqlite3 *disk_db = NULL; fprintf(stderr, "Opening disk database and trying to create the in memory database\n"); ret = sqlite3_open_v2("autocomplete.sqlite", &disk_db, SQLITE_OPEN_READONLY, NULL); if (SQLITE_OK != ret) { printf("Error opening database: %s\n", sqlite3_errmsg(disk_db)); goto end; } ret = sqlite3_open(":memory:", &db); if (SQLITE_OK != ret) { if (db == NULL) fprintf(stderr, "Insufficient Memory\n"); else printf("Error opening database: %s\n", sqlite3_errmsg(db)); goto close_and_end; } char *err; ret = sqlite3_exec(db, "CREATE TABLE autocomplete (english TEXT COLLATE NOCASE, tamil TEXT COLLATE NOCASE, score int)", NULL, NULL, &err); if (SQLITE_OK != ret) { printf("Error creating sqlite table: %s\n", sqlite3_errmsg(db)); goto close_and_end; } ret = sqlite3_prepare_v2(db, "INSERT INTO autocomplete VALUES (?, ?, ?)", -1, &stmt, NULL); if (SQLITE_OK != ret) { printf("Error creating prepared statement: %s\n", sqlite3_errmsg(db)); goto close_and_end; } ret = sqlite3_exec(db, "BEGIN TRANSACTION", NULL, NULL, &err); if (SQLITE_OK != ret) { printf("Error beginning a transaction: %s\n", sqlite3_errmsg(db)); goto close_and_end; } /* Select each record from the disk db and insert into the in-memory table */ ret = sqlite3_exec(disk_db, "SELECT english, tamil, score FROM autocomplete", disk_to_mem_cb, NULL, &err); if (SQLITE_OK != ret) { printf("Error conversion of disk_to_mem: %s\n", sqlite3_errmsg(db)); goto close_and_end; } ret = sqlite3_exec(db, "COMMIT", NULL, NULL, &err); if (SQLITE_OK != ret) { printf("Error committing a transaction: %s\n", sqlite3_errmsg(db)); goto close_and_end; } sqlite3_finalize(stmt); sqlite3_close(disk_db); fprintf(stderr, "In-memory database creation complete. About to create Indexes.\n"); /* Create Indexes */ fprintf(stderr, "Data inserted into tables. About to create english index\n"); ret = sqlite3_exec(db, "CREATE INDEX english_idx ON autocomplete (english)", NULL, NULL, &err); if (SQLITE_OK != ret) { printf("Error creating an index for the english column: %s\n", sqlite3_errmsg(db)); } fprintf(stderr, "Index created for english. Now creating index for english + tamil\n"); ret = sqlite3_exec(db, "CREATE INDEX eng_tam_idx ON autocomplete (english, tamil)", NULL, NULL, &err); if (SQLITE_OK != ret) { printf("Error creating an index for the english+tamil columns: %s\n", sqlite3_errmsg(db)); } fprintf(stderr, "Index created for english + tamil. Now creating index for english + tamil + score\n"); ret = sqlite3_exec(db, "CREATE INDEX eng_tam_score_idx ON autocomplete (english, tamil, score)", NULL, NULL, &err); if (SQLITE_OK != ret) { printf("Error creating an index for the english+tamil+score columns: %s\n", sqlite3_errmsg(db)); } fprintf(stderr, "Index created for english + tamil + score. Now creating index for english + score\n"); ret = sqlite3_exec(db, "CREATE INDEX english_score_idx ON autocomplete (english, score)", NULL, NULL, &err); if (SQLITE_OK != ret) { printf("Error creating an index for the english+tamil+score columns: %s\n", sqlite3_errmsg(db)); } ret = sqlite3_prepare_v2(db, "SELECT DISTINCT tamil FROM autocomplete WHERE english LIKE ? ORDER BY score DESC LIMIT 5", -1, &stmt, NULL); if (SQLITE_OK != ret) { printf("Error creating prepared statement: %s\n", sqlite3_errmsg(db)); goto close_and_end; } GtkWidget *window; gtk_init(NULL, NULL); window = gtk_window_new(GTK_WINDOW_TOPLEVEL); gtk_window_set_title(GTK_WINDOW(window), "Vaiyakani"); entry = gtk_entry_new(); suggestions = gtk_label_new(""); GtkWidget *box; box = gtk_box_new(GTK_ORIENTATION_HORIZONTAL, 10); gtk_container_add(GTK_CONTAINER(box), entry); gtk_container_add(GTK_CONTAINER(box), suggestions); gtk_container_add(GTK_CONTAINER(window), box); g_signal_connect(entry, "changed", kb, NULL); gtk_widget_show_all(window); gtk_main(); sqlite3_finalize(stmt); close_and_end: if (disk_db) sqlite3_close(disk_db); if (db) sqlite3_close(db); end: return ret; }
static gboolean load_database (GsPlugin *plugin, GCancellable *cancellable, GError **error) { GsPluginData *priv = gs_plugin_get_data (plugin); const gchar *statement; gboolean rebuild_ratings = FALSE; char *error_msg = NULL; gint result; gint64 stats_mtime = 0; gint64 now; g_autoptr(GError) error_local = NULL; g_debug ("trying to open database '%s'", priv->db_path); if (!gs_mkdir_parent (priv->db_path, error)) return FALSE; result = sqlite3_open (priv->db_path, &priv->db); if (result != SQLITE_OK) { g_set_error (error, GS_PLUGIN_ERROR, GS_PLUGIN_ERROR_FAILED, "Can't open Ubuntu review statistics database: %s", sqlite3_errmsg (priv->db)); return FALSE; } /* We don't need to keep doing fsync */ sqlite3_exec (priv->db, "PRAGMA synchronous=OFF", NULL, NULL, NULL); /* Create a table to store the stats */ result = sqlite3_exec (priv->db, "SELECT * FROM review_stats LIMIT 1", NULL, NULL, &error_msg); if (result != SQLITE_OK) { g_debug ("creating table to repair: %s", error_msg); sqlite3_free (error_msg); statement = "CREATE TABLE review_stats (" "package_name TEXT PRIMARY KEY," "one_star_count INTEGER DEFAULT 0," "two_star_count INTEGER DEFAULT 0," "three_star_count INTEGER DEFAULT 0," "four_star_count INTEGER DEFAULT 0," "five_star_count INTEGER DEFAULT 0);"; sqlite3_exec (priv->db, statement, NULL, NULL, NULL); rebuild_ratings = TRUE; } /* Create a table to store local reviews */ result = sqlite3_exec (priv->db, "SELECT * FROM reviews LIMIT 1", NULL, NULL, &error_msg); if (result != SQLITE_OK) { g_debug ("creating table to repair: %s", error_msg); sqlite3_free (error_msg); statement = "CREATE TABLE reviews (" "package_name TEXT PRIMARY KEY," "id TEXT," "version TEXT," "date TEXT," "rating INTEGER," "summary TEXT," "text TEXT);"; sqlite3_exec (priv->db, statement, NULL, NULL, NULL); rebuild_ratings = TRUE; } /* Create a table to store timestamps */ result = sqlite3_exec (priv->db, "SELECT value FROM timestamps WHERE key = 'stats_mtime' LIMIT 1", get_timestamp_sqlite_cb, &stats_mtime, &error_msg); if (result != SQLITE_OK) { g_debug ("creating table to repair: %s", error_msg); sqlite3_free (error_msg); statement = "CREATE TABLE timestamps (" "key TEXT PRIMARY KEY," "value INTEGER DEFAULT 0);"; sqlite3_exec (priv->db, statement, NULL, NULL, NULL); /* Set the time of database creation */ if (!set_timestamp (plugin, "stats_ctime", error)) return FALSE; } /* Download data if we have none or it is out of date */ now = g_get_real_time () / G_USEC_PER_SEC; if (stats_mtime == 0 || rebuild_ratings) { g_debug ("No Ubuntu review statistics"); if (!download_review_stats (plugin, cancellable, &error_local)) { g_warning ("Failed to get Ubuntu review statistics: %s", error_local->message); return TRUE; } } else if (now - stats_mtime > REVIEW_STATS_AGE_MAX) { g_debug ("Ubuntu review statistics was %" G_GINT64_FORMAT " days old, so regetting", (now - stats_mtime) / ( 60 * 60 * 24)); if (!download_review_stats (plugin, cancellable, error)) return FALSE; } else { g_debug ("Ubuntu review statistics %" G_GINT64_FORMAT " days old, so no need to redownload", (now - stats_mtime) / ( 60 * 60 * 24)); } return TRUE; }
int main(int argc, char **argv) { const char * const db_location = "cluster.sqlite"; const char * const select_query = "SELECT document_identifier, label FROM temporary_label_clustering ORDER BY document_identifier"; QUADTREE *tree = NULL; sqlite3 *db = NULL; char *zErrMsg = NULL; int rc = 0; uint64_t *validation, *verification; unsigned int label_buf[MAX_LABEL_COUNT]; struct verification_t v; // Allocate some memory for those things validation = calloc(sizeof(uint64_t), DOCUMENT_IDENTIFIER_COUNT * (MAX_LABEL_COUNT + 1)); verification = calloc(sizeof(uint64_t), DOCUMENT_IDENTIFIER_COUNT * (MAX_LABEL_COUNT + 1)); if (validation == NULL || verification == NULL) { fprintf(stderr, "Allocation error!\n"); return 1; } v.arr = validation; v.last_offset = 0; // Open the database rc = sqlite3_open(db_location, &db); if (rc) { fprintf(stderr, "Can't open database: %s\n", sqlite3_errmsg(db)); sqlite3_close(db); return 1; } // Instantiate the quadtree assert(!quadtree_init(&tree, nextpow2(MAX_DOCUMENT_IDENTIFIER)-1, nextpow2(MAX_DOCUMENT_IDENTIFIER)-1)); // Select the data out of the database fprintf(stderr, "Creating quadtree...\n"); rc = sqlite3_exec(db, select_query, create_tree_callback, tree, &zErrMsg); if (rc != SQLITE_OK) { fprintf(stderr, "SQL error: %s\n", zErrMsg); sqlite3_free(zErrMsg); sqlite3_close(db); return 1; } // Create the validation structure fprintf(stderr, "Creating validation structure...\n"); rc = sqlite3_exec(db, select_query, create_validation_callback, &v, &zErrMsg); if (rc != SQLITE_OK) { fprintf(stderr, "SQL error: %s\n", zErrMsg); sqlite3_free(zErrMsg); sqlite3_close(db); return 1; } // Verify the result fprintf(stderr, "Verifying (stage 1)...\n"); for (int i = 0; i < DOCUMENT_IDENTIFIER_COUNT; i++) { uint64_t *off = validation + (i * (MAX_LABEL_COUNT + 1)); uint64_t identifier = *off; unsigned int out = 0; assert(!quadtree_scan_x(tree, identifier, label_buf, &out, MAX_LABEL_COUNT)); for (int j = 0; j < out; j++) { unsigned int label = label_buf[j]; for (int k = 1; k < MAX_LABEL_COUNT; k++) { if (*(off + k) == label) { *(off + k) = 0; } } } } fprintf(stderr, "Verifying (stage 2)...\n"); for (int i = 0; i < DOCUMENT_IDENTIFIER_COUNT; i++) { uint64_t *off = validation + (i * (MAX_LABEL_COUNT + 1)); uint64_t passed = 1; for (int j = 1; j < MAX_LABEL_COUNT; j++) { uint64_t *suboff = off + j; if (*suboff) { passed = 0; fprintf(stderr, "%d/%d/%d/%d\n", *off, *suboff, i, j); assert(0); } } if (passed) { *off = 0; } } fprintf(stderr, "Verifying (stage 3)...\n"); assert(!memcmp(validation, verification, DOCUMENT_IDENTIFIER_COUNT * (MAX_LABEL_COUNT + 1) * sizeof(uint64_t))); return 0; }
Operacoes::GetResult() { //Pronto :) //Mais alguma coisa? char *sql, *end; int retval, i; int q_cnt = 5, q_size = 150; char **queries = malloc(sizeof (char) * q_cnt * q_size); char valida_name[11]; // definindo ponteiros sqlite3_stmt *stmt; sqlite3 *handle; // abrindo seu banco, antes de rodar o programa crie um banco com SQLite retval = sqlite3_open("POO", &handle); // caso de erro na conexão vai mostrar msg if (retval) { /** Erro no banco **/ } int result; sql = (char *) malloc(sizeof (char) * q_size); /*! \brief Cadastra Usuário No BD * * * Recebe o objeto User e apartir dele é gerado uma linha no BD, no entanto isso só ocorre caso\n * não exista nem um indentificador nem um nome igual na tabela */ if (currentAction == TYPES::ACTION_LIST::CADASTRAUSER) { Operacoes.CriaUser(sql, retval, handle); } /*! \brief Atualiza Usuário No BD * * * Recebe o objeto User e apartir dele são atualizados o nome e a senha, se existir um identificador e o novo nome não * existir ainda. */ else if (currentAction == TYPES::ACTION_LIST::UPDATEUSER) { Operacoes.UpdateUser(sql, retval, handle); } /*! \brief Deleta Usuário No BD * * * Recebe o objeto endereço que deve ser deletado e apartir dele faz um drop Delete na linha */ else if (currentAction == TYPES::ACTION_LIST::DELETEUSER) { Operacoes.DeleteUser(sql, retval, handle); } /*! \brief Procura um nome de Usuário No BD * * * Recebe um Name e procura na tabela se esse existe, caso sim armazena as informações dele em um objeto User */ else if (currentAction == TYPES::ACTION_LIST::FINDUSERN) { Operacoes.FindUserN(sql, retval, handle, queries, stmt); } /*! \brief Procura um id de Usuário No BD * * * Recebe um identificador e procura na tabela se esse existe, caso sim armazena as informações dele em um objeto User */ else if (currentAction == TYPES::ACTION_LIST::FINDUSERID) { Operacoes.FindUserID(sql, retval, handle, queries, stmt); } /*! \brief Cadastra Comentário No BD * * * Recebe o objeto Coment e apartir dele é gerado uma linha no BD, no entanto isso só ocorre caso\n * não exista o identificador do comentário na tabela */ else if (currentAction == TYPES::ACTION_LIST::CADASTRACOMENT) { Operacoes.CriaComent(sql, retval, handle); } /*! \brief Atualiza Comentário No BD * * * Recebe o objeto Coment e apartir dele é gerado uma linha no BD, no entanto isso só ocorre caso\n * não exista o identificador do comentário na tabela */ else if (currentAction == TYPES::ACTION_LIST::UPDATECOMENT) { Operacoes.UpdateComent(sql, retval, handle); } /*! \brief Deleta Comentário No BD * * * Recebe o id de um Comentário e apartir dele é feito um delete na linha caso essa exista. */ else if (currentAction == TYPES::ACTION_LIST::DELETECOMENT) { //Delete na entidade no BD Operacoes.DeleteComent(sql, retval, handle); } /*! \brief Procura um id de Comentário No BD * * * Recebe o id de busca e caso encontre coloca os valores da linha em um objeto Coment */ else if (currentAction == TYPES::ACTION_LIST::FINDCOMENT) { Operacoes.FindComentID(sql, retval, handle, queries, stmt); } /*! \brief Cadastra um Post No BD * * * Recebe o objeto Post e armazena no Banco de Dados, só armazena se o id do Post não existir */ else if (currentAction == TYPES::ACTION_LIST::CADASTRAPOST) { Operacoes.CriaPost(sql, retval, handle); } /*! \brief Atualiza um Post No BD * * * Recebe o id de um Post e atualiza seu texto, data e avaliação se esse post existir */ else if (currentAction == TYPES::ACTION_LIST::UPDATEPOST) { Operacoes.UpdatePost(sql, retval, handle); } /*! \brief Deleta um Post No BD * * * Recebe o id de um Post e deleta a linha em que ele se encontra */ else if (currentAction == TYPES::ACTION_LIST::DELETEPOST) { Operacoes.DeletePost(sql, retval, handle); } /*! \brief Encontra um Post pelo id No BD * * * Recebe o id de um Post e o armazena no objeto Post */ else if (currentAction == TYPES::ACTION_LIST::FINDPOST) { Operacoes.FindPostID(sql, retval, handle, queries, stmt); } // fecha a conexão free(sql); sqlite3_close(handle); return result; }
/****************************************************************************** * * * 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; assert(NULL != host); #if defined(HAVE_IBM_DB2) connect = zbx_strdup(connect, "PROTOCOL=TCPIP;"); if ('\0' != *host) connect = zbx_strdcatf(connect, "HOSTNAME=%s;", host); if (NULL != dbname && '\0' != *dbname) connect = zbx_strdcatf(connect, "DATABASE=%s;", dbname); 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 ('\0' != *host) { connect = zbx_strdcatf(connect, "//%s", host); if (0 != port) connect = zbx_strdcatf(connect, ":%d", port); if (NULL != dbname && '\0' != *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"); result = DBselect("show standard_conforming_strings"); if (NULL != (row = DBfetch(result))) ZBX_PG_ESCAPE_BACKSLASH = (0 == strcmp(row[0], "off")); DBfree_result(result); } 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; }
void disassemble(String filename){ sqlite3 *db; sqlite3_stmt *res; const char *tail; int rc; //printf("IN DISASSEMBLE!\n"); rc = sqlite3_open(DBNAME, &db); if (rc != SQLITE_OK){ fprintf(stderr, "Can't open database %s!\n", sqlite3_errmsg(db)); sqlite3_close(db); exit(1); } String query = "", root = ""; sprintf(query, "Select mountpt from CacheContent where filename = '%s';", filename); int good = 0; while (!good){ rc = sqlite3_prepare_v2(db, query, 1000, &res, &tail); if (rc != SQLITE_OK){ //printf("Disassemble: SQL Error: %s\n", sqlite3_errmsg(db)); }else {good = 1;} } if (sqlite3_step(res) == SQLITE_ROW){ strcpy(root, sqlite3_column_text(res,0)); } sqlite3_finalize(res); String volume = ""; sprintf(query, "Select fileloc from VolContent where filename = '%s%s'", root, filename); good = 0; while (!good){ rc = sqlite3_prepare_v2(db, query, 1000, &res, &tail); if (rc != SQLITE_OK){ } else {good = 1;} } if (sqlite3_step(res) == SQLITE_ROW){ strcpy(volume, sqlite3_column_text(res,0)); } sqlite3_finalize(res); String mv = ""; sprintf(mv, "mv '%s/%s' '%s/%s%s'", STORAGE_LOC, filename, volume, root, filename); system(mv); sqlite3_close(db); printf("[-] %s: %s\n", STORAGE_LOC, filename); FILE *fp1 = fopen("../file_transaction/assembled.txt", "rb"); FILE *fp2 = fopen("../file_transaction/disassembled.txt", "ab"); String line = ""; while (fgets(line, sizeof(line), fp1) != NULL){ String compare = ""; strcpy(compare, filename); strcat(compare, "\n"); if (strcmp(compare, line) != 0){ //remove assembled file from assembled txt fprintf(fp2, "%s", line); } } fclose(fp1); fclose(fp2); system("mv '../file_transaction/disassembled.txt' '../file_transaction/assembled.txt'"); }
// filename passed here has part1.xxxx // we remove part1 and select the root from cachecontent // then we assemble by checking from volcontent the locations of the parts // that is root/part%.filename // file is placed in assembly loc // orig file is placed in cvfsstore // should we update link in share or is that auto? void assemble(String filename){ char *err = 0; String comm, query, tempname; int rc; sqlite3 *db; sqlite3_stmt *res; char percent = '%'; const char *tail; strcpy(tempname, filename); /*Assumes only part1 of the file will be linked to share*/ /*The part1 name in the share would be part1.<filename>*/ /*All the fileparts in the database would be saved as part<number>.<filename>*/ /*This checks if part1 of a certain file is open*/ /*remove part1. in the filename*/ /*ex: part1.DOTS.mkv = DOTS.mkv*/ // remove part1 from filename //if (strstr(filename, "part1.") != NULL){ // memmove(filename, filename + strlen("part1."), 1 + strlen(filename + strlen("part1."))); //} // get the root (meron nang / sa dulo yun!!) rc = sqlite3_open(DBNAME, &db); if (rc != SQLITE_OK){ fprintf(stderr, "File Assembly: Can't open database: %s\n", sqlite3_errmsg(db)); sqlite3_close(db); exit(1); } sprintf(query, "SELECT mountpt from CacheContent WHERE filename='%s'", filename); rc = sqlite3_prepare_v2(db, query, 1000, &res, &tail); int good = 0; while (!good){ rc = sqlite3_prepare_v2(db, query, 1000, &res, &tail); if (rc == SQLITE_BUSY){ // db is locked? } else { good = 1; } } String root = ""; if (sqlite3_step(res) == SQLITE_ROW) { strcpy(root, sqlite3_column_text(res,0)); } sqlite3_finalize(res); if (strstr(filename, "part1.") != NULL){ memmove(filename, filename+strlen("part1."), 1+strlen(filename+strlen("part1."))); } /*Look for all the fileparts in the database. part<number>.<filename>*/ sprintf(query, "SELECT filename, fileloc FROM VolContent WHERE filename LIKE '%spart%c.%s'", root, percent, filename); rc = sqlite3_prepare_v2(db, query, 1000, &res, &tail); good = 0; while (!good) { rc = sqlite3_prepare_v2(db, query, 1000, &res, &tail); if (rc == SQLITE_BUSY){ // db is locked? } else { good = 1; } } String files = ""; String assfile = ""; String volname = ""; // for moving to store while (sqlite3_step(res) == SQLITE_ROW){ if (strstr(sqlite3_column_text(res,0), "part1.") != NULL){ //if file contains part1 strcpy(assfile, sqlite3_column_text(res,0)); //will be the filename sprintf(volname, "%s/%s", sqlite3_column_text(res,1), sqlite3_column_text(res,0)); } String name = ""; sprintf(name, "\"%s/%s\"", sqlite3_column_text(res,1), sqlite3_column_text(res,0)); strcat(files, name); strcat(files, " "); } sqlite3_finalize(res); sprintf(comm, "cat %s > '%s/part1.%s'", files, ASSEMBLY_LOC, filename); system(comm); syslog(LOG_INFO, "VolumeManagement: Assembled File: %s/%s\n", ASSEMBLY_LOC, assfile); // put orig file in store String mv = "", cp = ""; //copy original part1 of file to CVFStore folder sprintf(cp, "cp '%s' '%s/%s'", volname, STORAGE_LOC, tempname); //move assembled file from assembly to volume with part1 sprintf(mv, "mv '%s/part1.%s' '%s'", ASSEMBLY_LOC, filename, volname); system(cp); system(mv); printf("[+] %s: %s\n", STORAGE_LOC, tempname); FILE *fp1 = fopen("../file_transaction/assembled.txt", "a"); fprintf(fp1, "%s\n", tempname); fclose(fp1); sqlite3_close(db); }
/* * 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); }
// Open a connection to a valid SoftHSM v1 database sqlite3* openDB(char* dbPath) { int result; sqlite3* db = NULL; sqlite3_stmt* pragStatem = NULL; int dbVersion; // Open the database result = sqlite3_open(dbPath, &db); if (result) { fprintf(stderr, "ERROR: Could not open token database. " "Probably wrong path or privileges: %s\n", dbPath); return NULL; } // Check the schema version if (sqlite3_prepare_v2(db, "PRAGMA user_version;", -1, &pragStatem, NULL)) { fprintf(stderr, "ERROR: Could not prepare a SQL statement\n"); sqlite3_close(db); return NULL; } if (sqlite3_step(pragStatem) == SQLITE_ROW) { dbVersion = sqlite3_column_int(pragStatem, 0); sqlite3_finalize(pragStatem); if (dbVersion != 100) { fprintf(stderr, "ERROR: Wrong database schema version: %s\n", dbPath); sqlite3_close(db); return NULL; } } else { fprintf(stderr, "ERROR: The token database has not been initialized by SoftHSM\n"); sqlite3_finalize(pragStatem); sqlite3_close(db); return NULL; } // Check that the Token table exist result = sqlite3_exec(db, "SELECT COUNT(variableID) FROM Token;", NULL, NULL, NULL); if (result) { fprintf(stderr, "ERROR: The Token table is missing the in database\n"); sqlite3_close(db); return NULL; } // Check that the Objects table exist result = sqlite3_exec(db, "SELECT COUNT(objectID) FROM Objects;", NULL, NULL, NULL); if (result) { fprintf(stderr, "ERROR: The Objects table is missing the in database\n"); sqlite3_close(db); return NULL; } // Check that the Attributes table exist result = sqlite3_exec(db, "SELECT COUNT(attributeID) FROM Attributes;", NULL, NULL, NULL); if (result) { fprintf(stderr, "ERROR: The Attributes table is missing in the database\n"); sqlite3_close(db); return NULL; } return db; }
// Main function, the base TCP server int main(int argc, char *argv[]) { //-------------------- SET UP VARIABLES ----------------------- // Set up all required variables for sockets programming, starting with addrinfo "hints" struct and pointers to results list struct addrinfo hints, *result; // Integer variable used to set socket options int yes = 1; // Create command buffer, to send commands directly to the server char command[512] = { '\0' }; // Define a generic indexer variable for loops int i = 0; // Set up SQLite statement struct sqlite3_stmt *stmt; // Create a buffer to store queries to process on the database char query[256] = { '\0' }; //------------------ INITIALIZE SIGNAL HANDLERS --------------- // Install signal handlers for graceful shutdown // Install SIGHUP signal handler signal(SIGHUP, shutdown_handler); // Install SIGINT signal handler signal(SIGINT, shutdown_handler); // Install SIGTERM signal handler signal(SIGTERM, shutdown_handler); // Install signal handlers for statistics output // Install SIGUSR1 signal handler signal(SIGUSR1, stat_handler); // Install SIGUSR2 signal handler signal(SIGUSR2, stat_handler); //------------------ BEGIN SERVER INITIALIZATION -------------- // Read in terminal on which server was started term = strdup(ttyname(1)); // Print initialization message fprintf(stdout, "%s: %s %s - Justin Hill, Gordon Keesler, Matt Layher (CS5550 Spring 2012)\n", SERVER_NAME, INFO_MSG, SERVER_NAME); // Capture initial start time start_time = time(NULL); //------------------ PARSE COMMAND LINE ARGUMENTS ------------- // Iterate through all argv command line arguments, parsing out necessary flags for(i = 1; i < argc; i++) { // '-d' or '--daemon' flag: daemonize the server, and run it in the background if(strcmp("-d", argv[i]) == 0 || strcmp("--daemon", argv[i]) == 0) { // Set daemon flag to true, so we may daemonize later daemonized = 1; } // '-h' or '--help' flag: print help and usage for this server, then exit else if(strcmp("-h", argv[i]) == 0 || strcmp("--help", argv[i]) == 0) { // Print usage message fprintf(stdout, "usage: %s [-d | --daemon] [-h | --help] [-l | --lock lock_file] [-p | --port port] [-q | --queue queue_length] [-t | --threads thread_count]\n\n", SERVER_NAME); // Print out all available flags fprintf(stdout, "%s flags:\n", SERVER_NAME); fprintf(stdout, "\t-d | --daemon: daemonize - start server as a daemon, running it in the background\n"); fprintf(stdout, "\t-h | --help: help - print usage information and details about each flag the server accepts\n"); fprintf(stdout, "\t-l | --lock: lock_file - specify the location of the lock file utilized when the server is daemonized (default: %s)\n", LOCKFILE); fprintf(stdout, "\t-p | --port: port - specify an alternative port number to run the server (default: %s)\n", DEFAULT_PORT); fprintf(stdout, "\t-q | --queue: queue_length - specify the connection queue length for the incoming socket (default: %d)\n", QUEUE_LENGTH); fprintf(stdout, "\t-t | --threads: thread_count - specify the number of threads to generate (max number of clients) (default: %d)\n", NUM_THREADS); fprintf(stdout, "\n"); // Print out all available console commands via the common console_help() function console_help(); // Exit the server exit(0); } // '-l' or '--lock' flag: specify an alternate lock file location else if(strcmp("-l", argv[i]) == 0 || strcmp("--lock", argv[i]) == 0) { // Make sure that another argument exists, specifying the lockfile location if(argv[i+1] != NULL) { // Set lock file location as specified on the command line lock_location = argv[i+1]; i++; } else { // Print error and use default location if no lockfile was specified after the flag fprintf(stderr, "%s: %s no lockfile location specified, defaulting to %s\n", SERVER_NAME, ERROR_MSG, LOCKFILE); } } // '-p' or '--port' flag: specifies an alternative port number to run the server else if(strcmp("-p", argv[i]) == 0 || strcmp("--port", argv[i]) == 0) { // Make sure that another argument exists, specifying the port number if(argv[i+1] != NULL) { // Ensure this port is a valid integer if(validate_int(argv[i+1])) { // Set this port to be used if it's within the valid range, else use the default if(atoi(argv[i+1]) >= 0 && atoi(argv[i+1]) <= MAX_PORT) { port = argv[i+1]; i++; } else fprintf(stderr, "%s: %s port lies outside valid range (0-%d), defaulting to %s\n", SERVER_NAME, ERROR_MSG, MAX_PORT, DEFAULT_PORT); } else { // Print error and use default port if an invalid port number was specified fprintf(stderr, "%s: %s invalid port number specified, defaulting to %s\n", SERVER_NAME, ERROR_MSG, DEFAULT_PORT); } } else { // Print error and use default port if no port number was specified after the flag fprintf(stderr, "%s: %s no port number specified after flag, defaulting to %s\n", SERVER_NAME, ERROR_MSG, DEFAULT_PORT); } } // '-q' or '--queue' flag: specify the connection queue length else if(strcmp("-q", argv[i]) == 0 || strcmp("--queue", argv[i]) == 0) { // Make sure another argument exists, specifying the queue length if(argv[i+1] != NULL) { // Ensure this is a valid integer for queue length if(validate_int(argv[i+1])) { // Set connection queue length to the number specified on the command line, if it's a number more than 0, else use the default if(atoi(argv[i+1]) >= 1) { queue_length = atoi(argv[i+1]); i++; } else fprintf(stderr, "%s: %s cannot use negative or zero queue length, defaulting to length %d\n", SERVER_NAME, ERROR_MSG, QUEUE_LENGTH); } else { // Print error and use default queue length if an invalid number was specified fprintf(stderr, "%s: %s invalid queue length specified, defaulting to length %d\n", SERVER_NAME, ERROR_MSG, QUEUE_LENGTH); } } else { // Print error and use default queue length if no length was specified after the flag fprintf(stderr, "%s: %s no queue length specified after flag, default to length %d\n", SERVER_NAME, ERROR_MSG, QUEUE_LENGTH); } } // '-t' or '--threads' flag: specify the number of threads to generate in the thread pool else if(strcmp("-t", argv[i]) == 0 || strcmp("--threads", argv[i]) == 0) { // Make sure next argument exists, specifying the number of threads if(argv[i+1] != NULL) { // Ensure this number is a valid integer if(validate_int(argv[i+1])) { // Set number of threads to the number specified on the command line, if it's a number more than 0, else use the default if(atoi(argv[i+1]) >= 1) { num_threads = atoi(argv[i+1]); i++; } else fprintf(stderr, "%s: %s cannot use negative or zero threads, defaulting to %d threads\n", SERVER_NAME, ERROR_MSG, NUM_THREADS); } else { // Print error and use default number of threads if an invalid number was specified fprintf(stderr, "%s: %s invalid number of threads specified, defaulting to %d threads\n", SERVER_NAME, ERROR_MSG, NUM_THREADS); } } else { // Print error and use default number of threads if no count was specified after the flag fprintf(stderr, "%s: %s no thread count specified after flag, defaulting to %d threads\n", SERVER_NAME, ERROR_MSG, NUM_THREADS); } } else { // Else, an invalid flag or parameter was specified; print an error and exit fprintf(stderr, "%s: %s unknown parameter '%s' specified, please run '%s -h' for help and usage\n", SERVER_NAME, ERROR_MSG, argv[i], SERVER_NAME); exit(-1); } } //------------------------ OPEN SQLITE DATABASE ---------------- // Open database file, as specified in config header; check for success sqlite3_open(DB_FILE, &db); if(db == NULL) { // Print an error message and quit if database fails to open fprintf(stderr, "%s: %s sqlite: could not open database %s\n", SERVER_NAME, ERROR_MSG, DB_FILE); exit(-1); } // Create a query to truncate the files table in the database sprintf(query, "DELETE FROM files"); // Prepare, evaluate, and finalize SQLite query sqlite3_prepare_v2(db, query, strlen(query) + 1, &stmt, NULL); if(sqlite3_step(stmt) != SQLITE_DONE) { // On query failure, print an error and exit fprintf(stderr, "%s: %s sqlite: could not truncate files table\n", SERVER_NAME, ERROR_MSG); exit(-1); } sqlite3_finalize(stmt); //------------------------ INITIALIZE TCP SERVER --------------- // Clear the hints struct using memset to nullify it memset(&hints, 0, sizeof(hints)); // Set options for hints to use IPv4, a TCP connection, and the machine's current IP address hints.ai_family = AF_INET; // IPv4 hints.ai_socktype = SOCK_STREAM; // Reliable TCP connection hints.ai_flags = AI_PASSIVE; // Use my ip address // now populate our result addrinfo if((getaddrinfo(NULL, port, &hints, &result)) != 0) { // If getaddrinfo() fails, print an error and quit the program, since setup cannot continue. fprintf(stderr, "%s: %s getaddrinfo() call failed\n", SERVER_NAME, ERROR_MSG); exit(-1); } // Attempt to instantiate the local socket, using values set by getaddrinfo() if((loc_fd = socket(result->ai_family, result->ai_socktype, result->ai_protocol)) == -1) { // On socket creation failure, print an error and exit fprintf(stderr, "%s: %s local socket creation failed\n", SERVER_NAME, ERROR_MSG); exit(-1); } // Allow the system to free and re-bind the socket if it is already in use if(setsockopt(loc_fd, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(int)) == -1) { // If setting a socket option fails, terminate the program after printing an error fprintf(stderr, "%s: %s failed to set socket option: SO_REUSEADDR\n", SERVER_NAME, ERROR_MSG); exit(-1); } // Attempt to bind the local socket if((bind(loc_fd, result->ai_addr, result->ai_addrlen)) == -1) { // If socket binding fails, it's typically one of two scenarios: // 1) Check if socket is on a privileged port, and permission is denied if(atoi(port) < PRIVILEGED_PORT) fprintf(stderr, "%s: %s failed to bind local socket (permission denied?)\n", SERVER_NAME, ERROR_MSG); // 2) Else, the socket is probably already bound else fprintf(stderr, "%s: %s failed to bind local socket (socket already in use?)\n", SERVER_NAME, ERROR_MSG); // Exit on failure exit(-1); } // Free the results struct, as it is no longer needed freeaddrinfo(result); // Begin listening on the local socket, and set connection queue length as defined above if((listen(loc_fd, queue_length)) == -1) { // Print error message if socket fails to begin listening fprintf(stderr, "%s: %s failed to begin listening on local socket\n", SERVER_NAME, ERROR_MSG); } //-------------------------- DAEMONIZATION ------------------ // If server is being daemonized, do so now. if(daemonized == 1) daemonize(); else { // Initialize a thread pool, using number of threads as defined earlier threadpool = thpool_init(num_threads); // Initialize the network thread to handle all incoming connections pthread_create(&net_thread, NULL, &tcp_listen, NULL); // Print out server information and ready message fprintf(stdout, "%s: %s server initialized [PID: %d] [port: %s] [queue: %d] [threads: %d]\n", SERVER_NAME, OK_MSG, getpid(), port, queue_length, num_threads); // If server is not being daemonized, use the default console interface fprintf(stdout, "%s: %s type 'stop' or hit Ctrl+C (SIGINT) to stop server\n", SERVER_NAME, INFO_MSG); } //------------------------- CONSOLE COMMAND --------------- // Loop continuously until 'stop' is provided on the console while(1) { // Read in user input, clean it up fgets(command, sizeof(command), stdin); clean_string((char *)&command); // 'clear' - Clear the console if(strcmp(command, "clear") == 0) system("clear"); // 'help' - Display the common console help menu else if(strcmp(command, "help") == 0) console_help(); // 'stat' - Print out server statistics else if(strcmp(command, "stat") == 0) print_stats(); // 'stop' - Stop the server, breaking this loop else if(strcmp(command, "stop") == 0) break; // Else, print console error stating command does not exist else fprintf(stderr, "%s: %s unknown console command '%s', type 'help' for console command help\n", SERVER_NAME, ERROR_MSG, command); } // Send SIGINT to the server so that it will gracefully terminate via signal handler kill(getpid(), SIGINT); }
int pkgdb_open(struct pkgdb **db, pkgdb_t remote, int mode) { int retcode; struct stat st; char *errmsg; char localpath[MAXPATHLEN]; char remotepath[MAXPATHLEN]; char sql[BUFSIZ]; const char *dbdir; /* First check to make sure PKG_DBDIR exists before trying to use it */ dbdir = pkg_config("PKG_DBDIR"); if (eaccess(dbdir, mode) == -1) return (pkg_error_set(EPKG_FATAL, "Package database directory " "%s error: %s", dbdir, strerror(errno))); snprintf(localpath, sizeof(localpath), "%s/local.sqlite", dbdir); if ((*db = calloc(1, sizeof(struct pkgdb))) == NULL) return (pkg_error_set(EPKG_FATAL, "calloc(): %s", strerror(errno))); (*db)->remote = remote; retcode = stat(localpath, &st); if (retcode == -1 && errno != ENOENT) return (pkg_error_set(EPKG_FATAL, "can not stat %s: %s", localpath, strerror(errno))); if (remote == PKGDB_REMOTE) { snprintf(remotepath, sizeof(localpath), "%s/repo.sqlite", dbdir); retcode = stat(remotepath, &st); if (retcode == -1 && errno != ENOENT) return (pkg_error_set(EPKG_FATAL, "can not stat %s: %s", remotepath, strerror(errno))); } if (sqlite3_open(localpath, &(*db)->sqlite) != SQLITE_OK) return (ERROR_SQLITE((*db)->sqlite)); if (remote == PKGDB_REMOTE) { sqlite3_snprintf(BUFSIZ, sql, "ATTACH \"%s\" as remote;", remotepath); if (sqlite3_exec((*db)->sqlite, sql, NULL, NULL, &errmsg) != SQLITE_OK){ sqlite3_free(errmsg); return ERROR_SQLITE((*db)->sqlite); } } /* If the database is missing we have to initialize it */ if (retcode == -1) if ((retcode = pkgdb_init((*db)->sqlite)) != EPKG_OK) return (ERROR_SQLITE((*db)->sqlite)); sqlite3_create_function((*db)->sqlite, "regexp", 2, SQLITE_ANY, NULL, pkgdb_regex_basic, NULL, NULL); sqlite3_create_function((*db)->sqlite, "eregexp", 2, SQLITE_ANY, NULL, pkgdb_regex_extended, NULL, NULL); sqlite3_create_function((*db)->sqlite, "pkglt", 2, SQLITE_ANY, NULL, pkgdb_pkglt, NULL, NULL); sqlite3_create_function((*db)->sqlite, "pkggt", 2, SQLITE_ANY, NULL, pkgdb_pkggt, NULL, NULL); /* * allow forign key option which will allow to have clean support for * reinstalling */ if (sqlite3_exec((*db)->sqlite, "PRAGMA foreign_keys = ON;", NULL, NULL, &errmsg) != SQLITE_OK) { pkg_error_set(EPKG_FATAL, "sqlite: %s", errmsg); sqlite3_free(errmsg); return (EPKG_FATAL); } return (EPKG_OK); }
void Lite3Connector::open(char* databaseName) { int rc = sqlite3_open(databaseName, &conn); if (rc != SQLITE_OK) throw Lite3Exception(rc, "Database open failed", LITE3_MARK); }
//------------------------------------------------------------------------------ DWORD WINAPI Scan_chrome_history(LPVOID lParam) { FORMAT_CALBAK_READ_INFO data; //get child HTREEITEM hitem = NULL; if (!CONSOL_ONLY)hitem = (HTREEITEM)SendMessage(htrv_files, TVM_GETNEXTITEM,(WPARAM)TVGN_CHILD, (LPARAM)TRV_HTREEITEM_CONF[FILES_TITLE_APPLI]); if ((hitem == NULL && LOCAL_SCAN) || CONSOL_ONLY) { //get path of all profils users //HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\ProfileList HKEY CleTmp = 0; if (RegOpenKey(HKEY_LOCAL_MACHINE,"SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\ProfileList\\",&CleTmp)==ERROR_SUCCESS) { DWORD i, nbSubKey=0, key_size; sqlite3 *db_tmp; char tmp_key[MAX_PATH], tmp_key_path[MAX_PATH]; if (RegQueryInfoKey (CleTmp,0,0,0,&nbSubKey,0,0,0,0,0,0,0)==ERROR_SUCCESS) { #ifdef CMD_LINE_ONLY_NO_DB printf("\"file\";\"parameter\";\"date\";\"id_language_description\";\"session_id\";\"data\";\r\n"); #endif //get subkey for(i=0;i<nbSubKey;i++) { key_size = MAX_PATH; tmp_key[0] = 0; if (RegEnumKeyEx (CleTmp,i,tmp_key,&key_size,0,0,0,0)==ERROR_SUCCESS) { //generate the key path snprintf(tmp_key_path,MAX_PATH,"SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\ProfileList\\%s\\",tmp_key); //get profil path if (ReadValue(HKEY_LOCAL_MACHINE,tmp_key_path,"ProfileImagePath",tmp_key, MAX_PATH)) { //verify the path if %systemdrive% ReplaceEnv("SYSTEMDRIVE",tmp_key,MAX_PATH); //search file in this path snprintf(tmp_key_path,MAX_PATH,"%s\\Local Settings\\Application Data\\Google\\Chrome\\User Data\\Default\\*.*",tmp_key); WIN32_FIND_DATA wfd; HANDLE hfic = FindFirstFile(tmp_key_path, &wfd); if (hfic != INVALID_HANDLE_VALUE) { do { if (wfd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY){}else { if(wfd.cFileName[0] == '.' && (wfd.cFileName[1] == 0 || wfd.cFileName[1] == '.')){} else { //test all files snprintf(tmp_file_chrome,MAX_PATH,"%s\\Local Settings\\Application Data\\Google\\Chrome\\User Data\\Default\\%s",tmp_key,wfd.cFileName); //test to open file if (sqlite3_open(tmp_file_chrome, &db_tmp) == SQLITE_OK) { for (data.type =0;data.type <nb_sql_CHROME && start_scan;data.type = data.type+1) { if(!SQLITE_FULL_SPEED)sqlite3_exec(db_scan,"BEGIN TRANSACTION;", NULL, NULL, NULL); sqlite3_exec(db_tmp, sql_CHROME[data.type].sql, callback_sqlite_chrome, &data, NULL); if(!SQLITE_FULL_SPEED)sqlite3_exec(db_scan,"END TRANSACTION;", NULL, NULL, NULL); } sqlite3_close(db_tmp); } } } }while(FindNextFile (hfic,&wfd)); } } } } } RegCloseKey(CleTmp); } }else { sqlite3 *db_tmp; #ifdef CMD_LINE_ONLY_NO_DB printf("\"Chrome\";\"file\";\"parameter\";\"date\";\"id_language_description\";\"session_id\";\"data\";\r\n"); #endif while(hitem!=NULL) { //get item txt GetTextFromTrv(hitem, tmp_file_chrome, MAX_PATH); //test to open file if (sqlite3_open(tmp_file_chrome, &db_tmp) == SQLITE_OK) { for (data.type =0;data.type <nb_sql_CHROME && start_scan;data.type = data.type+1) { if(!SQLITE_FULL_SPEED)sqlite3_exec(db_scan,"BEGIN TRANSACTION;", NULL, NULL, NULL); sqlite3_exec(db_tmp, sql_CHROME[data.type].sql, callback_sqlite_chrome, &data, NULL); if(!SQLITE_FULL_SPEED)sqlite3_exec(db_scan,"END TRANSACTION;", NULL, NULL, NULL); } sqlite3_close(db_tmp); } hitem = (HTREEITEM)SendMessage(htrv_files, TVM_GETNEXTITEM,(WPARAM)TVGN_NEXT, (LPARAM)hitem); } } if (!CONSOL_ONLY)check_treeview(htrv_test, H_tests[(unsigned int)lParam], TRV_STATE_UNCHECK);//db_scan h_thread_test[(unsigned int)lParam] = 0; return 0; }
void initialize() { system("clear"); String ip = "", netmask = "", command = "", alltargetsStr = "", currtarget = "", iqn = "", sendtargets = "", sql = ""; String disklist = "", assocvol = "", mountpt = "", avspace = "", command1 = "", sql1 = ""; int counter = 1; //sqlite3 information sqlite3 *db; int rc = 0; //open sqlite3 db rc = sqlite3_open(DBNAME,&db); if (rc){ printf("\nCannot open database.\n"); exit(0); } // get network information of initiator // what if interface is not eth0? what if eth1...? runCommand("ip addr show eth0 | grep \'inet \' | awk \'{print $2}\' | cut -f1 -d\'/\'", ip); runCommand("ip addr show eth0 | grep \'inet \' | awk \'{print $2}\' | cut -f2 -d\'/\'", netmask); // printf("***** Network information *****\n"); ip[strlen(ip)] = '\0'; netmask[strlen(netmask)] = '\0'; syslog(LOG_INFO, "DiskPooling: Initiator IP address: %s/%s\n\n", ip, netmask); // do nmap for active hosts with port 3260 open // syslog(LOG_INFO, "DiskPooling: Scanning network...\n"); sprintf(command, "nmap -v -n %s%s%s -p 3260 | grep open | awk '/Discovered/ {print $NF}'", ip, "/", netmask); runCommand(command, alltargetsStr); // discover iscsi targets on hosts scanned successfully char *ptr; ptr = strtok(alltargetsStr, "\n"); while(ptr != NULL) { printf("%s is a target.\n", ptr); sprintf(sendtargets,"iscsiadm -m discovery -t sendtargets -p %s | awk '{print $2}'",ptr); runCommand(sendtargets,iqn); printf("%s\n", iqn); sprintf(sql,"insert into Target(tid, ipadd,iqn) values (%d, '%s','%s');",counter, ptr,iqn); printf("** initconf, sql = %s\n", sql); rc = sqlite3_exec(db,sql,0,0,0); if (rc != SQLITE_OK){ printf("\nDid not insert successfully!\n"); exit(0); } strcpy(sendtargets,""); strcpy(sql,""); strcpy(iqn, ""); ptr = strtok(NULL, "\n"); counter++; } printf("\n\nLogging in to targets..."); system("iscsiadm -m node --login"); printf("\n\nAvailable partitions written to file \"%s\"\n", AV_DISKS); sleep(5); sprintf(command, "cat /proc/partitions > '%s'", AV_DISKS); system(command); system("cat /proc/partitions"); makeVolume(0); system("cat '../file_transaction/AvailableDisks.txt' | grep sd[b-z] | awk '{print $4}' > SDNAME.txt"); FILE *fp; string l; fp = fopen("SDNAME.txt", "r"); if (fp == NULL) { printf("file not found\n"); exit(1); } while(fscanf(fp, "%s", l) != EOF) { printf("read: %s\n", s); } printf("closign file\n"); fclose(fp); // syslog(LOG_INFO, "DiskPooling: DONE!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n"); // syslog(LOG_INFO, "DiskPooling: Disklist before: %s\n\n", disklist); //strcat(disklist, "\n"); // syslog(LOG_INFO, "DiskPooling: PTR Before: %s\n\n", ptr1); // syslog(LOG_INFO, "DiskPooling: DIskList after: %s\n\n", disklist); counter = 1; while(fscanf(fp, "%s", l) != EOF) { // syslog(LOG_INFO, "DiskPooling: PTR: %s\n\n", ptr1); // syslog(LOG_INFO, "DiskPooling: INSIDE!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n"); printf("this line is read: %s\n", l); strcat(assocvol,"/dev/vg"); strcat(assocvol,l); strcat(assocvol,"/lv"); strcat(assocvol,l); strcat(mountpt,"/mnt/lv"); strcat(mountpt,l); sprintf(command1,"lvdisplay %s | grep 'LV Size' | awk '{print $3,$4}'",assocvol); runCommand(command1,avspace); // edit here not sure if working (assume: avspace = "12.3 GiB") double space_bytes = toBytes(avspace); sprintf(sql1,"update Target set assocvol = '%s', mountpt = '%s', avspace = %lf where tid = %d", assocvol, mountpt, space_bytes, counter); printf("just checking sql1 = %s\n", sql1); // syslog(LOG_INFO, "DiskPooling: SQL1 = %s\n", sql1); rc = sqlite3_exec(db,sql1,0,0,0); if (rc != SQLITE_OK){ syslog(LOG_INFO, "DiskPooling: Error: Target is not recorded"); exit(0); } strcpy(assocvol,""); strcpy(mountpt,""); strcpy(avspace,""); counter++; // printf("***************\n\n\n%s\n\n\n", ptr1); } printf("\n\nInitialization finished\n"); }
SWITCH_DECLARE(int) switch_core_db_open(const char *filename, switch_core_db_t **ppDb) { return sqlite3_open(filename, ppDb); }
int main(int argc, char *argv[]) { char *filename = NULL; //char *filename_suffix = NULL; char *inputsource = NULL; char *outputDB = NULL; //Find the last / in passed filename. if (strrchr(argv[1],'/') == NULL) { if (strcmp(argv[1],"-") == 0) { inputsource = "/dev/stdin"; if (argv[2] == NULL) { printf("Please input a name for the movie!\n"); return -1; } else { if (strrchr(argv[2],'/') == NULL) { filename = argv[2]; } else { filename = strrchr(argv[2],'/') + 1; } if (argv[3] != NULL && argc == 4) { outputDB = argv[3]; } else { outputDB = "/home/gsc/videoaudiofingerprint.db"; } } } else { filename = argv[1]; inputsource = argv[1]; if (argv[2] != NULL && argc == 3) { outputDB = argv[2]; } else { outputDB = "/home/gsc/videoaudiofingerprint.db"; } } } else { filename = strrchr(argv[1],'/') + 1; inputsource = argv[1]; if (argv[3] != NULL && argc == 4) { outputDB = argv[3]; } else { outputDB = "/home/gsc/videoaudiofingerprint.db"; } } printf("Filename = %s Input source = %s DB output = %s argc = %d\n",filename,inputsource,outputDB, argc); /*** DB initialization ***/ int retval = 0; // Create a handle for database connection, create a pointer to sqlite3 sqlite3 *handle; //Full array init of size 5h@60fps (a.k.a large enough) //TO FIX: use dynamic array? int *fullArray = (int*) calloc ( (1080000-1), sizeof (int)); // Create the database. If it doesnt exist, it would be created // pass a pointer to the pointer to sqlite3, in short sqlite3** retval = sqlite3_open(outputDB,&handle); // If connection failed, handle returns NULL if(retval) { printf("Database connection failed\n"); return -1; } char query1[] = "create table allmovies (allmovieskey INTEGER PRIMARY KEY,name TEXT,fps INTEGER, date INTEGER);"; // Execute the query for creating the table retval = sqlite3_exec(handle,query1,0,0,0); char query2[] = "PRAGMA count_changes = OFF"; retval = sqlite3_exec(handle,query2,0,0,0); char query3[] = "PRAGMA synchronous = OFF"; retval = sqlite3_exec(handle,query3,0,0,0); //Hashluma table char query_hash[] = "create table hashluma (avg_range int, movies TEXT)"; retval = sqlite3_exec(handle,query_hash,0,0,0); if (!retval) { //Populating the hash tables printf("Populating hashluma table\n"); char hashquery[50]; memset(hashquery, 0, 50); int i = 0; for(i=0; i <= 254; i++) { sprintf(hashquery, "insert into hashluma (avg_range) values (%d)", i); retval = sqlite3_exec(handle,hashquery,0,0,0); } } char table_query[150]; memset(table_query, 0, 150); sprintf(table_query,"create table '%s' (s_end FLOAT, luma INTEGER);",filename); int repeated = 0; retval = sqlite3_exec(handle,table_query,0,0,0); if (retval) { char error [100]; memset(error, 0, 100); sprintf(error,"Table for movie %s already exists! Skipping fingerprinting ... \n",filename); printf("%s",error); //Decide which is the best policy, not FP? overwrite? new file? repeated = 1; sqlite3_close(handle); return 0; } /*** DB init finished ***/ printf("Analyzing video %s\n",filename); av_register_all(); AVFormatContext *pFormatCtx; // Open video file if(av_open_input_file(&pFormatCtx, inputsource, NULL, 0, NULL)!=0) { printf("Could't open file %s\n", argv[1]); return -1; // Couldn't open file } // Retrieve stream information if(av_find_stream_info(pFormatCtx)<0) { printf("Could't find stream information\n"); return -1; // Couldn't find stream information } // Dump information about file onto standard error dump_format(pFormatCtx, 0, filename, 0); int i; AVCodecContext *pVideoCodecCtx; AVCodecContext *pAudioCodecCtx; // Find the first video stream int videoStream=-1; int audioStream=-1; for(i=0; i<pFormatCtx->nb_streams; i++) { if(pFormatCtx->streams[i]->codec->codec_type==CODEC_TYPE_VIDEO && videoStream==-1) videoStream=i; if(pFormatCtx->streams[i]->codec->codec_type==CODEC_TYPE_AUDIO && audioStream==-1) audioStream=i; } if(videoStream==-1 || audioStream==-1) return -1; // Didn't find both streams // Get a pointer to the codec context for the video stream pVideoCodecCtx=pFormatCtx->streams[videoStream]->codec; // Similar, for audio stream pAudioCodecCtx=pFormatCtx->streams[audioStream]->codec; AVCodec *pVideoCodec; AVCodec *pAudioCodec; // Find the decoder for the streams pVideoCodec=avcodec_find_decoder(pVideoCodecCtx->codec_id); pAudioCodec=avcodec_find_decoder(pAudioCodecCtx->codec_id); if(pVideoCodec==NULL) { fprintf(stderr, "Unsupported video codec!\n"); sqlite3_close(handle); return -1; // Codec not found } if(pAudioCodec==NULL) { fprintf(stderr, "Unsupported audio codec!\n"); sqlite3_close(handle); return -1; // Codec not found } // Open codecs if(avcodec_open(pVideoCodecCtx, pVideoCodec)<0) { sqlite3_close(handle); return -1; // Could not open codec } if(avcodec_open(pAudioCodecCtx, pAudioCodec)<0) { sqlite3_close(handle); return -1; // Could not open codec } AVFrame *pVideoFrame; AVFrame *pVideoFrameYUV; AVFrame *pAudioFrame; int samples = 0; // Allocate audio/video frame pVideoFrame=avcodec_alloc_frame(); pVideoFrameYUV=avcodec_alloc_frame(); pAudioFrame=avcodec_alloc_frame(); if(pVideoFrameYUV==NULL || pVideoFrame==NULL || pAudioFrame==NULL) { sqlite3_close(handle); return -1; } uint8_t *videoBuffer; int16_t *audioBuffer; int numVideoBytes; int numAudioBytes; // Determine required buffer size and allocate buffer numVideoBytes=avpicture_get_size(PIX_FMT_YUV420P, pVideoCodecCtx->width, pVideoCodecCtx->height); videoBuffer=(uint8_t *)av_mallocz(numVideoBytes*sizeof(uint8_t)); numAudioBytes = AVCODEC_MAX_AUDIO_FRAME_SIZE + FF_INPUT_BUFFER_PADDING_SIZE; audioBuffer=(int16_t *)av_mallocz(numAudioBytes); // Assign appropriate parts of videoBuffer to image planes in pVideoFrameYUV // Note that pVideoFrameYUV is an AVFrame, but AVFrame is a superset of AVPicture avpicture_fill((AVPicture *)pVideoFrameYUV, videoBuffer, PIX_FMT_YUV420P, pVideoCodecCtx->width, pVideoCodecCtx->height); int frameFinished = 0; AVPacket packet; av_init_packet(&packet); struct SwsContext * sws_context; double fps = 0.0; struct timeval tv; gettimeofday(&tv, NULL); char allmovies_query[150]; memset(allmovies_query, 0, 150); fps = (double)pFormatCtx->streams[videoStream]->r_frame_rate.num/(double)pFormatCtx->streams[videoStream]->r_frame_rate.den; //if (repeated) { // filename_suffix = (int)tv.tv_sec; // sprintf(filename, "%s_%d", filename, filename_suffix); // sprintf(allmovies_query, "insert into allmovies (name,fps,date) values ('%s',%d,%d);", filename, (int)(fps*100), filename_suffix); //} else { sprintf(allmovies_query, "insert into allmovies (name,fps,date) values ('%s',%d,%d);", filename, (int)(fps*100), (int)tv.tv_sec); //} retval = sqlite3_exec(handle,allmovies_query,0,0,0); printf("%d %d\n",pAudioCodecCtx->sample_rate,pAudioCodecCtx->channels); i = 0; unsigned int offset = 0; // bytes //fftw_complex *in; int totalSamples = 0; //in = (fftw_complex*) fftw_malloc(sizeof(fftw_complex) * N); int counter = 0; float audioTime = 0.0; while(av_read_frame(pFormatCtx, &packet)>=0) { // Decode video if(packet.stream_index==videoStream) { // Decode video frame avcodec_decode_video2(pVideoCodecCtx, pVideoFrame, &frameFinished, &packet); // Did we get a video frame? if(frameFinished) { if (pVideoCodecCtx->pix_fmt != PIX_FMT_YUV420P) { // Convert the image from its native format to YUV (PIX_FMT_YUV420P) //img_convert((AVPicture *)pVideoFrameYUV, PIX_FMT_YUV420P, (AVPicture*)pVideoFrame, pVideoCodecCtx->pix_fmt, pVideoCodecCtx->width, pVideoCodecCtx->height); sws_context = sws_getContext(pVideoCodecCtx->width, pVideoCodecCtx->height, pVideoCodecCtx->pix_fmt, pVideoCodecCtx->width, pVideoCodecCtx->height, PIX_FMT_YUV420P, SWS_FAST_BILINEAR, NULL, NULL, NULL); sws_scale(sws_context, pVideoFrame->data, pVideoFrame->linesize, 0, pVideoCodecCtx->height, pVideoFrameYUV->data, pVideoFrameYUV->linesize); sws_freeContext(sws_context); retval = AvgFrameImport(pVideoFrameYUV, pVideoCodecCtx->width, pVideoCodecCtx->height, i++, filename, handle, fps, fullArray); } else { retval = AvgFrameImport(pVideoFrame, pVideoCodecCtx->width, pVideoCodecCtx->height, i++, filename, handle, fps, fullArray); } } } // Decode audio // http://qtdvd.com/guides/ffmpeg.html#decode if (packet.stream_index == audioStream) { offset = 0; int frameSize; int length = 0; memset(audioBuffer, 0, sizeof(audioBuffer)); while (packet.size > 0) { //memset(audioBuffer, 0, sizeof(audioBuffer)); frameSize = numAudioBytes; //Copy decoded information into audioBuffer //frameSize gets set as the decoded frameSize, in bytes length = avcodec_decode_audio3(pAudioCodecCtx, audioBuffer, &frameSize, &packet); if (length <= 0) { // Error, see if we can recover. packet.size--; packet.data++; } else { //Slide pointer to next frame and update size printf("read %d bytes\n", length); packet.size -= length; packet.data += length; //Slide frame of audiobuffer memcpy((uint16_t*)(audioBuffer+offset), audioBuffer, frameSize); //Update offset offset += frameSize; } //Do something with audioBuffer //in = (fftw_complex*) fftw_malloc(sizeof(fftw_complex) * N); //if (counter%2) // printf("%f R: %d\n", audioTime, (int16_t)*audioBuffer); //else // printf("%f L: %d\n", audioTime, (int16_t)*audioBuffer); printf("%f %d\n", audioTime, (int16_t)*audioBuffer); fflush(stdout); } if (offset == 0) samples = 0; else samples = (unsigned int)offset/sizeof(short); totalSamples+=samples; if (counter%2) audioTime+=samples*1.0/pAudioCodecCtx->sample_rate; counter++; } } printf("Total time (s) (per audio sample calculation): %f\n",(float)(totalSamples*1.0/pAudioCodecCtx->sample_rate/pAudioCodecCtx->channels)); //Cut the large fullArray to the movie actual size int *shortArray = (int*) calloc ( i, sizeof (int)); memcpy(shortArray, fullArray, i*sizeof(int)); free(fullArray); //Do magic makeIndexes(shortArray, handle, filename, threshold, i, fps); // Free the packet that was allocated by av_read_frame av_free_packet(&packet); // Free the YUV image av_free(videoBuffer); av_free(audioBuffer); av_free(pVideoFrameYUV); // Free the YUV frame av_free(pVideoFrame); av_free(pAudioFrame); // Close the codec avcodec_close(pVideoCodecCtx); avcodec_close(pAudioCodecCtx); // Close the video file av_close_input_file(pFormatCtx); // Close DB handler sqlite3_close(handle); // Free full array free(shortArray); return 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->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 if (!check_same_thread && sqlite3_libversion_number() < 3003001) { PyErr_SetString(pysqlite_NotSupportedError, "shared connections not available"); return -1; } 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 SQL::openDB(const char name[]) { sqlite3_open(name, &db); }
int main(void) { int lfd; int cfd; int sfd; int rdy; struct sockaddr_in sin; struct sockaddr_in cin; int client[FD_SETSIZE]; /* 客户端连接的套接字描述符数组 */ int maxi; int maxfd; /* 最大连接数 */ fd_set rset; fd_set allset; socklen_t addr_len; /* 地址结构长度 */ int i; int n; int len; int opt = 1; /* 套接字选项 */ char addr_p[20]; sqlite3 *db = NULL; char *err_msg = NULL; msg_t msg; time_t ptime; char pestime[100] = {0}; /* 对server_addr_in 结构进行赋值 */ bzero(&sin,sizeof(struct sockaddr_in)); /* 先清零 */ sin.sin_family=AF_INET; sin.sin_addr.s_addr=htonl(INADDR_ANY); //表示接受任何ip地址 将ip地址转换成网络字节序 sin.sin_port=htons(PORT); //将端口号转换成网络字节序 /* 调用socket函数创建一个TCP协议套接口 */ if((lfd=socket(AF_INET,SOCK_STREAM,0))==-1) // AF_INET:IPV4;SOCK_STREAM:TCP { fprintf(stderr,"Socket error:%s\n\a",strerror(errno)); exit(1); } /*设置套接字选项 使用默认选项*/ setsockopt(lfd, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt)); /* 调用bind函数 将serer_addr结构绑定到sockfd上 */ if(bind(lfd,(struct sockaddr *)(&sin),sizeof(struct sockaddr))==-1) { fprintf(stderr,"Bind error:%s\n\a",strerror(errno)); exit(1); } /* 开始监听端口 等待客户的请求 */ if(listen(lfd,20)==-1) { fprintf(stderr,"Listen error:%s\n\a",strerror(errno)); exit(1); } printf("Accepting connections .......\n"); maxfd = lfd; /*对最大文件描述符进行初始化*/ maxi = -1; /*初始化客户端连接描述符集合*/ for(i = 0;i < FD_SETSIZE;i++) { client[i] = -1; } FD_ZERO(&allset); /* 清空文件描述符集合 */ FD_SET(lfd,&allset); /* 将监听字设置在集合内 */ int rc = sqlite3_open("chat_room.db",&db); if(rc != SQLITE_OK) { fprintf(stderr,"open database failed %s\n",sqlite3_errmsg(db)); } char sql_create_user_info[256] = {0}; //保存用户信息 sprintf(sql_create_user_info,"create table user_info(id INTEGER,name TEXT,password TEXT,primary key(id));"); sqlite3_exec(db,sql_create_user_info,NULL,0,&err_msg); char sql_create_log_info[256] = {0}; //保存已登录用户 sprintf(sql_create_log_info,"create table log_info(id INTEGER,name TEXT,connectfd INTEGER,primary key(id));"); sqlite3_exec(db,sql_create_log_info,NULL,0,&err_msg); char sql_create_record[256] = {0}; //保存服务器运行记录 sprintf(sql_create_record,"create table record(id INTEGER,name TEXT,size TEXT,target TEXT,msg TEXT,time TEXT,primary key(id));"); sqlite3_exec(db,sql_create_record,NULL,0,&err_msg); /* 开始服务程序的死循环 */ while(1) { rset = allset; /*得到当前可以读的文件描述符数*/ rdy = select(maxfd + 1, &rset, NULL, NULL, NULL); if(FD_ISSET(lfd, &rset)) { addr_len = sizeof(sin); /* 接受客户端的请求 */ if((cfd=accept(lfd,(struct sockaddr *)(&cin),&addr_len))==-1) { fprintf(stderr,"Accept error:%s\n\a",strerror(errno)); exit(1); } /*查找一个空闲位置*/ for(i = 0; i<FD_SETSIZE; i++) { //printf("%d\t",client[i]); if(client[i] <= 0) { client[i] = cfd; /* 将处理该客户端的连接套接字设置到该位置 */ break; } } /* 太多的客户端连接 服务器拒绝俄请求 跳出循环 */ if(i == FD_SETSIZE) { printf("too many clients"); exit(1); } FD_SET(cfd, &allset); /* 设置连接集合 */ if(cfd > maxfd) /* 新的连接描述符 */ { maxfd = cfd; } if(i > maxi) { maxi = i; } if(--rdy <= 0) /* 减少一个连接描述符 */ { continue; } } /* 对每一个连接描述符做处理 */ for(i = 0;i< FD_SETSIZE;i++) { if((sfd = client[i]) < 0) { continue; } if(FD_ISSET(sfd, &rset)) { n = read(sfd,&msg,sizeof(msg_t)); if(n == 0) //客户端异常退出 { printf("the other side has been closed. \n"); char sql_quit[256]; //删除登录状态 sprintf(sql_quit, "delete from log_info where connectfd = %d;", sfd); rc = sqlite3_exec(db,sql_quit,NULL,0,&err_msg); if(rc != SQLITE_OK) { fprintf(stderr,"%s",err_msg); } time(&ptime); //保存记录 strcpy(pestime,ctime(&ptime)); rc = sqlite3_exec(db, sql_quit, NULL, 0, &err_msg); sprintf(sql_quit, "insert into record (id,name,size,time) values(%d,'%s','%s','%s');",msg.id,msg.name,"下线",pestime); rc = sqlite3_exec(db, sql_quit, NULL, 0, &err_msg); memset(&msg,0,sizeof(msg_t)); fflush(stdout); /* 刷新 输出终端 */ close(sfd); FD_CLR(sfd, &allset); /*清空连接描述符数组*/ client[i] = -1; } else { msg_handle(&msg,sfd); /* 谐函数出错 */ if(n == 1) { exit(1); } } /*如果没有可以读的套接字 退出循环*/ if(--rdy <= 0) { break; } } } } close(lfd); /* 关闭链接套接字 */ return 0; }
int64 auth_verify_from_mydb_by_client(const char* guest, char* accesstoken, int accesslen) { int ret, row, col; sqlite3 *db = NULL; char *errmsg = NULL, **result, sql[1024]; uint64 time; int64 uid; // open database ret = sqlite3_open("./auth.db", &db); if (ret != SQLITE_OK) { LOGGER_ERROR("auth_verify_from_mydb_by_client open error: %s", sqlite3_errmsg(db)); goto QUIT; } // check table exist snprintf(sql, sizeof(sql), "select count(*) from sqlite_master where type='table' and name='guest'"); ret = sqlite3_get_table(db, sql, &result, &row, &col, &errmsg); if (ret != SQLITE_OK) { LOGGER_ERROR("auth_verify_from_mydb_by_client check table exist error: %d, %s", sqlite3_errcode(db), sqlite3_errmsg(db)); goto QUIT; } // if not exist then create if (atoi(result[1]) <= 0) { snprintf(sql, sizeof(sql), "create table guest(uid integer primary key autoincrement, name varchar(128), token varchar(128), time datatime)"); ret = sqlite3_exec(db, sql, NULL, NULL, &errmsg); if (ret != SQLITE_OK) { LOGGER_ERROR("auth_verify_from_mydb_by_client create table error: %d, %s", sqlite3_errcode(db), sqlite3_errmsg(db)); goto QUIT; } } // check guest if exist snprintf(sql, sizeof(sql), "select * from guest where name='%s'", guest); ret = sqlite3_get_table(db, sql, &result, &row, &col, &errmsg); if (ret != SQLITE_OK) { LOGGER_ERROR("auth_verify_from_mydb_by_client get table error: %d, %s", sqlite3_errcode(db), sqlite3_errmsg(db)); goto QUIT; } time = GetTimeSec(); snprintf(accesstoken, accesslen, "%lld", time); // if not exist then insert if (row <= 0) { snprintf(sql, sizeof(sql), "insert into guest (name, token, time) values('%s', '%s', %lld)", guest, accesstoken, time); ret = sqlite3_exec(db, sql, NULL, NULL, &errmsg); if (ret != SQLITE_OK) { LOGGER_ERROR("auth_verify_from_mydb_by_client insert guest error: %s, %s", guest, sqlite3_errmsg(db)); goto QUIT; } snprintf(sql, sizeof(sql), "select * from guest where name='%s'", guest); ret = sqlite3_get_table(db, sql, &result, &row, &col, &errmsg); if (ret != SQLITE_OK) { LOGGER_ERROR("auth_verify_from_mydb_by_client get table error: %d, %s", sqlite3_errcode(db), sqlite3_errmsg(db)); goto QUIT; } } else { snprintf(sql, sizeof(sql), "update guest set token='%s', time=%lld where name='%s'", accesstoken, time, guest); ret = sqlite3_exec(db, sql, NULL, NULL, &errmsg); if (ret != SQLITE_OK) { LOGGER_ERROR("auth_verify_from_mydb_by_client update guest error: %s, %s", guest, sqlite3_errmsg(db)); goto QUIT; } } uid = atoll(result[col]); QUIT: if (db) sqlite3_close(db); if (errmsg) sqlite3_free(errmsg); return uid; }