@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();
    }
  }
Exemplo n.º 2
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);
    }
  }
Exemplo n.º 3
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
  }
Exemplo n.º 4
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);
    }
  }
Exemplo n.º 5
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;
  }
Exemplo n.º 6
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);
   }
 }
Exemplo n.º 7
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);
  }
Exemplo n.º 8
0
  public static ZLdapContext toZLdapContext(
      com.zimbra.cs.account.Provisioning prov, ILdapContext ldapContext) {

    if (!(getInstance() instanceof UBIDLdapClient)) {
      Zimbra.halt(
          "LdapClient instance is not UBIDLdapClient",
          ServiceException.FAILURE("internal error, wrong ldap context instance", null));
    }

    // just a safety check, this should really not happen at this point
    if (ldapContext != null && !(ldapContext instanceof ZLdapContext)) {
      Zimbra.halt(
          "ILdapContext instance is not ZLdapContext",
          ServiceException.FAILURE("internal error, wrong ldap context instance", null));
    }

    return (ZLdapContext) ldapContext;
  }
Exemplo n.º 9
0
  private String acctAndDLDNCreate(String baseDn, IAttributes attrs) throws ServiceException {
    String rdnAttr = NAMING_RDN_ATTR_USER;
    String rdnValue = attrs.getAttrString(rdnAttr);

    if (rdnValue == null) throw ServiceException.FAILURE("missing rdn attribute" + rdnAttr, null);

    validateMailBranchEntryDN(baseDn);

    return rdnAttr + "=" + LdapUtil.escapeRDNValue(rdnValue) + "," + baseDn;
  }
Exemplo n.º 10
0
 protected SoapCLI() throws ServiceException {
   // get admin username from local config
   mUser = LC.zimbra_ldap_user.value();
   // get password from localconfig
   mPassword = LC.zimbra_ldap_password.value();
   // host can be specified
   mHost = "localhost";
   // get admin port number from provisioning
   com.zimbra.cs.account.Config conf = null;
   try {
     conf = Provisioning.getInstance().getConfig();
   } catch (ServiceException e) {
     throw ServiceException.FAILURE("Unable to connect to LDAP directory", e);
   }
   mPort = conf.getIntAttr(Provisioning.A_zimbraAdminPort, 0);
   if (mPort == 0)
     throw ServiceException.FAILURE("Unable to get admin port number from provisioning", null);
   mOptions = new Options();
   mHiddenOptions = new Options();
 }
Exemplo n.º 11
0
  public Domain getDomain() throws ServiceException {
    if (mDomain != null) return mDomain;

    Domain domain = Provisioning.getInstance().getDomain(mAccount);
    if (domain != null) return domain;

    Account galSyncAcct = getGalSyncAccount();
    if (galSyncAcct != null) domain = Provisioning.getInstance().getDomain(galSyncAcct);

    if (domain != null) return domain;

    throw ServiceException.FAILURE("Unable to get domain", null);
  }
Exemplo n.º 12
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());
      }
    }
Exemplo n.º 13
0
 private void connect() throws ServiceException {
   if (!connection.isClosed()) return;
   try {
     connection.connect();
     try {
       connection.login(dataSource.getDecryptedPassword());
     } catch (CommandFailedException e) {
       throw new LoginException(e.getError());
     }
   } catch (Exception e) {
     connection.close();
     throw ServiceException.FAILURE("Unable to connect to POP3 server: " + dataSource, e);
   }
 }
Exemplo n.º 14
0
  public void checkValue(Object value, boolean checkImmutable, Map attrsToModify)
      throws ServiceException {
    if ((value == null) || (value instanceof String)) {
      checkValue((String) value, checkImmutable, attrsToModify);
    } else if (value instanceof String[]) {
      String[] values = (String[]) value;
      for (int i = 0; i < values.length; i++) checkValue(values[i], checkImmutable, attrsToModify);
    }

    if (isDeprecated() && !DebugConfig.allowModifyingDeprecatedAttributes) {
      throw ServiceException.FAILURE(
          "modifying deprecated attribute is not allowed: " + mName, null);
    }
  }
