示例#1
0
// Checks cache consistency
void LdbCache::check(bool force)
{
	try {
		if (!m_db) opendb();
	} catch (const std::exception &ex) {
		PDEBUG << "Exception while opening database: " << ex.what() << endl;
		Logger::info() << "LdbCache: Database can't be opened, trying to repair it" << endl;
	}

	if (force || !m_db) {
		std::string path = cacheDir() + "/ldb";
		leveldb::Status status = leveldb::RepairDB(path, leveldb::Options());
		if (!status.ok()) {
			Logger::err() << "Error repairing database: " << status.ToString() << endl;
		} else {
			Logger::info() << "LdbCache: Database repaired" << endl;
		}
		closedb();
		opendb();
	}

	// Simply try to read all revisions
	Logger::info() << "LdbCache: Checking revisions..." << endl;
	std::vector<std::string> corrupted;
	size_t n = 0;
	leveldb::Iterator* it = m_db->NewIterator(leveldb::ReadOptions());
	for (it->SeekToFirst(); it->Valid(); it->Next()) {
		Revision rev(it->key().ToString());
		std::string value = it->value().ToString();
		MIStream rin(value.c_str(), value.length());
		if (!rev.load(rin)) {
			PDEBUG << "Revision " << it->key().ToString() << " corrupted!" << endl;
			corrupted.push_back(it->key().ToString());
		}
		++n;
	}
	if (!it->status().ok()) {
		Logger::err() << "Error iterating over cached revisions: " << it->status().ToString() << endl;
		Logger::err() << "Please re-run with --force to repair the database (might cause data loss)" << endl;
		return;
	}
	Logger::info() << "LdbCache: Checked " << n << " revisions, found " << corrupted.size() << " to be corrupted" << endl;

	for (size_t i = 0; i < corrupted.size(); i++) {
		Logger::err() << "LdbCache: Revision " << corrupted[i] << " is corrupted, removing from index file" << endl;
		leveldb::Status status = m_db->Delete(leveldb::WriteOptions(), corrupted[i]);
		if (!status.ok()) {
			Logger::err() << "Error: Can't remove from revision " << corrupted[i] << " from database: " << status.ToString() << endl;
			return;
		}
	}
}
示例#2
0
文件: tradump.c 项目: bazil/tra
void
main(int argc, char **argv)
{
	Db *db;

	fmtinstall('H', encodefmt);
	fmtinstall('P', pathfmt);
	fmtinstall('$', statfmt);
	fmtinstall('V', vtimefmt);

	ARGBEGIN{
	case 'V':
		traversion();
	default:
		usage();
	}ARGEND

	if(argc != 1)
		usage();

	db = opendb(argv[0]);
	if(db == nil)
		sysfatal("opendb '%s': %r", argv[0]);

	dumpdb(db, 1);
	exits(nil);
}
示例#3
0
static char *vacuum1_thread_writer(int iTid, void *pArg){
  Error err = {0};                /* Error code and message */
  Sqlite db = {0};                /* SQLite database connection */
  opendb(&err, &db, "test.db", 0);
  i64 i = 0;

  while( !timetostop(&err) ){
    i++;

    /* Insert lots of rows. Then delete some. */
    execsql(&err, &db, 
        "WITH loop(i) AS (SELECT 1 UNION ALL SELECT i+1 FROM loop WHERE i<100) "
        "INSERT INTO t1 SELECT randomblob(50), randomblob(2500) FROM loop"
    );

    /* Delete lots of rows */
    execsql(&err, &db, "DELETE FROM t1 WHERE rowid = :i", &i);
    clear_error(&err, SQLITE_LOCKED);

    /* Select the rows */
    execsql(&err, &db, "SELECT * FROM t1 ORDER BY x");
    clear_error(&err, SQLITE_LOCKED);
  }

  closedb(&err, &db);
  print_and_free_err(&err);
  return sqlite3_mprintf("ok");
}
示例#4
0
int main(int argc, char** argv) {

    webserver_initialise();

    int rc = parseargs(argc, argv);
    if (rc)return rc;

    logconsole(PKGBANNER);
    logconsole(PKGBUILD);

    rc = opendb();
    if (rc)return rc;

    webserver_set_defaults();

    webserver_add_search_int("/stanox", corpus_find_stanox);
    webserver_add_search_int("/nlc", corpus_find_nlc);
    webserver_add_search_int("/uic", corpus_find_uic);
    webserver_add_search_str("/3alpha", corpus_find_3alpha);
    webserver_add_search_str("/tiploc", corpus_find_tiploc);

    logconsole("Starting webserver on port %d", webserver.port);
    webserver_start();

    while (1) {
        sleep(60);
    }
}
示例#5
0
文件: compactdb.c 项目: 99years/plan9
void
main(int argc, char **argv)
{
	Avlwalk *w;
	Biobuf bout;
	Entry *e;

	quotefmtinstall();
	ARGBEGIN{
	default:
		usage();
	}ARGEND

	if(argc != 1)
		usage();

	Binit(&bout, 1, OWRITE);
	db = opendb(argv[0]);
	w = avlwalk(db->avl);
	while(e = (Entry*)avlnext(w))
		Bprint(&bout, "%q %q %luo %q %q %lud %lld\n",
			e->name, strcmp(e->name, e->d.name)==0 ? "-" : e->d.name, e->d.mode,
			e->d.uid, e->d.gid, e->d.mtime, e->d.length);
	if(Bterm(&bout) < 0)
		sysfatal("writing output: %r");

	exits(nil);
}
示例#6
0
// Adds the revision to the cache
void LdbCache::put(const std::string &id, const Revision &rev)
{
	if (!m_db) opendb();

	MOStream rout;
	rev.write(rout);
	std::vector<char> data(rout.data());
	leveldb::Status s = m_db->Put(leveldb::WriteOptions(), id, std::string(data.begin(), data.end()));
	if (!s.ok()) {
		throw PEX(str::printf("Error writing to cache: %s", s.ToString().c_str()));
	}
}
示例#7
0
// Checks if the diffstat of the given revision is already cached
bool LdbCache::lookup(const std::string &id)
{
	if (!m_db) opendb();

	std::string value;
	leveldb::Status s = m_db->Get(leveldb::ReadOptions(), id, &value);
	if (s.IsNotFound()) {
		return false;
	}
	if (!s.ok()) {
		throw PEX(str::printf("Error reading from cache: %s", s.ToString().c_str()));
	}
	return true;
}
示例#8
0
static char *vacuum1_thread_vacuumer(int iTid, void *pArg){
  Error err = {0};                /* Error code and message */
  Sqlite db = {0};                /* SQLite database connection */
  opendb(&err, &db, "test.db", 0);

  do{
    sql_script(&err, &db, "VACUUM");
    clear_error(&err, SQLITE_LOCKED);
  }while( !timetostop(&err) );

  closedb(&err, &db);
  print_and_free_err(&err);
  return sqlite3_mprintf("ok");
}
示例#9
0
文件: auth.c 项目: Jc2k/exact
/* auth_init: set up the auth tables.
 */
