Example #1
0
void CheckInternetOp::start()
{
    restart();
}
Example #2
0
static void pcap_handle(u_char *user, const struct pcap_pkthdr *h, const u_char *buf)
{
	static unsigned failCount = 0;
	pthread_t thread_lan;

#ifndef NO_ARP
	if (buf[0x0c]==0x88 && buf[0x0d]==0x8e) {
#endif
		if (memcmp(destMAC, buf+6, 6)!=0 && startMode>2)	/* 服务器MAC地址不符 */
			return;
		capBuf = buf;
		if (buf[0x0F]==0x00 && buf[0x12]==0x01 && buf[0x16]==0x01) {	/* 验证用户名 */
			if (startMode < 3) {
				memcpy(destMAC, buf+6, 6);
				print_log(_("** 认证服务器MAC: %s\n"), formatHex(destMAC, 6));
				startMode += 3;	/* 标记认证服务器MAC为已获取,可以锁定 */
			}
			if (proxyMode == 0) {
				if (startMode==3 && memcmp(buf+0x17, "User name", 9)==0)	/* 塞尔 */
					startMode = 5;
				switchState(ID_IDENTITY);
			} else {
				if (proxyClientRequested == 1) {
					print_log(_(">> 服务器已请求用户名\n"));
					proxy_send_to_lan(buf, h->len);
				} else {
					print_log(_("!! 在代理认证完成后收到用户名请求,将重启认证!\n"));
					switchState(ID_WAITCLIENT);
				}
			}
		}
		else if (buf[0x0F]==0x00 && buf[0x12]==0x01 && buf[0x16]==0x04)	{ /* 验证密码 */
			if (proxyMode == 0) {
				switchState(ID_CHALLENGE);
			} else {
				if (proxyClientRequested == 1) {
					print_log(_(">> 服务器已请求密码\n"));
					proxy_send_to_lan(buf, h->len);
				} else {
					print_log(_("!! 在代理认证完成后收到密码请求,将重启认证!\n"));
					switchState(ID_WAITCLIENT);
				}
			}
		}
		else if (buf[0x0F]==0x00 && buf[0x12]==0x03) {	/* 认证成功 */
			print_log(_(">> 认证成功!\n"));
			failCount = 0;
			proxySuccessCount++;
			if (proxyMode != 0) {
				proxy_send_to_lan(buf, h->len);
				if (proxySuccessCount >= proxyRequireSuccessCount) {
					pcap_breakloop(hPcapLan);
					proxyClientRequested = 0;
					proxySuccessCount = 0;
					memcpy(lastSuccessClientMAC, clientMAC, 6); // 备份本次认证成功的客户端MAC,用于通知掉线
					proxy_clear_client_mac(); // 重设MAC地址,以备下次使用不同客户端认证用
					print_log(_(">> 已关闭LAN监听线程\n"));
				}
			}
			if (!(startMode%3 == 2)) {
				getEchoKey(buf);
			}
			showRuijieMsg(buf, h->caplen);
			if (dhcpMode==1 || dhcpMode==2)	/* 二次认证第一次或者认证后 */
				switchState(ID_DHCP);
			else if (startMode%3 == 2)
				switchState(ID_WAITECHO);
			else
				switchState(ID_ECHO);
		}
		else if (buf[0x0F]==0x00 && buf[0x12]==0x01 && buf[0x16]==0x02)	/* 显示赛尔提示信息 */
			showCernetMsg(buf);
		else if (buf[0x0F] == 0x05)	/* (赛尔)响应在线 */
			switchState(ID_ECHO);
		else if (buf[0x0F]==0x00 && buf[0x12]==0x04) {  /* 认证失败或被踢下线 */
			if (state==ID_WAITECHO || state==ID_ECHO) {
				if (proxyMode == 0) {
					print_log(_(">> 认证掉线!\n"));
					showRuijieMsg(buf, h->caplen);
					if (restartOnLogOff) {
						print_log(_(">> 正在重新认证...\n"));
						switchState(ID_START);					
					} else {
						exit(1);
					}
				} else {
					pthread_create(&thread_lan, NULL, lan_thread, 0);
					print_log(_(">> 认证掉线,已发回客户端并重新启用对LAN的监听\n"));
					showRuijieMsg(buf, h->caplen);
					// clientMAC已经在成功时被清除了,所以使用lastSuccessClientMAC发送,发完清除
					memmove(clientMAC, lastSuccessClientMAC, 6);
					proxy_send_to_lan(buf, h->len);
					proxy_clear_client_mac();
					switchState(ID_WAITCLIENT);
				}
			}
			else if (buf[0x1b]!=0 || startMode%3==2) {
				print_log(_(">> 认证失败!\n"));
				showRuijieMsg(buf, h->caplen);
				if (maxFail && ++failCount>=maxFail) {
					print_log(_(">> 连续认证失败%u次,退出认证。\n"), maxFail);
					exit(EXIT_SUCCESS);
				}
				restart();
			} else {
				if (proxyMode == 0)
					switchState(ID_START);
				else
					switchState(ID_WAITCLIENT);
			}
		}
#ifndef NO_ARP
	} else if (gateMAC[0]!=0xFE && buf[0x0c]==0x08 && buf[0x0d]==0x06) {
		if (*(u_int32_t *)(buf+0x1c) == gateway) {
			char str[50];
			if (gateMAC[0] == 0xFF) {
				memcpy(gateMAC, buf+0x16, 6);
				print_log(_("** 网关MAC:\t%s\n"), formatHex(gateMAC, 6));
				sprintf(str, "arp -s %s %s", formatIP(gateway), formatHex(gateMAC, 6));
				system(str);
			} else if (buf[0x15]==0x02 && memcmp(&rip, buf+0x26, 4)==0
				&& memcmp(gateMAC, buf+0x16, 6)!=0) {
				print_log(_("** ARP欺骗:\t%s\n"), formatHex(buf+0x16, 6));
#ifndef NO_NOTIFY
				if (showNotify) {
					sprintf(str, _("欺骗源: %s"), formatHex(buf+0x16, 6));
					if (show_notify(_("MentoHUST - ARP提示"), str, 1000*showNotify) < 0)
						showNotify = 0;
				}
#endif
			}
		}
	}
#endif
}
Example #3
0
MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
{
    GlobalCache *globalCache = new GlobalCache();
    loginStatus = false;

    updateTimer = startTimer(100);

    QTimerEvent *e= new QTimerEvent(updateTimer);

    setWindowTitle("#precIsioN Billing Software 1.2");

    /* Setting height and width properties */
    QDesktopWidget *desktop = QApplication::desktop();
    int width = desktop->width();
    int height = desktop->height();
    GlobalCache::setScreenWidth(width);
    GlobalCache::setScreenHeight(height);
    resize(width/2, height/2);
    int sideWidth = 10; //width/48;
    int sideHeight = (height-50)/14;
    widgetWidth = width - 20; //sideWidth *46;
    widgetHeight = sideHeight * 14;

    /* Creating menu bar and status bar */
    menubar = new QMenuBar(this);
    setMenuBar(menubar);

    menuAdministrator = new QMenu(menubar);
    menuAdministrator->setTitle("Administrator");
    menubar->addMenu(menuAdministrator);

    QAction *homeAct = new QAction(("&Home"), this);
    homeAct->setShortcut(QKeySequence(tr("Ctrl+H")));
    menuAdministrator->addAction(homeAct);
    menuAdministrator->addSeparator();
    QAction *changePasswordAct = new QAction("Change Password", this);
    menuAdministrator->addAction(changePasswordAct);
    QAction *refreshAct = new QAction(("&Refresh"), this);
    refreshAct->setShortcut(QKeySequence(tr("Ctrl+R")));
    menuAdministrator->addAction(refreshAct);
    QAction *fullScreenAct = new QAction(("&Full Screen"), this);
    fullScreenAct->setShortcut(Qt::Key_F11);
    menuAdministrator->addAction(fullScreenAct);
    QAction *restartAct = new QAction("Restart", this);
    restartAct->setShortcut(QKeySequence((tr("Shift+Ctrl+X"))));
    menuAdministrator->addAction(restartAct);
    QAction *quitAct = new QAction(("Quit Application"), this);
    quitAct->setShortcut(QKeySequence(tr("Ctrl+X")));
    menuAdministrator->addAction(quitAct);

    menuStock = new QMenu(menubar);
    menuStock->setTitle("Stock");
    menubar->addMenu(menuStock);

    QAction *manageStockAct = new QAction(("Manage Stock"), this);
    manageStockAct->setShortcut(QKeySequence(tr("Ctrl+M")));
    menuStock->addAction(manageStockAct);
    QAction *bulkStockUpdationAct = new QAction("Bulk Stock Updation", this);
    bulkStockUpdationAct->setShortcut(QKeySequence(tr("Ctrl+U")));
    menuStock->addAction(bulkStockUpdationAct);
    menuStock->addSeparator();
    QAction *stockPruchaseInvoiceAct = new QAction(("Stock Purchase Invoice"), this);
    menuStock->addAction(stockPruchaseInvoiceAct);
    QAction *oldStockPurchaseInvoiceAct = new QAction(("Old Stock Purchase Invoice"), this);
    menuStock->addAction(oldStockPurchaseInvoiceAct);
    menuStock->addSeparator();
    QAction *stockUpdationAct = new QAction(("Single Stock Updation"), this);
    menuStock->addAction(stockUpdationAct);
    menuStock->addSeparator();
    QAction *addNewStockAct = new QAction(("Add New Stock"), this);
    menuStock->addAction(addNewStockAct);
    QAction *deleteStockact = new QAction(("Remove Stock"), this);
    menuStock->addAction(deleteStockact);
    QAction *updateStockAct = new QAction(("Edit Stock Details"), this);
    menuStock->addAction(updateStockAct);
    menuStock->addSeparator();
    QAction *checkStockAct = new QAction("Check Stock", this);
    checkStockAct->setShortcut(QKeySequence("Ctrl+F"));
    menuStock->addAction(checkStockAct);

    menuInvoice = new QMenu(menubar);
    menuInvoice->setTitle("Invoice");
    menubar->addMenu(menuInvoice);

    QAction *invoiceAct = new QAction(("&New Invoice"), this);
    invoiceAct->setShortcut(QKeySequence(tr("Ctrl+N")));
    menuInvoice->addAction(invoiceAct);
    QAction *setInvoiceAct = new QAction(("Set Invoice No"), this);
    menuInvoice->addAction(setInvoiceAct);
    QAction *cancelInvoiceAct = new QAction(("Cancel Invoice"), this);
    menuInvoice->addAction(cancelInvoiceAct);
    QAction *oldInvoiceAct = new QAction(("Old Invoices"), this);
    menuInvoice->addAction(oldInvoiceAct);

    menuEstimate = new QMenu(menubar);
    menuEstimate->setTitle("Estimate");
    menubar->addMenu(menuEstimate);

    QAction *estimateAct = new QAction(("&New Estimate"), this);
    estimateAct->setShortcut(QKeySequence(tr("Ctrl+E")));
    menuEstimate->addAction(estimateAct);
    QAction *setEstimateAct = new QAction(("Set Estimate No"), this);
    menuEstimate->addAction(setEstimateAct);
    QAction *cancelEstimateAct = new QAction(("Cancel Estimate"), this);
    menuEstimate->addAction(cancelEstimateAct);
    QAction *oldEstimateAct = new QAction(("Old Estimates"), this);
    menuEstimate->addAction(oldEstimateAct);
    menuEstimate->addSeparator();
    QAction *itemEstimateAct = new QAction("Item Estimates", this);
    menuEstimate->addAction(itemEstimateAct);


    menuDealer = new QMenu(menubar);
    menuDealer->setTitle("Dealer");
//    menubar->addMenu(menuDealer);

    QAction *dealerHomeAct = new QAction(("&Dealer Home"), this);
    dealerHomeAct->setShortcut(QKeySequence(tr("Ctrl+D")));
    menuDealer->addAction(dealerHomeAct);
    QAction *salesDetailsAct = new QAction(("Sales De&tais"), this);
    salesDetailsAct->setShortcut(QKeySequence(tr("Ctrl+T")));
    menuDealer->addAction(salesDetailsAct);
    QAction *addNewDealerAct = new QAction(("Add New Dealer"), this);
    menuDealer->addAction(addNewDealerAct);
    QAction *deleteDealerAct = new QAction(("Delete Dealer"), this);
    menuDealer->addAction(deleteDealerAct);
    QAction *updateDealerAct = new QAction(("Edit Dealer Details"), this);
    menuDealer->addAction(updateDealerAct);

    menuAccounts = new QMenu(menubar);
    menuAccounts->setTitle("Accounts");
    menubar->addMenu(menuAccounts);

    QAction *accountsAct = new QAction(("Accounts"), this);
    accountsAct->setShortcut(QKeySequence(tr("Ctrl+A")));
    menuAccounts->addAction(accountsAct);

    menuReports = new QMenu(menubar);
    menuReports->setTitle("Reports");
    menubar->addMenu(menuReports);

    QAction *todaysItemSalesAct = new QAction(("Today's &Item Sales"), this);
    todaysItemSalesAct->setShortcut(QKeySequence(tr("Ctrl+I")));
    menuReports->addAction(todaysItemSalesAct);
    QAction *dailyReportAct = new QAction(("Daily Sales &Report"), this);
    dailyReportAct->setShortcut(QKeySequence(tr("Ctrl+R")));
    menuReports->addAction(dailyReportAct);
    QAction *itemSalesReportAct = new QAction("Selected Item Sales Report", this);
    menuReports->addAction(itemSalesReportAct);
    QAction *historyItemSalesAct = new QAction(("History Item Sales"), this);
    menuReports->addAction(historyItemSalesAct);
    menuReports->addSeparator();
    QAction *purchaseReportAct = new QAction("Purchase Report", this);
    menuReports->addAction(purchaseReportAct);
    QAction *purchaseItemsAct = new QAction("Purchased Item Report", this);
    menuReports->addAction(purchaseItemsAct);

    menuSettings = new QMenu(menubar);
    menuSettings->setTitle("Settings");
    menubar->addMenu(menuSettings);

    QAction *configurationAct = new QAction(("Configure Product"), this);
    menuSettings->addAction(configurationAct);
    QAction *deleteDataAct = new QAction("Clear Data", this);
    menuSettings->addAction(deleteDataAct);
    QAction *backupAct = new QAction(("Backup"), this);
    menuSettings->addAction(backupAct);

    menuHelp = new QMenu(menubar);
    menuHelp->setTitle("Help");
    menubar->addMenu(menuHelp);

    QAction *shortcutAct = new QAction(("Shorcuts Used"), this);
    menuHelp->addAction(shortcutAct);
    QAction *aboutAct = new QAction(("About"), this);
    menuHelp->addAction(aboutAct);

    adminHome = new AdminHomeWidget(widgetWidth, this);
    adminHome->setGeometry(sideWidth, 50, widgetWidth, widgetHeight - 50);
    manageStock = new ManageStockWidget(widgetWidth, this);
    manageStock->setGeometry(sideWidth, 50, widgetWidth, widgetHeight - 50);
    purchaseInvoice = new StockPurchaseInvoiceWidget(widgetWidth, this);
    purchaseInvoice->setGeometry(sideWidth, 50, widgetWidth, widgetHeight - 50);
    oldPurchaseInvoice = new OldPurchaseInvoiceWidget(widgetWidth, this);
    oldPurchaseInvoice->setGeometry(sideWidth, 50, widgetWidth, widgetHeight - 50);
    invoice = new InvoiceWidget(widgetWidth, this);
    invoice->setGeometry(sideWidth, 50, widgetWidth, widgetHeight - 50);
    dailyReport = new DailySalesReportWidget(widgetWidth, this);
    dailyReport->setGeometry(sideWidth, 50, widgetWidth, widgetHeight - 50);
    itemSales = new TodaysItemSalesWidget(widgetWidth, this);
    itemSales->setGeometry(sideWidth, 50, widgetWidth, widgetHeight - 50);
    oldInvoice = new OldInvoicesWidget(widgetWidth, this);
    oldInvoice->setGeometry(sideWidth, 50, widgetWidth, widgetHeight - 50);
    allInvoices = new AllInvoices(widgetWidth, this);
    allInvoices->setGeometry(sideWidth, 50, widgetWidth, widgetHeight - 50);
    oldEstimate = new OldEstimates(widgetWidth, this);
    oldEstimate->setGeometry(sideWidth, 50, widgetWidth, widgetHeight - 50);
    itemEstimate = new ItemEstimateWidget(widgetWidth, this);
    itemEstimate->setGeometry(sideWidth, 50, widgetWidth, widgetHeight - 50);
    estimate = new EstimateWidget(widgetWidth, this);
    estimate->setGeometry(sideWidth, 50, widgetWidth, widgetHeight - 50);
    salesDetails = new SalesDetailsWidget(widgetWidth, this);
    salesDetails->setGeometry(sideWidth, 50, widgetWidth, widgetHeight - 50);
    accounts = new AccountsWidget(widgetWidth, this);
    accounts->setGeometry(sideWidth, 50, widgetWidth, widgetHeight - 50);
    purchaseReport = new PurchaseReportWidget(widgetWidth, this);
    purchaseReport->setGeometry(sideWidth, 50, widgetWidth, widgetHeight - 50);
    purchasedItems = new PurchasedItemWidget(widgetWidth, this);
    purchasedItems->setGeometry(sideWidth, 50, widgetWidth, widgetHeight - 50);
    historyDsr = new HistoryDSRWidget(widgetWidth, this);
    historyDsr->setGeometry(sideWidth, 50, widgetWidth, widgetHeight - 50);
    historyItemSales = new HistoryItemSalesWidget(widgetWidth, this);
    historyItemSales->setGeometry(sideWidth, 50, widgetWidth, widgetHeight - 50);
    historyinvoice = new HistoryInvoiceWidget(widgetWidth, this);
    historyinvoice->setGeometry(sideWidth, 50, widgetWidth, widgetHeight - 50);

    /* Main Window setup */

    connect( homeAct, SIGNAL(triggered()), this, SLOT(getAdminHome()));
    connect( todaysItemSalesAct, SIGNAL(triggered()), this, SLOT(getItemSales()));
    connect( dailyReportAct, SIGNAL(triggered()), this, SLOT(getDailySalesReport()));
    connect( itemSalesReportAct, SIGNAL(triggered()), this, SLOT(getItemSalesReport()));
    connect( bulkStockUpdationAct, SIGNAL(triggered()), this, SLOT(getBulkStockUpdationDialog()));
    connect( stockUpdationAct, SIGNAL(triggered()), this, SLOT(getStockUpdationDialog()));
    connect( addNewStockAct, SIGNAL(triggered()), this, SLOT(getAddNewStockDialog()));
    connect( deleteStockact, SIGNAL(triggered()), this, SLOT(getDeleteStockDialog()));
    connect( updateStockAct, SIGNAL(triggered()), this, SLOT(getUpdateStockDialog()));
    connect( checkStockAct, SIGNAL(triggered()), this, SLOT(getCheckStockDialog()));
    connect( changePasswordAct, SIGNAL(triggered()), this, SLOT(getChangePasswordDialog()));
    connect( refreshAct, SIGNAL(triggered()), this, SLOT(refresh()));
    connect( fullScreenAct, SIGNAL(triggered()), this, SLOT(getFullScreen()));
    connect( restartAct, SIGNAL(triggered()), this, SLOT(restart()));
    connect( quitAct, SIGNAL(triggered()), qApp, SLOT(quit()));
    connect( manageStockAct, SIGNAL(triggered()), this, SLOT(getManageStockWidget()));
    connect( stockPruchaseInvoiceAct, SIGNAL(triggered()), this, SLOT(getStockPurchaseInvoice()));
    connect( oldStockPurchaseInvoiceAct, SIGNAL(triggered()), this, SLOT(getOldStockPurchaseInvoice()));
    connect( invoiceAct, SIGNAL(triggered()), this, SLOT(getInvoice()));
    connect( setInvoiceAct, SIGNAL(triggered()), this, SLOT(getSetInvoiceDialog()));
    connect( cancelInvoiceAct, SIGNAL(triggered()), this, SLOT(cancelInvoice()));
    connect( oldInvoiceAct, SIGNAL(triggered()), this, SLOT(getOldInvoice()));
    connect( estimateAct, SIGNAL(triggered()), this, SLOT(getEstimate()));
    connect( setEstimateAct, SIGNAL(triggered()), this, SLOT(getSetEstimateDialog()));
    connect( cancelEstimateAct, SIGNAL(triggered()), this, SLOT(cancelEstimate()));
    connect( oldEstimateAct, SIGNAL(triggered()), this, SLOT(getOldEstimates()));
    connect( itemEstimateAct, SIGNAL(triggered()), this, SLOT(getItemEstimate()));
    connect( salesDetailsAct, SIGNAL(triggered()), this, SLOT(getSalesDetails()));
    connect( accountsAct, SIGNAL(triggered()), this, SLOT(getAccountsWidget()));
    connect( purchaseReportAct, SIGNAL(triggered()), this, SLOT(getPurchaseReport()));
    connect( purchaseItemsAct, SIGNAL(triggered()), this, SLOT(getPurchasedItems()));
    connect( historyItemSalesAct, SIGNAL(triggered()), this, SLOT(getHistoryItemSales()));
    connect( configurationAct, SIGNAL(triggered()), this, SLOT(getConfiguration()));
    connect( deleteDataAct, SIGNAL(triggered()), this, SLOT(getDeleteDataAct()));
    connect( backupAct, SIGNAL(triggered()), this, SLOT(getBackup()));
    connect( shortcutAct, SIGNAL(triggered()), this, SLOT(shortcuts()));
    connect( aboutAct, SIGNAL(triggered()), this, SLOT(about()));
    connect( qApp, SIGNAL(lastWindowClosed()), qApp, SLOT(quit()));

    hideAllWidgets();
    showMinimized();
}
Example #4
0
/*======================================================================*
                            kernel_main
 *======================================================================*/