Exemplo n.º 15
0
  static Conversation create(Mailbox mbox, int id, Message[] msgs) throws ServiceException {
    if (ZimbraLog.mailop.isDebugEnabled()) {
      StringBuilder msgIds = new StringBuilder();
      for (int i = 0; i < msgs.length; i++) msgIds.append(i > 0 ? "," : "").append(msgs[i].getId());
      ZimbraLog.mailop.debug("Adding Conversation: id=%d, message(s): %s.", id, msgIds);
    }

    assert (id != Mailbox.ID_AUTO_INCREMENT && msgs.length > 0);
    Arrays.sort(msgs, new Message.SortDateAscending());

    int date = 0, unread = 0, flags = 0;
    long tags = 0;
    CustomMetadataList extended = null;
    for (int i = 0; i < msgs.length; i++) {
      Message msg = msgs[i];
      if (msg == null) throw ServiceException.FAILURE("null Message in list", null);
      date = Math.max(date, msg.mData.date);
      unread += msg.mData.unreadCount;
      flags |= msg.mData.flags;
      tags |= msg.mData.tags;
      extended = MetadataCallback.duringConversationAdd(extended, msg);
    }

    UnderlyingData data = new UnderlyingData();
    data.id = id;
    data.type = TYPE_CONVERSATION;
    data.folderId = Mailbox.ID_FOLDER_CONVERSATIONS;
    data.subject =
        msgs.length > 0 ? DbMailItem.truncateSubjectToMaxAllowedLength(msgs[0].getSubject()) : "";
    data.date = date;
    data.size = msgs.length;
    data.unreadCount = unread;
    data.flags = flags;
    data.tags = tags;
    data.metadata = encodeMetadata(DEFAULT_COLOR_RGB, 1, extended, new SenderList(msgs));
    data.contentChanged(mbox);
    DbMailItem.create(mbox, data, null);

    Conversation conv = new Conversation(mbox, data);
    conv.finishCreation(null);

    DbMailItem.setParent(msgs, conv);
    for (int i = 0; i < msgs.length; i++) {
      mbox.markItemModified(msgs[i], Change.MODIFIED_PARENT);
      msgs[i].mData.parentId = id;
      msgs[i].mData.metadataChanged(mbox);
    }
    return conv;
  }
Exemplo n.º 16
0
 @Override
 public synchronized void test() throws ServiceException {
   validateDataSource();
   try {
     connect();
     if (dataSource.leaveOnServer() && !hasUIDL()) {
       throw RemoteServiceException.POP3_UIDL_REQUIRED();
     }
     connection.quit();
   } catch (IOException e) {
     throw ServiceException.FAILURE("Unable to connect to POP3 server: " + dataSource, e);
   } finally {
     connection.close();
   }
 }
Exemplo n.º 17
0
  private static String expandKey(String tokenize, String filterTemplate, String key)
      throws ServiceException {

    if (!filterTemplate.startsWith("(")) {
      if (filterTemplate.endsWith(")"))
        throw ServiceException.INVALID_REQUEST(
            "Unbalanced parenthesis in filter:" + filterTemplate, null);

      filterTemplate = "(" + filterTemplate + ")";
    }

    String query = null;
    Map<String, String> vars = new HashMap<String, String>();

    ZLdapFilterFactory filterFactory = ZLdapFilterFactory.getInstance();

    if (tokenize != null) {
      String tokens[] = key.split("\\s+");
      if (tokens.length > 1) {
        String q;
        if (GalConstants.TOKENIZE_KEY_AND.equals(tokenize)) {
          q = "(&";
        } else if (GalConstants.TOKENIZE_KEY_OR.equals(tokenize)) {
          q = "(|";
        } else {
          throw ServiceException.FAILURE(
              "invalid attribute value for tokenize key: " + tokenize, null);
        }

        for (String t : tokens) {
          vars.clear();
          vars.put("s", filterFactory.encodeValue(t));
          q = q + LdapUtil.expandStr(filterTemplate, vars);
        }
        q = q + ")";
        query = q;
      }
    }

    if (query == null) {
      vars.put("s", key == null ? null : filterFactory.encodeValue(key));
      query = LdapUtil.expandStr(filterTemplate, vars);
    }

    return query;
  }
Exemplo n.º 18
0
  public static TargetType getTargetType(Entry target) throws ServiceException {

    if (target instanceof CalendarResource) return TargetType.calresource;
    else if (target instanceof Account) return TargetType.account;
    else if (target instanceof Domain) return TargetType.domain;
    else if (target instanceof Cos) return TargetType.cos;
    else if (target instanceof DistributionList) return TargetType.dl;
    else if (target instanceof Server) return TargetType.server;
    else if (target instanceof Config) return TargetType.config;
    else if (target instanceof GlobalGrant) return TargetType.global;
    else if (target instanceof Zimlet) return TargetType.zimlet;
    else if (target instanceof XMPPComponent) return TargetType.xmppcomponent;
    else
      throw ServiceException.FAILURE(
          "internal error, target is : "
              + (target == null ? "null" : target.getClass().getCanonicalName()),
          null);
  }
