예제 #1
0
  public static ZimbraException wrap(Exception exception) {
    try {
      throw exception;
    } catch (LdapException ldapException) {
      return mExceptionMap.get(LDAP_EXCEPTION).create(ldapException);
    }
    /* $if ZimbraVersion >= 7.1.3 $ */
    catch (com.zimbra.cs.extension.ExtensionException extensionException) {
      return mExceptionMap.get(EXTENSION_EXCEPTION).create(extensionException);
    }
    /* $endif $ */
    catch (com.zimbra.cs.zimlet.ZimletException zimletException) {
      return mExceptionMap.get(ZIMLET_EXCEPTION).create(zimletException);
    } catch (com.zimbra.cs.account.AuthTokenException authTokenException) {
      return mExceptionMap.get(AUTH_TOKEN_EXCEPTION).create(authTokenException);
    } catch (ServiceException serviceException) {
      String code = serviceException.getCode();
      if (mExceptionMap.containsKey(code)) {
        return mExceptionMap.get(code).create(serviceException);
      }
    } catch (Throwable ignored) {
    }

    return mExceptionMap.get(DEFAULT).create(exception);
  }
예제 #2
0
  public static Period decodeMetadata(Metadata meta, ICalTimeZone tz, TimeZoneMap tzmap)
      throws ServiceException {
    String start = meta.get(FN_START);
    ParsedDateTime startTime;
    try {
      startTime = ParsedDateTime.parse(start, tzmap, tz, tzmap.getLocalTimeZone());
    } catch (ParseException e) {
      throw ServiceException.INVALID_REQUEST(
          "Invalid PERIOD start time in metadata: " + meta.toString(), e);
    }

    String end = meta.get(FN_END, null);
    if (end != null) {
      ParsedDateTime endTime;
      try {
        endTime = ParsedDateTime.parse(end, tzmap, tz, tzmap.getLocalTimeZone());
      } catch (ParseException e) {
        throw ServiceException.INVALID_REQUEST(
            "Invalid PERIOD end time in metadata: " + meta.toString(), e);
      }
      return new Period(startTime, endTime);
    } else {
      String durStr = meta.get(FN_DURATION, null);
      if (durStr == null)
        throw ServiceException.INVALID_REQUEST(
            "PERIOD in metadata missing both end time and duration: " + meta.toString(), null);
      ParsedDuration duration = ParsedDuration.parse(durStr);
      return new Period(startTime, duration);
    }
  }
  @Override
  public String writeStreamToStore(InputStream in, long actualSize, Mailbox mbox)
      throws IOException, ServiceException {
    MessageDigest digest;
    try {
      digest = MessageDigest.getInstance("SHA-256");
    } catch (NoSuchAlgorithmException e) {
      throw ServiceException.FAILURE("SHA-256 digest not found", e);
    }
    ByteUtil.PositionInputStream pin =
        new ByteUtil.PositionInputStream(new DigestInputStream(in, digest));

    HttpClient client = ZimbraHttpConnectionManager.getInternalHttpConnMgr().newHttpClient();
    PostMethod post = new PostMethod(getPostUrl(mbox));
    try {
      HttpClientUtil.addInputStreamToHttpMethod(post, pin, actualSize, "application/octet-stream");
      int statusCode = HttpClientUtil.executeMethod(client, post);
      if (statusCode == HttpStatus.SC_OK
          || statusCode == HttpStatus.SC_CREATED
          || statusCode == HttpStatus.SC_NO_CONTENT) {
        return getLocator(
            post, ByteUtil.encodeFSSafeBase64(digest.digest()), pin.getPosition(), mbox);
      } else {
        throw ServiceException.FAILURE("error POSTing blob: " + post.getStatusText(), null);
      }
    } finally {
      post.releaseConnection();
    }
  }
예제 #4
0
  public static void updateTask(DbConnection conn, ScheduledTask task) throws ServiceException {
    ZimbraLog.scheduler.debug("Updating %s", task);

    PreparedStatement stmt = null;
    try {
      stmt =
          conn.prepareStatement(
              "UPDATE  "
                  + TABLE_SCHEDULED_TASK
                  + " SET mailbox_id = ?, exec_time = ?, interval_millis = ?, metadata = ? "
                  + "WHERE class_name = ? AND name = ?");
      stmt.setInt(1, task.getMailboxId());
      stmt.setTimestamp(2, DbUtil.dateToTimestamp(task.getExecTime()));
      if (task.getIntervalMillis() > 0) {
        stmt.setLong(3, task.getIntervalMillis());
      } else {
        stmt.setNull(3, Types.INTEGER);
      }
      stmt.setString(4, getEncodedMetadata(task));
      stmt.setString(5, task.getClass().getName());
      stmt.setString(6, task.getName());

      int numRows = stmt.executeUpdate();
      if (numRows != 1) {
        String msg = String.format("Unexpected number of rows (%d) updated for %s", numRows, task);
        throw ServiceException.FAILURE(msg, null);
      }
    } catch (SQLException e) {
      throw ServiceException.FAILURE("Unable to update " + task, e);
    } finally {
      DbPool.closeStatement(stmt);
    }
  }