PUBLIC int kernel_main()
{
	disp_str("-----\"kernel_main\" begins-----\n");

	TASK*		p_task		= task_table;
	PROCESS*	p_proc		= proc_table;
	char*		p_task_stack	= task_stack + STACK_SIZE_TOTAL;
	u16		selector_ldt	= SELECTOR_LDT_FIRST;
	int i;
        u8              privilege;
        u8              rpl;
        int             eflags;
	for (i = 0; i < NR_TASKS+NR_PROCS; i++) {
                if (i < NR_TASKS) {     /* 任务 */
                        p_task    = task_table + i;
                        privilege = PRIVILEGE_TASK;
                        rpl       = RPL_TASK;
                        eflags    = 0x1202; /* IF=1, IOPL=1, bit 2 is always 1 */
                }
                else {                  /* 用户进程 */
                        p_task    = user_proc_table + (i - NR_TASKS);
                        privilege = PRIVILEGE_USER;
                        rpl       = RPL_USER;
                        eflags    = 0x202; /* IF=1, bit 2 is always 1 */
                }

		strcpy(p_proc->p_name, p_task->name);	// name of the process
		p_proc->pid = i;			// pid

		p_proc->ldt_sel = selector_ldt;

		memcpy(&p_proc->ldts[0], &gdt[SELECTOR_KERNEL_CS >> 3],
		       sizeof(DESCRIPTOR));
		p_proc->ldts[0].attr1 = DA_C | privilege << 5;
		memcpy(&p_proc->ldts[1], &gdt[SELECTOR_KERNEL_DS >> 3],
		       sizeof(DESCRIPTOR));
		p_proc->ldts[1].attr1 = DA_DRW | privilege << 5;
		p_proc->regs.cs	= (0 & SA_RPL_MASK & SA_TI_MASK) | SA_TIL | rpl;
		p_proc->regs.ds	= (8 & SA_RPL_MASK & SA_TI_MASK) | SA_TIL | rpl;
		p_proc->regs.es	= (8 & SA_RPL_MASK & SA_TI_MASK) | SA_TIL | rpl;
		p_proc->regs.fs	= (8 & SA_RPL_MASK & SA_TI_MASK) | SA_TIL | rpl;
		p_proc->regs.ss	= (8 & SA_RPL_MASK & SA_TI_MASK) | SA_TIL | rpl;
		p_proc->regs.gs	= (SELECTOR_KERNEL_GS & SA_RPL_MASK) | rpl;

		p_proc->regs.eip = (u32)p_task->initial_eip;
		p_proc->regs.esp = (u32)p_task_stack;
		p_proc->regs.eflags = eflags;

		p_task_stack -= p_task->stacksize;
		p_proc++;
		p_task++;
		selector_ldt += 1 << 3;
	}

	proc_table[0].ticks = proc_table[0].priority = 15;
	proc_table[1].ticks = proc_table[1].priority =  5;
	proc_table[2].ticks = proc_table[2].priority =  3;

	k_reenter = 0;
	ticks = 0;

	p_proc_ready	= proc_table;

	init_clock();
        init_keyboard();

	restart();

	while(1){}
}
Example #5
0
/**
 * \brief Changes the direction of this movement.
 *
 * The movement is restarted.
 *
 * \param direction8 the new direction (0 to 7)
 */