void auth_init() {
    logger(LOG_DEBUG, "initialising authentication tables\n");
    auth_init_mem();
    auth_alarm=conffile_param_int("flush");
    signal(14, auth_clean);
    alarm(auth_alarm);
    // create the empty output files, so our SMTP server doesn't blow up
#ifdef WITH_DB
    if(!strcmp(conffile_param("authtype"), "db"))
        opendb();
    else
        auth_write_text(); // so that the file exists
#else
    auth_write_text(); // so that the file exists
#endif
    logger(LOG_DEBUG, "authentication tables initialised\n");
}
示例#10
0
Revision *LdbCache::get(const std::string &id)
{
	if (!m_db) opendb();

	std::string value;
	leveldb::Status s = m_db->Get(leveldb::ReadOptions(), id, &value);
	if (!s.ok()) {
		throw PEX(str::printf("Error reading from cache: %s", s.ToString().c_str()));
	}

	Revision *rev = new Revision(id);
	MIStream rin(value.c_str(), value.length());
	if (!rev->load(rin)) {
		throw PEX(str::printf("Unable to read from cache: Data corrupted"));
	}
	return rev;
}
int main(int argc, char** argv)
{
    int batchSize;
    options_description batchOption("batch_write option");
    batchOption.add_options()("batch_size,b", value<int>(&batchSize)->default_value(1), "batch size");

    variables_map vm = parse(argc, argv, &batchOption);
    int total = vm["total"].as<int>();
    int valueSize = vm["size"].as<int>();
    std::cout << "batch size is " << batchSize << std::endl;

    DB* db = opendb();

    struct timeval tv;
    gettimeofday(&tv, 0);
    long start = tv.tv_sec * 1000000 + tv.tv_usec;
    int count = 0;
    std::string valuePrefix = std::string(valueSize, 'a');
    while (count != total) {
        WriteBatch batch;
        for (int j = 0; j < batchSize; j++, count++) {
            if (count == total)
                break;
            std::string tmp = std::to_string(count);
            std::string key = keyPrefix + tmp;
            std::string value = valuePrefix + tmp;
            auto s = batch.Put(key, value);
            if (!s.ok())
                std::cerr << "batch.Put():" << s.ToString() << std::endl;
            assert(s.ok());
        }
        auto s = db->Write(WriteOptions(), &batch);
        if (!s.ok())
            std::cerr << "db->Write():" << s.ToString() << std::endl;
        assert(s.ok());
    }
    gettimeofday(&tv, 0);
    long end = tv.tv_sec * 1000000 + tv.tv_usec;
    std::cout << total << " records batch put in " << end - start << " usec, "
              << double(end - start) / total << " usec average, throughput is "
              << (double)total * valueSize / (end - start) << " MB/s, rps is "
              << (double)1000000 * total / (end - start) << std::endl;

    delete db;
}
示例#12
0
/* open the connection */
static const response* sq_sender(str* sender, str* params)
{
  if(!opendb()) return &resp_internal;
  const response *r;
  
  if(sqlseq) {			/* dump the previous one */
    dosqlog();
    sqlseq = 0;
    session_delnum("sqlseq");
  }

  r = get_seq();
  if(r) return r;		/* seq error */

  str_copy(&qsender, sender);
  str_init(&qrecips);

  return 0;
  (void)params;
}
示例#13
0
static char *checkpoint_starvation_reader(int iTid, void *pArg){
  Error err = {0};
  Sqlite db = {0};

  opendb(&err, &db, "test.db", 0);
  while( !timetostop(&err) ){
    i64 iCount1, iCount2;
    sql_script(&err, &db, "BEGIN");
    iCount1 = execsql_i64(&err, &db, "SELECT count(x) FROM t1");
    usleep(CHECKPOINT_STARVATION_READMS*1000);
    iCount2 = execsql_i64(&err, &db, "SELECT count(x) FROM t1");
    sql_script(&err, &db, "COMMIT");

    if( iCount1!=iCount2 ){
      test_error(&err, "Isolation failure - %lld %lld", iCount1, iCount2);
    }
  }
  closedb(&err, &db);

  print_and_free_err(&err);
  return 0;
}
示例#14
0
static void checkpoint_starvation_main(int nMs, CheckpointStarvationCtx *p){
  Error err = {0};
  Sqlite db = {0};
  Threadset threads = {0};
  int nInsert = 0;
  int i;

  opendb(&err, &db, "test.db", 1);
  sql_script(&err, &db, 
      "PRAGMA page_size = 1024;"
      "PRAGMA journal_mode = WAL;"
      "CREATE TABLE t1(x);"
  );

  setstoptime(&err, nMs);

  for(i=0; i<4; i++){
    launch_thread(&err, &threads, checkpoint_starvation_reader, 0);
    usleep(CHECKPOINT_STARVATION_READMS*1000/4);
  }

  sqlite3_wal_hook(db.db, checkpoint_starvation_walhook, (void *)p);
  while( !timetostop(&err) ){
    sql_script(&err, &db, "INSERT INTO t1 VALUES(randomblob(1200))");
    nInsert++;
  }

  printf(" Checkpoint mode  : %s\n",
      p->eMode==SQLITE_CHECKPOINT_PASSIVE ? "PASSIVE" : "RESTART"
  );
  printf(" Peak WAL         : %d frames\n", p->nMaxFrame);
  printf(" Transaction count: %d transactions\n", nInsert);

  join_all_threads(&err, &threads);
  closedb(&err, &db);
  print_and_free_err(&err);
}
示例#15
0
static void vacuum1(int nMs){
  Error err = {0};
  Sqlite db = {0};
  Threadset threads = {0};

  opendb(&err, &db, "test.db", 1);
  sql_script(&err, &db, 
     "CREATE TABLE t1(x PRIMARY KEY, y BLOB);"
     "CREATE INDEX i1 ON t1(y);"
  );
  closedb(&err, &db);

  setstoptime(&err, nMs);

  sqlite3_enable_shared_cache(1);
  launch_thread(&err, &threads, vacuum1_thread_writer, 0);
  launch_thread(&err, &threads, vacuum1_thread_writer, 0);
  launch_thread(&err, &threads, vacuum1_thread_writer, 0);
  launch_thread(&err, &threads, vacuum1_thread_vacuumer, 0);
  join_all_threads(&err, &threads);
  sqlite3_enable_shared_cache(0);

  print_and_free_err(&err);
}
示例#16
0
frmBoxes::frmBoxes(const char *apppath, QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::frmBoxes)
{
#if (defined __APPLE__)
    #if (defined QT_NO_DEBUG)
    appath = apppath;
    QString apppathq = QString(appath);
    QStringList allparts = apppathq.split("/");
    QStringList rootdir = QStringList();//[allparts.length() - 4];
    for(int i = 0; i < allparts.length()-2; i++)
    {
        rootdir.append(allparts[i]);
    }
    QString wholepath = rootdir.join("/") + "/Resources/";
    std::string dbpath = wholepath.toStdString() + "veekun-pokedex.sqlite";
    std::string imgdbpath = wholepath.toStdString() + "images.sqlite";
    opendb(dbpath.c_str());
    openimgdb(imgdbpath.c_str());
#else
    opendb();
    openimgdb();
#endif
#else
    opendb("F:\\Dropbox\\PKMDS Databases\\veekun-pokedex.sqlite");
    openimgdb("F:\\Dropbox\\PKMDS Databases\\images.sqlite");
#endif
    ui->setupUi(this);
    ui->saBoxes->setVisible(false);
    ui->saBoxes->setEnabled(false);
    ui->sbBoxIncrem->setVisible(false);
    ui->sbBoxIncrem->setEnabled(false);
    mouseEventEater = new MouseEventEater(this);
    extern pkmviewer * pview;
    pview = new pkmviewer(this);
    partygraphics[0] = ui->pbPartySlot01;
    partygraphics[1] = ui->pbPartySlot02;
    partygraphics[2] = ui->pbPartySlot03;
    partygraphics[3] = ui->pbPartySlot04;
    partygraphics[4] = ui->pbPartySlot05;
    partygraphics[5] = ui->pbPartySlot06;
    boxgraphics[0] = ui->pbBoxSlot01;
    boxgraphics[1] = ui->pbBoxSlot02;
    boxgraphics[2] = ui->pbBoxSlot03;
    boxgraphics[3] = ui->pbBoxSlot04;
    boxgraphics[4] = ui->pbBoxSlot05;
    boxgraphics[5] = ui->pbBoxSlot06;
    boxgraphics[6] = ui->pbBoxSlot07;
    boxgraphics[7] = ui->pbBoxSlot08;
    boxgraphics[8] = ui->pbBoxSlot09;
    boxgraphics[9] = ui->pbBoxSlot10;
    boxgraphics[10] = ui->pbBoxSlot11;
    boxgraphics[11] = ui->pbBoxSlot12;
    boxgraphics[12] = ui->pbBoxSlot13;
    boxgraphics[13] = ui->pbBoxSlot14;
    boxgraphics[14] = ui->pbBoxSlot15;
    boxgraphics[15] = ui->pbBoxSlot16;
    boxgraphics[16] = ui->pbBoxSlot17;
    boxgraphics[17] = ui->pbBoxSlot18;
    boxgraphics[18] = ui->pbBoxSlot19;
    boxgraphics[19] = ui->pbBoxSlot20;
    boxgraphics[20] = ui->pbBoxSlot21;
    boxgraphics[21] = ui->pbBoxSlot22;
    boxgraphics[22] = ui->pbBoxSlot23;
    boxgraphics[23] = ui->pbBoxSlot24;
    boxgraphics[24] = ui->pbBoxSlot25;
    boxgraphics[25] = ui->pbBoxSlot26;
    boxgraphics[26] = ui->pbBoxSlot27;
    boxgraphics[27] = ui->pbBoxSlot28;
    boxgraphics[28] = ui->pbBoxSlot29;
    boxgraphics[29] = ui->pbBoxSlot30;
    boxpreviewgraphics[0] = ui->pbBox01;
    boxpreviewgraphics[1] = ui->pbBox02;
    boxpreviewgraphics[2] = ui->pbBox03;
    boxpreviewgraphics[3] = ui->pbBox04;
    boxpreviewgraphics[4] = ui->pbBox05;
    boxpreviewgraphics[5] = ui->pbBox06;
    boxpreviewgraphics[6] = ui->pbBox07;
    boxpreviewgraphics[7] = ui->pbBox08;
    boxpreviewgraphics[8] = ui->pbBox09;
    boxpreviewgraphics[9] = ui->pbBox10;
    boxpreviewgraphics[10] = ui->pbBox11;
    boxpreviewgraphics[11] = ui->pbBox12;
    boxpreviewgraphics[12] = ui->pbBox13;
    boxpreviewgraphics[13] = ui->pbBox14;
    boxpreviewgraphics[14] = ui->pbBox15;
    boxpreviewgraphics[15] = ui->pbBox16;
    boxpreviewgraphics[16] = ui->pbBox17;
    boxpreviewgraphics[17] = ui->pbBox18;
    boxpreviewgraphics[18] = ui->pbBox19;
    boxpreviewgraphics[19] = ui->pbBox20;
    boxpreviewgraphics[20] = ui->pbBox21;
    boxpreviewgraphics[21] = ui->pbBox22;
    boxpreviewgraphics[22] = ui->pbBox23;
    boxpreviewgraphics[23] = ui->pbBox24;
    this->setWindowFlags(Qt::MSWindowsFixedSizeDialogHint);

    //    connect(mouseEventEater, SIGNAL(send_rightButtonClicked(const QPoint&)),
    //                this, SLOT(rightButtonClicked(const QPoint&)));

    //    /*
    ////    QMenu* pContextMenu = new QMenu(this);
    ////    //    QTreeWidget* pTreeWidget = new QTreeWidget();
    ////    QAction* qaDeletePKM = new QAction(tr("Delete Pokemon"), pContextMenu);
    ////    ui->pbBoxSlot01->setContextMenuPolicy(Qt::ActionsContextMenu);
    ////    //    pTreeWidget->setContextMenuPolicy(Qt::ActionsContextMenu);
    ////    //    pTreeWidget->addAction(pOpenFile);
    ////    //connect(openAct, SIGNAL(triggered()), this, SLOT(open()));
    ////    //    connect(qaDeletePKM,
    ////    //            SIGNAL(triggered()),
    ////    //            this,
    ////    //            SLOT(frmBoxes::on_actionDeletePKM(QGraphicsView * gView)));
    ////    //    QString ss("QMenu{background-color: #ABABAB;border: 1px solid black;}");
    ////    this->connect(
    ////                qaDeletePKM,
    ////                SIGNAL(triggered()),
    ////                this,
    ////                SLOT(open())
    ////                );
    ////    ui->pbBoxSlot01->addAction(qaDeletePKM);
    ////    //    qApp->setStyleSheet(ss);
    ////    boxgraphics[0]->setContextMenuPolicy(Qt::CustomContextMenu);
    //*/
    //    boxgraphics[0]->setContextMenuPolicy(Qt::ActionsContextMenu);
    //    QMenu* pContextMenu = new QMenu(this);
    //    QAction* qaDeletePKM = new QAction(tr("Delete Pokemon"), pContextMenu);
    //    /*this->*//*QObject::*/connect(
    //                qaDeletePKM,
    //                SIGNAL(triggered()),
    //                /*this*/boxgraphics[0],
    //                SLOT(on_actionDeletePKM(boxgraphics[0]))
    //                );
    //    boxgraphics[0]->addAction(qaDeletePKM);
}
示例#17
0
LRESULT CALLBACK WndProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam)
{
	char filesizetxt[255];
	char sectionstxt[255];
	char entrypointtxt[255];

    switch(msg)
    {
		case WM_COMMAND:
		{
			if (LOWORD(wParam)==3) 
			{
				opendb();
				if (openfile() == 0) return 0;
				if (chkifexe() == 0) return 0;

				PE_pos = findPE();
				getentrypoint();
				get_num_of_sec();
				crtememspce();
				getheadersections();

				sprintf(filesizetxt,"File Size: %i",filesizedec);
				lb3->caption = filesizetxt;

				sprintf(sectionstxt,"Sections: %i",num_of_sec);
				lb4->caption = sectionstxt;

				sprintf(entrypointtxt,"Entry Point: %x%x%x%x",entrypoinywrd[3],entrypoinywrd[2],entrypoinywrd[1],entrypoinywrd[0]);
				lb5->caption = entrypointtxt;

				//sprintf(entrypointtxt,"Sections: %i",num_of_sec);
				//lb5->caption = entrypointtxt;
				
				fclose(thefile);
				break;
			}

			if (LOWORD(wParam) == 6)
			{
				if (strcmp("",tb1->caption) == 0) return 0;

				if (chkifnum() == false) return 0;

				//if (strcmp(sections[num_of_sec-1].name,".rsrc") == 0)
			//	{
					addnewsizes();

					wfile = fopen(tb1->caption, "r+b");
	
					setnewflesze();
					setnewhp();
					setnewrawsze();
					fillextra();


					fclose(wfile);



					MessageBox(NULL,"Process finshed!","blah",MB_OK);

			//	}

				if (sec_nme != NULL)
				{
					delete sec_nme;
					sec_nme=NULL;
				}
			}
			break;
		}
		case WM_CREATE:
		{
			lb1= new labelbox(hwnd);
			lb1->caption = "Filename:";
			lb1->width=50;

			tb1 = new editbox(hwnd);
			tb1->x = 60;
			tb1->width = 100;
			tb1->caption = "";

			b1 = new button(hwnd);
			b1->caption ="Broswe";
			b1->x =170;
			b1->width = 50;

			lb2 = new labelbox(hwnd);
			lb2->y = 40;
			lb2->width = 85;
			lb2->caption = "Bytes to allocate: ";


			tb2 = new editbox(hwnd);
			tb2->y = 40;
			tb2->x = 100;
			tb2->width = 30;
			tb2->caption = "";

			b2 = new button(hwnd);
			b2->caption ="Go!";
			b2->x =170;
			b2->y = 160;
			b2->width = 50;

			lb3 = new labelbox(hwnd);
			lb3->y = 80;
			lb3->width = 85;
			lb3->caption = "File size: ";

			lb4 = new labelbox(hwnd);
			lb4->y = 100;
			lb4->width = 85;
			lb4->caption = "Sections: ";

			lb5 = new labelbox(hwnd);
			lb5->y = 120;
			lb5->width = 110;
			lb5->caption = "Entry Point: ";

			break;
		}
		case WM_PAINT:
		{
			//BITMAP bm;
			PAINTSTRUCT ps;
		    HDC hdc;
		    hdc = BeginPaint(hwnd,&ps);
			EndPaint(hwnd, &ps);
		}
		break;
		case WM_CLOSE:
			

	
			DestroyWindow(hwnd);
        break;
        case WM_DESTROY:

			
			delete lb1;
			lb1 = NULL;

			delete tb1;
			tb1 = NULL;

			delete b1;
			b1 = NULL;

			delete lb2;
			lb2 = NULL;

			delete lb3;
			lb3 = NULL;

			delete lb4;
			lb4 = NULL;

		//	delete tb2;
		//	tb2 = NULL;
			if (sections != NULL)
			{
				if (sections[0].name!=NULL)
				{
					delete sections[0].name;
					sections[0].name = NULL;
				}
			}

			if (sections != NULL)
			{
				delete[] sections;
				sections = NULL;
			}
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                            

            PostQuitMessage(0);
        break;
        default:
            return DefWindowProc(hwnd, msg, wParam, lParam);
    }
    return 0;
}
示例#18
0
文件: applylog.c 项目: npe9/harvey
void
main(int argc, char **argv)
{ 
	char *f[10], *local, *name, *remote, *s, *t, verb;
	int fd, havedb, havelocal, i, k, n, nf, resolve1, skip;
	int checkedmatch1, checkedmatch2, 
		checkedmatch3, checkedmatch4;
	ulong now;
	Biobuf bin;
	Dir dbd, ld, nd, rd;
	Avlwalk *w;
	Entry *e;

	membogus(argv);
	quotefmtinstall();
	ARGBEGIN{
	case 's':
	case 'c':
		i = ARGC();
		addresolve(i, EARGF(usage()));
		break;
	case 'n':
		donothing = 1;
		verbose = 1;
		break;
	case 'S':
		safeinstall = 0;
		break;
	case 'T':
		timefile = EARGF(usage());
		break;
	case 't':
		tempspool = 0;
		break;
	case 'u':
		douid = 1;
		break;
	case 'v':
		verbose++;
		break;
	default:
		usage();
	}ARGEND

	if(argc < 3)
		usage();

	if(timefile)
		readtimefile();

	lroot = argv[1];
	if(!isdir(lroot))
		sysfatal("bad local root directory");
	rroot = argv[2];
	if(!isdir(rroot))
		sysfatal("bad remote root directory");

	match = argv+3;
	nmatch = argc-3;
	for(i=0; i<nmatch; i++)
		if(match[i][0] == '/')
			match[i]++;

	if((clientdb = opendb(argv[0])) == nil)
		sysfatal("opendb %q: %r", argv[2]);
	
	copyerr = opendb(nil);

	skip = 0;
	Binit(&bin, 0, OREAD);
	for(; s=Brdstr(&bin, '\n', 1); free(s)){
		t = estrdup(s);
		nf = tokenize(s, f, nelem(f));
		if(nf != 10 || strlen(f[2]) != 1){
			skip = 1;
			fprint(2, "warning: skipping bad log entry <%s>\n", t);
			free(t);
			continue;
		}
		free(t);
		now = strtoul(f[0], 0, 0);
		n = atoi(f[1]);
		verb = f[2][0];
		name = f[3];
		if(now < maxnow || (now==maxnow && n <= maxn))
			continue;
		local = mkname(localbuf, sizeof localbuf, lroot, name);
		if(strcmp(f[4], "-") == 0)
			f[4] = f[3];
		remote = mkname(remotebuf, sizeof remotebuf, rroot, f[4]);
		rd.name = f[4];
		rd.mode = strtoul(f[5], 0, 8);
		rd.uid = f[6];
		rd.gid = f[7];
		rd.mtime = strtoul(f[8], 0, 10);
		rd.length = strtoll(f[9], 0, 10);
		havedb = finddb(clientdb, name, &dbd)>=0;
		havelocal = localdirstat(local, &ld)>=0;

		resolve1 = resolve(name);

		/*
		 * if(!ismatch(name)){
		 *	skip = 1;
		 *	continue;
		 * }
		 * 
		 * This check used to be right here, but we want
		 * the time to be able to move forward past entries
		 * that don't match and have already been applied.
		 * So now every path below must checked !ismatch(name)
		 * before making any changes to the local file
		 * system.  The fake variable checkedmatch
		 * tracks whether !ismatch(name) has been checked.
		 * If the compiler doesn't produce any used/set
		 * warnings, then all the paths should be okay.
		 * Even so, we have the asserts to fall back on.
		 */
		switch(verb){
		case 'd':	/* delete file */
			delce(local);
			if(!havelocal)	/* doesn't exist; who cares? */
				break;
			if(access(remote, AEXIST) >= 0)	/* got recreated! */
				break;
			if(!ismatch(name)){
				skip = prstopped(skip, name);
				continue;
			}
			SET(checkedmatch1);
			if(!havedb){
				if(resolve1 == 's')
					goto DoRemove;
				else if(resolve1 == 'c')
					goto DoRemoveDb;
				conflict(name, "locally created; will not remove");
				skip = 1;
				continue;
			}
			assert(havelocal && havedb);
			if(dbd.mtime > rd.mtime)		/* we have a newer file than what was deleted */
				break;
			if(samecontents(local, remote) > 0){	/* going to get recreated */
				chat("= %q %luo %q %q %lud\n", name, rd.mode, rd.uid, rd.gid, rd.mtime);
				break;
			}
			if(!(dbd.mode&DMDIR) && (dbd.mtime != ld.mtime || dbd.length != ld.length)){	/* locally modified since we downloaded it */
				if(resolve1 == 's')
					goto DoRemove;
				else if(resolve1 == 'c')
					break;
				conflict(name, "locally modified; will not remove");
				skip = 1;
				continue;
			}
		    DoRemove:
			USED(checkedmatch1);
			assert(ismatch(name));
			chat("d %q %luo %q %q %lud\n", name, rd.mode, rd.uid, rd.gid, rd.mtime);
			if(donothing)
				break;
			if(remove(local) < 0){
				error("removing %q: %r", name);
				skip = 1;
				continue;
			}
		    DoRemoveDb:
			USED(checkedmatch1);
			assert(ismatch(name));
			removedb(clientdb, name);
			break;

		case 'a':	/* add file */
			if(!havedb){
				if(!ismatch(name)){
					skip = prstopped(skip, name);
					continue;
				}
				SET(checkedmatch2);
				if(!havelocal)
					goto DoCreate;
				if((ld.mode&DMDIR) && (rd.mode&DMDIR))
					break;
				if(samecontents(local, remote) > 0){
					chat("= %q %luo %q %q %lud\n", name, rd.mode, rd.uid, rd.gid, rd.mtime);
					goto DoCreateDb;
				}
				if(resolve1 == 's')
					goto DoCreate;
				else if(resolve1 == 'c')
					goto DoCreateDb;
				conflict(name, "locally created; will not overwrite");
				skip = 1;
				continue;
			}
			assert(havedb);
			if(dbd.mtime >= rd.mtime)	/* already created this file; ignore */
				break;
			if(havelocal){
				if((ld.mode&DMDIR) && (rd.mode&DMDIR))
					break;
				if(!ismatch(name)){
					skip = prstopped(skip, name);
					continue;
				}
				SET(checkedmatch2);
				if(samecontents(local, remote) > 0){
					chat("= %q %luo %q %q %lud\n", name, rd.mode, rd.uid, rd.gid, rd.mtime);
					goto DoCreateDb;
				}
				if(dbd.mtime==ld.mtime && dbd.length==ld.length)
					goto DoCreate;
				if(resolve1=='s')
					goto DoCreate;
				else if(resolve1 == 'c')
					goto DoCreateDb;
				conflict(name, "locally modified; will not overwrite");
				skip = 1;
				continue;
			}
			if(!ismatch(name)){
				skip = prstopped(skip, name);
				continue;
			}
			SET(checkedmatch2);
		    DoCreate:
			USED(checkedmatch2);
			assert(ismatch(name));
			if(notexists(remote)){
				addce(local);
				/* no skip=1 */
				break;;
			}
			chat("a %q %luo %q %q %lud\n", name, rd.mode, rd.uid, rd.gid, rd.mtime);
			if(donothing)
				break;
			if(rd.mode&DMDIR){
				fd = create(local, OREAD, DMDIR);
				if(fd < 0 && isdir(local))
					fd = open(local, OREAD);
				if(fd  < 0){
					error("mkdir %q: %r", name);
					skip = 1;
					continue;
				}
				nulldir(&nd);
				nd.mode = rd.mode;
				if(dirfwstat(fd, &nd) < 0)
					fprint(2, "warning: cannot set mode on %q\n", local);
				nulldir(&nd);
				nd.gid = rd.gid;
				if(dirfwstat(fd, &nd) < 0)
					fprint(2, "warning: cannot set gid on %q\n", local);
				if(douid){
					nulldir(&nd);
					nd.uid = rd.uid;
					if(dirfwstat(fd, &nd) < 0)
						fprint(2, "warning: cannot set uid on %q\n", local);
				}
				close(fd);
				rd.mtime = now;
			}else{
				if(copyfile(local, remote, name, &rd, 1, &k) < 0){
					if(k)
						addce(local);
					skip = 1;
					continue;
				}
			}
		    DoCreateDb:
			USED(checkedmatch2);
			assert(ismatch(name));
			insertdb(clientdb, name, &rd);
			break;
			
		case 'c':	/* change contents */
			if(!havedb){
				if(notexists(remote)){
					addce(local);
					/* no skip=1 */
					break;
				}
				if(!ismatch(name)){
					skip = prstopped(skip, name);
					continue;
				}
				SET(checkedmatch3);
				if(resolve1 == 's')
					goto DoCopy;
				else if(resolve1=='c')
					goto DoCopyDb;
				if(samecontents(local, remote) > 0){
					chat("= %q %luo %q %q %lud\n", name, rd.mode, rd.uid, rd.gid, rd.mtime);
					goto DoCopyDb;
				}
				if(havelocal)
					conflict(name, "locally created; will not update");
				else
					conflict(name, "not replicated; will not update");
				skip = 1;
				continue;
			}
			if(dbd.mtime >= rd.mtime)		/* already have/had this version; ignore */
				break;
			if(!ismatch(name)){
				skip = prstopped(skip, name);
				continue;
			}
			SET(checkedmatch3);
			if(!havelocal){
				if(notexists(remote)){
					addce(local);
					/* no skip=1 */
					break;
				}
				if(resolve1 == 's')
					goto DoCopy;
				else if(resolve1 == 'c')
					break;
				conflict(name, "locally removed; will not update");
				skip = 1;
				continue;
			}
			assert(havedb && havelocal);
			if(dbd.mtime != ld.mtime || dbd.length != ld.length){
				if(notexists(remote)){
					addce(local);
					/* no skip=1 */
					break;
				}
				if(samecontents(local, remote) > 0){
					chat("= %q %luo %q %q %lud\n", name, rd.mode, rd.uid, rd.gid, rd.mtime);
					goto DoCopyDb;
				}
				if(resolve1 == 's')
					goto DoCopy;
				else if(resolve1 == 'c')
					goto DoCopyDb;
				conflict(name, "locally modified; will not update [%llud %lud -> %llud %lud]", dbd.length, dbd.mtime, ld.length, ld.mtime);
				skip = 1;
				continue;
			}
		    DoCopy:
			USED(checkedmatch3);
			assert(ismatch(name));
			if(notexists(remote)){
				addce(local);
				/* no skip=1 */
				break;
			}
			chat("c %q\n", name);
			if(donothing)
				break;
			if(copyfile(local, remote, name, &rd, 0, &k) < 0){
				if(k)
					addce(local);
				skip = 1;
				continue;
			}
		    DoCopyDb:
			USED(checkedmatch3);
			assert(ismatch(name));
			if(!havedb){
				if(havelocal)
					dbd = ld;
				else
					dbd = rd;
			}
			dbd.mtime = rd.mtime;
			dbd.length = rd.length;
			insertdb(clientdb, name, &dbd);
			break;			

		case 'm':	/* change metadata */
			if(!havedb){
				if(notexists(remote)){
					addce(local);
					/* no skip=1 */
					break;
				}
				if(!ismatch(name)){
					skip = prstopped(skip, name);
					continue;
				}
				SET(checkedmatch4);
				if(resolve1 == 's'){
					USED(checkedmatch4);
					SET(checkedmatch2);
					goto DoCreate;
				}
				else if(resolve1 == 'c')
					goto DoMetaDb;
				if(havelocal)
					conflict(name, "locally created; will not update metadata");
				else
					conflict(name, "not replicated; will not update metadata");
				skip = 1;
				continue;
			}
			if(!(dbd.mode&DMDIR) && dbd.mtime > rd.mtime)		/* have newer version; ignore */
				break;
			if((dbd.mode&DMDIR) && dbd.mtime > now)
				break;
			if(havelocal && (!douid || strcmp(ld.uid, rd.uid)==0) && strcmp(ld.gid, rd.gid)==0 && ld.mode==rd.mode)
				break;
			if(!havelocal){
				if(notexists(remote)){
					addce(local);
					/* no skip=1 */
					break;
				}
				if(!ismatch(name)){
					skip = prstopped(skip, name);
					continue;
				}
				SET(checkedmatch4);
				if(resolve1 == 's'){
					USED(checkedmatch4);
					SET(checkedmatch2);
					goto DoCreate;
				}
				else if(resolve1 == 'c')
					break;
				conflict(name, "locally removed; will not update metadata");
				skip = 1;
				continue;
			}
			if(!(dbd.mode&DMDIR) && (dbd.mtime != ld.mtime || dbd.length != ld.length)){	/* this check might be overkill */
				if(notexists(remote)){
					addce(local);
					/* no skip=1 */
					break;
				}
				if(!ismatch(name)){
					skip = prstopped(skip, name);
					continue;
				}
				SET(checkedmatch4);
				if(resolve1 == 's' || samecontents(local, remote) > 0)
					goto DoMeta;
				else if(resolve1 == 'c')
					break;
				conflict(name, "contents locally modified (%s); will not update metadata to %s %s %luo",
					dbd.mtime != ld.mtime ? "mtime" :
					dbd.length != ld.length ? "length" : 
					"unknown",
					rd.uid, rd.gid, rd.mode);
				skip = 1;
				continue;
			}
			if((douid && strcmp(ld.uid, dbd.uid)!=0) || strcmp(ld.gid, dbd.gid)!=0 || ld.mode!=dbd.mode){
				if(notexists(remote)){
					addce(local);
					/* no skip=1 */
					break;
				}
				if(!ismatch(name)){
					skip = prstopped(skip, name);
					continue;
				}
				SET(checkedmatch4);
				if(resolve1 == 's')
					goto DoMeta;
				else if(resolve1 == 'c')
					break;
				conflict(name, "metadata locally changed; will not update metadata to %s %s %luo", rd.uid, rd.gid, rd.mode);
				skip = 1;
				continue;
			}
			if(!ismatch(name)){
				skip = prstopped(skip, name);
				continue;
			}
			SET(checkedmatch4);
		    DoMeta:
			USED(checkedmatch4);
			assert(ismatch(name));
			if(notexists(remote)){
				addce(local);
				/* no skip=1 */
				break;
			}
			chat("m %q %luo %q %q %lud\n", name, rd.mode, rd.uid, rd.gid, rd.mtime);
			if(donothing)
				break;
			nulldir(&nd);
			nd.gid = rd.gid;
			nd.mode = rd.mode;
			if(douid)
				nd.uid = rd.uid;
			if(dirwstat(local, &nd) < 0){
				error("dirwstat %q: %r", name);
				skip = 1;
				continue;
			}
		    DoMetaDb:
			USED(checkedmatch4);
			assert(ismatch(name));
			if(!havedb){
				if(havelocal)
					dbd = ld;
				else
					dbd = rd;
			}
			if(dbd.mode&DMDIR)
				dbd.mtime = now;
			dbd.gid = rd.gid;
			dbd.mode = rd.mode;
			if(douid)
				dbd.uid = rd.uid;
			insertdb(clientdb, name, &dbd);
			break;
		}
		if(!skip && !donothing){
			maxnow = now;
			maxn = n;
		}
	}

	w = avlwalk(copyerr->avl);
	while(e = (Entry*)avlnext(w))
		error("copying %q: %s\n", e->name, e->d.name);

	if(timefile)
		writetimefile();
	if(nconf)
		exits("conflicts");

	if(errors)
		exits("errors");
	exits(nil);
}
示例#19
0
int main(int argc, char *argv[])
{
    modbus_t            *ctx;
    struct timeval      timeout;
    int                 ret, i, rc, ii;
    int nb_pointers;
    //unit16_t *tab_rp_registers;
    uint16_t        regs[MODBUS_MAX_READ_REGISTERS] = {0};
    char            regs2[MODBUS_MAX_READ_REGISTERS]={0};
    FILE *fp = NULL;

    int err, rows, cols;
 

   if(argc != 5){
        printf("INsufficient argument");
        return -1;
    }
    err = opendb();
    if(err)
    {
	/*Database is not open*/
	return err;
    }


    ctx = modbus_new_rtu(MODBUS_SERIAL_DEV,
            MODBUS_SERIAL_BAUDRATE,
            MODBUS_SERIAL_PARITY,
            MODBUS_SERIAL_DATABITS,
            MODBUS_SERIAL_STOPBITS);
 
    if (ctx == NULL) {
        fprintf(stderr, "Unable to create the libmodbus context\n");
        exit(-1);
    }
 
    
    i = modbus_rtu_get_serial_mode(ctx);
    if( i == MODBUS_RTU_RS232)
    {
	printf("Serial mode = RS232\n");
	ret = modbus_rtu_set_serial_mode(ctx, MODBUS_RTU_RS232);
	if(ret < 0)
	    fprintf(stderr, "modbus_rtu_set_serial_mode() error: %s\n", strerror(errno));
    }
    else if(i == MODBUS_RTU_RS485)
    {
	printf("Serial mode = RS485\n");
	ret = modbus_rtu_set_serial_mode(ctx, MODBUS_RTU_RS485);
	if(ret < 0)
	    fprintf(stderr, "modbus_rtu_set_serial_mode() error: %s\n", strerror(errno));
    }
      else
    {
	printf("Serial mode = RS485\n");
	ret = modbus_rtu_set_serial_mode(ctx, MODBUS_RTU_RS485);
	if(ret < 0)
	    fprintf(stderr, "modbus_rtu_set_serial_mode() error: %s\n", strerror(errno));
    }
    /* set slave device ID */
    modbus_set_slave(ctx, strtol(argv[2], NULL, 10));
 
    /* Debug mode */
    modbus_set_debug(ctx, MODBUS_DEBUG);

    if (modbus_connect(ctx) == -1) {
        fprintf(stderr, "Connection failed: %s\n",
                modbus_strerror(errno));
        modbus_free(ctx);
        return -1;
    }


    /* Allocate and initialize the memory to store the registers */
    /*  nb_points = (UT_REGISTERS_NB > UT_INPUT_REGISTERS_NB) ?
        UT_REGISTERS_NB : UT_INPUT_REGISTERS_NB;
    tab_rp_registers = (uint16_t *) malloc(nb_points * sizeof(uint16_t));
    memset(tab_rp_registers, 0, nb_points * sizeof(uint16_t));
    */

     /* write data in test.txt */
    fp = fopen("test.txt", "w");
    if(fp == NULL)
    {
        printf("fail to open file!\n");
        return -1;
    }


 	

    rc = modbus_read_registers(ctx, strtol(argv[3], NULL, 16), strtol("1", NULL, 10), regs);
    if (rc < 0) {
	printf("1234\n");
        fprintf(stderr, "%s\n", modbus_strerror(errno));
    }
    else {
            printf("HOLDING REGISTERS:\n");
            for (ii=0; ii < rc; ii++) {
                sprintf(regs2, "%d", regs[ii]);
                fputs(regs2, fp);
                fputs("\n", fp);
                printf("[%d]=%d\n", ii, regs[ii]);
		sql_write2(argv[1], argv[2], argv[3], regs2, argv[4]);
		
            }
		if( mysql_query(dp, query))
		{
			fprintf(stderr, "%s\n", mysql_error(dp));
		}

		qp = mysql_store_result(dp);
		mysql_free_result(qp);
	
		mysql_close(dp);


    }

    fclose(fp);

    /* Close the connection */
    modbus_close(ctx);

    modbus_free(ctx);
 
    return 0;
}
示例#20
0
文件: ndb.c 项目: AustenConrad/plan-9
/*
 *  lookup info about a client in the database.  Find an address on the
 *  same net as riip.
 */
