예제 #1
0
void
StrategyChoiceManager::unsetStrategy(ControlParameters& parameters,
                                     ControlResponse& response)
{
  ndn::nfd::StrategyChoiceUnsetCommand command;

  if (!validateParameters(command, parameters))
    {
      static const Name ROOT_PREFIX;
      if (parameters.hasName() && parameters.getName() == ROOT_PREFIX)
        {
          NFD_LOG_DEBUG("strategy-choice result: FAIL reason: unset-root");
          setResponse(response, 403, "Cannot unset root prefix strategy");
        }
      else
        {
          NFD_LOG_DEBUG("strategy-choice result: FAIL reason: malformed");
          setResponse(response, 400, "Malformed command");
        }
      return;
    }

  m_strategyChoice.erase(parameters.getName());

  NFD_LOG_DEBUG("strategy-choice result: SUCCESS");
  setResponse(response, 200, "Success", parameters.wireEncode());
}
예제 #2
0
void
StrategyChoiceManager::setStrategy(ControlParameters& parameters,
                                   ControlResponse& response)
{
  ndn::nfd::StrategyChoiceSetCommand command;

  if (!validateParameters(command, parameters))
    {
      NFD_LOG_DEBUG("strategy-choice result: FAIL reason: malformed");
      setResponse(response, 400, "Malformed command");
      return;
    }

  const Name& prefix = parameters.getName();
  const Name& selectedStrategy = parameters.getStrategy();

  if (!m_strategyChoice.hasStrategy(selectedStrategy))
    {
      NFD_LOG_DEBUG("strategy-choice result: FAIL reason: unknown-strategy: "
                    << parameters.getStrategy());
      setResponse(response, 504, "Unsupported strategy");
      return;
    }

  if (m_strategyChoice.insert(prefix, selectedStrategy))
    {
      NFD_LOG_DEBUG("strategy-choice result: SUCCESS");
      setResponse(response, 200, "Success", parameters.wireEncode());
    }
  else
    {
      NFD_LOG_DEBUG("strategy-choice result: FAIL reason: not-installed");
      setResponse(response, 405, "Strategy not installed");
    }
}
예제 #3
0
void FuzzyCom::parseLog(char **tokens, int size) {
  if (size == 2) {
    logger.setTopic(tokens[1]);
    setResponse("Scoping logs");
  } else if (size == 1) {
    logger.setAllTopics();
    setResponse("Showing all logs");
  } else {
    setResponse("Invalid log command");
  }
}
예제 #4
0
void
StrategyChoiceManager::onValidatedStrategyChoiceRequest(const shared_ptr<const Interest>& request)
{
  static const Name::Component VERB_SET("set");
  static const Name::Component VERB_UNSET("unset");

  const Name& command = request->getName();
  const Name::Component& parameterComponent = command[COMMAND_PREFIX.size() + 1];

  ControlParameters parameters;
  if (!extractParameters(parameterComponent, parameters))
    {
      sendResponse(command, 400, "Malformed command");
      return;
    }

  const Name::Component& verb = command[COMMAND_PREFIX.size()];
  ControlResponse response;
  if (verb == VERB_SET)
    {
      setStrategy(parameters, response);
    }
  else if (verb == VERB_UNSET)
    {
      unsetStrategy(parameters, response);
    }
  else
    {
      NFD_LOG_DEBUG("command result: unsupported verb: " << verb);
      setResponse(response, 501, "Unsupported command");
    }

  sendResponse(command, response);
}
예제 #5
0
파일: queries.cpp 프로젝트: Zeirison/ark
void PasswordNeededQuery::execute()
{
    qCDebug(ARK) << "Executing password prompt";

    // If we are being called from the KPart, the cursor is probably Qt::WaitCursor
    // at the moment (#231974)
    QApplication::setOverrideCursor(QCursor(Qt::ArrowCursor));

    QPointer<KPasswordDialog> dlg = new KPasswordDialog;
    dlg.data()->setPrompt(xi18nc("@info", "The archive <filename>%1</filename> is password protected. Please enter the password.",
                                 m_data.value(QStringLiteral("archiveFilename")).toString()));

    if (m_data.value(QStringLiteral("incorrectTryAgain")).toBool()) {
        dlg.data()->showErrorMessage(i18n("Incorrect password, please try again."), KPasswordDialog::PasswordError);
    }

    const bool notCancelled = dlg.data()->exec();
    const QString password = dlg.data()->password();

    m_data[QStringLiteral("password")] = password;
    setResponse(notCancelled && !password.isEmpty());

    QApplication::restoreOverrideCursor();

    delete dlg.data();
}
예제 #6
0
파일: queries.cpp 프로젝트: Zeirison/ark
void OverwriteQuery::execute()
{
    // If we are being called from the KPart, the cursor is probably Qt::WaitCursor
    // at the moment (#231974)
    QApplication::setOverrideCursor(QCursor(Qt::ArrowCursor));

    KIO::RenameDialog_Options options = KIO::RenameDialog_Overwrite | KIO::RenameDialog_Skip;
    if (m_noRenameMode) {
        options = options | KIO::RenameDialog_NoRename;
    }
    if (m_multiMode) {
        options = options | KIO::RenameDialog_MultipleItems;
    }

    QUrl sourceUrl = QUrl::fromLocalFile(QDir::cleanPath(m_data.value(QStringLiteral("filename")).toString()));
    QUrl destUrl = QUrl::fromLocalFile(QDir::cleanPath(m_data.value(QStringLiteral("filename")).toString()));

    QPointer<KIO::RenameDialog> dialog = new KIO::RenameDialog(
        Q_NULLPTR,
        i18nc("@title:window", "File Already Exists"),
        sourceUrl,
        destUrl,
        options);
    dialog.data()->exec();

    m_data[QStringLiteral("newFilename")] = dialog.data()->newDestUrl().toDisplayString(QUrl::PreferLocalFile);

    setResponse(dialog.data()->result());

    delete dialog.data();

    QApplication::restoreOverrideCursor();
}
예제 #7
0
bool Transport::splitHeader(CStrRef header, String &name, const char *&value) {
  int pos = header.find(':');

  if (pos != String::npos) {
    name = header.substr(0, pos);
    value = header.data() + pos;

    do {
      value++;
    } while (*value == ' ');

    return true;
  }

  // header("HTTP/1.0 404 Not Found");
  // header("HTTP/1.0 404");
  if (strncasecmp(header.data(), "http/", 5) == 0) {
    int pos1 = header.find(' ');
    if (pos1 != String::npos) {
      int pos2 = header.find(' ', pos1 + 1);
      if (pos2 == String::npos) pos2 = header.size();
      if (pos2 - pos1 > 1) {
        setResponse(atoi(header.data() + pos1),
                    getResponseInfo().empty() ? "splitHeader"
                                              : getResponseInfo().c_str()
                   );
        return false;
      }
    }
  }

  throw InvalidArgumentException("header", header.c_str());
}
예제 #8
0
void Transport::addHeaderNoLock(const char *name, const char *value) {
  assert(name && *name);
  assert(value);

  if (!m_firstHeaderSet) {
    m_firstHeaderSet = true;
    m_firstHeaderFile = g_vmContext->getContainingFileName().data();
    m_firstHeaderLine = g_vmContext->getLine();
  }

  string svalue = value;
  Util::replaceAll(svalue, "\n", "");
  m_responseHeaders[name].push_back(svalue);

  if (strcasecmp(name, "Location") == 0 && m_responseCode != 201 &&
      !(m_responseCode >= 300 && m_responseCode <=307)) {
    /* Zend seems to set 303 on a post with HTTP version > 1.0 in the code but
     * in our testing we can only get it to give 302.
    Method m = getMethod();
    if (m != Method::GET && m != Method::HEAD) {
      setResponse(303);
    } else {
      setResponse(302);
    }
    */
    setResponse(302, "forced.302");
  }
}
예제 #9
0
void Transport::redirect(const char *location, int code /* = 302 */,
                         const char *info) {
  FiberWriteLock lock(this);
  addHeaderImpl("Location", location);
  setResponse(code, info);
  sendStringLocked(location, code);
}
예제 #10
0
FuzzyCom::FuzzyCom() {
  currentPos = 0;
  clearBuffer();
  for (int i = 0; i < 32; i++) {
    variables[i] = 0;
  }
  setResponse("No messages yet");
}
예제 #11
0
void CachedResource::responseReceived(const ResourceResponse& response)
{
    setResponse(response);
    m_responseTimestamp = std::chrono::system_clock::now();
    String encoding = response.textEncodingName();
    if (!encoding.isNull())
        setEncoding(encoding);
}
예제 #12
0
void CachedResource::responseReceived(const ResourceResponse& response)
{
    setResponse(response);
    m_responseTimestamp = currentTime();
    String encoding = response.textEncodingName();
    if (!encoding.isNull())
        setEncoding(encoding);
}
예제 #13
0
void FuzzyCom::parseGet(char **tokens, int size) {
  if (size == 2) {
    int var = atoi(tokens[1]);
    int val = get(var);
    sprintf(response, "get %d = %d", var, val);
  } else {
    setResponse("Invalid get command");
  }
}
예제 #14
0
void
FibManager::removeNextHop(ControlParameters& parameters,
                          ControlResponse& response)
{
  ndn::nfd::FibRemoveNextHopCommand command;
  if (!validateParameters(command, parameters))
    {
      NFD_LOG_DEBUG("remove-nexthop result: FAIL reason: malformed");
      setResponse(response, 400, "Malformed command");
      return;
    }

  NFD_LOG_TRACE("remove-nexthop prefix: " << parameters.getName()
                << " faceid: " << parameters.getFaceId());

  shared_ptr<Face> faceToRemove = m_getFace(parameters.getFaceId());
  if (static_cast<bool>(faceToRemove))
    {
      shared_ptr<fib::Entry> entry = m_managedFib.findExactMatch(parameters.getName());
      if (static_cast<bool>(entry))
        {
          entry->removeNextHop(faceToRemove);
          NFD_LOG_DEBUG("remove-nexthop result: OK prefix: " << parameters.getName()
                        << " faceid: " << parameters.getFaceId());

          if (!entry->hasNextHops())
            {
              m_managedFib.erase(*entry);
            }
        }
      else
        {
          NFD_LOG_DEBUG("remove-nexthop result: OK, but entry for face id "
                        << parameters.getFaceId() << " not found");
        }
    }
  else
    {
      NFD_LOG_DEBUG("remove-nexthop result: OK, but face id "
                    << parameters.getFaceId() << " not found");
    }

  setResponse(response, 200, "Success", parameters.wireEncode());
}
예제 #15
0
void
FibManager::addNextHop(ControlParameters& parameters,
                       ControlResponse& response)
{
  ndn::nfd::FibAddNextHopCommand command;

  if (!validateParameters(command, parameters))
    {
      NFD_LOG_DEBUG("add-nexthop result: FAIL reason: malformed");
      setResponse(response, 400, "Malformed command");
      return;
    }

  const Name& prefix = parameters.getName();
  FaceId faceId = parameters.getFaceId();
  uint64_t cost = parameters.getCost();

  NFD_LOG_TRACE("add-nexthop prefix: " << prefix
                << " faceid: " << faceId
                << " cost: " << cost);

  shared_ptr<Face> nextHopFace = m_getFace(faceId);
  if (static_cast<bool>(nextHopFace))
    {
      shared_ptr<fib::Entry> entry = m_managedFib.insert(prefix).first;

      entry->addNextHop(nextHopFace, cost);

      NFD_LOG_DEBUG("add-nexthop result: OK"
                    << " prefix:" << prefix
                    << " faceid: " << faceId
                    << " cost: " << cost);

      setResponse(response, 200, "Success", parameters.wireEncode());
    }
  else
    {
      NFD_LOG_DEBUG("add-nexthop result: FAIL reason: unknown-faceid: " << faceId);
      setResponse(response, 410, "Face not found");
    }
}
예제 #16
0
void WalkEncounter::respondTo(std::string input)
{
	_fCode = WALK_ENC_RETURN_TO_WALK;
	if (input == BASE_ENC_INPUT_HELP) {
		setResponse("You can type 'north/south/east/west' to move in this world!\nType 'character' to see your stats\nType 'quit' to exit\n");
	}else if (input == WALK_ENC_INPUT_NORTH) {
		_moveDelta = WALK_ENC_MOVE_NORTH_DELTA;
		setResponse("You walked north\n");
	}else if (input == WALK_ENC_INPUT_SOUTH) {
		_moveDelta = WALK_ENC_MOVE_SOUTH_DELTA;
		setResponse("You walked south\n");
	}else if (input == WALK_ENC_INPUT_WEST) {
		setResponse("You walked west\n");
		_moveDelta = WALK_ENC_MOVE_WEST_DELTA;
	}
	else if (input == WALK_ENC_INPUT_EAST) {
		_moveDelta = WALK_ENC_MOVE_EAST_DELTA;
		setResponse("You walked east\n");
	}else if (input == WALK_ENC_INPUT_CS) {
		setResponse("You looking at yourself\n");
		ignoreMove = true;
		_fCode = WALK_ENC_RETURN_TO_CS;
	}else {
		Encounter::respondTo(input);
	}
}
예제 #17
0
파일: queries.cpp 프로젝트: Zeirison/ark
void LoadCorruptQuery::execute()
{
    qCDebug(ARK) << "Executing LoadCorrupt prompt";
    QApplication::setOverrideCursor(QCursor(Qt::ArrowCursor));

    setResponse(KMessageBox::warningYesNo(Q_NULLPTR,
                                          xi18nc("@info", "The archive you're trying to open is corrupt.<nl/>"
                                                 "Some files may be missing or damaged."),
                                          i18nc("@title:window", "Corrupt archive"),
                                          KGuiItem(i18nc("@action:button", "Open as Read-Only")),
                                          KGuiItem(i18nc("@action:button", "Don't Open"))));
    QApplication::restoreOverrideCursor();
}
예제 #18
0
void TaskManagementMainTab::logoutButtonClicked() {
    auto url = state->taskState->host + "/knossos/session/";
    httpResponse response;
    response.length = 0;
    response.content = (char *)calloc(1, 10240);
    long httpCode;
    CURLcode code;

    setCursor(Qt::WaitCursor);
    bool result = taskState::httpDELETE(url.toUtf8().data(), &response, &httpCode, state->taskState->cookieFile.toUtf8().data(), &code, 5);
    setCursor(Qt::ArrowCursor);

    if(result == false) {
        setResponse("<font color='red'>Request failed. Please check your connection.</font>");
    }
    if(code == CURLE_OK) {
        resetSession("<font color='green'>Logged out successfully.</font>");
    } else {
        setResponse("<font color='red'>Request failed. Please check your connection.</font>");
    }

    free(response.content);
}
예제 #19
0
bool DocumentLoader::maybeLoadEmpty()
{
    bool shouldLoadEmpty = !m_substituteData.isValid() && (m_request.url().isEmpty() || SchemeRegistry::shouldLoadURLSchemeAsEmptyDocument(m_request.url().protocol()));
    if (!shouldLoadEmpty && !frameLoader()->client()->representationExistsForURLScheme(m_request.url().protocol()))
        return false;

    m_loadingEmptyDocument = true;
    if (m_request.url().isEmpty() && !frameLoader()->stateMachine()->creatingInitialEmptyDocument())
        m_request.setURL(blankURL());
    String mimeType = shouldLoadEmpty ? "text/html" : frameLoader()->client()->generatedMIMETypeForURLScheme(m_request.url().protocol());
    setResponse(ResourceResponse(m_request.url(), mimeType, 0, String(), String()));
    finishedLoading();
    return true;
}
예제 #20
0
void NetworkInterfaceMock::_cancelCommand_inlock(const CallbackHandle& cbHandle,
                                                 const ResponseStatus& response) {
    auto matchFn = stdx::bind(&NetworkOperation::isForCallback, stdx::placeholders::_1, cbHandle);
    for (auto list : {&_unscheduled, &_blackHoled, &_scheduled}) {
        auto noi = std::find_if(list->begin(), list->end(), matchFn);
        if (noi == list->end()) {
            continue;
        }
        _scheduled.splice(_scheduled.begin(), *list, noi);
        noi->setResponse(_now_inlock(), response);
        return;
    }
    // No not-in-progress network command matched cbHandle.  Oh, well.
}
void Resource::responseReceived(const ResourceResponse& response, PassOwnPtr<WebDataConsumerHandle>)
{
    m_responseTimestamp = currentTime();

    if (!m_revalidatingRequest.isNull()) {
        if (response.httpStatusCode() == 304) {
            revalidationSucceeded(response);
            return;
        }
        revalidationFailed();
    }

    setResponse(response);
    String encoding = response.textEncodingName();
    if (!encoding.isNull())
        setEncoding(encoding);
}
static Ref<Inspector::Protocol::Network::CachedResource> buildObjectForCachedResource(CachedResource* cachedResource, DocumentLoader* loader)
{
    auto resourceObject = Inspector::Protocol::Network::CachedResource::create()
        .setUrl(cachedResource->url())
        .setType(InspectorPageAgent::cachedResourceTypeJson(*cachedResource))
        .setBodySize(cachedResource->encodedSize())
        .release();

    auto resourceResponse = buildObjectForResourceResponse(cachedResource->response(), loader);
    resourceObject->setResponse(WTFMove(resourceResponse));

    String sourceMappingURL = InspectorPageAgent::sourceMapURLForResource(cachedResource);
    if (!sourceMappingURL.isEmpty())
        resourceObject->setSourceMapURL(sourceMappingURL);

    return resourceObject;
}
예제 #23
0
파일: queries.cpp 프로젝트: Zeirison/ark
void ContinueExtractionQuery::execute()
{
    qCDebug(ARK) << "Executing ContinueExtraction prompt";
    QApplication::setOverrideCursor(QCursor(Qt::ArrowCursor));

    QMessageBox box(QMessageBox::Warning,
                    i18n("Error during extraction"),
                    xi18n("Extraction of the entry:<nl/>"
                          "    <filename>%1</filename><nl/>"
                          "failed with the error message:<nl/>    %2<nl/><nl/>"
                          "Do you want to continue extraction?<nl/>", m_data.value(QStringLiteral("archiveEntry")).toString(),
                          m_data.value(QStringLiteral("error")).toString()),
                    QMessageBox::Yes|QMessageBox::Cancel);
    m_chkDontAskAgain = new QCheckBox(i18n("Don't ask again."));
    box.setCheckBox(m_chkDontAskAgain);
    setResponse(box.exec());
    QApplication::restoreOverrideCursor();
}
예제 #24
0
void FuzzyCom::parseMessage() {
  int messageLength;

  /*if (!isValidHeader()) {
    setResponse("Header mismatch");
    return;
  }
  messageLength = buffer[4];
  if (messageLength < 5 || messageLength > 255) {
    sprintf(response, "Message length invalid (%d)", messageLength);
    return;
  }


  if (strlen(buffer) + 1 != messageLength) {
    sprintf(response, "Message length mismatch (%d != %d)", messageLength, strlen(buffer) + 1);
    return;
  }

  strcpy(bufcopy, buffer + 5);
  */
  char bufcopy[255];
  strcpy(bufcopy, buffer);

  char *tokens[10];
  char *token;
  int total = 0;
  token = strtok(bufcopy, " \n");
  while (token != NULL) {
    tokens[total] = token;
    total++;
    token = strtok(NULL, " \n");
  }

  if (strcmp(tokens[0], "set") == 0) {
    parseSet(tokens, total);
  } else if (strcmp(tokens[0], "get") == 0) {
    parseGet(tokens, total);
  } else if (strcmp(tokens[0], "log") == 0) {
    parseLog(tokens, total);
  } else {
    setResponse("Command unknown");
  }
}
예제 #25
0
/**
 * CT-BCS Reset Card command
 *
 * @param ctx Reader context
 * @param lc Length of command
 * @param cmd Command
 * @param lr Length of response
 * @param rsp Response buffer
 * @return \ref OK, \ref ERR_MEMORY
 */