예제 #5
0
 /**
  * Remove mapping for a given localId
  *
  * @throws ServiceException
  */
 public void removeTagMapping(int tagId) throws ServiceException {
   // delete the mapping if it was needed and exists
   if (mappingRequired) {
     try {
       DataSourceMapping mapping = new DataSourceMapping(tagDs, tagId);
       mapping.delete();
       localIdFromRemote.remove(Integer.valueOf(mapping.getRemoteId()));
       remoteIdFromLocal.remove(tagId);
       if (localIdsByName.containsValue(tagId)) {
         Set<String> keysToRemove =
             new HashSet<
                 String>(); // should only be one, but naming conflicts might end up with more..
         for (Entry<String, Integer> entry : localIdsByName.entrySet()) {
           if (entry.getValue().equals(tagId)) {
             keysToRemove.add(entry.getKey());
           }
         }
         for (String key : keysToRemove) {
           localIdsByName.remove(key);
         }
       }
       OfflineLog.offline.debug("removed tag mapping for localId %d", tagId);
       // TODO: consider the case where we have > 63 tags.
       // we can move one of the overflow tags into a free slot, but we also have to apply the tag
       // to existing messages
     } catch (ServiceException se) {
       if (!MailServiceException.NO_SUCH_ITEM.equals(se.getCode())) {
         throw se;
       }
     }
   }
 }
예제 #6
0
파일: TargetType.java 프로젝트: koem/Zimbra
  /**
   * central place where a target should be loaded
   *
   * @param prov
   * @param targetType
   * @param targetBy
   * @param target
   * @return
   * @throws ServiceException
   */
  static Entry lookupTarget(
      Provisioning prov, TargetType targetType, TargetBy targetBy, String target, boolean mustFind)
      throws ServiceException {
    Entry targetEntry = null;

    switch (targetType) {
      case account:
        targetEntry = prov.get(AccountBy.fromString(targetBy.name()), target);
        if (targetEntry == null && mustFind) throw AccountServiceException.NO_SUCH_ACCOUNT(target);
        break;
      case calresource:
        targetEntry = prov.get(CalendarResourceBy.fromString(targetBy.name()), target);
        if (targetEntry == null && mustFind)
          throw AccountServiceException.NO_SUCH_CALENDAR_RESOURCE(target);
        break;
      case dl:
        targetEntry = prov.getAclGroup(DistributionListBy.fromString(targetBy.name()), target);
        if (targetEntry == null && mustFind)
          throw AccountServiceException.NO_SUCH_DISTRIBUTION_LIST(target);
        break;
      case domain:
        targetEntry = prov.get(DomainBy.fromString(targetBy.name()), target);
        if (targetEntry == null && mustFind) throw AccountServiceException.NO_SUCH_DOMAIN(target);
        break;
      case cos:
        targetEntry = prov.get(CosBy.fromString(targetBy.name()), target);
        if (targetEntry == null && mustFind) throw AccountServiceException.NO_SUCH_COS(target);
        break;
      case server:
        targetEntry = prov.get(ServerBy.fromString(targetBy.name()), target);
        if (targetEntry == null && mustFind) throw AccountServiceException.NO_SUCH_SERVER(target);
        break;
      case xmppcomponent:
        targetEntry = prov.get(XMPPComponentBy.fromString(targetBy.name()), target);
        if (targetEntry == null && mustFind)
          throw AccountServiceException.NO_SUCH_XMPP_COMPONENT(target);
        break;
      case zimlet:
        ZimletBy zimletBy = ZimletBy.fromString(targetBy.name());
        if (zimletBy != ZimletBy.name)
          throw ServiceException.INVALID_REQUEST("zimlet must be by name", null);
        targetEntry = prov.getZimlet(target);
        if (targetEntry == null && mustFind) throw AccountServiceException.NO_SUCH_ZIMLET(target);
        break;
      case config:
        targetEntry = prov.getConfig();
        break;
      case global:
        targetEntry = prov.getGlobalGrant();
        break;
      default:
        ServiceException.INVALID_REQUEST(
            "invallid target type for lookupTarget:" + targetType.toString(), null);
    }

    return targetEntry;
  }
