Search in sources :

Example 16 with InternetDomainName

use of com.google.common.net.InternetDomainName in project nomulus by google.

the class DomainCreateFlow method run.

@Override
public EppResponse run() throws EppException {
    extensionManager.register(FeeCreateCommandExtension.class, SecDnsCreateExtension.class, MetadataExtension.class, LaunchCreateExtension.class, AllocationTokenExtension.class);
    flowCustomLogic.beforeValidation();
    validateRegistrarIsLoggedIn(registrarId);
    verifyRegistrarIsActive(registrarId);
    extensionManager.validate();
    DateTime now = tm().getTransactionTime();
    DomainCommand.Create command = cloneAndLinkReferences((Create) resourceCommand, now);
    Period period = command.getPeriod();
    verifyUnitIsYears(period);
    int years = period.getValue();
    validateRegistrationPeriod(years);
    verifyResourceDoesNotExist(DomainBase.class, targetId, now, registrarId);
    // Validate that this is actually a legal domain name on a TLD that the registrar has access to.
    InternetDomainName domainName = validateDomainName(command.getFullyQualifiedDomainName());
    String domainLabel = domainName.parts().get(0);
    Registry registry = Registry.get(domainName.parent().toString());
    validateCreateCommandContactsAndNameservers(command, registry, domainName);
    TldState tldState = registry.getTldState(now);
    Optional<LaunchCreateExtension> launchCreate = eppInput.getSingleExtension(LaunchCreateExtension.class);
    boolean hasSignedMarks = launchCreate.isPresent() && !launchCreate.get().getSignedMarks().isEmpty();
    boolean hasClaimsNotice = launchCreate.isPresent() && launchCreate.get().getNotice() != null;
    if (launchCreate.isPresent()) {
        verifyNoCodeMarks(launchCreate.get());
        validateLaunchCreateNotice(launchCreate.get().getNotice(), domainLabel, isSuperuser, now);
    }
    boolean isSunriseCreate = hasSignedMarks && (tldState == START_DATE_SUNRISE);
    Optional<AllocationToken> allocationToken = verifyAllocationTokenIfPresent(command, registry, registrarId, now);
    boolean isAnchorTenant = isAnchorTenant(domainName, allocationToken, eppInput.getSingleExtension(MetadataExtension.class));
    verifyAnchorTenantValidPeriod(isAnchorTenant, years);
    // registering premium domains.
    if (!isSuperuser) {
        checkAllowedAccessToTld(registrarId, registry.getTldStr());
        checkHasBillingAccount(registrarId, registry.getTldStr());
        boolean isValidReservedCreate = isValidReservedCreate(domainName, allocationToken);
        verifyIsGaOrIsSpecialCase(tldState, isAnchorTenant, isValidReservedCreate, hasSignedMarks);
        if (launchCreate.isPresent()) {
            verifyLaunchPhaseMatchesRegistryPhase(registry, launchCreate.get(), now);
        }
        if (!isAnchorTenant && !isValidReservedCreate) {
            verifyNotReserved(domainName, isSunriseCreate);
        }
        if (hasClaimsNotice) {
            verifyClaimsPeriodNotEnded(registry, now);
        }
        if (now.isBefore(registry.getClaimsPeriodEnd())) {
            verifyClaimsNoticeIfAndOnlyIfNeeded(domainName, hasSignedMarks, hasClaimsNotice);
        }
        verifyPremiumNameIsNotBlocked(targetId, now, registrarId);
        verifySignedMarkOnlyInSunrise(hasSignedMarks, tldState);
    }
    String signedMarkId = null;
    if (hasSignedMarks) {
        // If a signed mark was provided, then it must match the desired domain label. Get the mark
        // at this point so that we can verify it before the "after validation" extension point.
        signedMarkId = tmchUtils.verifySignedMarks(launchCreate.get().getSignedMarks(), domainLabel, now).getId();
    }
    flowCustomLogic.afterValidation(DomainCreateFlowCustomLogic.AfterValidationParameters.newBuilder().setDomainName(domainName).setYears(years).setSignedMarkId(Optional.ofNullable(signedMarkId)).build());
    Optional<FeeCreateCommandExtension> feeCreate = eppInput.getSingleExtension(FeeCreateCommandExtension.class);
    FeesAndCredits feesAndCredits = pricingLogic.getCreatePrice(registry, targetId, now, years, isAnchorTenant, allocationToken);
    validateFeeChallenge(targetId, now, feeCreate, feesAndCredits);
    Optional<SecDnsCreateExtension> secDnsCreate = validateSecDnsExtension(eppInput.getSingleExtension(SecDnsCreateExtension.class));
    DateTime registrationExpirationTime = leapSafeAddYears(now, years);
    String repoId = createDomainRepoId(allocateId(), registry.getTldStr());
    Key<DomainHistory> domainHistoryKey = Key.create(Key.create(DomainBase.class, repoId), DomainHistory.class, allocateId());
    historyBuilder.setId(domainHistoryKey.getId());
    // Bill for the create.
    BillingEvent.OneTime createBillingEvent = createOneTimeBillingEvent(registry, isAnchorTenant, isSunriseCreate, isReserved(domainName, isSunriseCreate), years, feesAndCredits, domainHistoryKey, allocationToken, now);
    // Create a new autorenew billing event and poll message starting at the expiration time.
    BillingEvent.Recurring autorenewBillingEvent = createAutorenewBillingEvent(domainHistoryKey, registrationExpirationTime, getRenewalPriceInfo(isAnchorTenant, allocationToken, feesAndCredits));
    PollMessage.Autorenew autorenewPollMessage = createAutorenewPollMessage(domainHistoryKey, registrationExpirationTime);
    ImmutableSet.Builder<ImmutableObject> entitiesToSave = new ImmutableSet.Builder<>();
    entitiesToSave.add(createBillingEvent, autorenewBillingEvent, autorenewPollMessage);
    // Bill for EAP cost, if any.
    if (!feesAndCredits.getEapCost().isZero()) {
        entitiesToSave.add(createEapBillingEvent(feesAndCredits, createBillingEvent));
    }
    ImmutableSet<ReservationType> reservationTypes = getReservationTypes(domainName);
    ImmutableSet<StatusValue> statuses = reservationTypes.contains(NAME_COLLISION) ? ImmutableSet.of(SERVER_HOLD) : ImmutableSet.of();
    DomainBase domain = new DomainBase.Builder().setCreationRegistrarId(registrarId).setPersistedCurrentSponsorRegistrarId(registrarId).setRepoId(repoId).setIdnTableName(validateDomainNameWithIdnTables(domainName)).setRegistrationExpirationTime(registrationExpirationTime).setAutorenewBillingEvent(autorenewBillingEvent.createVKey()).setAutorenewPollMessage(autorenewPollMessage.createVKey()).setLaunchNotice(hasClaimsNotice ? launchCreate.get().getNotice() : null).setSmdId(signedMarkId).setDsData(secDnsCreate.map(SecDnsCreateExtension::getDsData).orElse(null)).setRegistrant(command.getRegistrant()).setAuthInfo(command.getAuthInfo()).setDomainName(targetId).setNameservers(command.getNameservers().stream().collect(toImmutableSet())).setStatusValues(statuses).setContacts(command.getContacts()).addGracePeriod(GracePeriod.forBillingEvent(GracePeriodStatus.ADD, repoId, createBillingEvent)).build();
    DomainHistory domainHistory = buildDomainHistory(domain, registry, now, period, registry.getAddGracePeriodLength());
    if (reservationTypes.contains(NAME_COLLISION)) {
        entitiesToSave.add(createNameCollisionOneTimePollMessage(targetId, domainHistory, registrarId, now));
    }
    entitiesToSave.add(domain, domainHistory, ForeignKeyIndex.create(domain, domain.getDeletionTime()), EppResourceIndex.create(Key.create(domain)));
    if (allocationToken.isPresent() && TokenType.SINGLE_USE.equals(allocationToken.get().getTokenType())) {
        entitiesToSave.add(allocationTokenFlowUtils.redeemToken(allocationToken.get(), domainHistory.createVKey()));
    }
    enqueueTasks(domain, hasSignedMarks, hasClaimsNotice);
    EntityChanges entityChanges = flowCustomLogic.beforeSave(DomainCreateFlowCustomLogic.BeforeSaveParameters.newBuilder().setNewDomain(domain).setHistoryEntry(domainHistory).setEntityChanges(EntityChanges.newBuilder().setSaves(entitiesToSave.build()).build()).setYears(years).build());
    persistEntityChanges(entityChanges);
    BeforeResponseReturnData responseData = flowCustomLogic.beforeResponse(BeforeResponseParameters.newBuilder().setResData(DomainCreateData.create(targetId, now, registrationExpirationTime)).setResponseExtensions(createResponseExtensions(feeCreate, feesAndCredits)).build());
    return responseBuilder.setResData(responseData.resData()).setExtensions(responseData.responseExtensions()).build();
}
Also used : InternetDomainName(com.google.common.net.InternetDomainName) DomainHistory(google.registry.model.domain.DomainHistory) BeforeResponseReturnData(google.registry.flows.custom.DomainCreateFlowCustomLogic.BeforeResponseReturnData) Recurring(google.registry.model.billing.BillingEvent.Recurring) AllocationToken(google.registry.model.domain.token.AllocationToken) MetadataExtension(google.registry.model.domain.metadata.MetadataExtension) DateTime(org.joda.time.DateTime) Create(google.registry.model.domain.DomainCommand.Create) FeeCreateCommandExtension(google.registry.model.domain.fee.FeeCreateCommandExtension) ImmutableSet.toImmutableSet(com.google.common.collect.ImmutableSet.toImmutableSet) ImmutableSet(com.google.common.collect.ImmutableSet) TldState(google.registry.model.tld.Registry.TldState) ImmutableObject(google.registry.model.ImmutableObject) FlowUtils.persistEntityChanges(google.registry.flows.FlowUtils.persistEntityChanges) EntityChanges(google.registry.flows.custom.EntityChanges) Autorenew(google.registry.model.poll.PollMessage.Autorenew) SecDnsCreateExtension(google.registry.model.domain.secdns.SecDnsCreateExtension) LaunchCreateExtension(google.registry.model.domain.launch.LaunchCreateExtension) GracePeriod(google.registry.model.domain.GracePeriod) Period(google.registry.model.domain.Period) DomainFlowUtils.validateRegistrationPeriod(google.registry.flows.domain.DomainFlowUtils.validateRegistrationPeriod) Registry(google.registry.model.tld.Registry) DomainBase(google.registry.model.domain.DomainBase) ReservationType(google.registry.model.tld.label.ReservationType) PollMessage(google.registry.model.poll.PollMessage) BillingEvent(google.registry.model.billing.BillingEvent) StatusValue(google.registry.model.eppcommon.StatusValue) DomainCommand(google.registry.model.domain.DomainCommand)