Exemplo n.º 19
0
 static boolean matchesGrantee(Grantee grantee, ZimbraACE ace) throws ServiceException {
   // set of zimbraIds the grantee in question can assume: including
   //   - zimbraId of the grantee
   //   - all zimbra internal admin groups the grantee is in
   Set<String> granteeIds = grantee.getIdAndGroupIds();
   if (granteeIds.contains(ace.getGrantee())) {
     return true;
   } else if (ace.getGranteeType() == GranteeType.GT_EXT_GROUP) {
     if (grantee.isAccount()) {
       return ace.matchesGrantee(grantee.getAccount(), true);
     } else {
       // we are collecting rights for a group grantee
       // TODO
       throw ServiceException.FAILURE("Not yet implemented", null);
     }
   } else {
     return false;
   }
 }
Exemplo n.º 20
0
  static String getSearchBase(Provisioning prov, TargetType tt) throws ServiceException {
    LdapDIT dit = ((LdapProvisioning) prov).getDIT();

    String base;

    switch (tt) {
      case account:
      case calresource:
      case dl:
        base = dit.mailBranchBaseDN();
        break;
      case domain:
        base = dit.domainBaseDN();
        break;
      case cos:
        base = dit.cosBaseDN();
        break;
      case server:
        base = dit.serverBaseDN();
        break;
      case xmppcomponent:
        base = dit.xmppcomponentBaseDN();
        break;
      case zimlet:
        base = dit.zimletBaseDN();
        break;
      case config:
        base = dit.configDN();
        break;
      case global:
        // is really an internal error, globalgrant should never appear in the
        // targetTypes if we get here, because it is not a sub-target of any
        // other target types.
        base = dit.globalGrantDN();
        break;
      default:
        throw ServiceException.FAILURE("internal error", null);
    }

    return base;
  }
Exemplo n.º 21
0
 @Override
 public synchronized void importData(List<Integer> folderIds, boolean fullSync)
     throws ServiceException {
   validateDataSource();
   connect();
   try {
     if (connection.getMessageCount() > 0) {
       if (dataSource.leaveOnServer()) {
         fetchAndRetainMessages();
       } else {
         fetchAndDeleteMessages();
       }
     }
     connection.quit();
   } catch (ServiceException e) {
     throw e;
   } catch (Exception e) {
     throw ServiceException.FAILURE("Synchronization of POP3 folder failed", e);
   } finally {
     connection.close();
   }
 }
Exemplo n.º 22
0
 public DbConnection getConnection() throws ServiceException {
   Connection dbconn = null;
   DbConnection conn = null;
   try {
     dbconn = mDataSource.getConnection();
     if (dbconn.getAutoCommit() != false) {
       dbconn.setAutoCommit(false);
     }
     conn = new DbConnection(dbconn);
     Db.getInstance().postOpen(conn);
   } catch (SQLException e) {
     try {
       if (dbconn != null && !dbconn.isClosed()) {
         dbconn.close();
       }
     } catch (SQLException e2) {
       ZimbraLog.sqltrace.warn("DB connection close caught exception", e);
     }
     throw ServiceException.FAILURE("getting database connection", e);
   }
   return conn;
 }
Exemplo n.º 23
0
  public static void deleteTask(DbConnection conn, String className, String taskName)
      throws ServiceException {

    ZimbraLog.scheduler.debug(
        "Deleting scheduled task from the database.  className=%s, taskName=%s",
        className, taskName);

    PreparedStatement stmt = null;
    try {
      stmt =
          conn.prepareStatement(
              "DELETE FROM " + TABLE_SCHEDULED_TASK + " WHERE class_name = ? AND name = ?");
      stmt.setString(1, className);
      stmt.setString(2, taskName);
      stmt.executeUpdate();
    } catch (SQLException e) {
      throw ServiceException.FAILURE(
          "Unable to delete scheduled task: className=" + className + ", taskName=" + taskName, e);
    } finally {
      DbPool.closeStatement(stmt);
    }
  }
Exemplo n.º 24
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);
 }
