コード例 #1
0
 protected boolean isVisibleTo(Branch.NameKey branchName, CurrentUser user) {
   ProjectState pe = projectCache.get(branchName.getParentKey());
   if (pe == null) {
     return false;
   }
   ProjectControl pc = pe.controlFor(user);
   return pc.controlForRef(branchName).isVisible();
 }
コード例 #2
0
 protected boolean isVisibleTo(Change change, CurrentUser user) throws OrmException {
   if (change == null) {
     return false;
   }
   ProjectState pe = projectCache.get(change.getProject());
   if (pe == null) {
     return false;
   }
   ProjectControl pc = pe.controlFor(user);
   ReviewDb db = dbProvider.get();
   return pc.controlFor(db, change).isVisible(db);
 }
コード例 #3
0
 private boolean inProject(final Change change) {
   if (projectControl == null) {
     // No --project option, so they want every project.
     return true;
   }
   return projectControl.getProject().getNameKey().equals(change.getProject());
 }
コード例 #4
0
  private Set<PatchSet.Id> parsePatchSetId(final String patchIdentity)
      throws UnloggedFailure, OrmException {
    // By commit?
    //
    if (patchIdentity.matches("^([0-9a-fA-F]{4," + RevId.LEN + "})$")) {
      final RevId id = new RevId(patchIdentity);
      final ResultSet<PatchSet> patches;
      if (id.isComplete()) {
        patches = db.patchSets().byRevision(id);
      } else {
        patches = db.patchSets().byRevisionRange(id, id.max());
      }

      final Set<PatchSet.Id> matches = new HashSet<PatchSet.Id>();
      for (final PatchSet ps : patches) {
        final Change change = db.changes().get(ps.getId().getParentKey());
        if (inProject(change)) {
          matches.add(ps.getId());
        }
      }

      switch (matches.size()) {
        case 1:
          return matches;
        case 0:
          throw error("\"" + patchIdentity + "\" no such patch set");
        default:
          throw error("\"" + patchIdentity + "\" matches multiple patch sets");
      }
    }

    // By older style change,patchset?
    //
    if (patchIdentity.matches("^[1-9][0-9]*,[1-9][0-9]*$")) {
      final PatchSet.Id patchSetId;
      try {
        patchSetId = PatchSet.Id.parse(patchIdentity);
      } catch (IllegalArgumentException e) {
        throw error("\"" + patchIdentity + "\" is not a valid patch set");
      }
      if (db.patchSets().get(patchSetId) == null) {
        throw error("\"" + patchIdentity + "\" no such patch set");
      }
      if (projectControl != null) {
        final Change change = db.changes().get(patchSetId.getParentKey());
        if (!inProject(change)) {
          throw error(
              "change "
                  + change.getId()
                  + " not in project "
                  + projectControl.getProject().getName());
        }
      }
      return Collections.singleton(patchSetId);
    }

    throw error("\"" + patchIdentity + "\" is not a valid patch set");
  }
コード例 #5
0
ファイル: GitwebServlet.java プロジェクト: netroby/gerrit
  private String[] makeEnv(final HttpServletRequest req, final ProjectControl project) {
    final EnvList env = new EnvList(_env);
    final int contentLength = Math.max(0, req.getContentLength());

    // These ones are from "The WWW Common Gateway Interface Version 1.1"
    //
    env.set("AUTH_TYPE", req.getAuthType());
    env.set("CONTENT_LENGTH", Integer.toString(contentLength));
    env.set("CONTENT_TYPE", req.getContentType());
    env.set("GATEWAY_INTERFACE", "CGI/1.1");
    env.set("PATH_INFO", req.getPathInfo());
    env.set("PATH_TRANSLATED", null);
    env.set("QUERY_STRING", req.getQueryString());
    env.set("REMOTE_ADDR", req.getRemoteAddr());
    env.set("REMOTE_HOST", req.getRemoteHost());
    env.set("HTTPS", req.isSecure() ? "ON" : "OFF");

    // The identity information reported about the connection by a
    // RFC 1413 [11] request to the remote agent, if
    // available. Servers MAY choose not to support this feature, or
    // not to request the data for efficiency reasons.
    // "REMOTE_IDENT" => "NYI"
    //
    env.set("REQUEST_METHOD", req.getMethod());
    env.set("SCRIPT_NAME", req.getContextPath() + req.getServletPath());
    env.set("SCRIPT_FILENAME", gitwebCgi.toAbsolutePath().toString());
    env.set("SERVER_NAME", req.getServerName());
    env.set("SERVER_PORT", Integer.toString(req.getServerPort()));
    env.set("SERVER_PROTOCOL", req.getProtocol());
    env.set("SERVER_SOFTWARE", getServletContext().getServerInfo());

    final Enumeration<String> hdrs = enumerateHeaderNames(req);
    while (hdrs.hasMoreElements()) {
      final String name = hdrs.nextElement();
      final String value = req.getHeader(name);
      env.set("HTTP_" + name.toUpperCase().replace('-', '_'), value);
    }

    env.set("GERRIT_CONTEXT_PATH", req.getContextPath() + "/");
    env.set("GERRIT_PROJECT_NAME", project.getProject().getName());

    if (project.forUser(anonymousUserProvider.get()).isVisible()) {
      env.set("GERRIT_ANONYMOUS_READ", "1");
    }

    String remoteUser = null;
    if (project.getCurrentUser().isIdentifiedUser()) {
      final IdentifiedUser u = (IdentifiedUser) project.getCurrentUser();
      final String user = u.getUserName();
      env.set("GERRIT_USER_NAME", user);
      if (user != null && !user.isEmpty()) {
        remoteUser = user;
      } else {
        remoteUser = "******" + u.getAccountId();
      }
    }
    env.set("REMOTE_USER", remoteUser);

    // Override CGI settings using alternative URI provided by gitweb.url.
    // This is required to trick gitweb into thinking that it's served under
    // different URL. Setting just $my_uri on the perl's side isn't enough,
    // because few actions (atom, blobdiff_plain, commitdiff_plain) rely on
    // URL returned by $cgi->self_url().
    //
    if (gitwebUrl != null) {
      int schemePort = -1;

      if (gitwebUrl.getScheme() != null) {
        if (gitwebUrl.getScheme().equals("http")) {
          env.set("HTTPS", "OFF");
          schemePort = 80;
        } else {
          env.set("HTTPS", "ON");
          schemePort = 443;
        }
      }

      if (gitwebUrl.getHost() != null) {
        env.set("SERVER_NAME", gitwebUrl.getHost());
        env.set("HTTP_HOST", gitwebUrl.getHost());
      }

      if (gitwebUrl.getPort() != -1) {
        env.set("SERVER_PORT", Integer.toString(gitwebUrl.getPort()));
      } else if (schemePort != -1) {
        env.set("SERVER_PORT", Integer.toString(schemePort));
      }

      if (gitwebUrl.getPath() != null) {
        env.set("SCRIPT_NAME", gitwebUrl.getPath().isEmpty() ? "/" : gitwebUrl.getPath());
      }
    }

    return env.getEnvArray();
  }