int
lookup(Bootp *bp, Info *iip, Info *riip)
{
	Ndbtuple *t, *nt;
	Ndbs s;
	char *hwattr;
	char *hwval, hwbuf[33];
	uchar ciaddr[IPaddrlen];

	if(opendb() == nil){
		warning(1, "can't open db");
		return -1;
	}

	memset(iip, 0, sizeof(*iip));

	/* client knows its address? */
	v4tov6(ciaddr, bp->ciaddr);
	if(validip(ciaddr)){
		if(lookupip(ciaddr, iip, 0) < 0) {
			if (debug)
				warning(0, "don't know %I", ciaddr);
			return -1;	/* don't know anything about it */
		}
		if(!samenet(riip->ipaddr, iip)){
			warning(0, "%I not on %I", ciaddr, riip->ipnet);
			return -1;
		}

		/*
		 *  see if this is a masquerade, i.e., if the ether
		 *  address doesn't match what we expected it to be.
		 */
		if(memcmp(iip->etheraddr, zeroes, 6) != 0)
		if(memcmp(bp->chaddr, iip->etheraddr, 6) != 0)
			warning(0, "ciaddr %I rcvd from %E instead of %E",
				ciaddr, bp->chaddr, iip->etheraddr);

		return 0;
	}

	if(bp->hlen > Maxhwlen)
		return -1;
	switch(bp->htype){
	case 1:
		hwattr = "ether";
		hwval = hwbuf;
		snprint(hwbuf, sizeof(hwbuf), "%E", bp->chaddr);
		break;
	default:
		syslog(0, blog, "not ethernet %E, htype %d, hlen %d",
			bp->chaddr, bp->htype, bp->hlen);
		return -1;
	}

	/*
	 *  use hardware address to find an ip address on
	 *  same net as riip
	 */
	t = ndbsearch(db, &s, hwattr, hwval);
	while(t){
		for(nt = t; nt; nt = nt->entry){
			if(strcmp(nt->attr, "ip") != 0)
				continue;
			parseip(ciaddr, nt->val);
			if(lookupip(ciaddr, iip, 0) < 0)
				continue;
			if(samenet(riip->ipaddr, iip)){
				ndbfree(t);
				return 0;
			}
		}
		ndbfree(t);
		t = ndbsnext(&s, hwattr, hwval);
	}
	return -1;
}
示例#21
0
frmBoxes::frmBoxes(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::frmBoxes)
{
    opendb();
    openimgdb();
    ui->setupUi(this);
    ui->saBoxes->setVisible(false);
    ui->saBoxes->setEnabled(false);
    ui->sbBoxIncrem->setVisible(false);
    ui->sbBoxIncrem->setEnabled(false);
    mouseEventEater = new MouseEventEater(this);
    extern pkmviewer * pview;
    pview = new pkmviewer(this);
    partygraphics[0] = ui->pbPartySlot01;
    partygraphics[1] = ui->pbPartySlot02;
    partygraphics[2] = ui->pbPartySlot03;
    partygraphics[3] = ui->pbPartySlot04;
    partygraphics[4] = ui->pbPartySlot05;
    partygraphics[5] = ui->pbPartySlot06;
    boxgraphics[0] = ui->pbBoxSlot01;
    boxgraphics[1] = ui->pbBoxSlot02;
    boxgraphics[2] = ui->pbBoxSlot03;
    boxgraphics[3] = ui->pbBoxSlot04;
    boxgraphics[4] = ui->pbBoxSlot05;
    boxgraphics[5] = ui->pbBoxSlot06;
    boxgraphics[6] = ui->pbBoxSlot07;
    boxgraphics[7] = ui->pbBoxSlot08;
    boxgraphics[8] = ui->pbBoxSlot09;
    boxgraphics[9] = ui->pbBoxSlot10;
    boxgraphics[10] = ui->pbBoxSlot11;
    boxgraphics[11] = ui->pbBoxSlot12;
    boxgraphics[12] = ui->pbBoxSlot13;
    boxgraphics[13] = ui->pbBoxSlot14;
    boxgraphics[14] = ui->pbBoxSlot15;
    boxgraphics[15] = ui->pbBoxSlot16;
    boxgraphics[16] = ui->pbBoxSlot17;
    boxgraphics[17] = ui->pbBoxSlot18;
    boxgraphics[18] = ui->pbBoxSlot19;
    boxgraphics[19] = ui->pbBoxSlot20;
    boxgraphics[20] = ui->pbBoxSlot21;
    boxgraphics[21] = ui->pbBoxSlot22;
    boxgraphics[22] = ui->pbBoxSlot23;
    boxgraphics[23] = ui->pbBoxSlot24;
    boxgraphics[24] = ui->pbBoxSlot25;
    boxgraphics[25] = ui->pbBoxSlot26;
    boxgraphics[26] = ui->pbBoxSlot27;
    boxgraphics[27] = ui->pbBoxSlot28;
    boxgraphics[28] = ui->pbBoxSlot29;
    boxgraphics[29] = ui->pbBoxSlot30;
    boxpreviewgraphics[0] = ui->pbBox01;
    boxpreviewgraphics[1] = ui->pbBox02;
    boxpreviewgraphics[2] = ui->pbBox03;
    boxpreviewgraphics[3] = ui->pbBox04;
    boxpreviewgraphics[4] = ui->pbBox05;
    boxpreviewgraphics[5] = ui->pbBox06;
    boxpreviewgraphics[6] = ui->pbBox07;
    boxpreviewgraphics[7] = ui->pbBox08;
    boxpreviewgraphics[8] = ui->pbBox09;
    boxpreviewgraphics[9] = ui->pbBox10;
    boxpreviewgraphics[10] = ui->pbBox11;
    boxpreviewgraphics[11] = ui->pbBox12;
    boxpreviewgraphics[12] = ui->pbBox13;
    boxpreviewgraphics[13] = ui->pbBox14;
    boxpreviewgraphics[14] = ui->pbBox15;
    boxpreviewgraphics[15] = ui->pbBox16;
    boxpreviewgraphics[16] = ui->pbBox17;
    boxpreviewgraphics[17] = ui->pbBox18;
    boxpreviewgraphics[18] = ui->pbBox19;
    boxpreviewgraphics[19] = ui->pbBox20;
    boxpreviewgraphics[20] = ui->pbBox21;
    boxpreviewgraphics[21] = ui->pbBox22;
    boxpreviewgraphics[22] = ui->pbBox23;
    boxpreviewgraphics[23] = ui->pbBox24;
    this->setWindowFlags(Qt::MSWindowsFixedSizeDialogHint);
}
int main(int argc, char** argv) {
	/// Serial port full path to open
	char *serialport = NULL;

	/// Database file to open
	char *databasename = NULL;

	/// List of columsn to log
	char *log_columns = NULL;

	/// Number of samples to take
	int samplecount = -1;

	/// Number of samples per second
	int samplespersecond = 1;

	/// Ask to show the capabilities of the OBD device then exit
	int showcapabilities = 0;

	/// Set if the user wishes to upgrade the baudrate
	long baudrate_upgrade = -1;

	/// Time between samples, measured in microseconds
	long frametime = 0;

	/// Spam all readings to stdout
	int spam_stdout = 0;

	/// Enable elm optimisations
	int enable_optimisations = 0;

	/// Enable serial logging
	int enable_seriallog = 0;

	/// Serial log filename
	char *seriallogname = NULL;

#ifdef OBDPLATFORM_POSIX
	/// Daemonise
	int daemonise = 0;
#endif //OBDPLATFORM_POSIX

	/// Requested baudrate
	long requested_baud = -1;

	// Config File
	struct OBDGPSConfig *obd_config = obd_loadConfig(0);

	if(NULL != obd_config) {
		samplespersecond = obd_config->samplerate;
		enable_optimisations = obd_config->optimisations;
		requested_baud = obd_config->baudrate;
		baudrate_upgrade = obd_config->baudrate_upgrade;
	}

	// Do not attempt to buffer stdout at all
	setvbuf(stdout, (char *)NULL, _IONBF, 0);

	int optc;
	int mustexit = 0;
	while ((optc = getopt_long (argc, argv, shortopts, longopts, NULL)) != -1) {
		switch (optc) {
			case 'h':
				printhelp(argv[0]);
				mustexit = 1;
				break;
			case 'v':
				printversion();
				mustexit = 1;
				break;
			case 's':
				if(NULL != serialport) {
					free(serialport);
				}
				serialport = strdup(optarg);
				break;
			case 'o':
				enable_optimisations = 1;
				break;
			case 't':
				spam_stdout = 1;
				break;
			case 'u':
				{
					int newout = open(optarg, O_CREAT|O_RDWR|O_APPEND,
						S_IRUSR|S_IWUSR|S_IRGRP|S_IROTH);
					if(-1 == newout) {
						perror(optarg);
					} else {
						printf("Redirecting output to %s\n", optarg);
						close(STDOUT_FILENO);
						close(STDERR_FILENO);
						dup2(newout, STDOUT_FILENO);
						dup2(newout, STDERR_FILENO);
					}
				}
				break;
#ifdef OBDPLATFORM_POSIX
			case 'm':
				daemonise = 1;
				break;
#endif //OBDPLATFORM_POSIX
			case 'c':
				samplecount = atoi(optarg);
				break;
			case 'b':
				requested_baud = strtol(optarg, (char **)NULL, 10);
				break;
			case 'B':
				baudrate_upgrade = strtol(optarg, (char **)NULL, 10);
				break;
			case 'd':
				if(NULL != databasename) {
					free(databasename);
				}
				databasename = strdup(optarg);
				break;
			case 'i':
				if(NULL != log_columns) {
					free(log_columns);
				}
				log_columns = strdup(optarg);
				break;
			case 'a':
				samplespersecond = atoi(optarg);
				break;
			case 'l':
				enable_seriallog = 1;
				if(NULL != seriallogname) {
					free(seriallogname);
				}
				seriallogname = strdup(optarg);
				break;
			case 'p':
				showcapabilities = 1;
				break;
			default:
				mustexit = 1;
				break;
		}
	}

	if(mustexit) exit(0);

	if(0 >= samplespersecond) {
		frametime = 0;
	} else {
		frametime = 1000000 / samplespersecond;
	}

	if(NULL == serialport) {
		if(NULL != obd_config && NULL != obd_config->obd_device) {
			serialport = strdup(obd_config->obd_device);
		} else {
			serialport = strdup(OBD_DEFAULT_SERIALPORT);
		}
	}
	if(NULL == databasename) {
		if(NULL != obd_config && NULL != obd_config->log_file) {
			databasename = strdup(obd_config->log_file);
		} else {
			databasename = strdup(OBD_DEFAULT_DATABASE);
		}
	}
	if(NULL == log_columns) {
		if(NULL != obd_config && NULL != obd_config->log_columns) {
			log_columns = strdup(obd_config->log_columns);
		} else {
			log_columns = strdup(OBD_DEFAULT_COLUMNS);
		}
	}


	if(enable_seriallog && NULL != seriallogname) {
		startseriallog(seriallogname);
	}


	// Open the serial port.
	int obd_serial_port = openserial(serialport, requested_baud, baudrate_upgrade);

	if(-1 == obd_serial_port) {
		fprintf(stderr, "Couldn't open obd serial port. Attempting to continue.\n");
	} else {
		fprintf(stderr, "Successfully connected to serial port. Will log obd data\n");
	}

	// Just figure out our car's OBD port capabilities and print them
	if(showcapabilities) {
		printobdcapabilities(obd_serial_port);
		
		printf("\n");

/*
		unsigned int retvals[50];
		int vals_returned;
		getobderrorcodes(obd_serial_port,
        		retvals, sizeof(retvals)/sizeof(retvals[0]), &vals_returned);

		int q = 0;
		int c = retvals[0];
		for(q=1;q<1+2*c && q+1<vals_returned;q+=2) {
			printf("Error: %s\n", obderrconvert(retvals[q], retvals[q+1]));
		}

*/

		closeserial(obd_serial_port);
		exit(0);
	}


#ifdef HAVE_GPSD
	// Open the gps device
	struct gps_data_t *gpsdata;
	gpsdata = opengps(GPSD_ADDR, GPSD_PORT);

	if(NULL == gpsdata) {
		fprintf(stderr, "Couldn't open gps port on startup.\n");
	} else {
		fprintf(stderr, "Successfully connected to gpsd. Will log gps data\n");
	}

#endif //HAVE_GPSD

	if(-1 == obd_serial_port
#ifdef HAVE_GPSD
		&& NULL == gpsdata
#endif //HAVE_GPSD
	) {
		fprintf(stderr, "Couldn't find either gps or obd to log. Exiting.\n");
		exit(1);
	}

#ifdef HAVE_DBUS
	obdinitialisedbus();
#endif //HAVE_DBUS

	// sqlite database
	sqlite3 *db;

	// sqlite statement
	sqlite3_stmt *obdinsert;

	// number of columns in the insert
	int obdnumcols;

	// sqlite return status
	int rc;

	// Open the database and create the obd table
	if(NULL == (db = opendb(databasename))) {
		closeserial(obd_serial_port);
		exit(1);
	}

	// Disable sqlite's synchronous pragma.
	/* char *zErrMsg;
	rc = sqlite3_exec(db, "PRAGMA synchronous=OFF",
					NULL, NULL, &zErrMsg);
	if(rc != SQLITE_OK) {
		printf("SQLite error %i: %s\n", rc, zErrMsg);
		sqlite3_free(zErrMsg);
	} */

	// Wishlist of commands from config file
	struct obdservicecmd **wishlist_cmds = NULL;
	obd_configCmds(log_columns, &wishlist_cmds);

	void *obdcaps = getobdcapabilities(obd_serial_port,wishlist_cmds);

	obd_freeConfigCmds(wishlist_cmds);
	wishlist_cmds=NULL;

	createobdtable(db,obdcaps);

	// Create the insert statement. On success, we'll have the number of columns
	if(0 == (obdnumcols = createobdinsertstmt(db,&obdinsert, obdcaps)) || NULL == obdinsert) {
		closedb(db);
		closeserial(obd_serial_port);
		exit(1);
	}

	createtriptable(db);

	createecutable(db);

	// All of these have obdnumcols-1 since the last column is time
	int cmdlist[obdnumcols-1]; // Commands to send [index into obdcmds_mode1]

	int i,j;
	for(i=0,j=0; i<sizeof(obdcmds_mode1)/sizeof(obdcmds_mode1[0]); i++) {
		if(NULL != obdcmds_mode1[i].db_column) {
			if(isobdcapabilitysupported(obdcaps,i)) {
				cmdlist[j] = i;
				j++;
			}
		}
	}

	freeobdcapabilities(obdcaps);
	// We create the gps table even if gps is disabled, so that other
	//  SQL commands expecting the table to at least exist will work.

	// sqlite statement
	sqlite3_stmt *gpsinsert;

	// number of columns in the insert
	int gpsnumcols;

	creategpstable(db);

	if(0 == (gpsnumcols = creategpsinsertstmt(db, &gpsinsert) || NULL == gpsinsert)) {
		closedb(db);
		closeserial(obd_serial_port);
		exit(1);
	}

#ifdef OBDPLATFORM_POSIX
	if(daemonise) {
		if(0 != obddaemonise()) {
			fprintf(stderr,"Couldn't daemonise, exiting\n");
			closeserial(obd_serial_port);
			exit(1);
		}
	}
#endif //OBDPLATFORM_POSIX

#ifdef HAVE_GPSD
	// Ping a message to stdout the first time we get
	//   enough of a satellite lock to begin logging
	int have_gps_lock = 0;
#endif //HAVE_GPSD


	install_signalhandlers();


	// The current thing returned by starttrip
	sqlite3_int64 currenttrip = 0;

	// Set when we're actually inside a trip
	int ontrip = 0;

	// The current time we're inserting
	double time_insert;

	// The last time we tried to check the gps daemon
	double time_lastgpscheck = 0;

	// Number of samples per transaction
	const int basetransactioncount = TRANSACTIONTIME * (0==samplespersecond?10:samplespersecond);

	// Store a few seconds worth of samples per transaction
	int transactioncount = 0;

	obdbegintransaction(db);

	while(samplecount == -1 || samplecount-- > 0) {

		struct timeval starttime; // start time through loop
		struct timeval endtime; // end time through loop
		struct timeval selecttime; // =endtime-starttime [for select()]

		if(0 != gettimeofday(&starttime,NULL)) {
			perror("Couldn't gettimeofday");
			break;
		}

#ifdef HAVE_DBUS
		enum obd_dbus_message msg_ret;
		while(OBD_DBUS_NOMESSAGE != (msg_ret = obdhandledbusmessages())) {
			switch(msg_ret) {
				case OBD_DBUS_STARTTRIP:
					if(!ontrip) {
						currenttrip = starttrip(db, time_insert);
						fprintf(stderr,"Created a new trip (%i)\n", (int)currenttrip);
						ontrip = 1;
					}
					break;
				case OBD_DBUS_NOMESSAGE:
				default:
					break;
			}
		}
#endif //HAVE_DBUS

		time_insert = (double)starttime.tv_sec+(double)starttime.tv_usec/1000000.0f;

		if(sig_starttrip) {
			if(ontrip) {
				fprintf(stderr,"Ending current trip\n");
				updatetrip(db, currenttrip, time_insert);
				ontrip = 0;
			}
			currenttrip = starttrip(db, time_insert);
			fprintf(stderr,"Created a new trip (%i)\n", (int)currenttrip);
			ontrip = 1;
			sig_starttrip = 0;
		}

		enum obd_serial_status obdstatus;
		if(-1 < obd_serial_port) {

			// Get all the OBD data
			for(i=0; i<obdnumcols-1; i++) {
				float val;
				unsigned int cmdid = obdcmds_mode1[cmdlist[i]].cmdid;
				int numbytes = enable_optimisations?obdcmds_mode1[cmdlist[i]].bytes_returned:0;
				OBDConvFunc conv = obdcmds_mode1[cmdlist[i]].conv;

				obdstatus = getobdvalue(obd_serial_port, cmdid, &val, numbytes, conv);
				if(OBD_SUCCESS == obdstatus) {
#ifdef HAVE_DBUS
					obddbussignalpid(&obdcmds_mode1[cmdlist[i]], val);
#endif //HAVE_DBUS
					if(spam_stdout) {
						printf("%s=%f\n", obdcmds_mode1[cmdlist[i]].db_column, val);
					}
					sqlite3_bind_double(obdinsert, i+1, (double)val);
					// printf("cmd: %02X, val: %f\n",obdcmds_mode1[cmdlist[i]].cmdid,val);
				} else {
					break;
				}
			}

			if(obdstatus == OBD_SUCCESS) {
				// If they're not on a trip but the engine is going, start a trip
				if(0 == ontrip) {
					printf("Creating a new trip\n");
					currenttrip = starttrip(db, time_insert);
					ontrip = 1;
				}
				sqlite3_bind_double(obdinsert, i+1, time_insert);
				sqlite3_bind_int64(obdinsert, i+2, currenttrip);

				// Do the OBD insert
				rc = sqlite3_step(obdinsert);
				if(SQLITE_DONE != rc) {
					printf("sqlite3 obd insert failed(%i): %s\n", rc, sqlite3_errmsg(db));
				}
			} else if(OBD_ERROR == obdstatus) {
				fprintf(stderr, "Received OBD_ERROR from serial read. Exiting\n");
				receive_exitsignal = 1;
			} else {
				// If they're on a trip, and the engine has desisted, stop the trip
				if(ontrip) {
					printf("Ending current trip\n");
					updatetrip(db, currenttrip, time_insert);
					ontrip = 0;
				}
			}
			sqlite3_reset(obdinsert);
		}

		// Constantly update the trip
		updatetrip(db, currenttrip, time_insert);

#ifdef HAVE_GPSD
		// Get the GPS data
		double lat,lon,alt,speed,course,gpstime;

		int gpsstatus = -1;
		if(NULL != gpsdata) {
			gpsstatus = getgpsposition(gpsdata, &lat, &lon, &alt, &speed, &course, &gpstime);
		} else {
			if(time_insert - time_lastgpscheck > 10) { // Try again once in a while
				gpsdata = opengps(GPSD_ADDR, GPSD_PORT);
				if(NULL != gpsdata) {
					printf("Delayed connection to gps achieved\n");
				} else {
					// fprintf(stderr, "Delayed connection to gps failed\n");
				}
				time_lastgpscheck = time_insert;
			}
		}
		if(gpsstatus < 0 || NULL == gpsdata) {
			// Nothing yet
		} else if(gpsstatus >= 0) {
			if(0 == have_gps_lock) {
				fprintf(stderr,"GPS acquisition complete\n");
				have_gps_lock = 1;
			}

			sqlite3_bind_double(gpsinsert, 1, lat);
			sqlite3_bind_double(gpsinsert, 2, lon);
			if(gpsstatus >= 1) {
				sqlite3_bind_double(gpsinsert, 3, alt);
			} else {
				sqlite3_bind_null(gpsinsert, 3);
			}
			sqlite3_bind_double(gpsinsert, 4, speed);
			sqlite3_bind_double(gpsinsert, 5, course);
			sqlite3_bind_double(gpsinsert, 6, gpstime);

			if(spam_stdout) {
				printf("gpspos=%f,%f,%f,%f,%f\n",
					lat, lon, (gpsstatus>=1?alt:-1000.0), speed, course);
			}

			// Use time worked out before.
			//  This makes table joins reliable, but the time itself may be wrong depending on gpsd lagginess
			sqlite3_bind_double(gpsinsert, 7, time_insert);

			sqlite3_bind_int64(gpsinsert, 8, currenttrip);

			// Do the GPS insert
			rc = sqlite3_step(gpsinsert);
			if(SQLITE_DONE != rc) {
				printf("sqlite3 gps insert failed(%i): %s\n", rc, sqlite3_errmsg(db));
			}
			sqlite3_reset(gpsinsert);
		}
#endif //HAVE_GPSD

		if(0 != gettimeofday(&endtime,NULL)) {
			perror("Couldn't gettimeofday");
			break;
		}

		// Set via the signal handler
		if(receive_exitsignal) {
			break;
		}


		// Commit this if we've done more than a certain number
		transactioncount++;
		transactioncount%=basetransactioncount;
		if(0 == transactioncount) {
			obdcommittransaction(db);
			obdbegintransaction(db);
		}

		
		// usleep() not as portable as select()

		if(0 < frametime) {
			selecttime.tv_sec = endtime.tv_sec - starttime.tv_sec;
			if (selecttime.tv_sec != 0) {
					endtime.tv_usec += 1000000*selecttime.tv_sec;
					selecttime.tv_sec = 0;
			}
			selecttime.tv_usec = (frametime) - 
					(endtime.tv_usec - starttime.tv_usec);
			if(selecttime.tv_usec < 0) {
					selecttime.tv_usec = 1;
			}
			select(0,NULL,NULL,NULL,&selecttime);
		}
	}

	obdcommittransaction(db);

	if(0 != ontrip) {
		updatetrip(db, currenttrip, time_insert);
		ontrip = 0;
	}

	sqlite3_finalize(obdinsert);
	sqlite3_finalize(gpsinsert);

	closeserial(obd_serial_port);
#ifdef HAVE_GPSD
	if(NULL != gpsdata) {
		gps_close(gpsdata);
	}
#endif //HAVE_GPSD
	closedb(db);

	if(enable_seriallog) {
		closeseriallog();
	}

	if(NULL != log_columns) free(log_columns);
	if(NULL != databasename) free(databasename);
	if(NULL != serialport) free(serialport);

	obd_freeConfig(obd_config);
	return 0;
}
示例#23
0
frmBoxes::frmBoxes(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::frmBoxes)
{
    opendb();
    openimgdb();
    ui->setupUi(this);
    ui->saBoxes->setVisible(false);
    ui->saBoxes->setEnabled(false);
    ui->sbBoxIncrem->setVisible(false);
    ui->sbBoxIncrem->setEnabled(false);
    mouseEventEater = new MouseEventEater(this);
    extern pkmviewer * pview;
    pview = new pkmviewer(this);
    partygraphics[0] = ui->pbPartySlot01;
    partygraphics[1] = ui->pbPartySlot02;
    partygraphics[2] = ui->pbPartySlot03;
    partygraphics[3] = ui->pbPartySlot04;
    partygraphics[4] = ui->pbPartySlot05;
    partygraphics[5] = ui->pbPartySlot06;
    boxgraphics[0] = ui->pbBoxSlot01;
    boxgraphics[1] = ui->pbBoxSlot02;
    boxgraphics[2] = ui->pbBoxSlot03;
    boxgraphics[3] = ui->pbBoxSlot04;
    boxgraphics[4] = ui->pbBoxSlot05;
    boxgraphics[5] = ui->pbBoxSlot06;
    boxgraphics[6] = ui->pbBoxSlot07;
    boxgraphics[7] = ui->pbBoxSlot08;
    boxgraphics[8] = ui->pbBoxSlot09;
    boxgraphics[9] = ui->pbBoxSlot10;
    boxgraphics[10] = ui->pbBoxSlot11;
    boxgraphics[11] = ui->pbBoxSlot12;
    boxgraphics[12] = ui->pbBoxSlot13;
    boxgraphics[13] = ui->pbBoxSlot14;
    boxgraphics[14] = ui->pbBoxSlot15;
    boxgraphics[15] = ui->pbBoxSlot16;
    boxgraphics[16] = ui->pbBoxSlot17;
    boxgraphics[17] = ui->pbBoxSlot18;
    boxgraphics[18] = ui->pbBoxSlot19;
    boxgraphics[19] = ui->pbBoxSlot20;
    boxgraphics[20] = ui->pbBoxSlot21;
    boxgraphics[21] = ui->pbBoxSlot22;
    boxgraphics[22] = ui->pbBoxSlot23;
    boxgraphics[23] = ui->pbBoxSlot24;
    boxgraphics[24] = ui->pbBoxSlot25;
    boxgraphics[25] = ui->pbBoxSlot26;
    boxgraphics[26] = ui->pbBoxSlot27;
    boxgraphics[27] = ui->pbBoxSlot28;
    boxgraphics[28] = ui->pbBoxSlot29;
    boxgraphics[29] = ui->pbBoxSlot30;
    boxpreviewgraphics[0] = ui->pbBox01;
    boxpreviewgraphics[1] = ui->pbBox02;
    boxpreviewgraphics[2] = ui->pbBox03;
    boxpreviewgraphics[3] = ui->pbBox04;
    boxpreviewgraphics[4] = ui->pbBox05;
    boxpreviewgraphics[5] = ui->pbBox06;
    boxpreviewgraphics[6] = ui->pbBox07;
    boxpreviewgraphics[7] = ui->pbBox08;
    boxpreviewgraphics[8] = ui->pbBox09;
    boxpreviewgraphics[9] = ui->pbBox10;
    boxpreviewgraphics[10] = ui->pbBox11;
    boxpreviewgraphics[11] = ui->pbBox12;
    boxpreviewgraphics[12] = ui->pbBox13;
    boxpreviewgraphics[13] = ui->pbBox14;
    boxpreviewgraphics[14] = ui->pbBox15;
    boxpreviewgraphics[15] = ui->pbBox16;
    boxpreviewgraphics[16] = ui->pbBox17;
    boxpreviewgraphics[17] = ui->pbBox18;
    boxpreviewgraphics[18] = ui->pbBox19;
    boxpreviewgraphics[19] = ui->pbBox20;
    boxpreviewgraphics[20] = ui->pbBox21;
    boxpreviewgraphics[21] = ui->pbBox22;
    boxpreviewgraphics[22] = ui->pbBox23;
    boxpreviewgraphics[23] = ui->pbBox24;
    this->setWindowFlags(Qt::MSWindowsFixedSizeDialogHint);

//    connect(mouseEventEater, SIGNAL(send_rightButtonClicked(const QPoint&)),
//                this, SLOT(rightButtonClicked(const QPoint&)));

//    /*
////    QMenu* pContextMenu = new QMenu(this);
////    //    QTreeWidget* pTreeWidget = new QTreeWidget();
////    QAction* qaDeletePKM = new QAction(tr("Delete Pokemon"), pContextMenu);
////    ui->pbBoxSlot01->setContextMenuPolicy(Qt::ActionsContextMenu);
////    //    pTreeWidget->setContextMenuPolicy(Qt::ActionsContextMenu);
////    //    pTreeWidget->addAction(pOpenFile);
////    //connect(openAct, SIGNAL(triggered()), this, SLOT(open()));
////    //    connect(qaDeletePKM,
////    //            SIGNAL(triggered()),
////    //            this,
////    //            SLOT(frmBoxes::on_actionDeletePKM(QGraphicsView * gView)));
////    //    QString ss("QMenu{background-color: #ABABAB;border: 1px solid black;}");
////    this->connect(
////                qaDeletePKM,
////                SIGNAL(triggered()),
////                this,
////                SLOT(open())
////                );
////    ui->pbBoxSlot01->addAction(qaDeletePKM);
////    //    qApp->setStyleSheet(ss);
////    boxgraphics[0]->setContextMenuPolicy(Qt::CustomContextMenu);
//*/
//    boxgraphics[0]->setContextMenuPolicy(Qt::ActionsContextMenu);
//    QMenu* pContextMenu = new QMenu(this);
//    QAction* qaDeletePKM = new QAction(tr("Delete Pokemon"), pContextMenu);
//    /*this->*//*QObject::*/connect(
//                qaDeletePKM,
//                SIGNAL(triggered()),
//                /*this*/boxgraphics[0],
//                SLOT(on_actionDeletePKM(boxgraphics[0]))
//                );
//    boxgraphics[0]->addAction(qaDeletePKM);
}
示例#24
0
文件: ndb.c 项目: AustenConrad/plan-9
/*
 *  do an ipinfo with defaults
 */