Example 17 with InternetDomainName

use of com.google.common.net.InternetDomainName in project nomulus by google.

the class CheckApiAction method doCheck.

private Map<String, Object> doCheck() {
    String domainString;
    InternetDomainName domainName;
    try {
        domainString = canonicalizeHostname(nullToEmpty(domain));
        domainName = validateDomainName(domainString);
    } catch (IllegalArgumentException | EppException e) {
        metricBuilder.status(INVALID_NAME);
        return fail("Must supply a valid domain name on an authoritative TLD");
    }
    try {
        // Throws an EppException with a reasonable error message which will be sent back to caller.
        validateDomainNameWithIdnTables(domainName);
        DateTime now = clock.nowUtc();
        Registry registry = Registry.get(domainName.parent().toString());
        try {
            verifyNotInPredelegation(registry, now);
        } catch (BadCommandForRegistryPhaseException e) {
            metricBuilder.status(INVALID_REGISTRY_PHASE);
            return fail("Check in this TLD is not allowed in the current registry phase");
        }
        boolean isRegistered = checkExists(domainString, now);
        Optional<String> reservedError = Optional.empty();
        boolean isReserved = false;
        if (!isRegistered) {
            reservedError = checkReserved(domainName);
            isReserved = reservedError.isPresent();
        }
        Availability availability = isRegistered ? REGISTERED : (isReserved ? RESERVED : AVAILABLE);
        String errorMsg = isRegistered ? "In use" : (isReserved ? reservedError.get() : null);
        ImmutableMap.Builder<String, Object> responseBuilder = new ImmutableMap.Builder<>();
        metricBuilder.status(SUCCESS).availability(availability);
        responseBuilder.put("status", "success").put("available", availability.equals(AVAILABLE));
        boolean isPremium = isDomainPremium(domainString, now);
        metricBuilder.tier(isPremium ? PREMIUM : STANDARD);
        responseBuilder.put("tier", isPremium ? "premium" : "standard");
        if (!AVAILABLE.equals(availability)) {
            responseBuilder.put("reason", errorMsg);
        }
        return responseBuilder.build();
    } catch (InvalidIdnDomainLabelException e) {
        metricBuilder.status(INVALID_NAME);
        return fail(e.getResult().getMsg());
    } catch (Exception e) {
        metricBuilder.status(UNKNOWN_ERROR);
        logger.atWarning().withCause(e).log("Unknown error.");
        return fail("Invalid request");
    }
}
Also used : Availability(google.registry.monitoring.whitebox.CheckApiMetric.Availability) InternetDomainName(com.google.common.net.InternetDomainName) JSONValue.toJSONString(org.json.simple.JSONValue.toJSONString) Registry(google.registry.model.tld.Registry) BadCommandForRegistryPhaseException(google.registry.flows.domain.DomainFlowUtils.BadCommandForRegistryPhaseException) DateTime(org.joda.time.DateTime) ImmutableMap(com.google.common.collect.ImmutableMap) InvalidIdnDomainLabelException(google.registry.flows.domain.DomainFlowUtils.InvalidIdnDomainLabelException) BadCommandForRegistryPhaseException(google.registry.flows.domain.DomainFlowUtils.BadCommandForRegistryPhaseException) InvalidIdnDomainLabelException(google.registry.flows.domain.DomainFlowUtils.InvalidIdnDomainLabelException)

