char *ConstructPrimaryOutputFilename(char *infileName, char *outfileName, char command)
{
    char *algorithmName = GetAlgorithmName(command);

    if (outfileName == NULL)
    {
        // The output filename is based on the input filename
        if (theFileName != infileName)
            strcpy(theFileName, infileName);

        // If the primary output filename has not been given, then we use
        // the input filename + the algorithm name + a simple suffix
        if (strlen(algorithmName) <= ALGORITHMNAMEMAXLENGTH)
        {
            strcat(theFileName, ".");
            strcat(theFileName, algorithmName);
        }
        else
            ErrorMessage("Algorithm Name is too long, so it will not be used in output filename.");

        strcat(theFileName, ".out.txt");
    }
    else
    {
        if (strlen(outfileName) > FILENAMEMAXLENGTH)
        {
            // The output filename is based on the input filename
            if (theFileName != infileName)
                strcpy(theFileName, infileName);

            if (strlen(algorithmName) <= ALGORITHMNAMEMAXLENGTH)
            {
                strcat(theFileName, ".");
                strcat(theFileName, algorithmName);
            }
            strcat(theFileName, ".out.txt");
            sprintf(Line, "Outfile filename is too long. Result placed in %s", theFileName);
            ErrorMessage(Line);
        }
        else
        {
            if (theFileName != outfileName)
                strcpy(theFileName, outfileName);
        }
    }

    return theFileName;
}
void WriteAlgorithmResults(graphP theGraph, int Result, char command, platform_time start, platform_time end, char *infileName)
{
	if (infileName)
		 sprintf(Line, "The graph '%s' ", infileName);
	else sprintf(Line, "The graph ");
	Message(Line);

	switch (command)
	{
		case 'p' : sprintf(Line, "is%s planar.\n", Result==OK ? "" : " not"); break;
		case 'd' : sprintf(Line, "is%s planar.\n", Result==OK ? "" : " not"); break;
		case 'o' : sprintf(Line, "is%s outerplanar.\n", Result==OK ? "" : " not"); break;
		case '2' : sprintf(Line, "has %s subgraph homeomorphic to K_{2,3}.\n", Result==OK ? "no" : "a"); break;
		case '3' : sprintf(Line, "has %s subgraph homeomorphic to K_{3,3}.\n", Result==OK ? "no" : "a"); break;
		case '4' : sprintf(Line, "has %s subgraph homeomorphic to K_4.\n", Result==OK ? "no" : "a"); break;
		default  : sprintf(Line, "has not been processed due to unrecognized command.\n"); break;
	}
	Message(Line);

	sprintf(Line, "Algorithm '%s' executed in %.3lf seconds.\n",
			GetAlgorithmName(command), platform_GetDuration(start,end));
	Message(Line);
}
Example #3
0
OGRLayer *GNMGenericNetwork::GetPath(GNMGFID nStartFID, GNMGFID nEndFID,
                          GNMGraphAlgorithmType eAlgorithm, char **papszOptions)
{

    if(!m_bIsGraphLoaded && LoadGraph() != CE_None)
    {
        return NULL;
    }

    GDALDriver* poMEMDrv =
            OGRSFDriverRegistrar::GetRegistrar()->GetDriverByName("Memory");
    if (poMEMDrv == NULL)
    {
        CPLError(CE_Failure, CPLE_AppDefined, "Cannot load 'Memory' driver");
        return NULL;
    }

    GDALDataset* poMEMDS =
            poMEMDrv->Create("dummy_name", 0, 0, 0, GDT_Unknown, NULL);
    OGRSpatialReference oDstSpaRef(GetProjectionRef());
    OGRLayer* poMEMLayer = poMEMDS->CreateLayer(GetAlgorithmName(eAlgorithm,
                               true), &oDstSpaRef, wkbGeometryCollection, NULL);

    OGRGNMWrappedResultLayer* poResLayer =
                              new OGRGNMWrappedResultLayer(poMEMDS, poMEMLayer);

    const bool bReturnEdges = CPLFetchBool(papszOptions, GNM_MD_FETCHEDGES, true);
    const bool bReturnVertices = CPLFetchBool(papszOptions, GNM_MD_FETCHVERTEX, true);

    switch (eAlgorithm)
    {
    case GATDijkstraShortestPath:
        {
            GNMPATH path = m_oGraph.DijkstraShortestPath(nStartFID, nEndFID);

            // fill features in result layer
            FillResultLayer(poResLayer, path, 1, bReturnVertices, bReturnEdges);
        }
        break;
    case GATKShortestPath:
        {
            int nK = atoi(CSLFetchNameValueDef(papszOptions, GNM_MD_NUM_PATHS,
                                               "1"));

            CPLDebug("GNM", "Search %d path(s)", nK);

            std::vector<GNMPATH> paths = m_oGraph.KShortestPaths(nStartFID,
                                                                 nEndFID, nK);

            // fill features in result layer
            for(size_t i = 0; i < paths.size(); ++i)
            {
                FillResultLayer(poResLayer, paths[i], static_cast<int>(i + 1), bReturnVertices,
                                bReturnEdges);
            }
        }
        break;
    case GATConnectedComponents:
        {
            GNMVECTOR anEmitters;
            if(NULL != papszOptions)
            {
                char** papszEmitter = CSLFetchNameValueMultiple(papszOptions, GNM_MD_EMITTER);
                for(int i = 0; papszEmitter[i] != NULL; ++i)
                {
                    GNMGFID nEmitter = atol(papszEmitter[i]);
                    anEmitters.push_back(nEmitter);
                }
                CSLDestroy(papszEmitter);
            }

            if(nStartFID != -1)
            {
                anEmitters.push_back(nStartFID);
            }

            if(nStartFID != -1)
            {
                anEmitters.push_back(nEndFID);
            }

            GNMPATH path = m_oGraph.ConnectedComponents(anEmitters);

            // fill features in result layer
            FillResultLayer(poResLayer, path, 1, bReturnVertices, bReturnEdges);
        }
        break;
    }

    return poResLayer;
}
Example #4
0
already_AddRefed<Promise>
WebAuthentication::MakeCredential(JSContext* aCx, const Account& aAccount,
                  const Sequence<ScopedCredentialParameters>& aCryptoParameters,
                  const ArrayBufferViewOrArrayBuffer& aChallenge,
                  const ScopedCredentialOptions& aOptions)
{
  MOZ_ASSERT(mParent);
  nsCOMPtr<nsIGlobalObject> global = do_QueryInterface(GetParentObject());
  if (!global) {
    return nullptr;
  }

  ErrorResult rv;
  RefPtr<Promise> promise = Promise::Create(global, rv);

  nsresult initRv = InitLazily();
  if (NS_FAILED(initRv)) {
    promise->MaybeReject(initRv);
    return promise.forget();
  }

  // 4.1.1.1 If timeoutSeconds was specified, check if its value lies within a
  // reasonable range as defined by the platform and if not, correct it to the
  // closest value lying within that range.

  double adjustedTimeout = 30.0;
  if (aOptions.mTimeoutSeconds.WasPassed()) {
    adjustedTimeout = aOptions.mTimeoutSeconds.Value();
    adjustedTimeout = std::max(15.0, adjustedTimeout);
    adjustedTimeout = std::min(120.0, adjustedTimeout);
  }

  // 4.1.1.2 Let promise be a new Promise. Return promise and start a timer for
  // adjustedTimeout seconds.

  RefPtr<CredentialRequest> requestMonitor = new CredentialRequest();
  requestMonitor->SetDeadline(TimeDuration::FromSeconds(adjustedTimeout));

  if (mOrigin.EqualsLiteral("null")) {
    // 4.1.1.3 If callerOrigin is an opaque origin, reject promise with a
    // DOMException whose name is "NotAllowedError", and terminate this
    // algorithm
    MOZ_LOG(gWebauthLog, LogLevel::Debug, ("Rejecting due to opaque origin"));
    promise->MaybeReject(NS_ERROR_DOM_NOT_ALLOWED_ERR);
    return promise.forget();
  }

  nsCString rpId;
  if (!aOptions.mRpId.WasPassed()) {
    // 4.1.1.3.a If rpId is not specified, then set rpId to callerOrigin, and
    // rpIdHash to the SHA-256 hash of rpId.
    rpId.Assign(NS_ConvertUTF16toUTF8(mOrigin));
  } else {
    // 4.1.1.3.b If rpId is specified, then invoke the procedure used for
    // relaxing the same-origin restriction by setting the document.domain
    // attribute, using rpId as the given value but without changing the current
    // document’s domain. If no errors are thrown, set rpId to the value of host
    // as computed by this procedure, and rpIdHash to the SHA-256 hash of rpId.
    // Otherwise, reject promise with a DOMException whose name is
    // "SecurityError", and terminate this algorithm.

    if (NS_FAILED(RelaxSameOrigin(aOptions.mRpId.Value(), rpId))) {
      promise->MaybeReject(NS_ERROR_DOM_SECURITY_ERR);
      return promise.forget();
    }
  }

  CryptoBuffer rpIdHash;
  if (!rpIdHash.SetLength(SHA256_LENGTH, fallible)) {
    promise->MaybeReject(NS_ERROR_OUT_OF_MEMORY);
    return promise.forget();
  }

  nsresult srv;
  nsCOMPtr<nsICryptoHash> hashService =
    do_CreateInstance(NS_CRYPTO_HASH_CONTRACTID, &srv);
  if (NS_WARN_IF(NS_FAILED(srv))) {
    promise->MaybeReject(NS_ERROR_DOM_SECURITY_ERR);
    return promise.forget();
  }

  srv = HashCString(hashService, rpId, rpIdHash);
  if (NS_WARN_IF(NS_FAILED(srv))) {
    promise->MaybeReject(NS_ERROR_DOM_SECURITY_ERR);
    return promise.forget();
  }

  // 4.1.1.4 Process each element of cryptoParameters using the following steps,
  // to produce a new sequence normalizedParameters.
  nsTArray<ScopedCredentialParameters> normalizedParams;
  for (size_t a = 0; a < aCryptoParameters.Length(); ++a) {
    // 4.1.1.4.a Let current be the currently selected element of
    // cryptoParameters.

    // 4.1.1.4.b If current.type does not contain a ScopedCredentialType
    // supported by this implementation, then stop processing current and move
    // on to the next element in cryptoParameters.
    if (aCryptoParameters[a].mType != ScopedCredentialType::ScopedCred) {
      continue;
    }

    // 4.1.1.4.c Let normalizedAlgorithm be the result of normalizing an
    // algorithm using the procedure defined in [WebCryptoAPI], with alg set to
    // current.algorithm and op set to 'generateKey'. If an error occurs during
    // this procedure, then stop processing current and move on to the next
    // element in cryptoParameters.

    nsString algName;
    if (NS_FAILED(GetAlgorithmName(aCx, aCryptoParameters[a].mAlgorithm,
                                   algName))) {
      continue;
    }

    // 4.1.1.4.d Add a new object of type ScopedCredentialParameters to
    // normalizedParameters, with type set to current.type and algorithm set to
    // normalizedAlgorithm.
    ScopedCredentialParameters normalizedObj;
    normalizedObj.mType = aCryptoParameters[a].mType;
    normalizedObj.mAlgorithm.SetAsString().Assign(algName);

    if (!normalizedParams.AppendElement(normalizedObj, mozilla::fallible)){
      promise->MaybeReject(NS_ERROR_OUT_OF_MEMORY);
      return promise.forget();
    }
  }

  // 4.1.1.5 If normalizedAlgorithm is empty and cryptoParameters was not empty,
  // cancel the timer started in step 2, reject promise with a DOMException
  // whose name is "NotSupportedError", and terminate this algorithm.
  if (normalizedParams.IsEmpty() && !aCryptoParameters.IsEmpty()) {
    promise->MaybeReject(NS_ERROR_DOM_NOT_SUPPORTED_ERR);
    return promise.forget();
  }

  // 4.1.1.6 If excludeList is undefined, set it to the empty list.

  // 4.1.1.7 If extensions was specified, process any extensions supported by
  // this client platform, to produce the extension data that needs to be sent
  // to the authenticator. If an error is encountered while processing an
  // extension, skip that extension and do not produce any extension data for
  // it. Call the result of this processing clientExtensions.

  // Currently no extensions are supported

  // 4.1.1.8 Use attestationChallenge, callerOrigin and rpId, along with the
  // token binding key associated with callerOrigin (if any), to create a
  // ClientData structure representing this request. Choose a hash algorithm for
  // hashAlg and compute the clientDataJSON and clientDataHash.

  CryptoBuffer challenge;
  if (!challenge.Assign(aChallenge)) {
    promise->MaybeReject(NS_ERROR_DOM_SECURITY_ERR);
    return promise.forget();
  }

  nsAutoCString clientDataJSON;
  srv = AssembleClientData(mOrigin, challenge, clientDataJSON);
  if (NS_WARN_IF(NS_FAILED(srv))) {
    promise->MaybeReject(NS_ERROR_DOM_SECURITY_ERR);
    return promise.forget();
  }

  CryptoBuffer clientDataHash;
  if (!clientDataHash.SetLength(SHA256_LENGTH, fallible)) {
    promise->MaybeReject(NS_ERROR_DOM_SECURITY_ERR);
    return promise.forget();
  }

  srv = HashCString(hashService, clientDataJSON, clientDataHash);
  if (NS_WARN_IF(NS_FAILED(srv))) {
    promise->MaybeReject(NS_ERROR_DOM_SECURITY_ERR);
    return promise.forget();
  }

  // 4.1.1.9 Initialize issuedRequests to an empty list.
  RefPtr<CredentialPromise> monitorPromise = requestMonitor->Ensure();

  // 4.1.1.10 For each authenticator currently available on this platform:
  // asynchronously invoke the authenticatorMakeCredential operation on that
  // authenticator with rpIdHash, clientDataHash, accountInformation,
  // normalizedParameters, excludeList and clientExtensions as parameters. Add a
  // corresponding entry to issuedRequests.
  for (Authenticator u2ftoken : mAuthenticators) {
    // 4.1.1.10.a For each credential C in excludeList that has a non-empty
    // transports list, optionally use only the specified transports to test for
    // the existence of C.
    U2FAuthMakeCredential(requestMonitor, u2ftoken, rpIdHash, clientDataJSON,
                          clientDataHash, aAccount, normalizedParams,
                          aOptions.mExcludeList, aOptions.mExtensions);
  }

  requestMonitor->CompleteTask();

  monitorPromise->Then(AbstractThread::MainThread(), __func__,
    [promise] (CredentialPtr aInfo) {
      promise->MaybeResolve(aInfo);
    },
    [promise] (nsresult aErrorCode) {
      promise->MaybeReject(aErrorCode);
  });

  return promise.forget();
}