int
lookupip(uchar *ipaddr, Info *iip, int gate)
{
	char ip[32];
	Ndbtuple *t, *nt;
	char *attrs[32], **p;

	if(opendb() == nil){
		warning(1, "can't open db");
		return -1;
	}

	p = attrs;
	*p++ = "ip";
	*p++ = "ipmask";
	*p++ = "@ipgw";
	if(!gate){
		*p++ = "bootf";
		*p++ = "bootf2";
		*p++ = "@tftp";
		*p++ = "@tftp2";
		*p++ = "rootpath";
		*p++ = "dhcp";
		*p++ = "vendorclass";
		*p++ = "ether";
		*p++ = "dom";
		*p++ = "@fs";
		*p++ = "@auth";
	}
	*p = 0;

	memset(iip, 0, sizeof(*iip));
	snprint(ip, sizeof(ip), "%I", ipaddr);
	t = ndbipinfo(db, "ip", ip, attrs, p - attrs);
	if(t == nil)
		return -1;
	
	for(nt = t; nt != nil; nt = nt->entry){
		if(strcmp(nt->attr, "ip") == 0)
			setipaddr(iip->ipaddr, nt->val);
		else
		if(strcmp(nt->attr, "ipmask") == 0)
			setipmask(iip->ipmask, nt->val);
		else
		if(strcmp(nt->attr, "fs") == 0)
			setipaddr(iip->fsip, nt->val);
		else
		if(strcmp(nt->attr, "auth") == 0)
			setipaddr(iip->auip, nt->val);
		else
		if(strcmp(nt->attr, "tftp") == 0)
			setipaddr(iip->tftp, nt->val);
		else
		if(strcmp(nt->attr, "tftp2") == 0)
			setipaddr(iip->tftp2, nt->val);
		else
		if(strcmp(nt->attr, "ipgw") == 0)
			setipaddr(iip->gwip, nt->val);
		else
		if(strcmp(nt->attr, "ether") == 0){
			/*
			 * this is probably wrong for machines with multiple
			 * ethers.  bootp or dhcp requests could come from any
			 * of the ethers listed in the ndb entry.
			 */
			if(memcmp(iip->etheraddr, noetheraddr, 6) == 0)
				parseether(iip->etheraddr, nt->val);
			iip->indb = 1;
		}
		else
		if(strcmp(nt->attr, "dhcp") == 0){
			if(iip->dhcpgroup[0] == 0)
				strcpy(iip->dhcpgroup, nt->val);
		}
		else
		if(strcmp(nt->attr, "bootf") == 0){
			if(iip->bootf[0] == 0)
				strcpy(iip->bootf, nt->val);
		}
		else
		if(strcmp(nt->attr, "bootf2") == 0){
			if(iip->bootf2[0] == 0)
				strcpy(iip->bootf2, nt->val);
		}
		else
		if(strcmp(nt->attr, "vendor") == 0){
			if(iip->vendor[0] == 0)
				strcpy(iip->vendor, nt->val);
		}
		else
		if(strcmp(nt->attr, "dom") == 0){
			if(iip->domain[0] == 0)
				strcpy(iip->domain, nt->val);
		}
		else
		if(strcmp(nt->attr, "rootpath") == 0){
			if(iip->rootpath[0] == 0)
				strcpy(iip->rootpath, nt->val);
		}
	}
	ndbfree(t);
	maskip(iip->ipaddr, iip->ipmask, iip->ipnet);
	return 0;
}