void JumpMovement::set_direction8(int direction8) {

  this->direction8 = direction8;
  restart();
}
Example #6
0
 Timer()
 {
     restart();
 }
Example #7
0
HighResolutionTimer::HighResolutionTimer() {
  restart();
}
Example #8
0
HumanConsole::HumanConsole(GameCenter* gameCenter) {
    this->gameCenter = gameCenter;
    restart();
}
Example #9
0
MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    // Register QtKeypadBridge for the virtual keyboard functionality
    ui->keypadWidget->installEventFilter(&qt_keypad_bridge);
    ui->lcdView->installEventFilter(&qt_keypad_bridge);

    //Emu -> GUI (QueuedConnection as they're different threads)
    connect(&emu, SIGNAL(serialChar(char)), this, SLOT(serialChar(char)), Qt::QueuedConnection);
    connect(&emu, SIGNAL(debugStr(QString)), this, SLOT(debugStr(QString))); //Not queued connection as it may cause a hang
    connect(&emu, SIGNAL(speedChanged(double)), this, SLOT(showSpeed(double)), Qt::QueuedConnection);
    connect(&emu, SIGNAL(statusMsg(QString)), ui->statusbar, SLOT(showMessage(QString)), Qt::QueuedConnection);
    connect(&emu, SIGNAL(turboModeChanged(bool)), ui->buttonSpeed, SLOT(setChecked(bool)), Qt::QueuedConnection);
    connect(&emu, SIGNAL(usblinkChanged(bool)), this, SLOT(usblinkChanged(bool)), Qt::QueuedConnection);

    //Menu "Emulator"
    connect(ui->buttonReset, SIGNAL(clicked(bool)), &emu, SLOT(reset()));
    connect(ui->actionReset, SIGNAL(triggered()), &emu, SLOT(reset()));
    connect(ui->actionRestart, SIGNAL(triggered()), this, SLOT(restart()));
    connect(ui->actionDebugger, SIGNAL(triggered()), &emu, SLOT(enterDebugger()));
    connect(ui->buttonPause, SIGNAL(clicked(bool)), &emu, SLOT(setPaused(bool)));
    connect(ui->buttonPause, SIGNAL(clicked(bool)), ui->actionPause, SLOT(setChecked(bool)));
    connect(ui->actionPause, SIGNAL(toggled(bool)), &emu, SLOT(setPaused(bool)));
    connect(ui->actionPause, SIGNAL(toggled(bool)), ui->buttonPause, SLOT(setChecked(bool)));
    connect(ui->buttonSpeed, SIGNAL(clicked(bool)), &emu, SLOT(setTurboMode(bool)));
    QShortcut *shortcut = new QShortcut(QKeySequence(Qt::Key_F11), this);
    shortcut->setAutoRepeat(false);
    connect(shortcut, SIGNAL(activated()), &emu, SLOT(toggleTurbo()));

    //Menu "Tools"
    connect(ui->buttonScreenshot, SIGNAL(clicked()), this, SLOT(screenshot()));
    connect(ui->actionScreenshot, SIGNAL(triggered()), this, SLOT(screenshot()));
    connect(ui->actionConnect, SIGNAL(triggered()), this, SLOT(connectUSB()));
    connect(ui->buttonUSB, SIGNAL(clicked(bool)), this, SLOT(connectUSB()));
    connect(ui->actionXModem, SIGNAL(triggered()), this, SLOT(xmodemSend()));
    ui->actionConnect->setShortcut(QKeySequence(Qt::Key_F10));
    ui->actionConnect->setAutoRepeat(false);

    //Menu "Flash"
    connect(ui->actionSave, SIGNAL(triggered()), this, SLOT(saveFlash()));
    connect(ui->actionCreate_flash, SIGNAL(triggered()), this, SLOT(createFlash()));

    //Debugging
    connect(ui->lineEdit, SIGNAL(returnPressed()), this, SLOT(debugCommand()));

    //File transfer
    connect(ui->refreshButton, SIGNAL(clicked(bool)), this, SLOT(reload_filebrowser()));
    connect(this, SIGNAL(usblink_progress_changed(int)), this, SLOT(changeProgress(int)), Qt::QueuedConnection);

    //Settings
    connect(ui->checkDebugger, SIGNAL(toggled(bool)), this, SLOT(setDebuggerOnStartup(bool)));
    connect(ui->checkWarning, SIGNAL(toggled(bool)), this, SLOT(setDebuggerOnWarning(bool)));
    connect(ui->uiDocks, SIGNAL(toggled(bool)), this, SLOT(setUIMode(bool)));
    connect(ui->checkAutostart, SIGNAL(toggled(bool)), this, SLOT(setAutostart(bool)));
    connect(ui->fileBoot1, SIGNAL(pressed()), this, SLOT(selectBoot1()));
    connect(ui->fileFlash, SIGNAL(pressed()), this, SLOT(selectFlash()));
    connect(ui->pathTransfer, SIGNAL(textEdited(QString)), this, SLOT(setUSBPath(QString)));
    connect(ui->spinGDB, SIGNAL(valueChanged(int)), this, SLOT(setGDBPort(int)));
    connect(ui->spinRDBG, SIGNAL(valueChanged(int)), this, SLOT(setRDBGPort(int)));
    connect(ui->orderDiags, SIGNAL(toggled(bool)), this, SLOT(setBootOrder(bool)));

    //Set up monospace fonts
    QFont monospace = QFontDatabase::systemFont(QFontDatabase::FixedFont);
    ui->debugConsole->setFont(monospace);
    ui->serialConsole->setFont(monospace);

    qRegisterMetaType<QVector<int>>();

#ifdef Q_OS_ANDROID
    //On android the settings file is deleted everytime you update or uninstall,
    //so choose a better, safer, location
    QString path = QStandardPaths::writableLocation(QStandardPaths::GenericDataLocation);
    settings = new QSettings(path + "/nspire_emu.ini", QSettings::IniFormat);
#else
    settings = new QSettings();
#endif

    //Load settings
    setUIMode(settings->value("docksEnabled", true).toBool());
    restoreGeometry(settings->value("windowGeometry").toByteArray());
    restoreState(settings->value("windowState").toByteArray(), WindowStateVersion);
    selectBoot1(settings->value("boot1", "").toString());
    selectFlash(settings->value("flash", "").toString());
    setDebuggerOnStartup(settings->value("debugOnStart", false).toBool());
    setDebuggerOnWarning(settings->value("debugOnWarn", false).toBool());
    setUSBPath(settings->value("usbdir", QString("ndless")).toString());
    setGDBPort(settings->value("gdbPort", 3333).toUInt());
    setRDBGPort(settings->value("rdbgPort", 3334).toUInt());
    setBootOrder(false);

    bool autostart = settings->value("emuAutostart", false).toBool();
    setAutostart(autostart);
    if(emu.boot1 != "" && emu.flash != "" && autostart)
        emu.start();
    else
        ui->statusbar->showMessage(trUtf8("Start the emulation via Emulation->Restart."));

    #ifdef Q_OS_MAC
        QTimer::singleShot(50, [&] {dockVisibilityChanged(false);}); // Trigger dock update (after UI was shown)
    #endif
}
Example #10
0
void Game::init() {
  restart(1);
}
Example #11
0
void	ft_ctrl_z(t_env *env)
{
	restart();
}
Example #12
0
	void CTokenizer::reset()
	{
        restart();
	}
Example #13
0
void EnsureSoapOp::start()
{
    restart();
}
Example #14
0
void CheckInternetOp::onTimeout()
{
    m_timer1.stop();
    LOG_DEBUG(QString::fromUtf8("retry %1/%2").arg(m_retryCount).arg(m_maxRetryCount));
    restart();
}
Example #15
0
    // The `run` method will start the game loop.
    void run()
    {
        while(true)
        {
            window.clear(sf::Color::Black);

            if(sf::Keyboard::isKeyPressed(sf::Keyboard::Key::Escape)) break;

            // The `P` key will toggle the pause. To prevent continuous
            // use of the pause button, we need to check if the input
            // was pressed last frame.
            if(sf::Keyboard::isKeyPressed(sf::Keyboard::Key::P))
            {
                // If `P` was not pressed last frame, we can toggle
                // the state.
                if(!pausePressedLastFrame)
                {
                    if(state == State::Paused)
                        state = State::InProgress;
                    else if(state == State::InProgress)
                        state = State::Paused;
                }

                pausePressedLastFrame = true;
            }
            else
                pausePressedLastFrame = false;

            // Let's also use the `R` key to restart the game.
            if(sf::Keyboard::isKeyPressed(sf::Keyboard::Key::R)) restart();

            // If the game is paused, we'll only draw game elements,
            // without updating them.
            if(state != State::Paused)
            {
                // The rest of the game loop code is exactly the same.

                ball.update();
                paddle.update();
                for(auto& brick : bricks)
                {
                    brick.update();
                    solveBrickBallCollision(brick, ball);
                }

                bricks.erase(
                    std::remove_if(std::begin(bricks), std::end(bricks),
                        [](const auto& mBrick)
                        {
                            return mBrick.destroyed;
                        }),
                    std::end(bricks));

                solvePaddleBallCollision(paddle, ball);
            }

            ball.draw(window);
            paddle.draw(window);
            for(auto& brick : bricks) brick.draw(window);

            window.display();
        }
    }