Exemplo n.º 25
0
  static SetCalendarItemData getSetCalendarItemData(
      ZimbraSoapContext zsc,
      OperationContext octxt,
      Account acct,
      Mailbox mbox,
      Element e,
      ParseMimeMessage.InviteParser parser)
      throws ServiceException {
    String partStatStr =
        e.getAttribute(MailConstants.A_CAL_PARTSTAT, IcalXmlStrMap.PARTSTAT_NEEDS_ACTION);

    // <M>
    Element msgElem = e.getElement(MailConstants.E_MSG);

    // check to see whether the entire message has been uploaded under separate cover
    String attachmentId = msgElem.getAttribute(MailConstants.A_ATTACHMENT_ID, null);
    Element contentElement = msgElem.getOptionalElement(MailConstants.E_CONTENT);

    InviteParserResult ipr = null;

    MimeMessage mm = null;
    if (attachmentId != null) {
      ParseMimeMessage.MimeMessageData mimeData = new ParseMimeMessage.MimeMessageData();
      mm = SendMsg.parseUploadedMessage(zsc, attachmentId, mimeData);
    } else if (contentElement != null) {
      mm = ParseMimeMessage.importMsgSoap(msgElem);
    } else {
      CalSendData dat = handleMsgElement(zsc, octxt, msgElem, acct, mbox, parser);
      mm = dat.mMm;
      ipr = parser.getResult();
    }

    if (ipr == null && msgElem.getOptionalElement(MailConstants.E_INVITE) != null) {
      ipr = parser.parse(zsc, octxt, mbox.getAccount(), msgElem.getElement(MailConstants.E_INVITE));
      // Get description texts out of the MimeMessage and set in the parsed invite.  Do it only if
      // the MimeMessage has text parts.  This prevents discarding texts when they're specified only
      // in the <inv> but not in mime parts.
      if (ipr != null && ipr.mInvite != null && mm != null) {
        String desc = Invite.getDescription(mm, MimeConstants.CT_TEXT_PLAIN);
        String descHtml = Invite.getDescription(mm, MimeConstants.CT_TEXT_HTML);
        if ((desc != null && desc.length() > 0) || (descHtml != null && descHtml.length() > 0))
          ipr.mInvite.setDescription(desc, descHtml);
      }
    }

    ParsedMessage pm = new ParsedMessage(mm, mbox.attachmentsIndexingEnabled());

    Invite inv = (ipr == null ? null : ipr.mInvite);
    if (inv == null || inv.getDTStamp() == -1) { // zdsync if -1 for 4.5 back compat
      CalendarPartInfo cpi = pm.getCalendarPartInfo();
      ZVCalendar cal = null;
      if (cpi != null && CalendarItem.isAcceptableInvite(mbox.getAccount(), cpi)) cal = cpi.cal;
      if (cal == null)
        throw ServiceException.FAILURE("SetCalendarItem could not build an iCalendar object", null);
      boolean sentByMe = false; // not applicable in the SetCalendarItem case
      Invite iCalInv = Invite.createFromCalendar(acct, pm.getFragment(), cal, sentByMe).get(0);

      if (inv == null) {
        inv = iCalInv;
      } else {
        inv.setDtStamp(iCalInv.getDTStamp()); // zdsync
        inv.setFragment(iCalInv.getFragment()); // zdsync
      }
    }
    inv.setPartStat(partStatStr);

    SetCalendarItemData sadata = new SetCalendarItemData();
    sadata.invite = inv;
    sadata.message = pm;
    return sadata;
  }