예제 #7
0
    // public only for unit test. TODO: cleanup unit test
    public Grantee(NamedEntry grantee, boolean adminOnly) throws ServiceException {
      super(grantee);

      Provisioning prov = grantee.getProvisioning();
      GroupMembership granteeGroups = null;

      if (grantee instanceof Account) {
        mGranteeType = GranteeType.GT_USER;
        mGranteeDomain = prov.getDomain((Account) grantee);
        granteeGroups = prov.getGroupMembership((Account) grantee, adminOnly);

      } else if (grantee instanceof DistributionList) {
        mGranteeType = GranteeType.GT_GROUP;
        mGranteeDomain = prov.getDomain((DistributionList) grantee);
        granteeGroups = prov.getGroupMembership((DistributionList) grantee, adminOnly);

      } else if (grantee instanceof DynamicGroup) {
        mGranteeType = GranteeType.GT_GROUP;
        mGranteeDomain = prov.getDomain((DynamicGroup) grantee);
        // no need to get membership for dynamic groups
        // dynamic groups cannot be nested, either as a members in another
        // dynamic group or a distribution list

      } else {
        if (adminOnly) {
          throw ServiceException.INVALID_REQUEST("invalid grantee type", null);
        } else {
          if (grantee instanceof Domain) {
            mGranteeType = GranteeType.GT_DOMAIN;
            mGranteeDomain = (Domain) grantee;
          }
        }
      }

      if (adminOnly) {
        if (!RightBearer.isValidGranteeForAdminRights(mGranteeType, grantee)) {
          throw ServiceException.INVALID_REQUEST("invalid grantee", null);
        }
      }

      if (mGranteeDomain == null) {
        throw ServiceException.FAILURE("internal error, cannot get domain for grantee", null);
      }

      // setup grantees ids
      mIdAndGroupIds = new HashSet<String>();
      mIdAndGroupIds.add(grantee.getId());
      if (granteeGroups != null) {
        mIdAndGroupIds.addAll(granteeGroups.groupIds());
      }
    }
예제 #8
0
  public Element handle(Element request, Map<String, Object> context) throws ServiceException {
    ZimbraSoapContext zsc = getZimbraSoapContext(context);
    Account account = getRequestedAccount(zsc);

    if (!canModifyOptions(zsc, account))
      throw ServiceException.PERM_DENIED("can not modify options");

    HashMap<String, Object> prefs = new HashMap<String, Object>();
    Map<String, Set<String>> name2uniqueAttrValues = new HashMap<String, Set<String>>();
    for (KeyValuePair kvp :
        request.listKeyValuePairs(AccountConstants.E_PREF, AccountConstants.A_NAME)) {
      String name = kvp.getKey(), value = kvp.getValue();
      char ch = name.length() > 0 ? name.charAt(0) : 0;
      int offset = ch == '+' || ch == '-' ? 1 : 0;
      if (!name.startsWith(PREF_PREFIX, offset))
        throw ServiceException.INVALID_REQUEST("pref name must start with " + PREF_PREFIX, null);

      AttributeInfo attrInfo =
          AttributeManager.getInstance().getAttributeInfo(name.substring(offset));
      if (attrInfo == null) {
        throw ServiceException.INVALID_REQUEST("no such attribute: " + name, null);
      }
      if (attrInfo.isCaseInsensitive()) {
        String valueLowerCase = Strings.nullToEmpty(value).toLowerCase();
        if (name2uniqueAttrValues.get(name) == null) {
          Set<String> set = new HashSet<String>();
          set.add(valueLowerCase);
          name2uniqueAttrValues.put(name, set);
          StringUtil.addToMultiMap(prefs, name, value);
        } else {
          Set<String> set = name2uniqueAttrValues.get(name);
          if (set.add(valueLowerCase)) {
            StringUtil.addToMultiMap(prefs, name, value);
          }
        }
      } else {
        StringUtil.addToMultiMap(prefs, name, value);
      }
    }

    if (prefs.containsKey(Provisioning.A_zimbraPrefMailForwardingAddress)) {
      if (!account.getBooleanAttr(Provisioning.A_zimbraFeatureMailForwardingEnabled, false))
        throw ServiceException.PERM_DENIED("forwarding not enabled");
    }

    // call modifyAttrs and pass true to checkImmutable
    Provisioning.getInstance().modifyAttrs(account, prefs, true, zsc.getAuthToken());

    Element response = zsc.createElement(AccountConstants.MODIFY_PREFS_RESPONSE);
    return response;
  }
예제 #9
0
  static boolean validateCrossDomainAdminGrant(Right right, GranteeType granteeType)
      throws ServiceException {
    if (right == Admin.R_crossDomainAdmin && granteeType != GranteeType.GT_DOMAIN) {
      throw ServiceException.INVALID_REQUEST(
          "grantee for right " + Admin.R_crossDomainAdmin.getName() + " must be a domain.", null);
    }

    if (right != Admin.R_crossDomainAdmin && granteeType == GranteeType.GT_DOMAIN) {
      throw ServiceException.INVALID_REQUEST(
          "grantee for right " + right.getName() + " cannot be a domain.", null);
    }

    return right == Admin.R_crossDomainAdmin;
  }