コード例 #6
0
ファイル: GitwebServlet.java プロジェクト: netroby/gerrit
  @Override
  protected void service(final HttpServletRequest req, final HttpServletResponse rsp)
      throws IOException {
    if (req.getQueryString() == null || req.getQueryString().isEmpty()) {
      // No query string? They want the project list, which we don't
      // currently support. Return to Gerrit's own web UI.
      //
      rsp.sendRedirect(req.getContextPath() + "/");
      return;
    }

    final Map<String, String> params = getParameters(req);
    String a = params.get("a");
    if (a != null) {
      if (deniedActions.contains(a)) {
        rsp.sendError(HttpServletResponse.SC_FORBIDDEN);
        return;
      }

      if (a.equals(PROJECT_LIST_ACTION)) {
        rsp.sendRedirect(
            req.getContextPath()
                + "/#"
                + PageLinks.ADMIN_PROJECTS
                + "?filter="
                + Url.encode(params.get("pf") + "/"));
        return;
      }
    }

    String name = params.get("p");
    if (name == null) {
      rsp.sendError(HttpServletResponse.SC_NOT_FOUND);
      return;
    }
    if (name.endsWith(".git")) {
      name = name.substring(0, name.length() - 4);
    }

    final Project.NameKey nameKey = new Project.NameKey(name);
    final ProjectControl project;
    try {
      project = projectControl.validateFor(nameKey);
      if (!project.allRefsAreVisible() && !project.isOwner()) {
        // Pretend the project doesn't exist
        throw new NoSuchProjectException(nameKey);
      }
    } catch (NoSuchProjectException e) {
      if (userProvider.get().isIdentifiedUser()) {
        rsp.sendError(HttpServletResponse.SC_NOT_FOUND);
      } else {
        // Allow anonymous users a chance to login.
        // Avoid leaking information by not distinguishing between
        // project not existing and no access rights.
        rsp.sendRedirect(getLoginRedirectUrl(req));
      }
      return;
    }

    try (Repository repo = repoManager.openRepository(nameKey)) {
      CacheHeaders.setNotCacheable(rsp);
      exec(req, rsp, project);
    } catch (RepositoryNotFoundException e) {
      getServletContext().log("Cannot open repository", e);
      rsp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
    }
  }
コード例 #7
0
 private boolean shouldReplicate(ProjectControl projectControl) {
   return projectControl.isReadable()
       && (!projectControl.isHidden() || config.replicateHiddenProjects());
 }
