Exemple #1
0
  private void cannotUnset(Entry entry, String attrName) {
    boolean good = false;

    try {
      unsetByEmptyString(entry, attrName);
    } catch (ServiceException e) {
      if (ServiceException.INVALID_REQUEST.equals(e.getCode())
          && e.getMessage().contains("is a required attribute")) good = true;
    }
    assertTrue(good);

    try {
      unsetByNull(entry, attrName);
    } catch (ServiceException e) {
      if (ServiceException.INVALID_REQUEST.equals(e.getCode())
          && e.getMessage().contains("is a required attribute")) good = true;
    }
    assertTrue(good);
  }
 public static void main(String[] args) {
   CliUtil.toolSetup();
   FixCalendarPriorityUtil util = null;
   try {
     util = new FixCalendarPriorityUtil();
   } catch (ServiceException e) {
     System.err.println(e.getMessage());
     System.exit(1);
   }
   try {
     CommandLine cl = util.getCommandLine(args);
     if (cl == null) return;
     util.doit(getZAuthToken(cl), cl.getOptionValues(O_ACCOUNT), cl.hasOption(O_SYNC));
     System.exit(0);
   } catch (ParseException e) {
     util.usage(e);
   } catch (Exception e) {
     System.err.println("Error occurred: " + e.getMessage());
     util.usage(null);
   }
   System.exit(1);
 }
Exemple #3
0
  @Test
  public void testCallbackMailSignature() throws Exception {
    Account acct = getAccount();
    String attrName = Provisioning.A_zimbraPrefMailSignature;

    unsetTest(acct, attrName);

    // set a limit on cos
    Cos cos = getCos();
    setAttr(cos, Provisioning.A_zimbraMailSignatureMaxLength, "10");

    // cannot have signature longer than the max len
    boolean good = false;
    Map<String, Object> attrs = new HashMap<String, Object>();
    attrs.put(attrName, "12345678901");
    try {
      prov.modifyAttrs(acct, attrs);
    } catch (ServiceException e) {
      if (ServiceException.INVALID_REQUEST.equals(e.getCode())
          && e.getMessage().contains("is longer than the limited value")) good = true;
    }
    assertTrue(good);
  }
