Checks for a valid IOU key in the iourc file (paranoid mode).
767755
def _check_iou_licence(self):
        
        try:
            license_check = self._config().getboolean("license_check", True)
        except ValueError:
            raise IOUError("Invalid licence check setting")
        if license_check is False:
            return

        config = configparser.ConfigParser()
        try:
            with open(self.iourc_path, encoding="utf-8") as f:
                config.read_file(f)
        except OSError as e:
            raise IOUError("Could not open iourc file {}: {}".format(self.iourc_path, e))
        except configparser.Error as e:
            raise IOUError("Could not parse iourc file {}: {}".format(self.iourc_path, e))
        except UnicodeDecodeError as e:
            raise IOUError("Non ascii characters in iourc file {}, please remove them: {}".format(self.iourc_path, e))
        if "license" not in config:
            raise IOUError("License section not found in iourc file {}".format(self.iourc_path))
        hostname = socket.gethostname()
        if len(hostname) > 15:
            log.warning("Older IOU images may not boot because hostname '{}' length is above 15 characters".format(hostname))
        if hostname not in config["license"]:
            raise IOUError("Hostname \"{}\" not found in iourc file {}".format(hostname, self.iourc_path))
        user_ioukey = config["license"][hostname]
        if user_ioukey[-1:] != ';':
            raise IOUError("IOU key not ending with ; in iourc file {}".format(self.iourc_path))
        if len(user_ioukey) != 17:
            raise IOUError("IOU key length is not 16 characters in iourc file {}".format(self.iourc_path))
        user_ioukey = user_ioukey[:16]

        # We can't test this because it's mean distributing a valid licence key
        # in tests or generating one
        if not hasattr(sys, "_called_from_test"):
            try:
                hostid = (yield from gns3server.utils.asyncio.subprocess_check_output("hostid")).strip()
            except FileNotFoundError as e:
                raise IOUError("Could not find hostid: {}".format(e))
            except subprocess.SubprocessError as e:
                raise IOUError("Could not execute hostid: {}".format(e))

            try:
                ioukey = int(hostid, 16)
            except ValueError:
                raise IOUError("Invalid hostid detected: {}".format(hostid))
            for x in hostname:
                ioukey += ord(x)
            pad1 = b'\x4B\x58\x21\x81\x56\x7B\x0D\xF3\x21\x43\x9B\x7E\xAC\x1D\xE6\x8A'
            pad2 = b'\x80' + 39 * b'\0'
            ioukey = hashlib.md5(pad1 + pad2 + struct.pack('!I', ioukey) + pad1).hexdigest()[:16]
            if ioukey != user_ioukey:
                raise IOUError("Invalid IOU license key {} detected in iourc file {} for host {}".format(user_ioukey,
                                                                                                         self.iourc_path,
                                                                                                         hostname))
1307304
boolean checkIntegrity () {
        if (headerType == null) return false;
        if (headerType == HeaderType.MODE_PARAMETER_HEADER_6 && longLba) return false;
        return true;
    }
787970
private synchronized String ufsFingerprint(long fileId) throws IOException {
    FileInfo fileInfo = mBlockWorker.getFileInfo(fileId);
    String dstPath = fileInfo.getUfsPath();
    try (CloseableResource<UnderFileSystem> ufsResource =
        mUfsManager.get(fileInfo.getMountId()).acquireUfsResource()) {
      UnderFileSystem ufs = ufsResource.get();
      return ufs.isFile(dstPath) ? ufs.getFingerprint(dstPath) : null;
    }
  }