예제 #10
0
 /** Tests Invalid image attachment (bug 71868). */
 @Test
 public void createInvalidImageAttachment() throws Exception {
   // Create a contact with an attachment.
   Map<String, String> attrs = new HashMap<String, String>();
   attrs.put("fullName", "Get Attachment Content");
   byte[] attachData = "attachment 1".getBytes();
   Attachment attachment = new Attachment(attachData, "image/png", "image", "file1.png");
   try {
     ParsedContact pc = new ParsedContact(attrs, Lists.newArrayList(attachment));
     Assert.fail("Expected INVALID_IMAGE exception");
   } catch (ServiceException se) {
     Assert.assertEquals("check the INVALID_IMAGE exception", "mail.INVALID_IMAGE", se.getCode());
   }
 }
예제 #11
0
  private static Account validateAuthTokenInternal(
      Provisioning prov, AuthToken at, boolean addToLoggingContext) throws ServiceException {
    if (prov == null) {
      prov = Provisioning.getInstance();
    }

    if (at.isExpired()) {
      throw ServiceException.AUTH_EXPIRED();
    }

    // make sure that the authenticated account is still active and has not been deleted since the
    // last request
    String acctId = at.getAccountId();
    Account acct = prov.get(AccountBy.id, acctId, at);

    if (acct == null) {
      throw ServiceException.AUTH_EXPIRED("account " + acctId + " not found");
    }

    if (addToLoggingContext) {
      ZimbraLog.addAccountNameToContext(acct.getName());
    }

    if (!acct.checkAuthTokenValidityValue(at)) {
      throw ServiceException.AUTH_EXPIRED("invalid validity value");
    }

    boolean delegatedAuth = at.isDelegatedAuth();
    String acctStatus = acct.getAccountStatus(prov);

    if (!delegatedAuth && !Provisioning.ACCOUNT_STATUS_ACTIVE.equals(acctStatus)) {
      throw ServiceException.AUTH_EXPIRED("account not active");
    }

    // if using delegated auth, make sure the "admin" is really an active admin account
    if (delegatedAuth) {

      // note that delegated auth allows access unless the account's in maintenance mode
      if (Provisioning.ACCOUNT_STATUS_MAINTENANCE.equals(acctStatus)) {
        throw ServiceException.AUTH_EXPIRED("delegated account in MAINTENANCE mode");
      }

      Account admin = prov.get(AccountBy.id, at.getAdminAccountId());
      if (admin == null) {
        throw ServiceException.AUTH_EXPIRED(
            "delegating account " + at.getAdminAccountId() + " not found");
      }

      boolean isAdmin = AdminAccessControl.isAdequateAdminAccount(admin);
      if (!isAdmin) {
        throw ServiceException.PERM_DENIED("not an admin for delegated auth");
      }

      if (!Provisioning.ACCOUNT_STATUS_ACTIVE.equals(admin.getAccountStatus(prov))) {
        throw ServiceException.AUTH_EXPIRED("delegating account is not active");
      }
    }

    return acct;
  }
예제 #12
0
 private void checkError() throws ServiceException {
   synchronized (mErrorLock) {
     if (mError != null)
       throw ServiceException.FAILURE(
           "Redo playback stopped due to an earlier error: " + mError.getMessage(), mError);
   }
 }
예제 #13
0
  static Boolean checkCrossDomainAdminRight(
      Provisioning prov, Domain granteeDomain, Entry target, boolean canDelegateNeeded)
      throws ServiceException {
    if (!(target instanceof Domain)) throw ServiceException.FAILURE("internal error", null);

    // see if there is a cross domain right on the target domain
    List<ZimbraACE> acl = ACLUtil.getAllACEs(target);
    if (acl == null) return Boolean.FALSE;

    for (ZimbraACE ace : acl) {
      /*
       * about the crossDomainAdmin right:
       *   - is a domain right
       *   - not inheritable from the global grant entry,
       *     i.e., can only be granted on domain, not the
       *     global grant.
       *   - cannot be bundled in a combo right
       *   - is the only right for that the grantee has
       *     to be a domain.
       */
      if (ace.getRight() == Admin.R_crossDomainAdmin) {

        if (ace.getGranteeType() == GranteeType.GT_DOMAIN
            && ace.getGrantee().equals(granteeDomain.getId())) {
          if (ace.deny()) return Boolean.FALSE;
          else if (canDelegateNeeded && ace.canExecuteOnly()) return false;
          else return Boolean.TRUE;
        }
      }
    }

    return Boolean.FALSE; // nope, no crossDomainAdmin
  }