Exemple #4
0
 public Element handleNetworkRequest(Element document, Map context)
     throws ServiceException
 {
     Element backup;
     String method;
     String bkupTarget;
     String label;
     Element response;
     Log.backup.info("Backup request started");
     ZimbraSoapContext lc = getZimbraSoapContext(context);
     checkRights(lc, context);
     backup = document.getElement("backup");
     method = backup.getAttribute("method");
     bkupTarget = backup.getAttribute("target", null);
     label = backup.getAttribute("label", null);
     response = lc.createElement(BackupService.BACKUP_RESPONSE);
     BackupManager mgr;
     BackupTarget backupTarget;
     boolean sync;
     boolean sentReportEmail;
     ServiceException error;
     mgr = BackupManager.getInstance();
     if(bkupTarget != null && "incremental".equals(method))
         throw ServiceException.FAILURE("Custom backup target is not allowed for incremental backup", null);
     backupTarget = mgr.getBackupTarget(bkupTarget, true);
     if("abort".equals(method))
     {
         BackupSet bak = backupTarget.getBackupSet(label);
         bak.abortFullBackup();
         break MISSING_BLOCK_LABEL_852;
     }
     if("delete".equals(method))
     {
         String val = backup.getAttribute("before");
         long cutoffTime = getCutoffTime(val, backupTarget);
         mgr.deleteBackups(backupTarget, cutoffTime);
         break MISSING_BLOCK_LABEL_852;
     }
     sync = backup.getAttributeBool("sync", false);
     sentReportEmail = false;
     error = null;
     BackupParams params;
     List syncBackups;
     BackupSet fullBak;
     BackupSet incrBak;
     params = new BackupParams();
     params.sync = sync;
     parseComponentIncludeExcludeAttrs(backup, params);
     Element fcOptsElem = backup.getOptionalElement("fileCopier");
     if(fcOptsElem != null)
         params.fcOpts = ParseXML.parseFileCopierOptions(fcOptsElem);
     syncBackups = new ArrayList();
     fullBak = null;
     incrBak = null;
     int size;
     try
     {
         com.zimbra.cs.backup.BackupManager.BackupMode backupMode = mgr.getBackupMode();
         boolean autoGroupedMode = com.zimbra.cs.backup.BackupManager.BackupMode.AUTO_GROUPED.equals(backupMode);
         if("full".equals(method))
         {
             params.zip = backup.getAttributeBool("zip", true);
             params.zipStore = backup.getAttributeBool("zipStore", true);
             List acctElems = backup.listElements("account");
             if(acctElems.size() > 0)
             {
                 params.redologs = false;
                 List acctNames = parseAccountNames(acctElems);
                 boolean all = acctNames.size() == 1 && "all".equals(acctNames.get(0));
                 if(all)
                 {
                     if(!sync)
                         fullBak = mgr.startBackupFull(backupTarget, params);
                     else
                         fullBak = mgr.backupFull(backupTarget, params, syncBackups);
                 } else
                 {
                     com.zimbra.cs.account.Account accounts[] = mgr.lookupAccounts(acctNames, com.zimbra.cs.account.Provisioning.AccountBy.name, backupTarget);
                     if(!sync)
                         fullBak = mgr.startBackupFull(accounts, backupTarget, params);
                     else
                         fullBak = mgr.backupFull(accounts, backupTarget, params, syncBackups);
                 }
             } else
             if(autoGroupedMode)
             {
                 if(backupTarget.isCustom())
                     throw ServiceException.FAILURE("Custom backup target is not allowed for auto-grouped backup", null);
                 params.redologs = true;
                 com.zimbra.cs.account.Account accounts[] = mgr.lookupAccountsByOldestBackup(backupTarget);
                 if(accounts == null || accounts.length == 0)
                     throw BackupServiceException.AUTO_GROUPED_BACKUP_TOO_SOON();
                 if(!sync)
                     fullBak = mgr.startBackupFull(accounts, backupTarget, params);
                 else
                     fullBak = mgr.backupFull(accounts, backupTarget, params, syncBackups);
             } else
             {
                 throw ServiceException.INVALID_REQUEST("Missing account list", null);
             }
         } else
         if("incremental".equals(method))
         {
             params.zip = backup.getAttributeBool("zip", true);
             params.zipStore = backup.getAttributeBool("zipStore", true);
             BackupSet baks[] = mgr.backupIncremental(backupTarget, params, syncBackups);
             incrBak = baks[0];
             fullBak = baks[1];
         } else
         {
             throw ServiceException.INVALID_REQUEST((new StringBuilder()).append("Invalid backup method: ").append(method).toString(), null);
         }
     }
     catch(IOException e)
     {
         throw ServiceException.FAILURE(e.getMessage(), e);
     }
     size = syncBackups.size();
     if(size > 0)
     {
         BackupSet baks[] = new BackupSet[size];
         syncBackups.toArray(baks);
         mgr.sendReportEmail(baks);
         sentReportEmail = true;
     }
     break MISSING_BLOCK_LABEL_756;
     Exception exception;
     exception;
     int size = syncBackups.size();
     if(size > 0)
     {
         BackupSet baks[] = new BackupSet[size];
         syncBackups.toArray(baks);
         mgr.sendReportEmail(baks);
         sentReportEmail = true;
     }
     throw exception;
     Element body = response.addElement("backup");
     if(fullBak != null)
         body.addAttribute("label", fullBak.getLabel());
     if(incrBak != null)
         body.addAttribute("incr-label", incrBak.getLabel());
     if(error != null && !sentReportEmail)
         mgr.sendErrorReportEmail(error);
     break MISSING_BLOCK_LABEL_852;
     ServiceException e;
     e;
     error = e;
     throw e;
     Exception exception1;
     exception1;
     if(error != null && !sentReportEmail)
         mgr.sendErrorReportEmail(error);
     throw exception1;
     Log.backup.info("Backup request finished");
     return response;
     IOException e;
     e;
     throw ServiceException.FAILURE(e.getMessage(), e);
 }