int ResetCard(struct scr *ctx, unsigned int lc, unsigned char *cmd,
			  unsigned int *lr, unsigned char *rsp)
{
	int response = 0;

	if (PC_to_RDR_IccPowerOn(ctx) < 0) {
		rsp[0] = HIGH(NOT_SUCCESSFUL);
		rsp[1] = LOW(NOT_SUCCESSFUL);
		*lr = 2;
		return OK;
	}

	if (RDR_APDUTransferMode(ctx))
		ccidAPDUInit(ctx);
	else
		ccidT1Init(ctx);

	if ((response = setResponse(ctx, cmd, lr, rsp)) < 0) {
		return response;
	}

	return OK;
}
예제 #26
0
void TaskManagementMainTab::loadLastSubmitButtonClicked() {
    auto url = state->taskState->host + "/knossos/activeTask/lastSubmit/";
    httpResponse response;
    response.length = 0;
    response.content = (char *)calloc(1, 10240);
    httpResponse header;
    header.length = 0;
    header.content = (char*)calloc(1, header.length + 1);
    long httpCode = 0;
    CURLcode code;

    setCursor(Qt::WaitCursor);
    bool success = taskState::httpFileGET(url.toUtf8().data(), nullptr, &response, &header, &httpCode, state->taskState->cookieFile.toUtf8().data(), &code, 10);
    setCursor(Qt::ArrowCursor);

    if(success == false) {
        resetSession(QString("<font color='red'>Could not find session cookie. Please login again.</font><br />%0").arg(response.content));
        return;
    }
    if(code != CURLE_OK) {
        setResponse(QString("<font color='red'>Request failed. Please check your connection.</font><br />%0").arg(response.content));
        return;
    }
    if(httpCode == 400) {
        setResponse(QString("<font color='red'>No submit found. Do you have an active task?</font><br />%0").arg(response.content));
        return;
    }
    else if(httpCode == 403) {
        setResponse(QString("<font color='red'>You are not authenticated. Permission denied.</font><br />%0").arg(response.content));
        return;
    }

    QDir taskDir(QStandardPaths::writableLocation(QStandardPaths::DataLocation) + "/tasks");
    taskDir.mkpath(".");

    QString tmpfilepath = taskDir.absolutePath() + "/lastSubmit.tmp.nml";
    FILE * const lastNml = fopen(tmpfilepath.toUtf8().constData(), "w");
    if (lastNml == nullptr) {
        statusLabel->setText("<font color='red'>Failed to get submit. No write permission in this folder.</font>");
        return;
    }
    fwrite(response.content, 1, response.length, lastNml);
    fclose(lastNml);

    // 200 - success. Retrieve the filename from response header and rename the previously created tmp.nml
    char filename[1024] = {};
    if (taskState::copyInfoFromHeader(filename, &header, "filename")) {
        QFile tmpfile(tmpfilepath);
        tmpfile.rename(taskDir.absolutePath() + "/" + filename);
        state->skeletonState->skeletonFileAsQString = tmpfile.fileName();
    }

    if (loadSkeletonSignal(state->skeletonState->skeletonFileAsQString) == false) {//BUG signals shall not be used to return something
        statusLabel->setText("<font color='red'>Failed to load skeleton.</font>");
    } else {
        statusLabel->setText("<font color='green'>Loaded last submit successfully.</font>");
    }

    free(header.content);
    free(response.content);
}
예제 #27
0
void Transport::redirect(const char *location, int code /* = 302 */,
                         const char *info) {
  addHeaderImpl("Location", location);
  setResponse(code, info);
  sendStringLocked("Moved", code);
}
예제 #28
0
void QGalleryAbstractRequest::execute()
{
    const int oldError = d_ptr->error;

    d_ptr->error = NoError;
    d_ptr->errorString = QString();

    if (!d_ptr->gallery) {
        d_ptr->state = Error;
        d_ptr->error = NoGallery;
        d_ptr->errorString = tr("No gallery has been set on the %1.", "%1 = class name")
                .arg(QString::fromLatin1(metaObject()->className()));

        if (d_ptr->response) {
            QScopedPointer<QGalleryAbstractResponse> oldResponse(d_ptr->response.take());

            Q_UNUSED(oldResponse);

            setResponse(0);
        }

        emit error(d_ptr->error, d_ptr->errorString);
        emit errorChanged();
    } else {
        QScopedPointer<QGalleryAbstractResponse> oldResponse(
                d_ptr->gallery.data()->createResponse(this));
        d_ptr->response.swap(oldResponse);

        if (d_ptr->response) {
            d_ptr->error = d_ptr->response->error();

            if (d_ptr->error != NoError) {
                d_ptr->errorString = d_ptr->response->errorString();
                d_ptr->state = Error;

                d_ptr->response.reset();

                if (oldResponse)
                    setResponse(0);

                emit error(d_ptr->error, d_ptr->errorString);
                emit errorChanged();
            } else {
                if (d_ptr->response->isActive()) {
                    d_ptr->state = Active;
                    d_ptr->wasIdle = false;
                } else if (d_ptr->response->isIdle()) {
                    d_ptr->state = Idle;
                    d_ptr->wasIdle = true;
                } else {
                    d_ptr->state = Finished;
                }

                connect(d_ptr->response.data(), SIGNAL(finished()), this, SLOT(_q_finished()));
                connect(d_ptr->response.data(), SIGNAL(resumed()), this, SLOT(_q_resumed()));
                connect(d_ptr->response.data(), SIGNAL(canceled()), this, SLOT(_q_canceled()));
                connect(d_ptr->response.data(), SIGNAL(progressChanged(int,int)),
                        this, SLOT(_q_progressChanged(int,int)));

                setResponse(d_ptr->response.data());
            }

            oldResponse.reset();
        } else {
예제 #29
0
bool EmulateTag::emulate(const uint16_t tgInitAsTargetTimeout){

  uint8_t command[] = {
        PN532_COMMAND_TGINITASTARGET,
        5,                  // MODE: PICC only, Passive only

        0x04, 0x00,         // SENS_RES
        0x00, 0x00, 0x00,   // NFCID1
        0x20,               // SEL_RES

        0,0,0,0,0,0,0,0,
        0,0,0,0,0,0,0,0,   // FeliCaParams
        0,0,

        0,0,0,0,0,0,0,0,0,0, // NFCID3t

        0, // length of general bytes
        0  // length of historical bytes
  };

  if(uidPtr != 0){  // if uid is set copy 3 bytes to nfcid1
    memcpy(command + 4, uidPtr, 3);
  }

  if(1 != pn532.tgInitAsTarget(command,sizeof(command), tgInitAsTargetTimeout)){
    DMSG("tgInitAsTarget failed or timed out!");
    pn532.inRelease();
    pn532.powerDown(0xF0);
    return false;
  }

  uint8_t compatibility_container[] = {
    0, 0x0F,
    0x20,
    0, 0x54,
    0, 0xFF,
    0x04,       // T
    0x06,       // L
    0xE1, 0x04, // File identifier
    ((NDEF_MAX_LENGTH & 0xFF00) >> 8), (NDEF_MAX_LENGTH & 0xFF), // maximum NDEF file size
    0x00,       // read access 0x0 = granted
    0x00        // write access 0x0 = granted | 0xFF = deny
  };

  if(tagWriteable == false){
    compatibility_container[14] = 0xFF;
  }

  tagWrittenByInitiator = false;

  uint8_t rwbuf[128];
  uint8_t sendlen;
  int16_t status;
  tag_file currentFile = NONE;
  uint16_t cc_size = sizeof(compatibility_container);
  bool runLoop = true;

  while(runLoop){
    status = pn532.tgGetData(rwbuf, sizeof(rwbuf));
    if(status < 0){
      DMSG("tgGetData failed!\n");
      pn532.inRelease();
      pn532.powerDown(0xF0);
      return true;
    }

    uint8_t p1 = rwbuf[C_APDU_P1];
    uint8_t p2 = rwbuf[C_APDU_P2];
    uint8_t lc = rwbuf[C_APDU_LC];
    uint16_t p1p2_length = ((int16_t) p1 << 8) + p2;

    switch(rwbuf[C_APDU_INS]){
    case ISO7816_SELECT_FILE:
      switch(p1){
      case C_APDU_P1_SELECT_BY_ID:
	if(p2 != 0x0c){
	  DMSG("C_APDU_P2 != 0x0c\n");
	  setResponse(COMMAND_COMPLETE, rwbuf, &sendlen);
	} else if(lc == 2 && rwbuf[C_APDU_DATA] == 0xE1 && (rwbuf[C_APDU_DATA+1] == 0x03 || rwbuf[C_APDU_DATA+1] == 0x04)){
	  setResponse(COMMAND_COMPLETE, rwbuf, &sendlen);
	  if(rwbuf[C_APDU_DATA+1] == 0x03){
	    currentFile = CC;
	  } else if(rwbuf[C_APDU_DATA+1] == 0x04){
	    currentFile = NDEF;
	  }
	} else {
	  setResponse(TAG_NOT_FOUND, rwbuf, &sendlen);
	}
	break;
      case C_APDU_P1_SELECT_BY_NAME: 
        const uint8_t ndef_tag_application_name_v2[] = {0, 0x7, 0xD2, 0x76, 0x00, 0x00, 0x85, 0x01, 0x01 };
	if(0 == memcmp(ndef_tag_application_name_v2, rwbuf + C_APDU_P2, sizeof(ndef_tag_application_name_v2))){
	  setResponse(COMMAND_COMPLETE, rwbuf, &sendlen);
	} else{
	  DMSG("function not supported\n");
	  setResponse(FUNCTION_NOT_SUPPORTED, rwbuf, &sendlen);
	} 
	break;
      }
      break;
    case ISO7816_READ_BINARY:
      switch(currentFile){
      case NONE:
	setResponse(TAG_NOT_FOUND, rwbuf, &sendlen);
	break;
      case CC:
	if( p1p2_length > NDEF_MAX_LENGTH){
	  setResponse(END_OF_FILE_BEFORE_REACHED_LE_BYTES, rwbuf, &sendlen);
	}else {
	  memcpy(rwbuf,compatibility_container + p1p2_length, lc);
	  setResponse(COMMAND_COMPLETE, rwbuf + lc, &sendlen, lc);
	}
	break;
      case NDEF:
	if( p1p2_length > NDEF_MAX_LENGTH){
	  setResponse(END_OF_FILE_BEFORE_REACHED_LE_BYTES, rwbuf, &sendlen);
	}else {
	  memcpy(rwbuf, ndef_file + p1p2_length, lc);
	  setResponse(COMMAND_COMPLETE, rwbuf + lc, &sendlen, lc);
	}
	break;
      }
      break;    
    case ISO7816_UPDATE_BINARY:
      if(!tagWriteable){
	  setResponse(FUNCTION_NOT_SUPPORTED, rwbuf, &sendlen);
      } else{      
	if( p1p2_length > NDEF_MAX_LENGTH){
	  setResponse(MEMORY_FAILURE, rwbuf, &sendlen);
	}
	else{
	  memcpy(ndef_file + p1p2_length, rwbuf + C_APDU_DATA, lc);
	  setResponse(COMMAND_COMPLETE, rwbuf, &sendlen);
	  tagWrittenByInitiator = true;
	}
      }
      break;
    default:
      DMSG("Command not supported!");
      DMSG_HEX(rwbuf[C_APDU_INS]);
      DMSG("\n");
      setResponse(FUNCTION_NOT_SUPPORTED, rwbuf, &sendlen);
    }
    status = pn532.tgSetData(rwbuf, sendlen);
    if(status < 0){
      DMSG("tgSetData failed\n!");
      pn532.inRelease();
      pn532.powerDown(0xF0);
      return true;
    }
  }
  pn532.inRelease();
  pn532.powerDown(0xF0);
  return true;
}
예제 #30
0
int SuccUBusScript::process(const TTroomScript *roomScript, const TTsentence *sentence) {
	if (!CTrueTalkManager::getStateValue(1))
		return 2;

	if (roomScript && roomScript->_scriptId == 101)
		_isRoom101 = true;

	int currState = getState();
	if (currState) {
		int currMode = sentence->_field2C;
		bool modeFlag1 = currMode == 11 || currMode == 13;
		bool modeFlag2 = currMode == 12;
		setState(0);

		switch (currState) {
		case 1:
			if (currMode == 3 || currMode == 10)
				return setResponse(70050, 0);
			break;

		case 2:
			if (modeFlag1 || modeFlag2)
				return setResponse(70070 + (getRandomBit() ? 254 : 0), 0);
			break;

		case 3:
			if (currMode == 3 || currMode == 10)
				return setResponse(70074, 0);
			break;

		case 4:
			if (currMode == 4)
				return setResponse(70077, 0);
			if (currMode == 3)
				return setResponse(getDialogueId(230117), 0);
			break;

		case 5:
			if (currMode == 3 || currMode == 10)
				return setResponse(70089, 0);
			break;

		case 6:
			if (modeFlag1)
				return setResponse(70103, 0);
			if (modeFlag2)
				return setResponse(70102, 0);
			break;

		case 7:
			if (modeFlag1)
				return setResponse(getDialogueId(230157), 0);
			break;

		case 8:
			if (modeFlag1)
				return setResponse(getDialogueId(230159), 0);
			break;

		case 9:
			if (modeFlag1)
				return setResponse(getDialogueId(230160), 0);
			break;

		case 10:
			if (modeFlag1)
				return setResponse(getDialogueId(230161), 0);
			break;

		case 11:
			if (modeFlag1)
				return setResponse(getDialogueId(230142), 0);
			break;

		case 12:
			return setResponse(70030, 0);

		default:
			break;
		}
	}

	if (processEntries(&_entries, _entryCount, roomScript, sentence) != 2) {
		uint tagId = g_vm->_trueTalkManager->_quotes.find(sentence->_normalizedLine.c_str());
		if (tagId && chooseResponse(roomScript, sentence, tagId) != 2) {
			addResponse(getDialogueId(230030));
			applyResponse();
		}
	}

	return 2;
}