예제 #14
0
  /**
   * Determines the set of {@link Message}s to be deleted from this <code>Conversation</code>.
   * Assembles a new {@link PendingDelete} object encapsulating the data on the items to be deleted.
   *
   * <p>A message will be deleted unless:
   *
   * <ul>
   *   <li>The caller lacks {@link ACL#RIGHT_DELETE} permission on the <code>Message</code>.
   *   <li>The caller has specified a {@link MailItem.TargetConstraint} that explicitly excludes the
   *       <code>Message</code>.
   *   <li>The caller has specified the maximum change number they know about, and the
   *       (modification/content) change number on the <code>Message</code> is greater.
   * </ul>
   *
   * As a result of all these constraints, no messages may actually be deleted.
   *
   * @throws ServiceException The following error codes are possible:
   *     <ul>
   *       <li><code>mail.MODIFY_CONFLICT</code> - if the caller specified a max change number and a
   *           modification check, and the modified change number of the <code>Message</code> is
   *           greater
   *       <li><code>service.FAILURE</code> - if there's a database failure fetching the message
   *           list
   *     </ul>
   */
  @Override
  PendingDelete getDeletionInfo() throws ServiceException {
    PendingDelete info = new PendingDelete();
    info.rootId = mId;
    info.itemIds.add(getType(), mId);

    if (mData.size == 0) return info;
    List<Message> msgs = getMessages();
    TargetConstraint tcon = mMailbox.getOperationTargetConstraint();

    boolean excludeModify = false, excludeAccess = false;
    for (Message child : msgs) {
      // silently skip explicitly excluded messages, PERMISSION_DENIED messages, and MODIFY_CONFLICT
      // messages
      if (!TargetConstraint.checkItem(tcon, child)) continue;
      else if (!child.canAccess(ACL.RIGHT_DELETE)) excludeAccess = true;
      else if (!child.checkChangeID()) excludeModify = true;
      else info.add(child.getDeletionInfo());
    }

    int totalDeleted = info.itemIds.size();
    if (totalDeleted == 1) {
      // if all messages have been excluded, some for "error" reasons, throw an exception
      if (excludeAccess)
        throw ServiceException.PERM_DENIED("you do not have sufficient permissions");
      if (excludeModify) throw MailServiceException.MODIFY_CONFLICT();
    }
    if (totalDeleted != msgs.size() + 1) info.incomplete = true;
    return info;
  }
예제 #15
0
파일: GetServer.java 프로젝트: koem/Zimbra
  public Element handle(Element request, Map<String, Object> context) throws ServiceException {

    ZimbraSoapContext zsc = getZimbraSoapContext(context);
    Provisioning prov = Provisioning.getInstance();

    boolean applyConfig = request.getAttributeBool(AdminConstants.A_APPLY_CONFIG, true);
    Set<String> reqAttrs = getReqAttrs(request, AttributeClass.server);

    Element d = request.getElement(AdminConstants.E_SERVER);
    String method = d.getAttribute(AdminConstants.A_BY);
    String name = d.getText();

    if (name == null || name.equals(""))
      throw ServiceException.INVALID_REQUEST("must specify a value for a server", null);

    Server server = prov.get(ServerBy.fromString(method), name);

    if (server == null) throw AccountServiceException.NO_SUCH_SERVER(name);

    AdminAccessControl aac = checkRight(zsc, context, server, AdminRight.PR_ALWAYS_ALLOW);

    // reload the server
    prov.reload(server);

    Element response = zsc.createElement(AdminConstants.GET_SERVER_RESPONSE);
    encodeServer(response, server, applyConfig, reqAttrs, aac.getAttrRightChecker(server));

    return response;
  }
예제 #16
0
  @Override
  public Element handle(Element request, Map<String, Object> context) throws ServiceException {
    ZimbraSoapContext zsc = getZimbraSoapContext(context);
    Mailbox mbox = getRequestedMailbox(zsc);

    String browseBy = request.getAttribute(MailConstants.A_BROWSE_BY);
    BrowseBy parsedBrowseBy = BrowseBy.valueOf(browseBy.toLowerCase());
    String regex = request.getAttribute(MailConstants.A_REGEX, "").toLowerCase();
    int max = (int) (request.getAttributeLong(MailConstants.A_MAX_TO_RETURN, 0));

    List<BrowseTerm> terms;
    try {
      terms = mbox.browse(getOperationContext(zsc, context), parsedBrowseBy, regex, max);
    } catch (IOException e) {
      throw ServiceException.FAILURE("Failed to browse terms", e);
    }

    Element response = zsc.createElement(MailConstants.BROWSE_RESPONSE);

    for (BrowseTerm term : terms) {
      if (term instanceof DomainBrowseTerm) {
        DomainBrowseTerm domain = (DomainBrowseTerm) term;
        Element e = response.addElement(MailConstants.E_BROWSE_DATA).setText(domain.getText());
        String flags = domain.getHeaderFlags();
        if (!flags.isEmpty()) {
          e.addAttribute(MailConstants.A_BROWSE_DOMAIN_HEADER, flags);
        }
        e.addAttribute(MailConstants.A_FREQUENCY, domain.getFreq());
      } else {
        Element e = response.addElement(MailConstants.E_BROWSE_DATA).setText(term.getText());
        e.addAttribute(MailConstants.A_FREQUENCY, term.getFreq());
      }
    }
    return response;
  }