Exemplo n.º 26
0
  /**
   * Retrieves scheduled tasks from the database.
   *
   * @param className the <tt>ScheduledTask</tt> class name, or <tt>null</tt> for all classes
   * @param mailboxId the mailbox ID, or <tt>0</tt> for all mailboxes
   */
  public static List<ScheduledTask> getTasks(String className, int mailboxId)
      throws ServiceException {
    ZimbraLog.scheduler.debug("Retrieving tasks for class %s, mailbox %d", className, mailboxId);

    List<ScheduledTask> tasks = new ArrayList<ScheduledTask>();

    DbConnection conn = null;
    PreparedStatement stmt = null;
    ResultSet rs = null;
    try {
      conn = DbPool.getConnection();
      String sql =
          "SELECT class_name, name, mailbox_id, exec_time, interval_millis, metadata "
              + "FROM "
              + TABLE_SCHEDULED_TASK;
      if (className != null) {
        sql += " WHERE class_name = ?";
      }
      if (mailboxId > 0) {
        if (className == null) {
          sql += " WHERE mailbox_id = ?";
        } else {
          sql += " AND mailbox_id = ?";
        }
      }
      stmt = conn.prepareStatement(sql);
      int i = 1;
      if (className != null) {
        stmt.setString(i++, className);
      }
      if (mailboxId > 0) {
        stmt.setInt(i++, mailboxId);
      }

      rs = stmt.executeQuery();
      while (rs.next()) {
        className = rs.getString("class_name");
        String name = rs.getString("name");
        ScheduledTask task = null;

        // Instantiate task
        try {
          Object obj = Class.forName(className).newInstance();
          if (obj instanceof ScheduledTask) {
            task = (ScheduledTask) obj;
          } else {
            ZimbraLog.scheduler.warn(
                "Class %s is not an instance of ScheduledTask for task %s", className, name);
            continue;
          }
        } catch (Exception e) {
          ZimbraLog.scheduler.warn(
              "Unable to instantiate class %s for task %s.  "
                  + "Class must be an instance of %s and have a constructor with no arguments.",
              className, name, ScheduledTask.class.getSimpleName(), e);
          continue;
        }

        // Set member vars
        task.setMailboxId(rs.getInt("mailbox_id"));
        task.setExecTime(DbUtil.timestampToDate(rs.getTimestamp("exec_time")));
        task.setIntervalMillis(rs.getLong("interval_millis"));

        try {
          setProperties(task, rs.getString("metadata"));
        } catch (ServiceException e) {
          ZimbraLog.scheduler.warn(
              "Unable to read metadata for %s.  Not scheduling this task.", task, e);
          continue;
        }

        tasks.add(task);
      }
    } catch (SQLException e) {
      throw ServiceException.FAILURE("Unable to get all DataSourceTasks", e);
    } finally {
      DbPool.closeResults(rs);
      DbPool.closeStatement(stmt);
      DbPool.quietClose(conn);
    }

    ZimbraLog.scheduler.info("Loaded %d scheduled data source tasks", tasks.size());
    return tasks;
  }
Exemplo n.º 27
0
 Account getAccount() throws ServiceException {
   if (mGranteeType != GranteeType.GT_USER) {
     throw ServiceException.FAILURE("internal error", null);
   }
   return (Account) mRightBearer;
 }
Exemplo n.º 28
0
  boolean renumberItem(OperationContext octxt, int id, MailItem.Type type, int newId)
      throws ServiceException {
    if (id == newId) {
      return true;
    } else if (id <= 0 || newId <= 0) {
      throw ServiceException.FAILURE(
          "invalid item id when renumbering (" + id + " => " + newId + ")", null);
    }

    lock.lock();
    try {
      boolean success = false;
      try {
        beginTransaction("renumberItem", octxt);
        MailItem item = getItemById(id, type);
        if (item.getId() == newId) {
          OfflineLog.offline.info(
              "Item already renumbered; no need to renumber (%d => %d)", id, newId);
          return true;
        } else if (item.getId() != id) {
          OfflineLog.offline.warn(
              "renumbering item which may have already been renumbered (%d => %d) : itemId = %d",
              id, newId, item.getId());
        }
        // changing a message's item id needs to purge its Conversation (virtual or real)
        if (item instanceof Message) uncacheItem(item.getParentId());

        // mark old blob as disposable, but don't reindex item because INDEX_ID should still be
        // correct
        MailboxBlob mblob = item.getBlob();
        if (mblob != null) {
          // register old blob for post-commit deletion
          item.markBlobForDeletion();
          item.mBlob = null;

          // copy blob to new id (note that item.getSavedSequence() may change again later)
          try {
            MailboxBlob newBlob =
                StoreManager.getInstance().copy(mblob, this, newId, item.getSavedSequence());
            markOtherItemDirty(newBlob);
          } catch (IOException e) {
            throw ServiceException.FAILURE(
                "could not link blob for renumbered item (" + id + " => " + newId + ")", e);
          }
        }

        // update the id in the database and in memory
        markItemDeleted(item.getType(), id);
        try {
          DbOfflineMailbox.renumberItem(item, newId);
          uncache(item);
        } catch (ServiceException se) {
          throw ServiceException.FAILURE(
              "Failure renumbering item name["
                  + item.getName()
                  + "] subject["
                  + item.getSubject()
                  + "]",
              se);
        }
        item.mId = item.mData.id = newId;
        item.markItemCreated();

        if (item instanceof Folder || item instanceof Tag) {
          // replace with the new item
          cache(item);
          if (item instanceof Folder) {
            // sub folders might have wrong id
            List<Folder> subFolders = ((Folder) item).getSubfolders(octxt);
            for (Folder subFolder : subFolders) {
              subFolder.mData.folderId = newId;
              subFolder.mData.parentId = newId;
              cache(subFolder); // make sure it's in the cache
            }
          }

          // msgs are lazy-loaded so purge is safe
          purge(MailItem.Type.MESSAGE);
        }
        success = true;
      } catch (MailServiceException.NoSuchItemException nsie) {
        // item deleted from local before sync completes renumbering
        OfflineLog.offline.info(
            "item %d deleted from local db before sync completes renumbering to %d", id, newId);
        TypedIdList tombstones = new TypedIdList();
        tombstones.add(type, newId, null);
        DbMailItem.writeTombstones(this, tombstones);
        success = true;
        return false;
      } finally {
        endTransaction(success);
      }
      mRenumbers.put(id, newId);
      return true;
    } finally {
      lock.release();
    }
  }