コード例 #8
0
  @Override
  protected void doGet(HttpServletRequest req, HttpServletResponse resp)
      throws ServletException, IOException {
    handleAuth(req);
    resp.setCharacterEncoding("UTF-8");
    final PrintWriter out = resp.getWriter();
    try {
      String pathInfo = req.getPathInfo();
      Pattern pattern = Pattern.compile("/([^/]*)(?:/([^/]*)(?:/(.*))?)?");
      Matcher matcher = pattern.matcher(pathInfo);
      matcher.matches();
      String projectName = null;
      String refName = null;
      String filePath = null;
      if (matcher.groupCount() > 0) {
        projectName = matcher.group(1);
        refName = matcher.group(2);
        filePath = matcher.group(3);
        if (projectName == null || projectName.equals("")) {
          projectName = null;
        } else {
          projectName = java.net.URLDecoder.decode(projectName, "UTF-8");
        }
        if (refName == null || refName.equals("")) {
          refName = null;
        } else {
          refName = java.net.URLDecoder.decode(refName, "UTF-8");
        }
        if (filePath == null || filePath.equals("")) {
          filePath = null;
        } else {
          filePath = java.net.URLDecoder.decode(filePath, "UTF-8");
        }
      }
      if (projectName != null) {
        if (filePath == null) filePath = "";
        NameKey projName = NameKey.parse(projectName);

        ProjectControl control;
        try {
          control = projControlFactory.controlFor(projName);
          if (!control.isVisible()) {
            log.debug("Project not visible!");
            resp.sendError(
                HttpServletResponse.SC_UNAUTHORIZED,
                "You need to be logged in to see private projects");
            return;
          }
        } catch (NoSuchProjectException e1) {
        }
        Repository repo = repoManager.openRepository(projName);
        if (refName == null) {
          JSONArray contents = new JSONArray();
          List<Ref> call;
          try {
            call = new Git(repo).branchList().call();
            Git git = new Git(repo);
            for (Ref ref : call) {
              JSONObject jsonObject = new JSONObject();
              try {
                jsonObject.put("name", ref.getName());
                jsonObject.put("type", "ref");
                jsonObject.put("size", "0");
                jsonObject.put("path", "");
                jsonObject.put("project", projectName);
                jsonObject.put("ref", ref.getName());
                lastCommit(git, null, ref.getObjectId(), jsonObject);
              } catch (JSONException e) {
              }
              contents.put(jsonObject);
            }
            String response = contents.toString();
            resp.setContentType("application/json");
            resp.setHeader("Cache-Control", "no-cache");
            resp.setHeader("ETag", "W/\"" + response.length() + "-" + response.hashCode() + "\"");
            log.debug(response);
            out.write(response);
          } catch (GitAPIException e) {
          }
        } else {
          Ref head = repo.getRef(refName);
          if (head == null) {
            JSONArray contents = new JSONArray();
            String response = contents.toString();
            resp.setContentType("application/json");
            resp.setHeader("Cache-Control", "no-cache");
            resp.setHeader("ETag", "W/\"" + response.length() + "-" + response.hashCode() + "\"");
            log.debug(response);
            out.write(response);
            return;
          }
          RevWalk walk = new RevWalk(repo);
          // add try catch to catch failures
          Git git = new Git(repo);
          RevCommit commit = walk.parseCommit(head.getObjectId());
          RevTree tree = commit.getTree();
          TreeWalk treeWalk = new TreeWalk(repo);
          treeWalk.addTree(tree);
          treeWalk.setRecursive(false);
          if (!filePath.equals("")) {
            PathFilter pathFilter = PathFilter.create(filePath);
            treeWalk.setFilter(pathFilter);
          }
          if (!treeWalk.next()) {
            CanonicalTreeParser canonicalTreeParser =
                treeWalk.getTree(0, CanonicalTreeParser.class);
            JSONArray contents = new JSONArray();
            if (canonicalTreeParser != null) {
              while (!canonicalTreeParser.eof()) {
                String path = canonicalTreeParser.getEntryPathString();
                FileMode mode = canonicalTreeParser.getEntryFileMode();
                listEntry(
                    path,
                    mode.equals(FileMode.TREE) ? "dir" : "file",
                    "0",
                    path,
                    projectName,
                    head.getName(),
                    git,
                    contents);
                canonicalTreeParser.next();
              }
            }
            String response = contents.toString();
            resp.setContentType("application/json");
            resp.setHeader("Cache-Control", "no-cache");
            resp.setHeader("ETag", "\"" + tree.getId().getName() + "\"");
            log.debug(response);
            out.write(response);
          } else {
            // if (treeWalk.isSubtree()) {
            // treeWalk.enterSubtree();
            // }

            JSONArray contents = getListEntries(treeWalk, repo, git, head, filePath, projectName);
            String response = contents.toString();

            resp.setContentType("application/json");
            resp.setHeader("Cache-Control", "no-cache");
            resp.setHeader("ETag", "\"" + tree.getId().getName() + "\"");
            log.debug(response);
            out.write(response);
          }
          walk.release();
          treeWalk.release();
        }
      }
    } catch (RepositoryNotFoundException e) {
      handleException(resp, e, 400);
    } catch (MissingObjectException e) {
      // example "Missing unknown 7035305927ca125757ecd8407e608f6dcf0bd8a5"
      // usually indicative of being unable to locate a commit from a submodule
      log.error(e.getMessage(), e);
      String msg =
          e.getMessage()
              + ".  This exception could have been caused by the use of a git submodule, "
              + "which is currently not supported by the repository browser.";
      handleException(resp, new Exception(msg), 501);
    } catch (IOException e) {
      handleException(resp, e, 500);
    } finally {
      out.close();
    }
  }