예제 #17
0
 // timeStr must have the format HHMM.  Hour range is 0-24, and minute range is 0-59.
 // Special value "2400" is allowed for denoting end time of the working hours that coincides
 // with the end of the day.
 public HourMinute(String hhmmStr, boolean isEndTime, String dayStr) throws ServiceException {
   boolean good = false;
   if (hhmmStr.length() == 4) {
     try {
       int hh = Integer.parseInt(hhmmStr.substring(0, 2));
       int mm = Integer.parseInt(hhmmStr.substring(2));
       if ((hh >= 0 && hh <= 23 && mm >= 0 && mm <= 59) || (isEndTime && hh == 24 && mm == 0)) {
         hour = hh;
         minute = mm;
         good = true;
       }
     } catch (NumberFormatException e) {
     }
   }
   if (!good)
     throw ServiceException.INVALID_REQUEST(
         "Working hours spec day section \""
             + dayStr
             + "\" has invalid "
             + (isEndTime ? "end" : "start")
             + " time \""
             + hhmmStr
             + "\"",
         null);
 }
예제 #18
0
  protected void doGet(HttpServletRequest req, HttpServletResponse resp)
      throws ServletException, IOException {

    try {
      // check the auth token
      AuthToken authToken = getAdminAuthTokenFromCookie(req, resp);
      if (authToken == null) return;
      // take the host name
      Provisioning prov = Provisioning.getInstance();
      String hostName = req.getParameter(P_HOST);
      Server server = prov.get(Key.ServerBy.name, hostName);
      if (server == null) {
        throw ServiceException.INVALID_REQUEST(
            "server with name " + hostName + " could not be found", null);
      }
      // call RemoteManager
      RemoteManager rmgr = RemoteManager.getRemoteManager(server);
      RemoteResult rr = rmgr.execute(RemoteCommands.COLLECT_CONFIG_FILES);
      // stream the data
      resp.setContentType(DOWNLOAD_CONTENT_TYPE);
      ContentDisposition cd =
          new ContentDisposition(Part.INLINE).setParameter("filename", hostName + ".conf.tgz");
      resp.addHeader("Content-Disposition", cd.toString());
      ByteUtil.copy(new ByteArrayInputStream(rr.getMStdout()), true, resp.getOutputStream(), false);
    } catch (ServiceException e) {
      returnError(resp, e);
      return;
    }
  }
예제 #19
0
  /*
   * Get email local part attr from attrs and form the email with the default domain
   */
  @Override
  public String dnToEmail(String dn, IAttributes attrs) throws ServiceException {
    String localPart = attrs.getAttrString(DEFAULT_NAMING_RDN_ATTR_USER);

    if (localPart != null) return localPart + "@" + defaultDomain();
    else throw ServiceException.FAILURE("unable to map dn [" + dn + "] to email", null);
  }
예제 #20
0
 public static UCServiceBy fromString(String s) throws ServiceException {
   try {
     return UCServiceBy.valueOf(s);
   } catch (IllegalArgumentException e) {
     throw ServiceException.INVALID_REQUEST("unknown key: " + s, e);
   }
 }
예제 #21
0
  @Override
  public Element handle(Element request, Map<String, Object> context) throws ServiceException {
    ZimbraSoapContext zsc = getZimbraSoapContext(context);
    Mailbox mbox = getRequestedMailbox(zsc);
    OperationContext octxt = getOperationContext(zsc, context);
    ItemIdFormatter ifmt = new ItemIdFormatter(zsc);

    Element meta = request.getElement(MailConstants.E_METADATA);
    String section = meta.getAttribute(MailConstants.A_SECTION);
    section = section.trim();
    if (section.length() == 0 || section.length() > 36)
      throw ServiceException.INVALID_REQUEST(
          "invalid length for custom metadata section name", null);

    CustomMetadata custom = new CustomMetadata(section);
    for (Element.KeyValuePair kvp : meta.listKeyValuePairs())
      custom.put(kvp.getKey(), kvp.getValue());

    ItemId iid = new ItemId(request.getAttribute(MailConstants.A_ID), zsc);
    mbox.setCustomData(octxt, iid.getId(), MailItem.Type.UNKNOWN, custom);

    Element response = zsc.createElement(MailConstants.SET_METADATA_RESPONSE);
    response.addAttribute(MailConstants.A_ID, ifmt.formatItemId(iid));
    return response;
  }