Exemplo n.º 29
0
  @Override
  public Element handle(Element request, Map<String, Object> context) throws ServiceException {
    if (true) throw WikiServiceException.ERROR("Deprecated");
    ZimbraSoapContext zsc = getZimbraSoapContext(context);
    OperationContext octxt = getOperationContext(zsc, context);

    Element msgElem = request.getElement(MailConstants.E_WIKIWORD);
    String subject = msgElem.getAttribute(MailConstants.A_NAME, null);
    String id = msgElem.getAttribute(MailConstants.A_ID, null);
    int ver = (int) msgElem.getAttributeLong(MailConstants.A_VERSION, 0);
    int itemId;
    if (id == null) {
      itemId = 0;
    } else {
      ItemId iid = new ItemId(id, zsc);
      itemId = iid.getId();
    }

    ItemId fid = getRequestedFolder(request, zsc);
    ByteArrayInputStream is = null;
    try {
      byte[] rawData = msgElem.getText().getBytes("UTF-8");
      is = new ByteArrayInputStream(rawData);
    } catch (IOException ioe) {
      throw ServiceException.FAILURE("can't get the content", ioe);
    }
    Mailbox mbox = MailboxManager.getInstance().getMailboxByAccountId(zsc.getRequestedAccountId());
    Document wikiItem = null;
    WikiPage.WikiContext ctxt = new WikiPage.WikiContext(octxt, zsc.getAuthToken());
    if (itemId == 0) {
      // create a new page
      wikiItem =
          mbox.createDocument(
              octxt,
              fid.getId(),
              subject,
              WikiItem.WIKI_CONTENT_TYPE,
              getAuthor(zsc),
              null,
              true,
              is,
              MailItem.TYPE_WIKI);
    } else {
      // add a new revision
      WikiPage oldPage = WikiPage.findPage(ctxt, zsc.getRequestedAccountId(), itemId);
      if (oldPage == null)
        throw new WikiServiceException.NoSuchWikiException("page id=" + id + " not found");
      if (oldPage.getLastVersion() != ver) {
        throw MailServiceException.MODIFY_CONFLICT(
            new Argument(MailConstants.A_NAME, subject, Argument.Type.STR),
            new Argument(MailConstants.A_ID, oldPage.getId(), Argument.Type.IID),
            new Argument(MailConstants.A_VERSION, oldPage.getLastVersion(), Argument.Type.NUM));
      }
      wikiItem = mbox.addDocumentRevision(octxt, itemId, getAuthor(zsc), subject, null, true, is);
    }

    Element response = zsc.createElement(MailConstants.SAVE_WIKI_RESPONSE);
    Element m = response.addElement(MailConstants.E_WIKIWORD);
    m.addAttribute(MailConstants.A_ID, new ItemIdFormatter(zsc).formatItemId(wikiItem));
    m.addAttribute(MailConstants.A_VERSION, wikiItem.getVersion());
    return response;
  }
Exemplo n.º 30
0
 private ServiceException UNSUPPORTED(String msg) {
   return ServiceException.FAILURE(msg + " unsupported in " + getClass().getCanonicalName(), null);
 }