26114
private static boolean verifyFile(Configuration conf,
      FileSystem srcFs, FileSystem parityFs,
      FileStatus stat, Path parityPath, Codec codec,
      long blockOffset, Progressable reporter) 
    throws IOException, InterruptedException {
    Path srcPath = stat.getPath();
    LOG.info("Verify file: " + srcPath + " at offset: " + blockOffset);
    int limit = (int) Math.min(stat.getBlockSize(), DEFAULT_VERIFY_LEN);
    if (reporter == null) {
      reporter = RaidUtils.NULL_PROGRESSABLE;
    }
    
    // try to decode.
    Decoder decoder = new Decoder(conf, codec);
    if (codec.isDirRaid) {
      decoder.connectToStore(srcPath);
    }
    
    List<Long> errorOffsets = new ArrayList<Long>();
    // first limit bytes
    errorOffsets.add(blockOffset);
    long left = Math.min(stat.getBlockSize(), stat.getLen() - blockOffset);
    if (left > limit) {
      // last limit bytes
      errorOffsets.add(blockOffset + left - limit);
      // random limit bytes.
      errorOffsets.add(blockOffset + 
          rand.nextInt((int)(left - limit)));
    }
 
    byte[] buffer = new byte[limit];
    FSDataInputStream is = srcFs.open(srcPath);
    try {
      for (long errorOffset : errorOffsets) {
        is.seek(errorOffset);
        is.read(buffer);
        // calculate the oldCRC.
        CRC32 oldCrc = new CRC32();
        oldCrc.update(buffer);
        
        CRC32 newCrc = new CRC32();
        DecoderInputStream stream = decoder.new DecoderInputStream(
            RaidUtils.NULL_PROGRESSABLE, limit, stat.getBlockSize(), errorOffset, 
            srcFs, srcPath, parityFs, parityPath, null, null, false);
        try {
          stream.read(buffer);
          newCrc.update(buffer);
          if (oldCrc.getValue() != newCrc.getValue()) {
            LogUtils.logFileCheckMetrics(LOGRESULTS.FAILURE, codec, srcPath, 
                srcFs, errorOffset, limit, null, reporter);
            LOG.error("mismatch crc, old " + oldCrc.getValue() + 
                ", new " + newCrc.getValue() + ", for file: " + srcPath
                + " at offset " + errorOffset + ", read limit " + limit);
            return false;
          }
        } finally {
          reporter.progress();
          if (stream != null) {
            stream.close();
          }
        }
      }
      return true;
    } finally {
      is.close();
    }
  }
1216063
def isValid( self ):
        
        check = nativestring(self._filepathEdit.text()).split(os.path.pathsep)[0]
        if ( self.filepathMode() == XFilepathEdit.Mode.SaveFile ):
            check = os.path.dirname(check)
        
        return os.path.exists(check)
78520
private boolean checkOSSCredentials(UnderFileSystemConfiguration conf) {
    return conf.isSet(PropertyKey.OSS_ACCESS_KEY)
        && conf.isSet(PropertyKey.OSS_SECRET_KEY)
        && conf.isSet(PropertyKey.OSS_ENDPOINT_KEY);
  }
803618
private static boolean checkIpv4(byte[] bytes, int pos, int length) {
		int start = pos;
		for (int i = pos; i < length; i++) {
			// assume at least one more symbol is present after dot
			if (i == length - 1 && bytes[i] == '.') {
				return false;
			}
			if (bytes[i] == '.' || i == length - 1) {
				int v;
				if (i - start == 0 && i != length - 1) {
					return false;
				}
				try {
					v = trimAndDecodePositiveInt(bytes, start, i - start);
				} catch (ParseException e) {
					return false;
				}
				if (v < 0 || v > 255) return false;
				start = i + 1;
			}
		}
		return true;
	}
172056
def check_singlekey(self):
        """"""
        if len(self._qsequences) == 0:
            return True
        else:
            keystr = self._qsequences[0]
            valid_single_keys = (EDITOR_SINGLE_KEYS if
                                 self.context == 'editor' else SINGLE_KEYS)
            if any((m in keystr for m in ('Ctrl', 'Alt', 'Shift', 'Meta'))):
                return True
            else:
                # This means that the the first subsequence is composed of
                # a single key with no modifier.
                valid_single_keys = (EDITOR_SINGLE_KEYS if
                                     self.context == 'editor' else SINGLE_KEYS)
                if any((k == keystr for k in valid_single_keys)):
                    return True
                else:
                    return False
257457
def check_abi(abi):
    """"""
    if not abi:
        return None
    abi = abi.lower()
    # valid_abis maps input name to canonical name
    if is_windows:
        valid_abis = {'ia32'  : 'ia32',
                      'x86'   : 'ia32',
                      'ia64'  : 'ia64',
                      'em64t' : 'em64t',
                      'amd64' : 'em64t'}
    if is_linux:
        valid_abis = {'ia32'   : 'ia32',
                      'x86'    : 'ia32',
                      'x86_64' : 'x86_64',
                      'em64t'  : 'x86_64',
                      'amd64'  : 'x86_64'}
    if is_mac:
        valid_abis = {'ia32'   : 'ia32',
                      'x86'    : 'ia32',
                      'x86_64' : 'x86_64',
                      'em64t'  : 'x86_64'}
    try:
        abi = valid_abis[abi]
    except KeyError:
        raise SCons.Errors.UserError("Intel compiler: Invalid ABI %s, valid values are %s"% \
              (abi, list(valid_abis.keys())))
    return abi