Example 18 with InternetDomainName

use of com.google.common.net.InternetDomainName in project gravitee-access-management by gravitee-io.

the class VirtualHostValidatorImpl method isValidDomainOrSubDomain.

public boolean isValidDomainOrSubDomain(String domain, List<String> domainRestrictions) {
    boolean isSubDomain = false;
    if (CollectionUtils.isEmpty(domainRestrictions)) {
        return true;
    }
    for (String domainRestriction : domainRestrictions) {
        InternetDomainName domainIDN = InternetDomainName.from(domain);
        InternetDomainName parentIDN = InternetDomainName.from(domainRestriction);
        if (domainIDN.equals(parentIDN)) {
            return true;
        }
        while (!isSubDomain && domainIDN.hasParent()) {
            isSubDomain = parentIDN.equals(domainIDN);
            domainIDN = domainIDN.parent();
        }
        if (isSubDomain) {
            break;
        }
    }
    return isSubDomain;
}
Also used : InternetDomainName(com.google.common.net.InternetDomainName)

Example 19 with InternetDomainName

use of com.google.common.net.InternetDomainName in project heritrix3 by internetarchive.

the class HostQuotaEnforcer method shouldProcess.

@Override
protected boolean shouldProcess(CrawlURI curi) {
    String uriHostname = serverCache.getHostFor(curi.getUURI()).getHostName();
    if (getApplyToSubdomains() && InternetDomainName.isValid(host) && InternetDomainName.isValid(uriHostname)) {
        InternetDomainName h = InternetDomainName.from(host);
        InternetDomainName uriHostOrAncestor = InternetDomainName.from(uriHostname);
        while (true) {
            if (uriHostOrAncestor.equals(h)) {
                return true;
            }
            if (uriHostOrAncestor.hasParent()) {
                uriHostOrAncestor = uriHostOrAncestor.parent();
            } else {
                break;
            }
        }
        return false;
    } else {
        return serverCache.getHostFor(curi.getUURI()) == serverCache.getHostFor(host);
    }
}
Also used : InternetDomainName(com.google.common.net.InternetDomainName)