예제 #22
0
 private static IRecurrence getRecurrenceForDay(
     int dayOfWeek, StartSpec startSpec, TimeRange timeRange, ICalTimeZone tz, TimeZoneMap tzmap)
     throws ServiceException {
   // DTSTART
   String dateStr = startSpec.getDateString(dayOfWeek);
   String dtStartStr;
   if (tz.sameAsUTC())
     dtStartStr =
         String.format("%sT%02d%02d00Z", dateStr, timeRange.start.hour, timeRange.start.minute);
   else
     dtStartStr =
         String.format(
             "TZID=\"%s\":%sT%02d%02d00",
             tz.getID(), dateStr, timeRange.start.hour, timeRange.start.minute);
   ParsedDateTime dtStart;
   try {
     dtStart = ParsedDateTime.parse(dtStartStr, tzmap);
   } catch (ParseException e) {
     throw ServiceException.INVALID_REQUEST("Bad date/time value \"" + dtStartStr + "\"", e);
   }
   // DURATION
   ParsedDuration dur = timeRange.getDuration();
   // RRULE
   String dayName = DayOfWeekName.lookup(dayOfWeek);
   String ruleStr = String.format("FREQ=WEEKLY;INTERVAL=1;BYDAY=%s", dayName);
   return new Recurrence.SimpleRepeatingRule(dtStart, dur, new ZRecur(ruleStr, tzmap), null);
 }
예제 #23
0
  public Element handle(Element request, Map<String, Object> context) throws ServiceException {

    ZimbraSoapContext zsc = getZimbraSoapContext(context);
    Provisioning prov = Provisioning.getInstance();

    String id = request.getAttribute(AdminConstants.E_ID);

    Domain domain = prov.get(DomainBy.id, id);
    if (domain == null) throw AccountServiceException.NO_SUCH_DOMAIN(id);

    if (domain.isShutdown())
      throw ServiceException.PERM_DENIED(
          "can not access domain, domain is in " + domain.getDomainStatusAsString() + " status");

    checkRight(zsc, context, domain, Admin.R_deleteDomain);

    String name = domain.getName();

    prov.deleteDomain(id);

    ZimbraLog.security.info(
        ZimbraLog.encodeAttrs(new String[] {"cmd", "DeleteDomain", "name", name, "id", id}));

    Element response = zsc.createElement(AdminConstants.DELETE_DOMAIN_RESPONSE);
    return response;
  }
 public static Operation fromString(String s) throws ServiceException {
   try {
     return Operation.valueOf(s);
   } catch (IllegalArgumentException e) {
     throw ServiceException.INVALID_REQUEST("unknown operation: " + s, e);
   }
 }
예제 #25
0
파일: TargetType.java 프로젝트: koem/Zimbra
 public static TargetType fromCode(String s) throws ServiceException {
   try {
     return TargetType.valueOf(s);
   } catch (IllegalArgumentException e) {
     throw ServiceException.INVALID_REQUEST("unknown target type: " + s, e);
   }
 }
예제 #26
0
 public static Account validateAuthToken(
     Provisioning prov, AuthToken at, boolean addToLoggingContext) throws ServiceException {
   try {
     return validateAuthTokenInternal(prov, at, addToLoggingContext);
   } catch (ServiceException e) {
     if (ServiceException.AUTH_EXPIRED.equals(e.getCode())) {
       // we may not want to expose the details to malicious caller
       // debug log the message and throw a vanilla AUTH_EXPIRED
       ZimbraLog.account.debug("auth token validation failed", e);
       throw ServiceException.AUTH_EXPIRED();
     } else {
       // rethrow the same exception
       throw e;
     }
   }
 }
예제 #27
0
  /** Saves the given task to the database. */
  public static void createTask(DbConnection conn, ScheduledTask task) throws ServiceException {

    ZimbraLog.scheduler.debug("Creating %s", task);

    PreparedStatement stmt = null;
    try {
      stmt =
          conn.prepareStatement(
              "INSERT INTO "
                  + TABLE_SCHEDULED_TASK
                  + " (class_name, name, mailbox_id, exec_time, interval_millis, metadata) "
                  + "VALUES (?, ?, ?, ?, ?, ?)");
      stmt.setString(1, task.getClass().getName());
      stmt.setString(2, task.getName());
      stmt.setInt(3, task.getMailboxId());
      stmt.setTimestamp(4, DbUtil.dateToTimestamp(task.getExecTime()));
      if (task.getIntervalMillis() > 0) {
        stmt.setLong(5, task.getIntervalMillis());
      } else {
        stmt.setNull(5, Types.INTEGER);
      }
      stmt.setString(6, getEncodedMetadata(task));
      stmt.executeUpdate();
    } catch (SQLException e) {
      throw ServiceException.FAILURE("Unable to create " + task, e);
    } finally {
      DbPool.closeStatement(stmt);
    }
  }