1043638
def iourc_path(self):
        

        iourc_path = self._config().get("iourc_path")
        if not iourc_path:
            # look for the iourc file in the temporary  dir.
            path = os.path.join(self.temporary_directory, "iourc")
            if os.path.exists(path):
                return path
            # look for the iourc file in the user home dir.
            path = os.path.join(os.path.expanduser("~/"), ".iourc")
            if os.path.exists(path):
                return path
            # look for the iourc file in the current working dir.
            path = os.path.join(self.working_dir, "iourc")
            if os.path.exists(path):
                return path
        return iourc_path
25680
private boolean isPrivateHeaderTrusted(HeaderKeys key) {
        HttpServiceContextImpl hisc = getServiceContext();
        InetAddress remoteAddr = null;       
        String address = null;
        if (hisc != null && (remoteAddr = hisc.getRemoteAddr()) != null) {
            address = remoteAddr.getHostAddress();
        }

        boolean trusted = false;
        if (address != null) {
            trusted = HttpDispatcher.usePrivateHeaders(address, key.getName());
        }

        if (!trusted) {
            if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
                Tr.debug(tc, "isPrivateHeaderTrusted: " + key.getName() + " is not trusted for host " + address);
            }
            return false;
        }
        return true;
    }
1095973
protected Boolean containsKeyIntern(final FileCacheKey fileCacheKey) throws IOException {
      for(String file: directory.listAll()) {
         if(file.equals(fileCacheKey.getFileName())) {
            return true;
         }
      }
      return false;
   }
890479
def validate(self, sig=None):
        ''''''
        if sig is not None:
            sig_mtime, sig_size, sig_md5 = sig
        else:
            try:
                with open(self.sig_file()) as sig:
                    sig_mtime, sig_size, sig_md5 = sig.read().strip().split()
            except:
                return False
        if not self.exists():
            if (self + '.zapped').is_file():
                with open(self + '.zapped') as sig:
                    line = sig.readline()
                    return sig_md5 == line.strip().rsplit('\t', 3)[-1]
            else:
                return False
        if sig_mtime == os.path.getmtime(self) and sig_size == os.path.getsize(
                self):
            return True
        return fileMD5(self) == sig_md5
1213920
def _exists(self, key):
        
        filecache, keycache = self._fileslist()
        msg = keycache.get(key, None)
        if msg:
            path = msg.filename
            meta = filecache[path]
            return path, meta["hostname"], meta.get("flags", "")
        raise KeyError("not found %s" % key)
291410
def Verify(self, public_key):
    
    # TODO(amoser): We have to do this manually for now since cryptography does
    # not yet support cert verification. There is PR 2460:
    # https://github.com/pyca/cryptography/pull/2460/files
    # that will add it, once it's in we should switch to using this.

    # Note that all times here are in UTC.
    now = rdfvalue.RDFDatetime.Now().AsDatetime()
    if now > self._value.not_valid_after:
      raise VerificationError("Certificate expired!")
    if now < self._value.not_valid_before:
      raise VerificationError("Certificate not yet valid!")

    public_key.Verify(
        self._value.tbs_certificate_bytes,
        self._value.signature,
        hash_algorithm=self._value.signature_hash_algorithm)
    return True
1276199
def _check_certificate(self):
        
        if (self.file_name.startswith("jdk-") and self.repo == "sbo" and
                self.downder == "wget"):
            certificate = (' --no-check-certificate --header="Cookie: '
                           'oraclelicense=accept-securebackup-cookie"')
            self.msg.template(78)
            print("| '{0}' need to go ahead downloading".format(
                certificate[:23].strip()))
            self.msg.template(78)
            print("")
            self.downder_options += certificate
            if not self.msg.answer() in ["y", "Y"]:
                raise SystemExit()
82741
private void check(CryptoMode cryptoMode) {
        // For modes that use AES/GCM, we prefer using the BouncyCastle provider unless the
        // user has explicitly overridden us (i.e., with the FIPS-compliant BouncyCastle
        // implementation).
        boolean preferBC = (cryptoMode == CryptoMode.AuthenticatedEncryption)
                           || (cryptoMode == CryptoMode.StrictAuthenticatedEncryption);

        boolean haveOverride = (cryptoProvider != null && alwaysUseCryptoProvider);

        if (preferBC && !haveOverride) {
            if (!CryptoRuntime.isBouncyCastleAvailable()) {
                CryptoRuntime.enableBouncyCastle();
                if (!CryptoRuntime.isBouncyCastleAvailable()) {
                    throw new UnsupportedOperationException(
                        "The Bouncy castle library jar is required on the classpath to enable authenticated encryption");
                }
            }
            if (!CryptoRuntime.isAesGcmAvailable())
                throw new UnsupportedOperationException(
                    "More recent version of the Bouncy castle library is required to enable authenticated encryption");
        }
    }