Example 20 with InternetDomainName

use of com.google.common.net.InternetDomainName in project dcache by dCache.

the class StrategyIdMapper method discoverNFS4Domain.

/**
 * Auto-discovers NFSv4 domain from DNS server. if provided {@code configuredDomain} is null or
 * an empty string, a local DNS server will be queried for the {@code _nfsv4idmapdomain} text
 * record. If the record exists that will be used as the domain. When the record does not exist,
 * the domain part of the DNS domain will used.
 *
 * @param configuredDomain nfs4domain to be used.
 * @return NFSv4 domain
 * @see <a href="http://docs.oracle.com/cd/E19253-01/816-4555/epubp/index.html">nfsmapid and DNS
 * TXT Records</a>
 */
private String discoverNFS4Domain(String configuredDomain) throws NamingException, UnknownHostException {
    if (!Strings.isNullOrEmpty(configuredDomain)) {
        LOGGER.info("Using config provided nfs4domain: {}", configuredDomain);
        return configuredDomain;
    }
    // Java doesn't provide a way to discover local domain.....
    String fqdn = InetAddress.getLocalHost().getCanonicalHostName();
    if (!InternetDomainName.isValid(fqdn)) {
        LOGGER.warn("The FQDN {} can't be associated with a domain name, using default nfs4domain: {}", fqdn, DEFAULT_NFS4_DOMAIN);
        return DEFAULT_NFS4_DOMAIN;
    }
    InternetDomainName domainName = InternetDomainName.from(fqdn);
    if (!domainName.hasParent()) {
        // DNS is not configured, or we got something like localhost
        LOGGER.warn("The FQDN {} has no parent, using default nfs4domain: {}", fqdn, DEFAULT_NFS4_DOMAIN);
        return DEFAULT_NFS4_DOMAIN;
    }
    // try to get TXT record from DNS a server
    Hashtable<String, String> env = new Hashtable<>();
    env.put("java.naming.factory.initial", "com.sun.jndi.dns.DnsContextFactory");
    DirContext dirContext = new InitialDirContext(env);
    InternetDomainName domain = domainName.parent();
    // we can't use InternetDomainName#child as leading underscore is not allowed by domain names
    String idmapDomainRecord = NFS4_DNS_TXT_REC + "." + domain.toString();
    try {
        Attributes attrs = dirContext.getAttributes(idmapDomainRecord, new String[] { "TXT" });
        Attribute txtAttr = attrs.get("TXT");
        if (txtAttr != null) {
            NamingEnumeration e = txtAttr.getAll();
            String txtRecord = e.next().toString();
            LOGGER.info("Using nfs4domain from DNS TXT record: {}", txtRecord);
            return txtRecord;
        }
    } catch (CommunicationException e) {
        LOGGER.warn("DNS query to discover NFS domain name failed: {}", Throwables.getRootCause(e).getMessage());
    } catch (NameNotFoundException e) {
    // nfsv4idmapdomain record doesn't exists
    }
    // The DNS hasn't corresponding TXT record. Use domain name.
    LOGGER.info("Using DNS domain as nfs4domain: {}", domain);
    return domain.toString();
}
Also used : InternetDomainName(com.google.common.net.InternetDomainName) CommunicationException(javax.naming.CommunicationException) Attribute(javax.naming.directory.Attribute) NameNotFoundException(javax.naming.NameNotFoundException) Hashtable(java.util.Hashtable) Attributes(javax.naming.directory.Attributes) NamingEnumeration(javax.naming.NamingEnumeration) InitialDirContext(javax.naming.directory.InitialDirContext) DirContext(javax.naming.directory.DirContext) InitialDirContext(javax.naming.directory.InitialDirContext)