Exemple #5
0
    @Override
    public Collection<AddressObject> match(DavContext ctxt, AddressbookCollection folder) {
      // search the folder for #key:val where key is mName and val is mTextMatch.mText.
      // boolean ignoreCase = mCollation.equals(DavElements.ASCII);
      ArrayList<AddressObject> result = new ArrayList<AddressObject>();
      StringBuilder search = new StringBuilder();
      if (mNegate) search.append("!");
      AttrMapping mapping = sAttrMappings.get(mEnclosingFilter.getName().toUpperCase());
      if (mapping == null) return result;
      String[] attrs = mapping.getAttrs();
      search.append("(");
      boolean first = true;
      for (String key : attrs) {
        if (!first) search.append(" OR ");
        search.append("#").append(key).append(":");
        if (mMatch == MatchType.contains || mMatch == MatchType.ends_with) search.append("*");
        search.append(mText);
        if (mMatch == MatchType.contains || mMatch == MatchType.starts_with) search.append("*");
        first = false;
      }
      search.append(")");
      String filter = search.toString();
      ZimbraLog.dav.debug("Search Filter: %s", filter);
      ZimbraQueryResults zqr = null;
      try {
        Mailbox mbox = ctxt.getTargetMailbox();
        if (mbox == null) {
          ZimbraLog.dav.debug("Can't get target mailbox for %s", ctxt.getUser());
          return result;
        }
        zqr =
            mbox.index.search(
                ctxt.getOperationContext(),
                filter,
                EnumSet.of(MailItem.Type.CONTACT),
                SortBy.NAME_ASC,
                100);
        while (zqr.hasNext()) {
          ZimbraHit hit = zqr.getNext();
          if (hit instanceof ContactHit) {
            result.add(new AddressObject(ctxt, ((ContactHit) hit).getContact()));
          }
        }
      } catch (Exception e) {
        ZimbraLog.dav.warn("can't get target mailbox", e);
        return result;
      } finally {
        Closeables.closeQuietly(zqr);
      }
      boolean includeGal = true;
      if (includeGal) {
        StringBuilder query = new StringBuilder();
        if (mMatch == MatchType.contains || mMatch == MatchType.ends_with) query.append("*");
        query.append(mText);
        if (mMatch == MatchType.contains || mMatch == MatchType.starts_with) query.append("*");
        ZimbraLog.dav.debug("Gal query: %s", query.toString());

        GalSearchParams params = new GalSearchParams(ctxt.getAuthAccount());
        params.setType(GalSearchType.account);
        params.setQuery(query.toString());
        params.setResultCallback(new Callback(ctxt, result, params));
        GalSearchControl gal = new GalSearchControl(params);
        try {
          gal.search();
        } catch (ServiceException e) {
          if (ServiceException.PERM_DENIED.equals(e.getCode()))
            ZimbraLog.dav.debug(
                "Can't get gal search result for %s (%s)", ctxt.getUser(), e.getMessage());
          else ZimbraLog.dav.error("Can't get gal search result for %s", ctxt.getUser());
        }
      }
      return result;
    }
  public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
      throws IOException, ServletException {
    if (!isHttpReq(request, response)) {
      return;
    }
    HttpServletRequest req = (HttpServletRequest) request;
    HttpServletResponse resp = (HttpServletResponse) response;

    AuthToken authToken;
    try {
      authToken = getAuthTokenForApp(req, resp, false);
    } catch (ServiceException se) {
      ZimbraLog.zimlet.info("can't get authToken: " + se.getMessage());
      resp.sendError(HttpServletResponse.SC_FORBIDDEN);
      return;
    }

    if (authToken == null) {
      // error was already sent out
      return;
    }

    boolean isAdminAuth = false;
    //		ZimbraLog.zimlet.info(">>> isAdminAuth: "+isAdminAuth);

    // get list of allowed zimlets
    Provisioning prov = Provisioning.getInstance();
    List<Zimlet> allowedZimlets = new LinkedList<Zimlet>();
    List<Zimlet> allZimlets = new LinkedList<Zimlet>();
    try {
      isAdminAuth =
          AdminAccessControl.getAdminAccessControl(authToken)
              .isSufficientAdminForZimletFilterServlet();

      // add all available zimlets
      if (!isAdminAuth) {
        // zimlets for this account's COS
        Account account = prov.get(AccountBy.id, authToken.getAccountId(), authToken);
        for (String zimletName : ZimletUtil.getAvailableZimlets(account).getZimletNamesAsArray()) {
          Zimlet zimlet = prov.getZimlet(zimletName);
          if (zimlet == null) continue;
          if (zimlet.isEnabled()) {
            allowedZimlets.add(zimlet);
          }
          allZimlets.add(zimlet);
        }
      }

      // add the admin zimlets
      else {
        allZimlets = prov.listAllZimlets();
        Iterator<Zimlet> iter = allZimlets.iterator();
        while (iter.hasNext()) {
          Zimlet zimlet = iter.next();
          if (zimlet.isExtension()) {
            if (zimlet.isEnabled()) {
              allowedZimlets.add(zimlet);
            }
          }
        }
      }
    } catch (ServiceException e) {
      ZimbraLog.zimlet.info("unable to get list of zimlets");
      resp.sendError(HttpServletResponse.SC_FORBIDDEN);
      return;
    }

    // order by priority
    List<Zimlet> zimletList = ZimletUtil.orderZimletsByPriority(allowedZimlets);
    Set<String> allowedZimletNames = getZimletNames(zimletList);
    Set<String> allZimletNames = getZimletNames(allZimlets);

    // get list of zimlets for request
    Set<String> zimletNames = new LinkedHashSet<String>();
    String uri = req.getRequestURI();
    boolean isZimletRes = uri.startsWith(ZIMLET_RES_URL_PREFIX);
    if (isZimletRes) {
      zimletNames.addAll(allowedZimletNames);
    } else {
      Matcher matcher = mPattern.matcher(uri);
      if (!matcher.matches()) {
        ZimbraLog.zimlet.info("no zimlet specified in request");
        resp.sendError(HttpServletResponse.SC_FORBIDDEN);
        return;
      }
      zimletNames.add(matcher.group(1));
    }

    // check access
    File basedir = new File(LC.zimlet_directory.value());
    File devdir = new File(basedir, ZimletUtil.ZIMLET_DEV_DIR);
    Iterator<String> iter = zimletNames.iterator();
    while (iter.hasNext()) {
      String zimletName = iter.next();
      try {
        File devfile = new File(devdir, zimletName);
        if (devfile.exists()) {
          continue;
        }

        Zimlet zimlet = prov.getZimlet(zimletName);
        if (zimlet == null) {
          ZimbraLog.zimlet.info("no such zimlet: " + zimletName);
          iter.remove();
          allZimlets.remove(zimlet);
          continue;
        }

        if (!allowedZimletNames.contains(zimletName)) {
          ZimbraLog.zimlet.info(
              "unauthorized request to zimlet "
                  + zimletName
                  + " from user "
                  + authToken.getAccountId());
          iter.remove();
          allZimlets.remove(zimlet);
          continue;
        }

        if (zimlet.isExtension() && !isAdminAuth) {
          //					ZimbraLog.zimlet.info("!!!!! removing extension zimlet: "+zimletName);
          iter.remove();
          allZimlets.remove(zimlet);
        }
      } catch (ServiceException se) {
        ZimbraLog.zimlet.info(
            "service exception to zimlet "
                + zimletName
                + " from user "
                + authToken.getAccountId()
                + ": "
                + se.getMessage());
        iter.remove();
      }
    }

    if (!isZimletRes) {
      Matcher matcher = mPattern.matcher(uri);
      if (matcher.matches()) {
        String zimletName = matcher.group(1);
        if (!zimletNames.contains(zimletName)) {
          resp.sendError(HttpServletResponse.SC_FORBIDDEN);
          return;
        }
      }
    }

    // force compilation of template
    if (uri.endsWith(".template.js")) {
      Matcher matcher = mPattern.matcher(uri);
      if (matcher.matches()) {
        String zimletName = matcher.group(1);
        String opath = matcher.group(3);
        String ipath = opath.replaceAll(".js$", "");
        boolean isDevZimlet = uri.indexOf("_dev") != -1;
        File zimletDir = new File(isDevZimlet ? devdir : basedir, zimletName);
        File ifile = new File(zimletDir, ipath);
        File ofile = new File(zimletDir, opath);
        if (!ofile.exists() || (ifile.exists() && ifile.lastModified() > ofile.lastModified())) {
          String prefix = zimletName + ".";
          try {
            TemplateCompiler.compile(
                zimletDir, zimletDir, prefix, new String[] {ipath}, true, true);
          } catch (IOException e) {
            // ignore, let fail
          }
        }
      }
    }

    // process request
    req.setAttribute(ZimletFilter.ALLOWED_ZIMLETS, zimletNames);
    req.setAttribute(ZimletFilter.ALL_ZIMLETS, allZimletNames);
    chain.doFilter(req, resp);
  }