vcl 4.0;

import std;
import directors;

#
# These nets/machines are allowed /repo access
#
acl repoallowed {
  "10.5.78.0"/24;
  "10.5.125.0"/24;
  "10.5.127.0"/24;
  "10.5.129.0"/24;
  "10.5.128.84"/32;
  "10.5.128.85"/32;
  "10.5.128.86"/32;
  "10.5.128.87"/32;
  "10.5.128.69"/32;
  "10.16.0.0"/24;
}

acl purge {
  "127.0.0.1"/32;
}

backend localapache { 
  .host = "127.0.0.1"; 
  .port = "8080";
  .first_byte_timeout = 60s;
  .between_bytes_timeout = 60s;
  .probe = { 
      .url = "/"; 
      .interval = 5s; 
      .timeout = 5s;
      .window = 5;
      .threshold = 3; }
}

sub vcl_recv {
    # This gets arround the silly, ::1 that Apache adds on the proxies (still need to look at that)
    set req.http.X-Forwarded-For = regsub(req.http.X-Forwarded-For, "^([a-f0-9:.]+), .+$", "\1");

    set req.backend_hint = localapache;
    unset req.http.cookie;
    set req.http.clear-cookies = "yes";

    if (req.method == "PURGE") {
        if (!client.ip ~ purge) {
            return (synth(405, "Not allowed"));
        }
        return(purge);
    }

    if (req.url ~ "^/repo/" && !(std.ip(req.http.X-Forwarded-For, "0.0.0.0") ~ repoallowed)) {
        return(synth(403, "Access denied."));
    }
    if (req.url ~ "^/mash/") {
        return (pipe);
    }
    if (req.url ~ "^/compose/") {
        return (pipe);
    }
    if (req.url ~ "h264") {
        return (pipe);
    }
    if (req.url ~ "^/mass-rebuild/") {
        return (pipe);
    }

    # Rewrite toplink URLs to improve cache hit ratio
    # See: https://pagure.io/fedora-infrastructure/issue/7383
    set req.url = regsub(req.url, "^/repos/[^/]+/[^/]+/[^/]+/toplink/", "/");

    return (hash);
}