Aggregations

InternetDomainName (com.google.common.net.InternetDomainName)23 DateTime (org.joda.time.DateTime)5 Registry (google.registry.model.tld.Registry)4 ImmutableList (com.google.common.collect.ImmutableList)3 ImmutableMap (com.google.common.collect.ImmutableMap)3 AllocationToken (google.registry.model.domain.token.AllocationToken)3 ImmutableSet (com.google.common.collect.ImmutableSet)2 DomainCommand (google.registry.model.domain.DomainCommand)2 Check (google.registry.model.domain.DomainCommand.Check)2 AllocationTokenExtension (google.registry.model.domain.token.AllocationTokenExtension)2 TldState (google.registry.model.tld.Registry.TldState)2 MalformedURLException (java.net.MalformedURLException)2 HashSet (java.util.HashSet)2 Preconditions.checkArgument (com.google.common.base.Preconditions.checkArgument)1 Strings (com.google.common.base.Strings)1 ImmutableList.toImmutableList (com.google.common.collect.ImmutableList.toImmutableList)1 ImmutableMap.toImmutableMap (com.google.common.collect.ImmutableMap.toImmutableMap)1 ImmutableMultimap (com.google.common.collect.ImmutableMultimap)1 ImmutableSet.toImmutableSet (com.google.common.collect.ImmutableSet.toImmutableSet)1 Maps (com.google.common.collect.Maps)1