Example #1
0
int main(int argc, char **argv)
{

  if ( argc == 2 ) {
	if ( strcmp(argv[1], "--create-bootloader-keys") == 0 ) {
	  if ( !readKeys("keys.txt") ) {
		fprintf(stderr, "Aborted.\n");
		return 1;
	  }
	  if ( !writeBootloaderKeys("aes_keys.c") ) {
	    fprintf(stderr, "Aborted.\n");
	    return 1;
	  }
	  return 0;
    } else {
      printUsage(argv[0]);
      return 1;
    }
  } else if ( argc != 3 ) {
    printUsage(argv[0]);
    return 1;
  }

  char *plainPath = argv[1];
  char *encryptedPath = argv[2];


  if ( !readKeys("keys.txt") ) {
    fprintf(stderr, "Aborted.\n");
    return 1;
  }

  if ( !readPlainFile(plainPath) ) {
    fprintf(stderr, "Aborted.\n");
    return 1;
  }

  if ( !writeHeader() ) {
    fprintf(stderr, "Aborted.\n");
    return 1;
  }

  if ( !encrypt() ) {
    fprintf(stderr, "Aborted.\n");
    return 1;
  }

  if ( !writeEncryptedFile(encryptedPath) ) {
    fprintf(stderr, "Aborted.\n");
    return 1;
  }
  

  return 0;
}
Example #2
0
osgAnimation::Channel* readFbxChannels(FbxAnimCurve* curveX, FbxAnimCurve* curveY,
    FbxAnimCurve* curveZ,
    const FbxDouble3& defaultValue,
    const char* targetName, const char* channelName)
{
    if (!(curveX && curveX->KeyGetCount()) &&
        !(curveY && curveY->KeyGetCount()) &&
        !(curveZ && curveZ->KeyGetCount()))
    {
        return 0;
    }

    FbxAnimCurveDef::EInterpolationType interpolationType = FbxAnimCurveDef::eInterpolationConstant;
    if (curveX && curveX->KeyGetCount()) interpolationType = curveX->KeyGetInterpolation(0);
    else if (curveY && curveY->KeyGetCount()) interpolationType = curveY->KeyGetInterpolation(0);
    else if (curveZ && curveZ->KeyGetCount()) interpolationType = curveZ->KeyGetInterpolation(0);

    osgAnimation::Channel* pChannel = 0;

    if (interpolationType == FbxAnimCurveDef::eInterpolationCubic)
    {
        osgAnimation::Vec3CubicBezierKeyframeContainer* pKeyFrameCntr = new osgAnimation::Vec3CubicBezierKeyframeContainer;
        readKeys(curveX, curveY, curveZ, defaultValue, *pKeyFrameCntr);
        reorderControlPoints(*pKeyFrameCntr);

        osgAnimation::Vec3CubicBezierChannel* pCubicChannel = new osgAnimation::Vec3CubicBezierChannel;
        pCubicChannel->getOrCreateSampler()->setKeyframeContainer(pKeyFrameCntr);
        pChannel = pCubicChannel;
    }
    else
    {
        osgAnimation::Vec3KeyframeContainer* pKeyFrameCntr = new osgAnimation::Vec3KeyframeContainer;
        readKeys(curveX, curveY, curveZ, defaultValue, *pKeyFrameCntr);

        if (interpolationType == FbxAnimCurveDef::eInterpolationConstant)
        {
            osgAnimation::Vec3StepChannel* pStepChannel = new osgAnimation::Vec3StepChannel;
            pStepChannel->getOrCreateSampler()->setKeyframeContainer(pKeyFrameCntr);
            pChannel = pStepChannel;
        }
        else
        {
            osgAnimation::Vec3LinearChannel* pLinearChannel = new osgAnimation::Vec3LinearChannel;
            pLinearChannel->getOrCreateSampler()->setKeyframeContainer(pKeyFrameCntr);
            pChannel = pLinearChannel;
        }
    }

    pChannel->setTargetName(targetName);
    pChannel->setName(channelName);

    return pChannel;
}
Example #3
0
void interrupt10ms(void)
{
  Tenms |= 1;			// 10 mS has passed

  uint8_t enuk = KEY_MENU;
  uint8_t in = readKeys();
  for (uint8_t i = 1; i != uint8_t(1 << TRM_BASE); i <<= 1) {
    uint8_t value = (in & i);
    keys[enuk].input(value);
    ++enuk;
  }

#if defined(REV9E)
  checkRotaryEncoder();
  static rotenc_t rePreviousValue;
  rotenc_t reNewValue = (x9de_rotenc / 2);
  int8_t scrollRE = reNewValue - rePreviousValue;
  if (scrollRE) {
    rePreviousValue = reNewValue;
    if (scrollRE < 0) {
      putEvent(EVT_KEY_FIRST(KEY_MINUS));
    }
    else {
      putEvent(EVT_KEY_FIRST(KEY_PLUS)); 
    }
  }
#endif
}
Example #4
0
int main(void)
{
    //control the main work flow
    result_txt = fopen("./result.txt", "w+");
    log_txt = fopen("./log.txt", "w+");
    //read data:
    readData();
    readKeys();
    //omp section start
    omp_set_num_threads(core_number);
    //start parallel computing to calculate signatures for each column
#pragma omp parallel
    {
#pragma omp for
        for (int col = 499; col >= 0; col--)
        {
            calcSignatures(col);
        }
    }
    //omp section ends, all signatures are calculated into an array
    printf("%d columns have blocks, total block number is %ld\n", total_col_has_neighbours, total_block_number);
    fprintf(log_txt, "%d columns have blocks, total block number is %ld\n", total_col_has_neighbours, total_block_number);
    //sorting all signatures
    printf("\nQuick sorting all signatures...\n");
    fprintf(log_txt, "\nQuick sorting all signatures......\n");
    quicksort(signatures, 0, total_block_number);
    printf("Quick sorting finished! \n\nStart collision detecting...\n");
    fprintf(log_txt, "Quick sorting finished! \n\nStart collision detecting...\n");
    //compare sorted signatures, if they are equal then collisions are detected.
    int i = 0;
    while (i < total_block_number)
    {
        if (signatures[i] == signatures[i + 1] && correspond_col[i] != correspond_col[i + 1]) 
        {
            int last_same_index = i + 1;
            while (signatures[i] == signatures[last_same_index])
            {
                last_same_index += 1;
            }
            collision_number += 1;
            fprintf(result_txt, "Signature %ld -- block: M%d ,M%d, M%d, M%d -- collisions in columns: ", signatures[i], signatures_one[i], signatures_two[i], signatures_three[i], signatures_four[i]);
            for (int j = i; j < last_same_index && (i == j || correspond_col[i] != correspond_col[j]); j++)
            {
                fprintf(result_txt, "%d ", correspond_col[j]);
            }
            fprintf(result_txt, "\n");
            i = last_same_index;
        }
        else
        {
            i += 1;
        }
    }
    printf("%ld collisions are detected.\n", collision_number);
    fprintf(log_txt, "%ld collisions are detected.\n", collision_number);
    printf("\nLogs are recorded in the log.txt file.\n");
    printf("Collisions are recorded in the result.txt file.\n");
    fclose(result_txt);
    fclose(log_txt);
}
osgAnimation::Channel* readFbxChannelsQuat(
    KFbxAnimCurve* curveX, KFbxAnimCurve* curveY, KFbxAnimCurve* curveZ,
    const fbxDouble3& defaultValue,
    const char* targetName, ERotationOrder rotOrder)
{
    if (!(curveX && curveX->KeyGetCount()) &&
        !(curveY && curveY->KeyGetCount()) &&
        !(curveZ && curveZ->KeyGetCount()))
    {
        return 0;
    }

    osgAnimation::QuatSphericalLinearChannel* pChannel = new osgAnimation::QuatSphericalLinearChannel;
    pChannel->setTargetName(targetName);
    pChannel->setName("quaternion");
    typedef std::vector<osgAnimation::TemplateKeyframe<osg::Vec3> > KeyFrameCntr;
    KeyFrameCntr eulerFrameCntr;
    readKeys(curveX, curveY, curveZ, defaultValue, eulerFrameCntr, static_cast<float>(osg::PI / 180.0));

    osgAnimation::QuatSphericalLinearSampler::KeyframeContainerType& quatFrameCntr =
        *pChannel->getOrCreateSampler()->getOrCreateKeyframeContainer();
    quatFrameCntr.reserve(eulerFrameCntr.size());

    for (KeyFrameCntr::iterator it = eulerFrameCntr.begin(), end = eulerFrameCntr.end();
        it != end; ++it)
    {
        const osg::Vec3& euler = it->getValue();
        quatFrameCntr.push_back(osgAnimation::QuatKeyframe(
            it->getTime(), makeQuat(euler, rotOrder)));
    }

    return pChannel;
}
Example #6
0
int main(int argc, char* argv[])
{
	if (!glfwInit())
	{
		printf("can't initialize GLFW\n");
		return 1;
	} else
		printf("GLFW initialized.\n");

	glfwOpenWindow(windowWidth, windowHeight, 0, 0, 0, 8, 24, 8, GLFW_WINDOW);
	getInfo();
	setCallbacks();

	if (glewInit() != GLEW_OK)
	{
		printf("can't initialize GLEW\n");
		glfwTerminate();
		return 1;
	} else
		printf("GLEW initialized.\n");
	if (!GLEW_VERSION_2_0)
	{
		printf("need OpenGL 3.0 at least\n");
		glfwTerminate();
		return 1;
	}

	//importFile("./../../thirdparty/models/Free House 01/FreeHouse01.3DS");
	srand((int)glfwGetTime());
	scene = new aspglScene();
	scene->setupScene(windowWidth, windowHeight);
	timer = new aspglTimer();
 	bool bContinue = true;
	glfwSwapInterval(-1);
	double t = glfwGetTime(); //get time in seconds
	while (bContinue)
	{
		readKeys();
		//timer->beginQuery();
		scene->render();
		//timer->endQuery("Frame render end");
		scene->animate(dt);
		glfwSwapBuffers();
		dt = (float)(glfwGetTime() - t);
		t = (float)glfwGetTime();
		bContinue = glfwGetKey( GLFW_KEY_ESC ) != GLFW_PRESS;
	}

	delete timer;
	delete scene;

	glfwTerminate();

	return 1;
}
Example #7
0
void TinyGameLibrary::mainLoop()
{
    m_run = true;
    while (m_run) {
        SDL_RenderClear(m_renderer);
        readKeys();
        moveObjects();
        renderLevel();
        SDL_RenderPresent(m_renderer);
        SDL_Delay(1000 / 30);
    }
}
Example #8
0
bool Wallet::writeWallet(const QString& newPassphrase) {
    EC_KEY* keys = readKeys(keyFilePath());
    auto ledger = DependencyManager::get<Ledger>();
    // Remove any existing locker, because it will be out of date.
    if (!_publicKeys.isEmpty() && !ledger->receiveAt(_publicKeys.first(), _publicKeys.first(), QByteArray())) {
        return false;  // FIXME: receiveAt could fail asynchronously.
    }
    if (keys) {
        // we read successfully, so now write to a new temp file
        QString tempFileName = QString("%1.%2").arg(keyFilePath(), QString("temp"));
        QString oldPassphrase = *_passphrase;
        if (!newPassphrase.isEmpty()) {
            setPassphrase(newPassphrase);
        }

        if (writeKeys(tempFileName, keys)) {
            if (writeSecurityImage(_securityImage, tempFileName)) {
                // ok, now move the temp file to the correct spot
                QFile(QString(keyFilePath())).remove();
                QFile(tempFileName).rename(QString(keyFilePath()));
                qCDebug(commerce) << "wallet written successfully";
                emit keyFilePathIfExistsResult(getKeyFilePath());
                if (!walletIsAuthenticatedWithPassphrase() || !ledger->receiveAt()) {
                    // FIXME: Should we fail the whole operation?
                    // Tricky, because we'll need the the key and file from the TEMP location...
                    qCWarning(commerce) << "Failed to update locker";
                }
                return true;
            } else {
                qCDebug(commerce) << "couldn't write security image to temp wallet";
            }
        } else {
            qCDebug(commerce) << "couldn't write keys to temp wallet";
        }
        // if we are here, we failed, so cleanup
        QFile(tempFileName).remove();
        if (!newPassphrase.isEmpty()) {
            setPassphrase(oldPassphrase);
        }

    } else {
        qCDebug(commerce) << "couldn't read wallet - bad passphrase?";
        // TODO: review this, but it seems best to reset the passphrase
        // since we couldn't decrypt the existing wallet (or is doesn't
        // exist perhaps).
        setPassphrase("");
    }
    return false;
}
Example #9
0
//-----------------------------------------------------PLAYER NAME ENTERING
void PlayerEnterName::run(int& yPos) {
  string name = "";
  draw(name, yPos);
  bool done = false;
  while(done == false) {
    if(eng->config->BOT_PLAYING == false) {
      readKeys(name, done, yPos);
    } else {
      name = "AZATHOTH";
      done = true;
    }
  }

  ActorDefinition& iDef = *(eng->player->getDef());
  iDef.name_a = iDef.name_the = name;

  yPos++;
}
Example #10
0
MarkerReturnData Marker::run(const MarkerTask_t markerTask, Item* itemThrown) {
  pos_ = eng->player->pos;

  MarkerReturnData data;

  if(
    markerTask == markerTask_aimRangedWeapon  ||
    markerTask == markerTask_look             ||
    markerTask == markerTask_aimThrownWeapon) {
    //Attempt to place marker at target.
    if(setCoordToTargetIfVisible() == false) {
      //Else NULL the target, and attempt to place marker at closest visible enemy.
      //This sets a new target if successful.
      eng->player->target = NULL;
      setCoordToClosestEnemyIfVisible();
    }
  }

  eng->log->clearLog();

  eng->renderer->drawMapAndInterface(false);
  draw(markerTask);
  eng->renderer->updateScreen();

  if(
    markerTask == markerTask_look ||
    markerTask == markerTask_aimRangedWeapon ||
    markerTask == markerTask_aimThrownWeapon) {
    eng->look->markerAtCoord(pos_, markerTask, itemThrown);
  }

  eng->renderer->drawMapAndInterface(false);
  draw(markerTask);
  eng->renderer->updateScreen();

  isDone_ = false;
  while(isDone_ == false) {
    readKeys(markerTask, data, itemThrown);
  }

  return data;
}
osgAnimation::Channel* readFbxChannels(KFbxAnimCurve* curveX, KFbxAnimCurve* curveY,
    KFbxAnimCurve* curveZ,
    const fbxDouble3& defaultValue,
    const char* targetName, const char* channelName)
{
    if (!(curveX && curveX->KeyGetCount()) &&
        !(curveY && curveY->KeyGetCount()) &&
        !(curveZ && curveZ->KeyGetCount()))
    {
        return 0;
    }

    osgAnimation::Vec3LinearChannel* pChannel = new osgAnimation::Vec3LinearChannel;
    osgAnimation::Vec3KeyframeContainer* pKeyFrameCntr =
        pChannel->getOrCreateSampler()->getOrCreateKeyframeContainer();

    pChannel->setTargetName(targetName);
    pChannel->setName(channelName);
    readKeys(curveX, curveY, curveZ, defaultValue, *pKeyFrameCntr);

    return pChannel;
}
Example #12
0
bool Wallet::writeWallet(const QString& newPassphrase) {
    EC_KEY* keys = readKeys(keyFilePath().toStdString().c_str());
    if (keys) {
        // we read successfully, so now write to a new temp file
        QString tempFileName = QString("%1.%2").arg(keyFilePath(), QString("temp"));
        QString oldPassphrase = *_passphrase;
        if (!newPassphrase.isEmpty()) {
            setPassphrase(newPassphrase);
        }
        if (writeKeys(tempFileName.toStdString().c_str(), keys)) {
            if (writeSecurityImage(_securityImage, tempFileName)) {
                // ok, now move the temp file to the correct spot
                QFile(QString(keyFilePath())).remove();
                QFile(tempFileName).rename(QString(keyFilePath()));
                qCDebug(commerce) << "wallet written successfully";
                emit keyFilePathIfExistsResult(getKeyFilePath());
                return true;
            } else {
                qCDebug(commerce) << "couldn't write security image to temp wallet";
            }
        } else {
            qCDebug(commerce) << "couldn't write keys to temp wallet";
        }
        // if we are here, we failed, so cleanup
        QFile(tempFileName).remove();
        if (!newPassphrase.isEmpty()) {
            setPassphrase(oldPassphrase);
        }

    } else {
        qCDebug(commerce) << "couldn't read wallet - bad passphrase?";
        // TODO: review this, but it seems best to reset the passphrase
        // since we couldn't decrypt the existing wallet (or is doesn't
        // exist perhaps).
        setPassphrase("");
    }
    return false;
}
Example #13
0
void Wallet::sendChallengeOwnershipResponses() {
    if (_pendingChallenges.size() == 0 || getSalt().length() == 0) {
        return;
    }
    auto nodeList = DependencyManager::get<NodeList>();

    EC_KEY* ec = readKeys(keyFilePath());

    for (const auto& packet: _pendingChallenges) {

        // With EC keys, we receive a nonce from the metaverse server, which is signed
        // here with the private key and returned.  Verification is done at server.

        QString sig;
        bool challengeOriginatedFromClient = packet->getType() == PacketType::ChallengeOwnershipRequest;
        int status;
        int idByteArraySize;
        int textByteArraySize;
        int challengingNodeUUIDByteArraySize;

        packet->readPrimitive(&idByteArraySize);
        packet->readPrimitive(&textByteArraySize);  // returns a cast char*, size
        if (challengeOriginatedFromClient) {
            packet->readPrimitive(&challengingNodeUUIDByteArraySize);
        }

        // "encryptedText"  is now a series of random bytes, a nonce
        QByteArray id = packet->read(idByteArraySize);
        QByteArray text = packet->read(textByteArraySize);
        QByteArray challengingNodeUUID;
        if (challengeOriginatedFromClient) {
            challengingNodeUUID = packet->read(challengingNodeUUIDByteArraySize);
        }

        if (ec) {
            ERR_clear_error();
            sig = signWithKey(text, ""); // base64 signature, QByteArray cast (on return) to QString FIXME should pass ec as string so we can tell which key to sign with
            status = 1;
        } else {
            qCDebug(commerce) << "During entity ownership challenge, creating the EC-signed nonce failed.";
            status = -1;
        }

        QByteArray textByteArray;
        if (status > -1) {
            textByteArray = sig.toUtf8();
        }
        textByteArraySize = textByteArray.size();
        int idSize = id.size();
        // setup the packet
        const SharedNodePointer sendingNode = nodeList->nodeWithLocalID(packet->getSourceID());
        if (!sendingNode.isNull()) {
            if (challengeOriginatedFromClient) {
                auto textPacket = NLPacket::create(PacketType::ChallengeOwnershipReply,
                    idSize + textByteArraySize + challengingNodeUUIDByteArraySize + 3 * sizeof(int),
                    true);

                textPacket->writePrimitive(idSize);
                textPacket->writePrimitive(textByteArraySize);
                textPacket->writePrimitive(challengingNodeUUIDByteArraySize);
                textPacket->write(id);
                textPacket->write(textByteArray);
                textPacket->write(challengingNodeUUID);

                qCDebug(commerce) << "Sending ChallengeOwnershipReply Packet containing signed text" << textByteArray << "for id" << id;

                nodeList->sendPacket(std::move(textPacket), *sendingNode);
            } else {
                auto textPacket = NLPacket::create(PacketType::ChallengeOwnership, idSize + textByteArraySize + 2 * sizeof(int), true);

                textPacket->writePrimitive(idSize);
                textPacket->writePrimitive(textByteArraySize);
                textPacket->write(id);
                textPacket->write(textByteArray);

                qCDebug(commerce) << "Sending ChallengeOwnership Packet containing signed text" << textByteArray << "for id" << id;

                nodeList->sendPacket(std::move(textPacket), *sendingNode);
            }
        } else {
            qCDebug(commerce) << "Challenging Node Local ID" << packet->getSourceID() << "disconnected before response";
        }


        if (status == -1) {
            qCDebug(commerce) << "During entity ownership challenge, signing the text failed.";
            long error = ERR_get_error();
            if (error != 0) {
                const char* error_str = ERR_error_string(error, NULL);
                qCWarning(entities) << "EC error:" << error_str;
            }
        }
    }

    EC_KEY_free(ec);
    _pendingChallenges.clear();
}
Example #14
0
/// Read the content of the named file.  The file content is read into the
/// buffer in one-shot and then digested.
int ibis::dictionary::read(const char* name) {
    if (name == 0 || *name == 0) return -1;
    std::string evt = "dictionary::read(";
    evt += name;
    evt += ')';
    // open the file to read
    int ierr = 0;
    FILE* fptr = fopen(name, "rb");
    if (fptr == 0) {
	LOGGER(ibis::gVerbose > 3)
	    << "Warning -- " << evt << " failed to open the file ... "
	    << (errno ? strerror(errno) : "no free stdio stream");
	return -2;
    }

    ibis::util::timer mytimer(evt.c_str(), 4);
    IBIS_BLOCK_GUARD(fclose, fptr);
    ierr = fseek(fptr, 0, SEEK_END); // to the end
    if (ierr != 0) {
	LOGGER(ibis::gVerbose > 1)
	    << "Warning -- " << evt << " failed to seek to the end of the file";
	return -3;
    }

    long int sz = ftell(fptr); // file size
    if (sz < 24) { // must be the old style dictionary file
	return readRaw(evt.c_str(), fptr);
    }
    else {
	char header[20];
	ierr = fseek(fptr, 0, SEEK_SET);
	if (ierr != 0) {
	    LOGGER(ibis::gVerbose > 1)
		<< "Warning -- " << evt << " failed to seek to the beginning "
		"of the file";
	    return -4;
	}

	ierr = fread(header, 1, 20, fptr);
	if (ierr != 20) {
	    LOGGER(ibis::gVerbose > 1)
		<< "Warning -- " << evt << " failed to read the 20-byte header";
	    return -5;
	}
	if (header[0] == _fastbit_dictionary_header[0] &&
	    header[1] == _fastbit_dictionary_header[1] &&
	    header[2] == _fastbit_dictionary_header[2] &&
	    header[3] == _fastbit_dictionary_header[3] &&
	    header[4] == _fastbit_dictionary_header[4] &&
	    header[5] == _fastbit_dictionary_header[5] &&
	    header[6] == _fastbit_dictionary_header[6] &&
	    header[7] == _fastbit_dictionary_header[7] &&
	    header[8] == _fastbit_dictionary_header[8] &&
	    header[9] == _fastbit_dictionary_header[9] &&
	    header[10] == _fastbit_dictionary_header[10] &&
	    header[11] == _fastbit_dictionary_header[11] &&
	    header[12] == _fastbit_dictionary_header[12] &&
	    header[13] == _fastbit_dictionary_header[13] &&
	    header[14] == _fastbit_dictionary_header[14] &&
	    header[15] == _fastbit_dictionary_header[15] &&
	    header[16] == _fastbit_dictionary_header[16] &&
	    header[17] == _fastbit_dictionary_header[17] &&
	    header[18] == _fastbit_dictionary_header[18] &&
	    header[19] == _fastbit_dictionary_header[19]) {
	    // got the expected header
	    return readKeys(evt.c_str(), fptr);
	}
	else {
	    LOGGER(ibis::gVerbose > 2)
		<< evt << " did not find the expected header, assume "
		"to be an old-style dictionary";
	    return readRaw(evt.c_str(), fptr);
	}
    }
} // ibis::dictionary::read
Example #15
0
void Input::waitKeyDown(int key)
{
    while(!keyDown[key])
        readKeys();
}
Example #16
0
int main()
{
  uint8_t index = 0;
  uint8_t maxhsize = DISPLAY_CHAR_WIDTH;
  FRESULT fr;
  uint32_t state = ST_START;
  uint32_t nameCount = 0;
  uint32_t vpos = 0;
  uint32_t hpos = 0;

#if defined(PCBTARANIS)
  wdt_reset();
  RCC_AHB1PeriphClockCmd(PWR_RCC_AHB1Periph | KEYS_RCC_AHB1Periph | LCD_RCC_AHB1Periph | BACKLIGHT_RCC_AHB1Periph | I2C_RCC_AHB1Periph | SD_RCC_AHB1Periph, ENABLE);
  RCC_APB1PeriphClockCmd(LCD_RCC_APB1Periph | BACKLIGHT_RCC_APB1Periph | INTERRUPT_5MS_APB1Periph | I2C_RCC_APB1Periph | SD_RCC_APB1Periph, ENABLE);
  RCC_APB2PeriphClockCmd(BACKLIGHT_RCC_APB2Periph, ENABLE);
#endif

  pwrInit();
  delaysInit();               //needed for lcdInit()
  lcdInit();
  backlightInit();

  lcd_clear();
  lcd_putsn(0, 0, (const char *)bootloaderVersion, 0); // trick to avoid bootloaderVersion to be optimized out ...
  lcd_putsLeft(0, BOOTLOADER_TITLE);
  lcd_invert_line(0);
  lcdRefresh();

  keysInit();
  i2cInit();

  __enable_irq();
  init10msTimer();

#if defined(PCBTARANIS)
  // SD card detect pin
  sdInit();
  usbInit();
#endif

  for (;;) {
    wdt_reset();

    if (Tenms) {
      Tenms = 0;

      lcdRefreshWait();
      lcd_clear();
      lcd_putsLeft(0, BOOTLOADER_TITLE);
      lcd_invert_line(0);

      uint8_t event = getEvent();

      if (state != ST_USB) {
        if (usbPlugged()) {
          state = ST_USB;
          if (!unlocked) {
            unlocked = 1;
            unlockFlash();
          }
          usbPluggedIn();
        }
      }

      if (state == ST_START) {
        lcd_putsLeft(2*FH, "\010Write Firmware");
        lcd_putsLeft(3*FH, "\010Restore EEPROM");
        lcd_putsLeft(4*FH, "\010Exit");
        lcd_invert_line(2+vpos);
        lcd_putsLeft(7*FH, INDENT "Or plug in a USB cable for mass storage");
        if (event == EVT_KEY_FIRST(BOOT_KEY_DOWN)) {
          vpos == 2 ? vpos = 0 : vpos = vpos+1;
        }
        else if (event == EVT_KEY_FIRST(BOOT_KEY_UP)) {
          vpos == 0 ? vpos = 2 : vpos = vpos-1;
        }
        else if (event == EVT_KEY_BREAK(BOOT_KEY_MENU)) {
          switch (vpos) {
            case 0:
              state = ST_FLASH_MENU;
              break;
            case 1:
              state = ST_RESTORE_MENU;
              break;
            default:
              state = ST_REBOOT;
          }
        }
      }

      if (state == ST_USB) {
        lcd_putsLeft(4*FH, "\026USB Connected");
        if (usbPlugged() == 0) {
          vpos = 0;
          if (unlocked) {
            lockFlash();
            unlocked = 0;
          }
          state = ST_START;
        }
#if defined(PCBSKY9X)
        usbMassStorage();
#endif
      }

      if (state == ST_FLASH_MENU || state == ST_RESTORE_MENU) {
        sdInit();
        memoryType = (state == ST_RESTORE_MENU ? MEM_EEPROM : MEM_FLASH);
        state = ST_DIR_CHECK;
      }

      else if (state == ST_DIR_CHECK) {
        fr = f_chdir(getBinaryPath());
        if (fr == FR_OK) {
          state = ST_OPEN_DIR;
        }
        else {
          lcd_putsLeft(2*FH, INDENT "Directory is missing!");
          if (event == EVT_KEY_BREAK(BOOT_KEY_EXIT) || event == EVT_KEY_BREAK(BOOT_KEY_MENU)) {
            vpos = 0;
            state = ST_START;
          }
        }
      }

      if (state == ST_OPEN_DIR) {
        index = 0;
        fr = f_opendir(&Dj, ".");
        if (fr == FR_OK) {
          state = ST_FILE_LIST;
          nameCount = fillNames(0);
          hpos = 0;
          vpos = 0;
        }
      }

      if (state == ST_FILE_LIST) {
        uint32_t limit = 6;
        if (nameCount < limit) {
          limit = nameCount;
        }
        maxhsize = 0;
        for (uint32_t i=0; i<limit; i++) {
          uint32_t x;
          x = strlen(Filenames[i]);
          if (x > maxhsize) {
            maxhsize = x;
          }
          if (x > DISPLAY_CHAR_WIDTH) {
            if (hpos + DISPLAY_CHAR_WIDTH > x) {
              x = x - DISPLAY_CHAR_WIDTH;
            }
            else {
              x = hpos;
            }
          }
          else {
            x = 0;
          }
          lcd_putsnAtt(INDENT_WIDTH, 16 + FH * i, &Filenames[i][x], DISPLAY_CHAR_WIDTH, 0);
        }

        if (event == EVT_KEY_REPT(BOOT_KEY_DOWN) || event == EVT_KEY_FIRST(BOOT_KEY_DOWN)) {
          if (vpos < limit - 1) {
            vpos += 1;
          }
          else {
            if (nameCount > limit) {
              index += 1;
              nameCount = fillNames(index);
            }
          }
        }
        else if (event == EVT_KEY_REPT(BOOT_KEY_UP) || event == EVT_KEY_FIRST(BOOT_KEY_UP)) {
          if (vpos > 0) {
            vpos -= 1;
          }
          else {
            if (index) {
              index -= 1;
              nameCount = fillNames(index);
            }
          }
        }
#if !defined(PCBTARANIS)
        else if (event == EVT_KEY_REPT(BOOT_KEY_RIGHT) || event == EVT_KEY_FIRST(BOOT_KEY_RIGHT)) {
          if (hpos + DISPLAY_CHAR_WIDTH < maxhsize) {
            hpos += 1;
          }
        }
        else if (event == EVT_KEY_REPT(BOOT_KEY_LEFT) || event == EVT_KEY_FIRST(BOOT_KEY_LEFT)) {
          if (hpos) {
            hpos -= 1;
          }
        }
#endif
        else if (event == EVT_KEY_BREAK(BOOT_KEY_MENU)) {
          // Select file to flash
          state = ST_FLASH_CHECK;
          Valid = 0;
        }
        else if (event == EVT_KEY_FIRST(BOOT_KEY_EXIT)) {
          state = ST_START;
          vpos = 0;
        }

        lcd_invert_line(2 + vpos);
      }

      else if (state == ST_FLASH_CHECK) {
        int result = menuFlashFile(vpos, event);
        FirmwareSize = FileSize[vpos] - BOOTLOADER_SIZE;
        if (result == 0) {
          // canceled
          state = ST_FILE_LIST;
        }
        else if (result == 1) {
          // confirmed
          firmwareAddress = FIRMWARE_ADDRESS + BOOTLOADER_SIZE;
          firmwareWritten = 0;
          eepromAddress = 0;
          eepromWritten = 0;
          state = ST_FLASHING;
        }
      }

      else if (state == ST_FLASHING) {
        // commit to flashing
        lcd_putsLeft(4*FH, "\032Writing...");
        
        if (!unlocked && (memoryType == MEM_FLASH)) {
          unlocked = 1;
          unlockFlash();
        }
        
        int progress;
        if (memoryType == MEM_FLASH) {
          writeFlashBlock();
          firmwareWritten += sizeof(Block_buffer);
          progress = (200*firmwareWritten) / FirmwareSize;
        }
        else {
          writeEepromBlock();
          eepromWritten += sizeof(Block_buffer);
          progress = (200*eepromWritten) / EESIZE;
        }

        lcd_rect( 3, 6*FH+4, 204, 7);
        lcd_hline(5, 6*FH+6, progress, FORCE);
        lcd_hline(5, 6*FH+7, progress, FORCE);
        lcd_hline(5, 6*FH+8, progress, FORCE);

        fr = f_read(&FlashFile, (BYTE *)Block_buffer, sizeof(Block_buffer), &BlockCount);
        if (BlockCount == 0) {
          state = ST_FLASH_DONE; // EOF
        }
        if (firmwareWritten >= FLASHSIZE - BOOTLOADER_SIZE) {
          state = ST_FLASH_DONE; // Backstop
        }
        if (eepromWritten >= EESIZE) {
          state = ST_FLASH_DONE; // Backstop
        }
      }

      if (state == ST_FLASH_DONE) {
        if (unlocked) {
          lockFlash();
          unlocked = 0;
        }
        lcd_putsLeft(4*FH, "\024Writing Complete");
        if (event == EVT_KEY_FIRST(BOOT_KEY_EXIT) || event == EVT_KEY_BREAK(BOOT_KEY_MENU)) {
          state = ST_START;
          vpos = 0;
        }
      }

      if (event == EVT_KEY_LONG(BOOT_KEY_EXIT)) {
        state = ST_REBOOT;
      }

      lcdRefresh();

      if (PowerUpDelay < 20) {	// 200 mS
        PowerUpDelay += 1;
      }
      else {
        sdPoll10ms();
      }
    }

    if (state != ST_FLASHING && state != ST_USB) {
#if defined(REV9E)
      if (pwrPressed()) {
#else
      if (pwrCheck() == e_power_off) {
#endif
        lcdOff(); // this drains LCD caps
        pwrOff();
        for (;;) {
          // Wait for power to go off
        }
      }
    }

    if (state == ST_REBOOT) {
      if (readKeys() == 0) {
        lcd_clear();
        lcdRefresh();
        lcdRefreshWait();
        RCC->CSR |= RCC_CSR_RMVF;   //clear the reset flags in RCC clock control & status register
        NVIC_SystemReset();
      }
    }
  }

  return 0;
}
Example #17
0
/** Play FLA movies
	@param flaName FLA movie name */
void playFlaMovie(int8 *flaName) {
	int32 i;
	int32 quit = 0;
	int32 currentFrame;
	int16 tmpValue;
	int8 fileNamePath[256];

	stopSamples();

	// Play FLA PCX instead of movies
	if (cfgfile.Movie == CONF_MOVIE_FLAPCX) {
		fla_pcxList(flaName);
		return;
	}

	stopMusic();

	// take extension if movie name has it
	for (i = 0; i < (int32)strlen(flaName); i++) {
		if(flaName[i] == '.') {
			flaName[i] = 0;
		}
	}

	sprintf(fileNamePath, FLA_DIR);
	strcat(fileNamePath, flaName);
	strcat(fileNamePath, FLA_EXT);

	_fadeOut = -1;
	fadeOutFrames = 0;

	if (!fropen2(&frFla, fileNamePath, "rb"))
		return;

	workVideoBufferCopy = workVideoBuffer;

	frread(&frFla, &flaHeaderData.version, 6);
	frread(&frFla, &flaHeaderData.numOfFrames, 4);
	frread(&frFla, &flaHeaderData.speed, 1);
	frread(&frFla, &flaHeaderData.var1, 1);
	frread(&frFla, &flaHeaderData.xsize, 2);
	frread(&frFla, &flaHeaderData.ysize, 2);

	frread(&frFla, &samplesInFla, 2);
	frread(&frFla, &tmpValue, 2);

	for (i = 0; i < samplesInFla; i++) {
		int16 var0;
		int16 var1;
		frread(&frFla, &var0, 2);
		frread(&frFla, &var1, 2);
		flaSampleTable[i] = var0;
	}

	if (!strcmp(flaHeaderData.version, "V1.3")) {
		currentFrame = 0;

		if (!quit) {
			do {
				if (currentFrame == flaHeaderData.numOfFrames)
					quit = 1;
				else {
					processFrame();
					scaleFla2x();
					copyScreen(workVideoBuffer, frontVideoBuffer);

					// Only blit to screen if isn't a fade
					if (_fadeOut == -1) {
						convertPalToRGBA(palette, paletteRGBACustom);
						if (!currentFrame) // fade in the first frame
							fadeIn(paletteRGBACustom);
						else
							setPalette(paletteRGBACustom);
					}

					// TRICKY: fade in tricky
					if (fadeOutFrames >= 2) {
						flip();
						convertPalToRGBA(palette, paletteRGBACustom);
						fadeToPal(paletteRGBACustom);
						_fadeOut = -1;
						fadeOutFrames = 0;
					}

					currentFrame++;

					fpsCycles(flaHeaderData.speed + 1);

					readKeys();

					if (skipIntro)
						break;
				}
			} while (!quit);
		}
	}
	
	if (cfgfile.CrossFade) {
		crossFade(frontVideoBuffer, paletteRGBACustom);
	} else {
		fadeToBlack(paletteRGBACustom);
	}

	stopSamples();
}
Example #18
0
void Wallet::handleChallengeOwnershipPacket(QSharedPointer<ReceivedMessage> packet, SharedNodePointer sendingNode) {
    auto nodeList = DependencyManager::get<NodeList>();

    // With EC keys, we receive a nonce from the metaverse server, which is signed
    // here with the private key and returned.  Verification is done at server.

    bool challengeOriginatedFromClient = packet->getType() == PacketType::ChallengeOwnershipRequest;
    int status;
    int certIDByteArraySize;
    int textByteArraySize;
    int challengingNodeUUIDByteArraySize;

    packet->readPrimitive(&certIDByteArraySize);
    packet->readPrimitive(&textByteArraySize);  // returns a cast char*, size
    if (challengeOriginatedFromClient) {
        packet->readPrimitive(&challengingNodeUUIDByteArraySize);
    }

    // "encryptedText"  is now a series of random bytes, a nonce
    QByteArray certID = packet->read(certIDByteArraySize);
    QByteArray text = packet->read(textByteArraySize);
    QByteArray challengingNodeUUID;
    if (challengeOriginatedFromClient) {
        challengingNodeUUID = packet->read(challengingNodeUUIDByteArraySize);
    }

    EC_KEY* ec = readKeys(keyFilePath().toStdString().c_str());
    QString sig;

   if (ec) {
        ERR_clear_error();
        sig = signWithKey(text, ""); // base64 signature, QByteArray cast (on return) to QString FIXME should pass ec as string so we can tell which key to sign with
        status = 1;
    } else {
        qCDebug(commerce) << "During entity ownership challenge, creating the EC-signed nonce failed.";
        status = -1;
    }

    EC_KEY_free(ec);

    QByteArray textByteArray;
    if (status > -1) {
        textByteArray = sig.toUtf8();
    }
    textByteArraySize = textByteArray.size();
    int certIDSize = certID.size();
    // setup the packet
    if (challengeOriginatedFromClient) {
        auto textPacket = NLPacket::create(PacketType::ChallengeOwnershipReply,
            certIDSize + textByteArraySize + challengingNodeUUIDByteArraySize + 3 * sizeof(int),
            true);

        textPacket->writePrimitive(certIDSize);
        textPacket->writePrimitive(textByteArraySize);
        textPacket->writePrimitive(challengingNodeUUIDByteArraySize);
        textPacket->write(certID);
        textPacket->write(textByteArray);
        textPacket->write(challengingNodeUUID);

        qCDebug(commerce) << "Sending ChallengeOwnershipReply Packet containing signed text" << textByteArray << "for CertID" << certID;

        nodeList->sendPacket(std::move(textPacket), *sendingNode);
    } else {
        auto textPacket = NLPacket::create(PacketType::ChallengeOwnership, certIDSize + textByteArraySize + 2 * sizeof(int), true);

        textPacket->writePrimitive(certIDSize);
        textPacket->writePrimitive(textByteArraySize);
        textPacket->write(certID);
        textPacket->write(textByteArray);

        qCDebug(commerce) << "Sending ChallengeOwnership Packet containing signed text" << textByteArray << "for CertID" << certID;

        nodeList->sendPacket(std::move(textPacket), *sendingNode);
    }

    if (status == -1) {
        qCDebug(commerce) << "During entity ownership challenge, signing the text failed.";
        long error = ERR_get_error();
        if (error != 0) {
            const char* error_str = ERR_error_string(error, NULL);
            qCWarning(entities) << "EC error:" << error_str;
        }
    }
}
/*
 * Prompts the user for a file to load.
 * Returns a pointer to a newly-allocated string. The caller is responsible
 * for free()ing it.
 */
char* startFileChooser() {
    char* retval;
    char cwd[256];
    getcwd(cwd, 256);
    DIR* dp = opendir(cwd);
    struct dirent *entry;
    if (dp == NULL) {
        iprintf("Error opening directory.\n");
        return 0;
    }
    while (true) {
        numFiles=0;
        std::vector<char*> filenames;
        std::vector<bool> directory;
        while ((entry = readdir(dp)) != NULL) {
            char* ext = strrchr(entry->d_name, '.')+1;
            if (entry->d_type & DT_DIR || strcmpi(ext, "cgb") == 0 || strcmpi(ext, "gbc") == 0 || strcmpi(ext, "gb") == 0 || strcmpi(ext, "sgb") == 0 ||
					strcmpi(ext, "gbs") == 0) {
                if (!(strcmp(".", entry->d_name) == 0)) {
                    directory.push_back(entry->d_type & DT_DIR);
                    char *name = (char*)malloc(sizeof(char)*(strlen(entry->d_name)+1));
                    strcpy(name, entry->d_name);
                    filenames.push_back(name);
                    numFiles++;
                }
            }
        }

        quickSort(filenames, directory, nameSortFunction, 0, numFiles - 1);

        scrollY=0;
        updateScrollDown();
        bool readDirectory = false;
        while (!readDirectory) {
            consoleClear();
            for (int i=scrollY; i<scrollY+filesPerPage && i<numFiles; i++) {
                if (i == fileSelection)
                    iprintf("* ");
                else if (i == scrollY && i != 0)
                    iprintf("^ ");
                else if (i == scrollY+filesPerPage-1 && scrollY+filesPerPage-1 != numFiles-1)
                    iprintf("v ");
                else
                    iprintf("  ");
                char outBuffer[32];

                int maxLen = 29;
                if (directory[i])
                    maxLen--;
                strncpy(outBuffer, filenames[i], maxLen);
                outBuffer[maxLen] = '\0';
                if (directory[i])
                    iprintf("%s/\n", outBuffer);
                else
                    iprintf("%s\n", outBuffer);
            }

            while (true) {
                swiWaitForVBlank();
                readKeys();
                if (keyJustPressed(KEY_A)) {
                    if (directory[fileSelection]) {
                        closedir(dp);
                        dp = opendir(filenames[fileSelection]);
                        chdir(filenames[fileSelection]);
                        readDirectory = true;
                        break;
                    }
                    else {
                        // Copy the result to a new allocation, as the
                        // filename would become unavailable when freed.
                        retval = (char*) malloc(sizeof(char) * (strlen(filenames[fileSelection]) + 1));
                        strcpy(retval, filenames[fileSelection]);
                        // free memory used for filenames in this dir
                        for (int i=0; i<numFiles; i++) {
                            free(filenames[i]);
                        }
                        goto end;
                    }
                }
                else if (keyJustPressed(KEY_B)) {
                    if (numFiles >= 1 && strcmp(filenames[0], "..") == 0) {
                        closedir(dp);
                        dp = opendir("..");
                        chdir("..");
                        readDirectory = true;
                        break;
                    }
                }
                else if (keyPressedAutoRepeat(KEY_UP)) {
                    if (fileSelection > 0) {
                        fileSelection--;
                        updateScrollUp();
                        break;
                    }
                }
                else if (keyPressedAutoRepeat(KEY_DOWN)) {
                    if (fileSelection < numFiles-1) {
                        fileSelection++;
                        updateScrollDown();
                        break;
                    }
                }
                else if (keyPressedAutoRepeat(KEY_RIGHT)) {
                    fileSelection += filesPerPage/2;
                    updateScrollDown();
                    break;
                }
                else if (keyPressedAutoRepeat(KEY_LEFT)) {
                    fileSelection -= filesPerPage/2;
                    updateScrollUp();
                    break;
                }
            }
        }
        // free memory used for filenames
        for (int i=0; i<numFiles; i++) {
            free(filenames[i]);
        }
        fileSelection = 0;
    }
end:
    closedir(dp);
    consoleClear();
    return retval;
}
Example #20
0
//-------------------------------------------------------------------------
void mainLoop()
{
	beginFrame();
	readKeys();

	switch(m_gameState)
	{
		case GSTATE_PreFrontEnd:
			m_scrollText = 0;
			m_userKeyBits = 0;
			m_timer = 0;
			m_lives = 3;
			m_willy.position.x = 29*8;
			m_willy.position.y = 64+8;
			m_willy.direction = 1;
			m_score = 0;
			m_oldScore = 0;
			m_gameState = GSTATE_FrontEnd;
			renderFrontEnd(FERState_PreRender);
			drawScores();
			
		case GSTATE_FrontEnd:
		{
			char feState;

			if(!m_userKeyBits)
			{
				if(++m_timer > FETime)
				{
					m_timer = 0;
					m_gameState = GSTATE_TextScroll;
					m_scrollText = (char*)szIntroText;
					feState = FERState_PreTextScroll;
				}
				else
				{
					feState = FERState_TitleFlash;
				}
			}
			else
			{
				m_gameState = GSTATE_PrePreIngame;
				feState = FERState_Cleanup;
			}

			renderFrontEnd(feState);
			
			break;
		}
			
		case GSTATE_TextScroll:
		{
			char feState = FERState_NOP;
			
			if(!m_userKeyBits)
			{
				if(++m_timer > ScrollTimer)
				{
					if(!*(++m_scrollText))
					{
						m_gameState = GSTATE_PreDemo;
						feState = FERState_Cleanup;
					}
					m_timer = 0;
				}
			}
			else 
			{
				m_gameState = GSTATE_PrePreIngame;
				feState = FERState_Cleanup;
			}

			renderFrontEnd(feState);
			
			break;
		}
			
		case GSTATE_PreDemo:
			m_timer = 0;
			m_level = LEVEL_Central_Cavern;
			prepLevel();
			m_gameState = GSTATE_Demo;
			
		case GSTATE_Demo:
		{
			if(m_userKeyBits)
				m_gameState = GSTATE_PreFrontEnd;
			else
			{
				runGame();
				if(++m_timer > DemoTime)
				{
					m_timer = 0;
					if(LEVEL_The_Final_Barrier < ++m_level)
						m_gameState = GSTATE_PreFrontEnd;
					else
						prepLevel();
				}	
			}
			break;
		}
			
		case GSTATE_PrePreIngame:
			m_level = LEVEL_Central_Cavern;
			m_gameState = GSTATE_PreIngame;
			
		case GSTATE_PreIngame:
			m_userKeyBits = 0;
			m_hMotion = 0;
			prepLevel();
			m_gameState = GSTATE_Ingame;
			
		case GSTATE_Ingame:
		{
			char state = runGame();
			if(ColDie == state)
				m_gameState = GSTATE_PreDied;
			else if(ColDoor == state)
				m_gameState = GSTATE_PreBeatLevel;
			break;
		}
			
		case GSTATE_PreBeatLevel:
			m_gameState = GSTATE_BeatLevel;
	
		case GSTATE_BeatLevel:
			m_score += 24;
			drawScores();
			m_airAmount -= 2 * AirScaler; 
			if(m_airAmount <= 0)
			{
				m_airAmount = 0;
				if(LEVEL_The_Final_Barrier != m_level)
				{
					++m_level;
					m_gameState = GSTATE_PreIngame;
				}
				else
				{
					m_gameState = GSTATE_Won;
				}
			}
			renderFrame();
			break;
			
		case GSTATE_PreDied:
			--m_lives;
			undrawLife();
			renderFrontEnd(FERState_FlashColour);
			if(!m_lives)
				m_gameState = GSTATE_PreLost;
			else
				m_gameState = GSTATE_PreIngame;
			break;
			
		case GSTATE_PreLost:
			m_level = LEVEL_The_Final_Barrier+1;
			setupLostScreen();
			prepLevel();
			m_gameState = GSTATE_Lost;
			
		case GSTATE_Lost:
			if(renderLostScreen())		
				m_gameState = GSTATE_PreFrontEnd;
			break;
			
		case GSTATE_Won:
			m_gameState = GSTATE_PreFrontEnd;
			break;
	}
	syncEndFrame();
}