예제 #28
0
파일: ImapProxy.java 프로젝트: koem/Zimbra
  ImapProxy(final ImapHandler handler, final ImapPath path) throws ServiceException {
    mHandler = handler;
    mPath = path;

    Account acct = handler.getCredentials().getAccount();
    Server server = Provisioning.getInstance().getServer(path.getOwnerAccount());
    String host = server.getServiceHostname();
    if (acct == null)
      throw ServiceException.PROXY_ERROR(
          new Exception("no such authenticated user"), path.asImapPath());

    ImapConfig config = new ImapConfig();
    config.setAuthenticationId(acct.getName());
    config.setMechanism(ZimbraAuthenticator.MECHANISM);
    config.setAuthenticatorFactory(sAuthenticatorFactory);
    config.setReadTimeout(LC.javamail_imap_timeout.intValue());
    config.setConnectTimeout(config.getReadTimeout());
    config.setHost(host);
    if (server.isImapServerEnabled()) {
      config.setPort(server.getIntAttr(Provisioning.A_zimbraImapBindPort, ImapConfig.DEFAULT_PORT));
    } else if (server.isImapSSLServerEnabled()) {
      config.setPort(
          server.getIntAttr(Provisioning.A_zimbraImapSSLBindPort, ImapConfig.DEFAULT_SSL_PORT));
      config.setSecurity(MailConfig.Security.SSL);
    } else {
      throw ServiceException.PROXY_ERROR(
          new Exception("no open IMAP port for server " + host), path.asImapPath());
    }

    ZimbraLog.imap.info(
        "opening proxy connection (user="******", host="
            + host
            + ", path="
            + path.getReferent().asImapPath()
            + ')');

    ImapConnection conn = mConnection = new ImapConnection(config);
    try {
      conn.connect();
      conn.authenticate(AuthProvider.getAuthToken(acct).getEncoded());
    } catch (Exception e) {
      dropConnection();
      throw ServiceException.PROXY_ERROR(e, null);
    }
  }
예제 #29
0
  private List<Appointement> getSortedRdv() {
    try {
      client = ZMailbox.getByName(login, pass, "https://zimbra.inria.fr/service/soap/");
      XMLElement req = new XMLElement(ZimbraNamespace.E_BATCH_REQUEST);
      Element gas = req.addElement(MailConstants.GET_APPT_SUMMARIES_REQUEST);

      Calendar cal = Calendar.getInstance();
      Date today = cal.getTime();
      //		cal.add(Calendar.HOUR, -1); // to get previous year add -1
      gas.addAttribute(MailConstants.A_CAL_START_TIME, today.getTime());

      cal.add(Calendar.MONTH, 1); // to get previous year add -1
      Date nextYear = cal.getTime();

      gas.addAttribute(MailConstants.A_CAL_END_TIME, nextYear.getTime());
      gas.addAttribute(MailConstants.A_FOLDER, zimbraFolderId);
      Element resp = client.invoke(req);
      List<Appointement> lists = new ArrayList<Appointement>();

      for (Element e : resp.listElements()) {
        for (Element appt : e.listElements(MailConstants.E_APPOINTMENT)) {
          Appointement a = new Appointement();
          a.setLabel("" + appt.toXML().attribute("name").getData());
          a.setLocation("" + appt.toXML().attribute("loc").getData());
          String duration = "" + appt.toXML().attribute("d").getData();
          a.setDuration(Long.parseLong(duration) / 1000);
          ZDateTime dated =
              new ZDateTime("" + appt.toXML().element("inst").attribute("ridZ").getData());
          a.setDate(dated.getDate());
          lists.add(a);
        }
      }
      Collections.sort(
          lists,
          new Comparator<Appointement>() {

            public int compare(Appointement appt1, Appointement appt2) {
              return appt1.getDate().compareTo(appt2.getDate());
            }
          });

      return lists;
    } catch (ServiceException e) {
      e.printStackTrace();
    }
    return new ArrayList<Appointement>();
  }
예제 #30
0
 public static AdsConnectionType fromString(String s) throws ServiceException {
   try {
     return AdsConnectionType.valueOf(s);
   } catch (IllegalArgumentException e) {
     throw ServiceException.INVALID_REQUEST(
         "invalid type: " + s + ", valid values: " + Arrays.asList(AdsConnectionType.values()), e);
   }
 }