Example #16
0
QLuaApplication::Private::Thread::Thread(QLuaApplication::Private *d) 
  : QThread(d->theApp), d(d), engine(0), loop(0)
{
  connect(this,SIGNAL(restart()),d,SLOT(start()),Qt::QueuedConnection);
}
Example #17
0
void
start_tcl(void)
{
    char *id = "start_tcl";
    char buf[BUFSIZ];
    int fd;
    int tot, len;

    interp = Tcl_CreateInterp();

    if (Tcl_Init(interp) == TCL_ERROR)
    {
        sprintf(log_buffer, "Tcl_Init error: %s",
                Tcl_GetStringResult(interp));
        log_err(-1, id, log_buffer);
        die(0);
    }

#if TCLX
#if TCL_MINOR_VERSION < 5  && TCL_MAJOR_VERSION < 8
    if (TclX_Init(interp) == TCL_ERROR)
    {
#else

    if (Tclx_Init(interp) == TCL_ERROR)
    {
#endif
        sprintf(log_buffer, "Tclx_Init error: %s",
                Tcl_GetStringResult(interp));
        log_err(-1, id, log_buffer);
        die(0);
    }

#endif
    add_cmds(interp);

    if (initfil)
    {
        int  code;

        code = Tcl_EvalFile(interp, initfil);

        if (code != TCL_OK)
        {
            char *trace;

            trace = (char *)Tcl_GetVar(interp, "errorInfo", 0);

            if (trace == NULL)
                trace = (char *)Tcl_GetStringResult(interp);

            fprintf(stderr, "%s: TCL error @ line %d: %s\n",
                    initfil, interp->errorLine, trace);

            sprintf(log_buffer, "%s: TCL error @ line %d: %s",
                    initfil, interp->errorLine,
                    Tcl_GetStringResult(interp));

            log_err(-1, id, log_buffer);

            die(0);
        }

        sprintf(log_buffer, "init file %s", initfil);

        log_record(PBSEVENT_SYSTEM, PBS_EVENTCLASS_SERVER,
                   id, log_buffer);
    }

    if ((fd = open(bodyfil, O_RDONLY)) == -1)
    {
        log_err(errno, id, bodyfil);
        die(0);
    }

    sprintf(log_buffer, "body file: %s", bodyfil);

    log_record(PBSEVENT_SYSTEM, PBS_EVENTCLASS_SERVER, id, log_buffer);

    if (body)
        free(body);

    if ((body = malloc(BUFSIZ)) == NULL)
    {
        log_err(errno, id, "malloc");
        die(0);
    }

    for (tot = 0; (len = read(fd, buf, sizeof(buf))) > 0; tot += len)
    {
        if ((body = realloc(body, tot + len + 1)) == NULL)
        {
            log_err(errno, id, "realloc");
            die(0);
        }

        memcpy(&body[tot], buf, len);
    }

    if (len == -1)
    {
        log_err(errno, id, bodyfil);
        die(0);
    }

    body[tot] = '\0';

    close(fd);

#if TCL_MAJOR_VERSION >= 8

    if (body_obj == NULL)
    {
        body_obj = Tcl_NewStringObj(body, tot);
        Tcl_IncrRefCount(body_obj);
    }
    else
    {
        Tcl_SetStringObj(body_obj, body, tot);
    }

#endif
}

int

addclient(name)
char *name;
{
    static char id[] = "addclient";

    struct hostent  *host, *gethostbyname();

    struct  in_addr saddr;

    if ((host = gethostbyname(name)) == NULL)
    {
        sprintf(log_buffer, "host %s not found", name);
        log_err(-1, id, log_buffer);
        return -1;
    }

    if (numclients >= START_CLIENTS)
    {
        pbs_net_t *newclients;

        newclients = realloc(okclients,
                             sizeof(pbs_net_t) * (numclients + 1));

        if (newclients == NULL)
            return -1;

        okclients = newclients;
    }

    memcpy((char *)&saddr, host->h_addr, host->h_length);

    okclients[numclients++] = saddr.s_addr;
    return 0;
}

/*
 * read_config - read and process the configuration file (see -c option)
 *
 * Currently, the only statement is $clienthost to specify which systems
 * can contact the scheduler.
 */
#define CONF_LINE_LEN 120

static
int
read_config(file)
char *file;
{
    static char *id = "read_config";
    FILE *conf;
    int i;
    char line[CONF_LINE_LEN];
    char *token;

    struct specialconfig
    {
        char *name;
        int (*handler)();
    } special[] =

    {
        {"clienthost", addclient },
        { NULL,  NULL }
    };


#if !defined(DEBUG) && !defined(NO_SECURITY_CHECK)

    if (chk_file_sec(file, 0, 0, S_IWGRP | S_IWOTH, 1, 0))
        return (-1);

#endif

    if ((conf = fopen(file, "r")) == NULL)
    {
        log_err(errno, id, "cannot open config file");
        return (-1);
    }

    while (fgets(line, CONF_LINE_LEN, conf))
    {

        if ((line[0] == '#') || (line[0] == '\n'))
            continue;  /* ignore comment & null line */
        else if (line[0] == '$')   /* special */
        {

            if ((token = strtok(line, " \t")) == NULL)
                token = "";

            for (i = 0; special[i].name; i++)
            {
                if (strcmp(token + 1, special[i].name) == 0)
                    break;
            }

            if (special[i].name == NULL)
            {
                sprintf(log_buffer, "config name %s not known",
                        token);
                log_record(PBSEVENT_ERROR,
                           PBS_EVENTCLASS_SERVER,
                           msg_daemonname, log_buffer);
                return (-1);
            }

            token = strtok(NULL, " \t");

            if (*(token + strlen(token) - 1) == '\n')
                *(token + strlen(token) - 1) = '\0';

            if (special[i].handler(token))
            {
                fclose(conf);
                return (-1);
            }

        }
        else
        {
            log_record(PBSEVENT_ERROR, PBS_EVENTCLASS_SERVER,
                       msg_daemonname,
                       "invalid line in config file");
            fclose(conf);
            return (-1);
        }
    }

    fclose(conf);

    return (0);
}

void
restart(sig)
int sig;
{
    char    *id = "restart";

    if (sig)
    {
        sprintf(log_buffer, "restart on signal %d", sig);
        log_close(1);
        log_open(logfile, path_log);
    }
    else
    {
        sprintf(log_buffer, "restart command");
    }

    log_record(PBSEVENT_SYSTEM, PBS_EVENTCLASS_SERVER, id, log_buffer);

    Tcl_DeleteInterp(interp);

    if (configfile)
    {
        if (read_config(configfile) != 0)
            die(0);
    }

    start_tcl();
}

void
badconn(msg)
char *msg;
{
    static char id[] = "badconn";

    struct in_addr addr;
    char  buf[5*sizeof(addr) + 100];

    struct hostent *phe;

    addr = saddr.sin_addr;
    phe = gethostbyaddr((void *) & addr, sizeof(addr), AF_INET);

    if (phe == NULL)
    {
        char hold[6];
        int i;
        union
        {

            struct in_addr aa;
            u_char  bb[sizeof(addr)];
        } uu;

        uu.aa = addr;
        sprintf(buf, "%u", uu.bb[0]);

        for (i = 1; i < (int)sizeof(addr); i++)
        {
            sprintf(hold, ".%u", uu.bb[i]);
            strcat(buf, hold);
        }
    }
    else
    {
        strncpy(buf, phe->h_name, sizeof(buf));
        buf[sizeof(buf)-1] = '\0';
    }

    sprintf(log_buffer, "%s on port %u %s", buf, ntohs(saddr.sin_port), msg);

    log_err(-1, id, log_buffer);
    return;
}

unsigned int
server_command()
{
    static char id[] = "server_command";
    int  new_socket;
    int  i;
    torque_socklen_t slen;
    unsigned int  cmd;
    pbs_net_t addr;

    slen = sizeof(saddr);
    new_socket = accept(server_sock,
                        (struct sockaddr *) & saddr, &slen);

    if (new_socket == -1)
    {
        log_err(errno, id, "accept");
        return SCH_ERROR;
    }

    if (ntohs(saddr.sin_port) >= IPPORT_RESERVED)
    {
        badconn("non-reserved port");
        close(new_socket);
        return SCH_ERROR;
    }

    addr = (pbs_net_t)saddr.sin_addr.s_addr;

    for (i = 0; i < numclients; i++)
    {
        if (addr == okclients[i])
            break;
    }

    if (i == numclients)
    {
        badconn("unauthorized host");
        close(new_socket);
        return SCH_ERROR;
    }

    if ((connector = socket_to_conn(new_socket)) < 0)
    {
        log_err(errno, id, "socket_to_conn");
        return SCH_ERROR;
    }

    if (get_4byte(new_socket, &cmd) != 1)
    {
        log_err(errno, id, "get4bytes");
        return SCH_ERROR;
    }

    return cmd;
}


/*
 * lock_out - lock out other daemons from this directory.
 */

static void lock_out(fds, op)
int fds;
int op;  /* F_WRLCK  or  F_UNLCK */
{

    struct flock flock;

    flock.l_type   = op;
    flock.l_whence = SEEK_SET;
    flock.l_start  = 0;
    flock.l_len    = 0; /* whole file */

    if (fcntl(fds, F_SETLK, &flock) < 0)
    {
        (void)strcpy(log_buffer, "pbs_sched: another scheduler running\n");
        log_err(errno, msg_daemonname, log_buffer);
        fprintf(stderr, log_buffer);
        exit(1);
    }
}

int main(argc, argv)
int  argc;
char *argv[];
{
    char  *id = "main";
    int  code;

    struct hostent *hp;
    int  go, c, errflg = 0;
    int  lockfds;
    int  t = 1;
    char  *ptr;
    pid_t  pid;
    char  *cp, host[100];
    char  *homedir = PBS_SERVER_HOME;
    unsigned int port;
    char  path_priv[_POSIX_PATH_MAX];
    char  *dbfile = "sched_out";
    int  alarm_time = 180;

    struct sigaction act;
    caddr_t  curr_brk = 0, next_brk;
    extern char *optarg;
    extern int optind, opterr;
    fd_set  fdset;

#ifndef DEBUG
    if (IamRoot() == 0)
    {
        return (1);
    }
#endif /* DEBUG */

    glob_argv = argv;

    if ((cp = strrchr(argv[0], '/')) == NULL)
        cp = argv[0];
    else
        cp++;

    msg_daemonname = strdup(cp);

    port = get_svrport(PBS_SCHEDULER_SERVICE_NAME, "tcp",
                       PBS_SCHEDULER_SERVICE_PORT);

    while ((c = getopt(argc, argv, "L:S:d:i:b:t:p:a:vc:")) != EOF)
    {
        switch (c)
        {

        case 'L':
            logfile = optarg;
            break;

        case 'S':
            port = (unsigned int)atoi(optarg);

            if (port == 0)
            {
                fprintf(stderr,
                        "%s: illegal port\n", optarg);
                errflg = 1;
            }

            break;

        case 'd':
            homedir = optarg;
            break;

        case 'i':  /* initialize */
            initfil = optarg;
            break;

        case 'b':
            bodyfil = optarg;
            break;

        case 't':
            termfil = optarg;
            break;

        case 'p':
            dbfile = optarg;
            break;

        case 'a':
            alarm_time = strtol(optarg, &ptr, 10);

            if (alarm_time <= 0 || *ptr != '\0')
            {
                fprintf(stderr,
                        "%s: bad alarm time\n", optarg);
                errflg = 1;
            }

            break;

        case 'c':
            configfile = optarg;
            break;

        case 'v':
            verbose = 1;
            break;

        case '?':
            errflg = 1;
            break;
        }
    }

    if (errflg || optind != argc)
    {
        static char *options[] =
        {
            "[-L logfile]",
            "[-S port]",
            "[-d home]",
            "[-i init]",
            "[-b body]",
            "[-t term]",
            "[-p output]",
            "[-a alarm]",
            "[-c configfile]",
            "[-v]",
            NULL
        };
        int i;

        fprintf(stderr, "usage: %s\n", argv[0]);

        for (i = 0; options[i]; i++)
            fprintf(stderr, "\t%s\n", options[i]);

        exit(1);
    }

    /* Save the original working directory for "restart" */
    if ((oldpath = getcwd((char *)NULL, MAXPATHLEN)) == NULL)
    {
        fprintf(stderr, "cannot get current working directory\n");
        exit(1);
    }

    (void)sprintf(path_priv, "%s/sched_priv", homedir);
#if !defined(DEBUG) && !defined(NO_SECURITY_CHECK)
    c  = chk_file_sec(path_priv, 1, 0, S_IWGRP | S_IWOTH, 1, 0);
    c |= chk_file_sec(PBS_ENVIRON, 0, 0, S_IWGRP | S_IWOTH, 0, 0);

    if (c != 0) exit(1);

#endif  /* not DEBUG and not NO_SECURITY_CHECK */
    if (chdir(path_priv) == -1)
    {
        perror(path_priv);
        exit(1);
    }

    (void)sprintf(path_log, "%s/sched_logs", homedir);
    (void)strcpy(pbs_current_user, "Scheduler");

    /* The following is code to reduce security risks                */
    /* start out with standard umask, system resource limit infinite */

    umask(022);

    if (setup_env(PBS_ENVIRON) == -1)
        exit(1);

    c = getgid();

    (void)setgroups(1, (gid_t *)&c); /* secure suppl. group ids */

    c = sysconf(_SC_OPEN_MAX);

    while (--c > 2)
        (void)close(c); /* close any file desc left open by parent */

#ifndef DEBUG
#ifdef _CRAY
    (void)limit(C_JOB,      0, L_CPROC, 0);

    (void)limit(C_JOB,      0, L_CPU,   0);

    (void)limit(C_JOBPROCS, 0, L_CPU,   0);

    (void)limit(C_PROC,     0, L_FD,  255);

    (void)limit(C_JOB,      0, L_FSBLK, 0);

    (void)limit(C_JOBPROCS, 0, L_FSBLK, 0);

    (void)limit(C_JOB,      0, L_MEM  , 0);

    (void)limit(C_JOBPROCS, 0, L_MEM  , 0);

#else /* not  _CRAY */
    {

        struct rlimit rlimit;

        rlimit.rlim_cur = RLIM_INFINITY;
        rlimit.rlim_max = RLIM_INFINITY;
        (void)setrlimit(RLIMIT_CPU,   &rlimit);
        (void)setrlimit(RLIMIT_FSIZE, &rlimit);
        (void)setrlimit(RLIMIT_DATA,  &rlimit);
        (void)setrlimit(RLIMIT_STACK, &rlimit);
#ifdef  RLIMIT_RSS
        (void)setrlimit(RLIMIT_RSS  , &rlimit);
#endif  /* RLIMIT_RSS */
#ifdef  RLIMIT_VMEM
        (void)setrlimit(RLIMIT_VMEM  , &rlimit);
#endif  /* RLIMIT_VMEM */
    }
#endif /* not _CRAY */

#if !defined(NO_SECURITY_CHECK)
    c = 0;

    if (initfil)
    {
        if (*initfil != '/')
        {
            (void)sprintf(log_buffer, "%s/%s", path_priv, initfil);
            c |= chk_file_sec(log_buffer, 0, 0, S_IWGRP | S_IWOTH, 1, 0);
        }
        else
        {
            c |= chk_file_sec(initfil, 0, 0, S_IWGRP | S_IWOTH, 1, 0);
        }
    }

    if (bodyfil)
    {
        if (*bodyfil != '/')
        {
            (void)sprintf(log_buffer, "%s/%s", path_priv, bodyfil);
            c |= chk_file_sec(log_buffer, 0, 0, S_IWGRP | S_IWOTH, 1, 0);
        }
        else
        {
            c |= chk_file_sec(bodyfil, 0, 0, S_IWGRP | S_IWOTH, 1, 0);
        }
    }

    if (termfil)
    {
        if (*termfil != '/')
        {
            (void)sprintf(log_buffer, "%s/%s", path_priv, termfil);
            c |= chk_file_sec(log_buffer, 0, 0, S_IWGRP | S_IWOTH, 1, 0);
        }
        else
        {
            c |= chk_file_sec(termfil, 0, 0, S_IWGRP | S_IWOTH, 1, 0);
        }
    }

    if (c) exit(1);

#endif /* not NO_SECURITY_CHECK */
#endif /* not DEBUG */

    if (log_open(logfile, path_log) == -1)
    {
        fprintf(stderr, "%s: logfile could not be opened\n", argv[0]);
        exit(1);
    }

    if (gethostname(host, sizeof(host)) == -1)
    {
        char *prob = "gethostname";

        log_err(errno, id, prob);
        perror(prob);
        die(0);
    }

    if ((hp = gethostbyname(host)) == NULL)
    {
        char *prob = "gethostbyname";

        log_err(errno, id, prob);
        perror(prob);
        die(0);
    }

    if ((server_sock = socket(AF_INET, SOCK_STREAM, 0)) < 0)
    {
        char *prob = "socket";

        log_err(errno, id, prob);
        perror(prob);
        die(0);
    }

    if (setsockopt(server_sock, SOL_SOCKET, SO_REUSEADDR,
                   (char *)&t, sizeof(t)) == -1)
    {
        char *prob = "setsockopt";

        log_err(errno, id, prob);
        perror(prob);
        die(0);
    }

    saddr.sin_family = AF_INET;

    saddr.sin_port = htons((unsigned short)port);
    memcpy(&saddr.sin_addr, hp->h_addr, hp->h_length);

    if (bind(server_sock, (struct sockaddr *)&saddr, sizeof(saddr)) < 0)
    {
        char *prob = "bind";

        log_err(errno, id, prob);
        perror(prob);
        die(0);
    }

    if (listen(server_sock, 5) < 0)
    {
        char *prob = "listen";

        log_err(errno, id, prob);
        perror(prob);
        die(0);
    }

    okclients = (pbs_net_t *)calloc(START_CLIENTS, sizeof(pbs_net_t));

    addclient("localhost");   /* who has permission to call MOM */
    addclient(host);

    if (configfile)
    {
        if (read_config(configfile) != 0)
            die(0);
    }

    lockfds = open("sched.lock", O_CREAT | O_TRUNC | O_WRONLY, 0644);

    if (lockfds < 0)
    {
        char *prob = "lock file";

        log_err(errno, id, prob);
        perror(prob);
        die(0);
    }

    lock_out(lockfds, F_WRLCK);

#ifndef DEBUG
    lock_out(lockfds, F_UNLCK);

    if ((pid = fork()) == -1)       /* error on fork */
    {
        char *prob = "fork";

        log_err(errno, id, prob);
        perror(prob);
        die(0);
    }
    else if (pid > 0)               /* parent exits */
        exit(0);

    if ((pid = setsid()) == -1)
    {
        log_err(errno, id, "setsid");
        die(0);
    }

    lock_out(lockfds, F_WRLCK);

    freopen(dbfile, "a", stdout);
    setvbuf(stdout, NULL, _IOLBF, 0);
    dup2(fileno(stdout), fileno(stderr));
#else
    pid = getpid();
    setvbuf(stdout, NULL, _IOLBF, 0);
    setvbuf(stderr, NULL, _IOLBF, 0);
#endif
    freopen("/dev/null", "r", stdin);

    /* write schedulers pid into lockfile */
    (void)sprintf(log_buffer, "%d\n", pid);
    (void)write(lockfds, log_buffer, strlen(log_buffer) + 1);

#if (PLOCK_DAEMONS & 2)
    (void)plock(PROCLOCK); /* lock daemon into memory */
#endif

    sprintf(log_buffer, "%s startup pid %d", argv[0], pid);
    log_record(PBSEVENT_SYSTEM, PBS_EVENTCLASS_SERVER, id, log_buffer);

    sprintf(log_buffer, "%s using TCL %s (%s)", argv[0],
            TCL_VERSION, TCL_PATCH_LEVEL);
    fprintf(stderr, "%s\n", log_buffer);
    log_record(PBSEVENT_SYSTEM, PBS_EVENTCLASS_SERVER, id, log_buffer);

    fullresp(0);
    sigemptyset(&allsigs);
    act.sa_flags = 0;
    sigaddset(&allsigs, SIGHUP);    /* remember to block these */
    sigaddset(&allsigs, SIGINT);    /* during critical sections */
    sigaddset(&allsigs, SIGTERM);   /* so we don't get confused */
    act.sa_mask = allsigs;

    act.sa_handler = restart;       /* do a restart on SIGHUP */
    sigaction(SIGHUP, &act, NULL);

    act.sa_handler = toolong; /* handle an alarm call */
    sigaction(SIGALRM, &act, NULL);

    act.sa_handler = die;           /* bite the biscuit for all following */
    sigaction(SIGINT, &act, NULL);
    sigaction(SIGTERM, &act, NULL);

    start_tcl();

    FD_ZERO(&fdset);

    for (go = 1; go;)
    {
        unsigned int cmd;


        FD_SET(server_sock, &fdset);

        if (select(FD_SETSIZE, &fdset, NULL, NULL, NULL) == -1)
        {
            if (errno != EINTR)
                log_err(errno, id, "select");

            continue;
        }

        if (!FD_ISSET(server_sock, &fdset))
            continue;

        cmd = server_command();

        if (cmd == (unsigned)SCH_ERROR || cmd == (unsigned)SCH_SCHEDULE_NULL)
            continue;

        if (sigprocmask(SIG_BLOCK, &allsigs, &oldsigs) == -1)
            log_err(errno, id, "sigprocmaskSIG_BLOCK)");

        if (verbose)
        {
            sprintf(log_buffer, "command %d", cmd);
            log_record(PBSEVENT_SYSTEM, PBS_EVENTCLASS_SERVER,
                       id, log_buffer);
        }

        switch (cmd)
        {

        case SCH_SCHEDULE_NEW:

        case SCH_SCHEDULE_TERM:

        case SCH_SCHEDULE_TIME:

        case SCH_SCHEDULE_RECYC:

        case SCH_SCHEDULE_CMD:

        case SCH_SCHEDULE_FIRST:
            alarm(alarm_time);

#if TCL_MAJOR_VERSION >= 8
            /* execute compiled body code for TCL-8 */
            code = Tcl_EvalObj(interp, body_obj);
#else
            code = Tcl_Eval(interp, body);
#endif
            alarm(0);

            switch (code)
            {

            case TCL_OK:

            case TCL_RETURN:
                break;

            default:
            {

                char *trace;
                char  codename[20];

                switch (code)
                {

                case TCL_BREAK:
                    strcpy(codename, "break");
                    break;

                case TCL_CONTINUE:
                    strcpy(codename, "continue");
                    break;

                default:
                    strcpy(codename, "<unknown>");
                    break;
                }

                trace = (char *)Tcl_GetVar(interp, "errorInfo", 0);

                if (trace == NULL)
                    trace = (char *)Tcl_GetStringResult(interp);

                fprintf(stderr, "%s: TCL interpreter return code %d (%s) @ line %d: %s\n",
                        bodyfil, code, codename,
                        interp->errorLine, trace);

                sprintf(log_buffer,
                        "%s: TCL error @ line %d: %s",
                        bodyfil, interp->errorLine,
                        Tcl_GetStringResult(interp));

                log_err(-1, id, log_buffer);

                die(0);
            }
            }

            break;

        case SCH_CONFIGURE:

        case SCH_RULESET:
            restart(0);
            break;

        case SCH_QUIT:
            go = 0;
            break;

        default:
            log_err(-1, id, "unknown command");
            break;
        }

        if (connector >= 0 && server_disconnect(connector))
        {
            log_err(errno, id, "server_disconnect");
            die(0);
        }

        connector = -1;

        if (verbose)
        {
            next_brk = (caddr_t)sbrk(0);

            if (next_brk > curr_brk)
            {
                sprintf(log_buffer, "brk point %p", next_brk);
                log_record(PBSEVENT_SYSTEM,
                           PBS_EVENTCLASS_SERVER,
                           id, log_buffer);
                curr_brk = next_brk;
            }
        }

        if (sigprocmask(SIG_SETMASK, &oldsigs, NULL) == -1)
            log_err(errno, id, "sigprocmask(SIG_SETMASK)");
    }

    if (termfil)
    {
        code = Tcl_EvalFile(interp, termfil);

        if (code != TCL_OK)
        {
            char *trace;

            trace = (char *)Tcl_GetVar(interp, "errorInfo", 0);

            if (trace == NULL)
                trace = (char *)Tcl_GetStringResult(interp);

            fprintf(stderr, "%s: TCL error @ line %d: %s\n",
                    termfil, interp->errorLine, trace);

            sprintf(log_buffer, "%s: TCL error @ line %d: %s",
                    termfil, interp->errorLine,
                    Tcl_GetStringResult(interp));

            log_err(-1, id, log_buffer);

            die(0);
        }

        sprintf(log_buffer, "term file: %s", termfil);

        log_record(PBSEVENT_SYSTEM, PBS_EVENTCLASS_SERVER,
                   id, log_buffer);
    }

    sprintf(log_buffer, "%s normal finish pid %d", argv[0], pid);

    log_record(PBSEVENT_SYSTEM, PBS_EVENTCLASS_SERVER, id, log_buffer);

    (void)close(server_sock);
    exit(0);
}
Example #18
0
 block_profiler(char const* description, bool enable_logging = true)
   : stats_(get_stats(description)), measuring_(false),
     enable_logging_(enable_logging)
 {
     restart();
 }
/*! \brief Constructor
*/
MillisecondTimer::MillisecondTimer()
{
	restart();
}
Example #20
0
ApplicationController::ApplicationController(oak::Application* application) :
    _app(application),
    _window(nullptr),
    _timer(nullptr),
    _splinePainter(nullptr),
    _staticTextPainter(nullptr),
    _vertexArray(nullptr),
    _config({ g_DefaultWindowFullscreen,
              g_DefaultVSyncOn,
              g_DefaultAnimationOn,
              g_DefaultUseTessellation,
              g_DefaultHelpVisible,
              g_DefaultRandomSplines,
              g_DefaultContinuityConstraint,
              g_DefaultCurvesCount,
            }),
    _openGL(_app->openGLMajor(), _app->openGLMinor())
{
    memset(_fps, 0, 5 * sizeof(int));
    _referenceTimePoint = std::chrono::time_point_cast<std::chrono::seconds>(_fpsClock.now());

    _window = new oak::Window(WINDOW_X, WINDOW_Y, WINDOW_W, WINDOW_H, _app->args()[0]);
    _window->setVSync(_config.vsyncOn);
    setContinuityConstraint(_config.constraint);

    LOG_INFO() << _app->glRenderer() << std::endl; // e.g. Intel HD Graphics 3000 OpenGL Engine
    LOG_INFO() << _app->glVersion() << std::endl;  // e.g. 3.2 INTEL-8.0.61

    /* GL settings */
    if (_openGL.hasVBO())
    {
        _vertexArray = new OpenglVertexArray;
        _vertexArray->bind();
    }

    // TODO: move it back in window::resize
    if (_openGL._major < 3)
    {
#if 0
        GLfloat aspect = (GLfloat)width / height;
        GLfloat maxX = 1.0;
        GLfloat maxY = 1.0;


        if (width >= height)
        {
            maxX = 1.0f * aspect;
        }
        else
        {
            maxY = 1.0f / aspect;
        }

        //gluOrtho2D(0, maxX, 0, maxY);
#endif
        glMatrixMode(GL_PROJECTION);
        glLoadIdentity();
        gluOrtho2D(-1, 1, -1, 1);
    }

    _window->onKey(
        [this] (oak::Window* window, unsigned char key, int x, int y)
        {
            keyPressed(window, key, x, y);
        });

    _window->onPaint(
        [this] (oak::Window* window)
        {
            std::chrono::high_resolution_clock::time_point newTimePoint = _fpsClock.now();
            int seconds = std::chrono::duration_cast<std::chrono::seconds>(newTimePoint - _referenceTimePoint).count();
            if (seconds >= 9)
            {
                memset(_fps, 0, 5 * sizeof(int));
                _referenceTimePoint += std::chrono::seconds(seconds - 1);
                seconds = 1;
            }
            else if (seconds >= 5)
            {
                memmove(_fps, _fps + seconds - 4, (5+4 - seconds) * sizeof(int));
                memset(_fps + 5+4 - seconds, 0, (seconds - 4) * sizeof(int));
                _referenceTimePoint += std::chrono::seconds(seconds - 4);
                seconds = 4;
            }
            _fps[seconds]++;
            int sum = 0;
            int count = 0;
            float fps = 0.0f;
            for (int i = 0; i < seconds; i++)
            {
                sum += _fps[i] * g_fpsWeights[i];
                count += g_fpsWeights[i];
            }
            if (count != 0)
                fps = (float)sum/count;

            glClear(GL_COLOR_BUFFER_BIT);
            try
            {
                if (_splinePainter)
                {
                    _splinePainter->paint(window);
                }
                if (_config.helpVisible && _staticTextPainter)
                {
                    updateOptionTexts(_staticTextPainter->staticText().lines(), fps);
                    _staticTextPainter->paint(window);
                }
            }
            catch(int errorCode)
            {
                _app->exit(errorCode);
            }

        });

    _timer = new oak::Timer(TIMER_MS, true,
        [this] (oak::Timer*)
        {
            if (_config.animatingOn)
            {
                oak::Spline::animate(_splinePainter->objects());
                _window->repaint();
            }
        });

    restart(true, true);
    _timer->start();
}
Example #21
0
/**
* I2C.begin for I2C.
*/
void PCA9685::begin()
{
  Wire.begin();
  restart();
}
Example #22
0
void ApplicationController::setRandomSplines(bool random)
{
    _config.randomSplines = random;
    _config.animatingOn = true;
    restart(false, true);
}
Example #23
0
/**
 * \brief Changes the distance of the jump.
 *
 * The movement is restarted.
 *
 * \param distance the new distance in pixels
 */
void JumpMovement::set_distance(int distance) {

  this->distance = distance;
  restart();
}
Example #24
0
int main(int argc, char *argv[])
{
    int dummysigalrm, foreground = 0;
    struct timeval tv, difftime, curtime, lasttime, *timeout;
    fd_set rfds, readers;
    int nfds, n, i, secs, ch;
    struct sigaction sa;
    time_t boottime;
    struct option long_options[] = {
	{"config", 1, 0, 'c'},
	{"debug", 2, 0, 'd'},
	{"foreground", 0, 0, 'f'},
	{"disable-vifs", 0, 0, 'N'},
	{"help", 0, 0, 'h'},
	{"version", 0, 0, 'v'},
	{"quit-daemon", 0, 0, 'q'},
	{"reload-config", 0, 0, 'l'},
	{"show-routes", 0, 0, 'r'},
	{"table-id", 1, 0, 't'},
	{"syslog-level", 1, 0, 's'},   /* Compat */
	{"loglevel", 1, 0, 's'},
	/* {"show-cache", 0, 0, 'i'}, */
	/* {"show-debug", 0, 0, 'p'}, */
	{0, 0, 0, 0}
    };

    snprintf(versionstring, sizeof (versionstring), "pimd version %s", todaysversion);

    while ((ch = getopt_long(argc, argv, "c:d::fhlNvqrt:s:", long_options, NULL)) != EOF) {
	const char *errstr;

	switch (ch) {
	    case 'c':
		if (optarg)
		    config_file = optarg;
		break;

	    case 'd':
		if (!optarg) {
		    debug = DEBUG_DEFAULT;
		} else {
		    char *p,*q;
		    size_t i, len;
		    struct debugname *d;

		    debug = 0;
		    p = optarg; q = NULL;
		    while (p) {
			q = strchr(p, ',');
			if (q)
			    *q++ = '\0';
			len = strlen(p);
			for (i = 0, d = debugnames; i < ARRAY_LEN(debugnames); i++, d++) {
			    if (len >= d->nchars && strncmp(d->name, p, len) == 0)
				break;
			}

			if (i == ARRAY_LEN(debugnames))
			    return usage();

			debug |= d->level;
			p = q;
		    }
		}
		break;

	    case 'f':
		foreground = 1;
		break;

	    case 'h':
		return usage();
	    case 'l':
		return killshow(SIGHUP, NULL);

	    case 'N':
		disable_all_by_default = 1;
		break;

	    case 'v':
		printf("%s\n", versionstring);
		return 0;

	    case 'q':
		return killshow(SIGTERM, NULL);

	    case 'r':
		return killshow(SIGUSR1, _PATH_PIMD_DUMP);

	    case 's':
		if (!optarg) {
			fprintf(stderr, "Missing syslog level argument!\n");
			return usage();
		}

		if (isdigit((int)optarg[0]))
		    syslog_level = strtonum(optarg, LOG_ALERT, LOG_DEBUG, &errstr);
		else
		    syslog_level = lvltonum(optarg, &errstr);

		if (errstr) {
		    fprintf(stderr, "Syslog level %s is %s!\n", optarg, errstr);
		    return usage();
		}
		break;

	    case 't':
		if (!optarg) {
			fprintf(stderr, "Missing Table ID argument!\n");
			return usage();
		}

		mrt_table_id = strtonum(optarg, 0, 999999999, &errstr);
		if (errstr) {
		    fprintf(stderr, "Table ID %s!\n", errstr);
		    return usage();
		}
		break;

#if 0 /* XXX: TODO */
	    case 'i':
		return killshow(SIGUSR2, _PATH_PIMD_CACHE);

	    case 'p':
		return killshow(SIGQUIT, NULL);
#endif
	    default:
		return usage();
	}
    }

    argc -= optind;
    if (argc > 0)
	return usage();

    if (geteuid() != 0)
	errx(1, "Need root privileges to start.");

    setlinebuf(stderr);

    if (debug != 0) {
	struct debugname *d;
	char c;
	int tmpd = debug;

	fprintf(stderr, "debug level 0x%lx ", debug);
	c = '(';
	for (d = debugnames; d < debugnames + ARRAY_LEN(debugnames); d++) {
	    if ((tmpd & d->level) == d->level) {
		tmpd &= ~d->level;
		fprintf(stderr, "%c%s", c, d->name);
		c = ',';
	    }
	}
	fprintf(stderr, ")\n");
    }

    /*
     * Create directory for runtime files
     */
    if (-1 == mkdir(_PATH_PIMD_RUNDIR, 0755) && errno != EEXIST)
	err(1, "Failed creating %s directory for runtime files", _PATH_PIMD_RUNDIR);

    /*
     * Setup logging
     */
#ifdef LOG_DAEMON
    openlog("pimd", LOG_PID, LOG_DAEMON);
    setlogmask(LOG_UPTO(syslog_level));
#else
    openlog("pimd", LOG_PID);
#endif /* LOG_DAEMON */

    logit(LOG_NOTICE, 0, "%s starting ...", versionstring);

    do_randomize();
    time(&boottime);

    callout_init();
    init_igmp();
    init_pim();
    init_routesock(); /* Both for Linux netlink and BSD routing socket */
    init_pim_mrt();
    init_timers();

    /* Start up the log rate-limiter */
    resetlogging(NULL);

    /* TODO: check the kernel DVMRP/MROUTED/PIM support version */

    init_vifs();
    init_rp_and_bsr();   /* Must be after init_vifs() */

#ifdef RSRR
    rsrr_init();
#endif /* RSRR */

    sa.sa_handler = handler;
    sa.sa_flags = 0;	/* Interrupt system calls */
    sigemptyset(&sa.sa_mask);
    sigaction(SIGALRM, &sa, NULL);
    sigaction(SIGHUP, &sa, NULL);
    sigaction(SIGTERM, &sa, NULL);
    sigaction(SIGINT, &sa, NULL);
    sigaction(SIGUSR1, &sa, NULL);
    sigaction(SIGUSR2, &sa, NULL);

    FD_ZERO(&readers);
    FD_SET(igmp_socket, &readers);
    nfds = igmp_socket + 1;
    for (i = 0; i < nhandlers; i++) {
	FD_SET(ihandlers[i].fd, &readers);
	if (ihandlers[i].fd >= nfds)
	    nfds = ihandlers[i].fd + 1;
    }

    IF_DEBUG(DEBUG_IF)
	dump_vifs(stderr);
    IF_DEBUG(DEBUG_PIM_MRT)
	dump_pim_mrt(stderr);

    /* schedule first timer interrupt */
    timer_setTimer(TIMER_INTERVAL, timer, NULL);

    if (!debug && !foreground) {
	/* Detach from the terminal */
	haveterminal = 0;
	if (fork())
	    exit(0);

	close(STDIN_FILENO);
	close(STDOUT_FILENO);
	close(STDERR_FILENO);

	n = open("/dev/null", O_RDWR, 0);
	if (n >= 0) {
	    dup2(n, STDIN_FILENO);
	    dup2(n, STDOUT_FILENO);
	    dup2(n, STDERR_FILENO);
	}
#ifdef SYSV
	setpgrp();
#else
#ifdef TIOCNOTTY
	n = open("/dev/tty", 2);
	if (n >= 0) {
	    (void)ioctl(n, TIOCNOTTY, (char *)0);
	    (void)close(n);
	}
#else
	if (setsid() < 0)
	    perror("setsid");
#endif /* TIOCNOTTY */
#endif /* SYSV */
    } /* End of child process code */

    if (pidfile(NULL))
	warn("Cannot create pidfile");

    /*
     * Main receive loop.
     */
    dummysigalrm = SIGALRM;
    difftime.tv_usec = 0;
    gettimeofday(&curtime, NULL);
    lasttime = curtime;
    while (1) {
	memcpy(&rfds, &readers, sizeof(rfds));
	secs = timer_nextTimer();
	if (secs == -1)
	    timeout = NULL;
	else {
	    timeout = &tv;
	    timeout->tv_sec = secs;
	    timeout->tv_usec = 0;
	}

	if (boottime) {
	    time_t n;

	    time(&n);
	    if (n > boottime + 15) {
		struct rp_hold *rph = g_rp_hold;

		while(rph) {
		    add_rp_grp_entry(&cand_rp_list, &grp_mask_list,
				     rph->address, 1, (uint16_t)0xffffff,
				     rph->group, rph->mask,
				     curr_bsr_hash_mask, curr_bsr_fragment_tag);
		    rph = rph->next;
		}
		boottime = 0;
	    }
	}

	if (sighandled) {
	    if (sighandled & GOT_SIGINT) {
		sighandled &= ~GOT_SIGINT;
		break;
	    }
	    if (sighandled & GOT_SIGHUP) {
		sighandled &= ~GOT_SIGHUP;
		restart(SIGHUP);

		/* reconstruct readers and nfds */
		FD_ZERO(&readers);
		FD_SET(igmp_socket, &readers);
		nfds = igmp_socket + 1;
		for (i = 0; i < nhandlers; i++) {
		    FD_SET(ihandlers[i].fd, &readers);
		    if (ihandlers[i].fd >= nfds)
			nfds = ihandlers[i].fd + 1;
		}
		memcpy(&rfds, &readers, sizeof(rfds));
	    }
	    if (sighandled & GOT_SIGUSR1) {
		sighandled &= ~GOT_SIGUSR1;
		fdump(SIGUSR1);
	    }
	    if (sighandled & GOT_SIGUSR2) {
		sighandled &= ~GOT_SIGUSR2;
		cdump(SIGUSR2);
	    }
	    if (sighandled & GOT_SIGALRM) {
		sighandled &= ~GOT_SIGALRM;
		timer(&dummysigalrm);
	    }
	}
	if ((n = select(nfds, &rfds, NULL, NULL, timeout)) < 0) {
	    if (errno != EINTR) /* SIGALRM is expected */
		logit(LOG_WARNING, errno, "select failed");
	    continue;
	}
	if (n > 0) {
	    /* TODO: shall check first igmp_socket for better performance? */
	    for (i = 0; i < nhandlers; i++) {
		if (FD_ISSET(ihandlers[i].fd, &rfds)) {
		    (*ihandlers[i].func)(ihandlers[i].fd, &rfds);
		}
	    }
	}

	/*
	 * Handle timeout queue.
	 *
	 * If select + packet processing took more than 1 second,
	 * or if there is a timeout pending, age the timeout queue.
	 *
	 * If not, collect usec in difftime to make sure that the
	 * time doesn't drift too badly.
	 *
	 * If the timeout handlers took more than 1 second,
	 * age the timeout queue again.  XXX This introduces the
	 * potential for infinite loops!
	 */
	do {
	    /*
	     * If the select timed out, then there's no other
	     * activity to account for and we don't need to
	     * call gettimeofday.
	     */
	    if (n == 0) {
		curtime.tv_sec = lasttime.tv_sec + secs;
		curtime.tv_usec = lasttime.tv_usec;
		n = -1;	/* don't do this next time through the loop */
	    } else
		gettimeofday(&curtime, NULL);
	    difftime.tv_sec = curtime.tv_sec - lasttime.tv_sec;
	    difftime.tv_usec += curtime.tv_usec - lasttime.tv_usec;
	    while (difftime.tv_usec >= 1000000) {
		difftime.tv_sec++;
		difftime.tv_usec -= 1000000;
	    }
	    if (difftime.tv_usec < 0) {
		difftime.tv_sec--;
		difftime.tv_usec += 1000000;
	    }
	    lasttime = curtime;
	    if (secs == 0 || difftime.tv_sec > 0)
		age_callout_queue(difftime.tv_sec);
	    secs = -1;
	} while (difftime.tv_sec > 0);
    } /* Main loop */

    logit(LOG_NOTICE, 0, "%s exiting.", versionstring);
    cleanup();
    exit(0);
}
Example #25
0
int uhd_device::readSamples(short *buf, int len, bool *overrun,
			TIMESTAMP timestamp, bool *underrun, unsigned *RSSI)
{
	ssize_t rc;
	uhd::time_spec_t ts;
	uhd::rx_metadata_t metadata;
	uint32_t pkt_buf[rx_spp];

	if (skip_rx)
		return 0;

	// Shift read time with respect to transmit clock
	timestamp += ts_offset;

	ts = convert_time(timestamp, actual_smpl_rt);
	LOG(DEEPDEBUG) << "Requested timestamp = " << ts.get_real_secs();

	// Check that timestamp is valid
	rc = rx_smpl_buf->avail_smpls(timestamp);
	if (rc < 0) {
		LOG(ERROR) << rx_smpl_buf->str_code(rc);
		LOG(ERROR) << rx_smpl_buf->str_status();
		return 0;
	}

	// Receive samples from the usrp until we have enough
	while (rx_smpl_buf->avail_smpls(timestamp) < len) {
		size_t num_smpls = usrp_dev->get_device()->recv(
					(void*)pkt_buf,
					rx_spp,
					metadata,
					uhd::io_type_t::COMPLEX_INT16,
					uhd::device::RECV_MODE_ONE_PACKET);

		rx_pkt_cnt++;

		// Check for errors 
		rc = check_rx_md_err(metadata, num_smpls);
		switch (rc) {
		case ERROR_UNRECOVERABLE:
			LOG(ALARM) << "UHD: Version " << uhd::get_version_string();
			LOG(ALARM) << "UHD: Unrecoverable error, exiting...";
			exit(-1);
		case ERROR_TIMING:
			restart(prev_ts);
		case ERROR_UNHANDLED:
			continue;
		}


		ts = metadata.time_spec;
		LOG(DEEPDEBUG) << "Received timestamp = " << ts.get_real_secs();

		rc = rx_smpl_buf->write(pkt_buf,
					num_smpls,
					metadata.time_spec);

		// Continue on local overrun, exit on other errors
		if ((rc < 0)) {
			LOG(ERROR) << rx_smpl_buf->str_code(rc);
			LOG(ERROR) << rx_smpl_buf->str_status();
			if (rc != smpl_buf::ERROR_OVERFLOW)
				return 0;
		}
	}

	// We have enough samples
	rc = rx_smpl_buf->read(buf, len, timestamp);
	if ((rc < 0) || (rc != len)) {
		LOG(ERROR) << rx_smpl_buf->str_code(rc);
		LOG(ERROR) << rx_smpl_buf->str_status();
		return 0;
	}

	return len;
}
/*! This function performs the initial set-up of the simulation. First, the
 *  parameterfile is set, then routines for setting units, reading
 *  ICs/restart-files are called, auxialiary memory is allocated, etc.
 */
void begrun(void)
{
  struct global_data_all_processes all;

  if(ThisTask == 0)
    {
      printf("\nThis is Gadget, version `%s'.\n", GADGETVERSION);
      printf("\nRunning on %d processors.\n", NTask);
    }

  read_parameter_file(ParameterFile);	/* ... read in parameters for this run */

#ifdef INJECT_GAS
  All.MaxInject = (int) (1.1*((All.Injection_dNdt * All.TimeMax)));
#endif

  allocate_commbuffers();	/* ... allocate buffer-memory for particle 
				   exchange during force computation */
  set_units();

#if defined(PERIODIC) && (!defined(PMGRID) || defined(FORCETEST))
  ewald_init();
#endif

  open_outputfiles();

  random_generator = gsl_rng_alloc(gsl_rng_ranlxd1);
  gsl_rng_set(random_generator, 42);	/* start-up seed */

#ifdef PMGRID
  long_range_init();
#endif

  All.TimeLastRestartFile = CPUThisRun;

  if(RestartFlag == 0 || RestartFlag == 2)
    {
      set_random_numbers();

      init();			/* ... read in initial model */
    }
  else
    {
      all = All;		/* save global variables. (will be read from restart file) */

      restart(RestartFlag);	/* ... read restart file. Note: This also resets 
				   all variables in the struct `All'. 
				   However, during the run, some variables in the parameter
				   file are allowed to be changed, if desired. These need to 
				   copied in the way below.
				   Note:  All.PartAllocFactor is treated in restart() separately.  
				 */

      All.MinSizeTimestep = all.MinSizeTimestep;
      All.MaxSizeTimestep = all.MaxSizeTimestep;
      All.BufferSize = all.BufferSize;
      All.BunchSizeForce = all.BunchSizeForce;
      All.BunchSizeDensity = all.BunchSizeDensity;
      All.BunchSizeHydro = all.BunchSizeHydro;
      All.BunchSizeDomain = all.BunchSizeDomain;

      All.TimeLimitCPU = all.TimeLimitCPU;
      All.ResubmitOn = all.ResubmitOn;
      All.TimeBetSnapshot = all.TimeBetSnapshot;
      All.TimeBetStatistics = all.TimeBetStatistics;
      All.CpuTimeBetRestartFile = all.CpuTimeBetRestartFile;
      All.ErrTolIntAccuracy = all.ErrTolIntAccuracy;
      All.MaxRMSDisplacementFac = all.MaxRMSDisplacementFac;

      All.ErrTolForceAcc = all.ErrTolForceAcc;

      All.TypeOfTimestepCriterion = all.TypeOfTimestepCriterion;
      All.TypeOfOpeningCriterion = all.TypeOfOpeningCriterion;
      All.NumFilesWrittenInParallel = all.NumFilesWrittenInParallel;
      All.TreeDomainUpdateFrequency = all.TreeDomainUpdateFrequency;

      All.SnapFormat = all.SnapFormat;
      All.NumFilesPerSnapshot = all.NumFilesPerSnapshot;
      All.MaxNumNgbDeviation = all.MaxNumNgbDeviation;
      All.ArtBulkViscConst = all.ArtBulkViscConst;


      All.OutputListOn = all.OutputListOn;
      All.CourantFac = all.CourantFac;

      All.OutputListLength = all.OutputListLength;
      memcpy(All.OutputListTimes, all.OutputListTimes, sizeof(double) * All.OutputListLength);


      strcpy(All.ResubmitCommand, all.ResubmitCommand);
      strcpy(All.OutputListFilename, all.OutputListFilename);
      strcpy(All.OutputDir, all.OutputDir);
      strcpy(All.RestartFile, all.RestartFile);
      strcpy(All.EnergyFile, all.EnergyFile);
      strcpy(All.InfoFile, all.InfoFile);
      strcpy(All.CpuFile, all.CpuFile);
      strcpy(All.TimingsFile, all.TimingsFile);
      strcpy(All.SnapshotFileBase, all.SnapshotFileBase);

      if(All.TimeMax != all.TimeMax)
	readjust_timebase(All.TimeMax, all.TimeMax);
    }

#ifdef PMGRID
  long_range_init_regionsize();
#endif

  if(All.ComovingIntegrationOn)
    init_drift_table();

  if(RestartFlag == 2)
    All.Ti_nextoutput = find_next_outputtime(All.Ti_Current + 1);
  else
    All.Ti_nextoutput = find_next_outputtime(All.Ti_Current);


  All.TimeLastRestartFile = CPUThisRun;
}
Example #27
0
void MainWindow::createMenus()
{
    openAct = new QAction(tr("读取地图(&M)"), this);
    saveAct = new QAction(tr("存档(&S)"), this);
    loadAct = new QAction(tr("读档(&R)"), this);
    rechargeAct = new QAction(tr("充值(&C)"), this);
    exitAct = new QAction(tr("退出(&E)"), this);

    restartAct = new QAction(tr("重新开始(&L)"), this);
    hardAct = new QAction(tr("困难"), this);
    mediumAct = new QAction(tr("中等"), this);
    easyAct = new QAction(tr("简单"), this);
    foresoundAct = new QAction(tr("音效开关(&O)"), this);

    manualAct = new QAction(tr("用户手册(&U)"), this);
    aboutAct = new QAction(tr("关于(&A)"), this);

    fileMenu = menuBar()->addMenu(tr("文件(&F)"));
    settingMenu = menuBar()->addMenu(tr("游戏设置(&G)"));
    helpMenu = menuBar()->addMenu(tr("帮助(&H)"));

    fileMenu->addAction(openAct);
    openAct->setShortcut(QKeySequence("Ctrl+m"));
    fileMenu->addSeparator();
    fileMenu->addAction(saveAct);
    saveAct->setShortcut(QKeySequence("Ctrl+s"));
    fileMenu->addAction(loadAct);
    loadAct->setShortcut(QKeySequence("Ctrl+r"));
    fileMenu->addSeparator();
    fileMenu->addAction(rechargeAct);
    rechargeAct->setShortcut(QKeySequence("Ctrl+c"));
    fileMenu->addSeparator();
    fileMenu->addAction(exitAct);
    exitAct->setShortcut(QKeySequence("Ctrl+e"));

    settingMenu->addAction(restartAct);
    restartAct->setShortcut(QKeySequence("Ctrl+l"));
    settingMenu->addSeparator();
    difficultyMenu = settingMenu->addMenu(tr("选择难度(&D)"));
    settingMenu->addSeparator();
    settingMenu->addAction(foresoundAct);
    foresoundAct->setCheckable(true);
    foresoundAct->setChecked(true);
    foresoundAct->setShortcut(QKeySequence("Ctrl+o"));

    difficultyMenu->addAction(hardAct);
    hardAct->setCheckable(true);
    hardAct->setChecked(false);
    difficultyMenu->addAction(mediumAct);
    mediumAct->setCheckable(true);
    mediumAct->setChecked(true);
    difficultyMenu->addAction(easyAct);
    easyAct->setCheckable(true);
    easyAct->setChecked(false);

    helpMenu->addAction(manualAct);
    manualAct->setShortcut(QKeySequence("Ctrl+u"));
    helpMenu->addAction(aboutAct);
    aboutAct->setShortcut(QKeySequence("Ctrl+a"));

    connect(exitAct, SIGNAL(triggered()), this, SLOT(close()));
    connect(openAct, SIGNAL(triggered()), this, SLOT(open()));
    connect(saveAct, SIGNAL(triggered()), this, SLOT(save()));
    connect(loadAct, SIGNAL(triggered()), this, SLOT(load()));
    connect(rechargeAct, SIGNAL(triggered()),this, SLOT(recharge()));

    connect(restartAct, SIGNAL(triggered()), this, SLOT(restart()));
    connect(hardAct, SIGNAL(triggered()), this, SLOT(hard()));
    connect(mediumAct, SIGNAL(triggered()), this, SLOT(medium()));
    connect(easyAct, SIGNAL(triggered()), this, SLOT(easy()));
    connect(foresoundAct, SIGNAL(triggered()), this, SLOT(foresound()));

    connect(manualAct, SIGNAL(triggered()), this, SLOT(manual()));
    connect(aboutAct, SIGNAL(triggered()), this, SLOT(about()));
}
Example #28
0
std::string Stencil::call(const Call& call) {
	auto what = call.what();
	
	// Getting content
	if(what=="html():string"){
		return html();
	}
	else if(what=="cila():string"){
		return cila();
	}

	// Setting content
	else if(what=="html(string)"){
		std::string string = call.arg(0);
		           html(string);
	}
	else if(what=="cila(string)"){
		std::string string = call.arg(0);
		           cila(string);
	}

	// Patching content
	else if(what=="patch(string)"){
		std::string string = call.arg(0);
		           patch(string);	
	}

	// Saving
	else if(what=="html(string).write()"){
		std::string string = call.arg(0);
		           html(string).write();
	}
	else if(what=="cila(string).write()"){
		std::string string = call.arg(0);
		           cila(string).write();
	}

	// Conversion of content...
	// ... HTML to Cila
	else if(what=="html(string).cila():string"){
		std::string string = call.arg(0);
		return     html(string).cila();
	}
	// ... Cila to HTML
	else if(what=="cila(string).html():string"){
		std::string string = call.arg(0);
		return     cila(string).html();
	}

	// Rendering HTML
	else if(what=="html(string).render().html():string"){
		std::string string = call.arg(0);
		return     html(string).render().html();
	}
	else if(what=="html(string).refresh().html():string"){
		std::string string = call.arg(0);
		return     html(string).refresh().html();
	}

	// Rendering Cila
	else if(what=="cila(string).render().cila():string"){
		std::string string = call.arg(0);
		return     cila(string).render().cila();
	}

	// Update <input>s
	else if(what=="inputs({string,string}).render().html():string"){
		auto values = call.arg<std::map<std::string,std::string>>(0);
		return     inputs(     values    ).render().html();
	}
	
	// Restart
	else if(what=="restart().html():string"){
		return     restart().html();
	}    

	// Access to context
	else if(what=="interact(string):string"){
		std::string string = call.arg(0);
		return     interact(string);
	}

	else return Component::call(call);

	return "";
}
Example #29
0
int
pthread_rwlock_unlock (pthread_rwlock_t *rwlock)
{
  pthread_descr torestart;
  pthread_descr th;

  __pthread_lock (&rwlock->__rw_lock, NULL);
  if (rwlock->__rw_writer != NULL)
    {
      /* Unlocking a write lock.  */
      if (rwlock->__rw_writer != thread_self ())
	{
	  __pthread_unlock (&rwlock->__rw_lock);
	  return EPERM;
	}
      rwlock->__rw_writer = NULL;

      if (rwlock->__rw_kind == PTHREAD_RWLOCK_PREFER_READER_NP
	  || (th = dequeue (&rwlock->__rw_write_waiting)) == NULL)
	{
	  /* Restart all waiting readers.  */
	  torestart = rwlock->__rw_read_waiting;
	  rwlock->__rw_read_waiting = NULL;
	  __pthread_unlock (&rwlock->__rw_lock);
	  while ((th = dequeue (&torestart)) != NULL)
	    restart (th);
	}
      else
	{
	  /* Restart one waiting writer.  */
	  __pthread_unlock (&rwlock->__rw_lock);
	  restart (th);
	}
    }
  else
    {
      /* Unlocking a read lock.  */
      if (rwlock->__rw_readers == 0)
	{
	  __pthread_unlock (&rwlock->__rw_lock);
	  return EPERM;
	}

      --rwlock->__rw_readers;
      if (rwlock->__rw_readers == 0)
	/* Restart one waiting writer, if any.  */
	th = dequeue (&rwlock->__rw_write_waiting);
      else
	th = NULL;

      __pthread_unlock (&rwlock->__rw_lock);
      if (th != NULL)
	restart (th);

      /* Recursive lock fixup */

      if (rwlock->__rw_kind == PTHREAD_RWLOCK_PREFER_WRITER_NP)
	{
	  pthread_descr self = thread_self();
	  pthread_readlock_info *victim = rwlock_remove_from_list(self, rwlock);

	  if (victim != NULL)
	    {
	      if (victim->pr_lock_count == 0)
		{
		  victim->pr_next = self->p_readlock_free;
		  self->p_readlock_free = victim;
		}
	    }
	  else
	    {
	      if (self->p_untracked_readlock_count > 0)
		self->p_untracked_readlock_count--;
	    }
	}
    }

  return 0;
}
Example #30
0
void ReconnectRouterOp::onTimeout()
{
    m_timer1.stop();
    LOG_DEBUG(QString::fromUtf8("retry %1/%2").arg(m_retryCount).arg(m_maxRetryCount));
    restart();
}