rem
stringlengths
0
477k
add
stringlengths
0
313k
context
stringlengths
6
599k
session.processOfflineQueue(userId);
session.processQueue(userId);
private void processOfflineQueue() { assertIsReachable(environment); XMPPSession session = null; try { session = new XMPPSessionImpl(); session.login(environment, credentials); final JabberId userId = JabberIdBuilder.build( credentials.getUsername(), Constants.Jabber.DOMAIN, credentials.getResource()); session.processOfflineQueue(userId); } finally { Assert.assertNotNull(session, "User {0}'s session is null.", credentials.getUsername()); Assert.assertTrue(session.isLoggedIn(), "User {0} not logged in.", credentials.getUsername()); session.logout(); } }
public void login(final LoginMonitor monitor, final Credentials credentials) { synchronized(getImplLock()) { getImpl().login(monitor, credentials); } }
public void login(final LoginMonitor monitor) { synchronized(getImplLock()) { getImpl().login(monitor); } }
public void login(final LoginMonitor monitor, final Credentials credentials) { synchronized(getImplLock()) { getImpl().login(monitor, credentials); } }
public Group(Group group) { this(group.getFieldTag(), group.getDelimeter(), group.getFieldOrder()); setFields(group); setGroups(group);
public Group(int field, int delim) { this(field, delim, null);
public Group(Group group) { this(group.getFieldTag(), group.getDelimeter(), group.getFieldOrder()); setFields(group); setGroups(group); }
final Comparator<User> comparator) {
final Comparator<? super User> comparator) {
public static void sortTeamMembers(final List<TeamMember> list, final Comparator<User> comparator) { Collections.sort(list, comparator); }
displayDocumentHistoryListAvatar();
displayDocumentHistoryAvatar();
public void openMainWindow() { Assert.assertIsNull("Cannot reopen main window.", mainWindow); // Schedule a job for the event-dispatching thread: creating and // showing this application's GUI. javax.swing.SwingUtilities.invokeLater(new Runnable() { public void run() { mainWindow = BrowserWindow.open(); displayTitleAvatar(); displayLogoAvatar(); displayMainBrowserAvatar(); displayDocumentHistoryListAvatar(); } }); }
displayDocumentHistoryListAvatar();
displayDocumentHistoryAvatar();
public void run() { mainWindow = BrowserWindow.open(); displayTitleAvatar(); displayLogoAvatar(); displayMainBrowserAvatar(); displayDocumentHistoryListAvatar(); }
AvatarFactory.create(AvatarId.DOCUMENT_HISTORY_LIST).reload();
AvatarFactory.create(AvatarId.DOCUMENT_HISTORY).reload();
public void reloadMainBrowserAvatar() { // NOTE Wierd AvatarFactory.create(AvatarId.BROWSER_MAIN).reload(); // NOTE Super wierd AvatarFactory.create(AvatarId.DOCUMENT_HISTORY_LIST).reload(); }
setInput(AvatarId.DOCUMENT_HISTORY_LIST, documentId);
setInput(AvatarId.DOCUMENT_HISTORY, documentId);
public void selectDocument(final Long documentId) { setInput(AvatarId.DOCUMENT_HISTORY_LIST, documentId); setInput(AvatarId.SESSION_SEND_FORM, documentId); setInput(AvatarId.SESSION_SEND_KEY_FORM, documentId); }
final Connection connection = getInputConnection(); if (null != connection) { final String connectionText; switch(getInputConnection()) { case ONLINE: connectionJLabel.setForeground(Colors.Browser.MainStatus.CONNECTION_FOREGROUND_ONLINE); if (null != profile) { connectionText = profile.getName(); } else { connectionText = getString(Connection.ONLINE); } break; case OFFLINE: connectionJLabel.setForeground(Colors.Browser.MainStatus.CONNECTION_FOREGROUND_OFFLINE); connectionText = getString(Connection.OFFLINE); break; default: throw Assert.createUnreachable("UNKNOWN CONNECTION"); } connectionJLabel.setText(connectionText);
final String connectionText; switch(getInputConnection()) { case ONLINE: connectionJLabel.setForeground(Colors.Browser.MainStatus.CONNECTION_FOREGROUND_ONLINE); connectionText = profile.getName(); break; case OFFLINE: connectionJLabel.setForeground(Colors.Browser.MainStatus.CONNECTION_FOREGROUND_OFFLINE); connectionText = getString(Connection.OFFLINE); break; default: throw Assert.createUnreachable("UNKNOWN CONNECTION");
private void reloadConnection() { connectionJLabel.setText(""); final Connection connection = getInputConnection(); if (null != connection) { final String connectionText; switch(getInputConnection()) { case ONLINE: connectionJLabel.setForeground(Colors.Browser.MainStatus.CONNECTION_FOREGROUND_ONLINE); if (null != profile) { connectionText = profile.getName(); } else { connectionText = getString(Connection.ONLINE); } break; case OFFLINE: connectionJLabel.setForeground(Colors.Browser.MainStatus.CONNECTION_FOREGROUND_OFFLINE); connectionText = getString(Connection.OFFLINE); break; default: throw Assert.createUnreachable("UNKNOWN CONNECTION"); } connectionJLabel.setText(connectionText); } }
connectionJLabel.setText(connectionText);
private void reloadConnection() { connectionJLabel.setText(""); final Connection connection = getInputConnection(); if (null != connection) { final String connectionText; switch(getInputConnection()) { case ONLINE: connectionJLabel.setForeground(Colors.Browser.MainStatus.CONNECTION_FOREGROUND_ONLINE); if (null != profile) { connectionText = profile.getName(); } else { connectionText = getString(Connection.ONLINE); } break; case OFFLINE: connectionJLabel.setForeground(Colors.Browser.MainStatus.CONNECTION_FOREGROUND_OFFLINE); connectionText = getString(Connection.OFFLINE); break; default: throw Assert.createUnreachable("UNKNOWN CONNECTION"); } connectionJLabel.setText(connectionText); } }
if (isRoundCorners()) {
if (nativeSkin.isRounded()) {
protected void paintComponent(final Graphics g) { super.paintComponent(g); if (isRoundCorners()) { final Graphics g2 = g.create(); try { // These images help to make the rounded corners look good. g2.drawImage(Images.BrowserTitle.DIALOG_TOP_LEFT_INNER, 0, 0, Images.BrowserTitle.DIALOG_TOP_LEFT_INNER.getWidth(), Images.BrowserTitle.DIALOG_TOP_LEFT_INNER.getHeight(), this); g2.drawImage(Images.BrowserTitle.DIALOG_BOTTOM_LEFT_INNER, 0, getSize().height - Images.BrowserTitle.DIALOG_BOTTOM_LEFT_INNER.getHeight(), Images.BrowserTitle.DIALOG_BOTTOM_LEFT_INNER.getWidth(), Images.BrowserTitle.DIALOG_BOTTOM_LEFT_INNER.getHeight(), this); g2.drawImage(Images.BrowserTitle.DIALOG_TOP_RIGHT_INNER, getSize().width - Images.BrowserTitle.DIALOG_TOP_RIGHT_INNER.getWidth(), 0, Images.BrowserTitle.DIALOG_TOP_RIGHT_INNER.getWidth(), Images.BrowserTitle.DIALOG_TOP_RIGHT_INNER.getHeight(), this); g2.drawImage(Images.BrowserTitle.DIALOG_BOTTOM_RIGHT_INNER, getSize().width - Images.BrowserTitle.DIALOG_BOTTOM_RIGHT_INNER.getWidth(), getSize().height - Images.BrowserTitle.DIALOG_BOTTOM_RIGHT_INNER.getHeight(), Images.BrowserTitle.DIALOG_BOTTOM_RIGHT_INNER.getWidth(), Images.BrowserTitle.DIALOG_BOTTOM_RIGHT_INNER.getHeight(), this); } finally { g2.dispose(); } } }
public void setUtcTimeOnly(int field, Date value, boolean includeMillseconds) { String s = FieldValueConverter.UtcTimeOnlyConverter.convert(value, includeMillseconds); setField(new StringField(field, s));
public void setUtcTimeOnly(int field, Date value) { setUtcTimeOnly(field, value, false);
public void setUtcTimeOnly(int field, Date value, boolean includeMillseconds) { String s = FieldValueConverter.UtcTimeOnlyConverter.convert(value, includeMillseconds); setField(new StringField(field, s)); }
logVariable("team", team);
void handleDraftCreated(final Long containerId, final JabberId createdBy, final Calendar createdOn) { logApiId(); logVariable("containerId", containerId); logVariable("createdBy", createdBy); logVariable("createdOn", createdOn); final ContainerDraft draft = new ContainerDraft(); draft.setContainerId(containerId); final List<TeamMember> team = readTeam(containerId); draft.setOwner(team.get(indexOf(team, createdBy))); containerIO.createDraft(draft); // fire event notifyDraftCreated(read(containerId), readDraft(containerId), remoteEventGenerator); }
logVariable("user", user);
logger.logVariable("user", user);
public void service() { logApiId(); final User user = read(readJabberId("userId")); logVariable("user", user); if (null != user) { writeJabberId("id", user.getId()); writeString("name", user.getName()); if (user.isSetOrganization()) writeString("organization", user.getOrganization()); if (user.isSetTitle()) writeString("title", user.getTitle()); } }
static void notifyArtifactClosed(final UUID artifactUniqueId) { try { DocumentModel.getInternalModel(sContext).close(artifactUniqueId); }
static void notifyArtifactClosed(final UUID artifactUniqueId, final JabberId artifactClosedBy) { try { final InternalDocumentModel iDModel = DocumentModel.getInternalModel(sContext); iDModel.close(artifactUniqueId, artifactClosedBy); }
static void notifyArtifactClosed(final UUID artifactUniqueId) { try { DocumentModel.getInternalModel(sContext).close(artifactUniqueId); } catch(final ParityException px) { sLogger.fatal("Could not close artifact.", px); return; } }
sLogger.error("Could not create system message for key request.", px);
sLogger.error("Could not process key request: " + artifactUniqueId, px);
static void notifyKeyRequested(final UUID artifactUniqueId, final JabberId requestedBy) { try { final Document document = DocumentModel.getInternalModel(sContext).get(artifactUniqueId); SystemMessageModel.getInternalModel(sContext).createKeyRequest(document.getId(), requestedBy); } catch(final ParityException px) { sLogger.error("Could not create system message for key request.", px); return; } }
final User loggedInUser = xmppHelper.getUser(); final User keyHolder = getArtifactKeyHolder(artifactId); auditor.requestKey(artifactId, loggedInUser.getId(), currentDateTime(), loggedInUser.getId(), keyHolder.getId());
void sendKeyRequest(final Long artifactId) throws ParityException { logger.info("sendKeyRequest(Long)"); logger.debug(artifactId); synchronized(SessionModelImpl.xmppHelperLock) { assertIsLoggedIn("Cannot request key while offline.", xmppHelper); try { final UUID artifactUniqueId = getArtifactUniqueId(artifactId); xmppHelper.sendKeyRequest(artifactUniqueId); } catch(SmackException sx) { logger.error("Cannot send key request.", sx); throw ParityErrorTranslator.translate(sx); } catch(RuntimeException rx) { logger.error("Cannot send key request.", rx); throw ParityErrorTranslator.translate(rx); } } }
public void documentReactivated(final JabberId reactivatedBy, final List<JabberId> team, final UUID uniqueId, final Long versionId, final String name, final byte[] content) { handleDocumentReactivated(reactivatedBy, team, uniqueId, versionId, name, content); }
SessionModelXMPPHelper() { super(); this.xmppSession = XMPPSessionFactory.createSession(); this.xmppArtifactListener = new XMPPArtifactListener() { public void confirmReceipt(final UUID uniqueId, final Long versionId, final JabberId receivedFrom) { handleConfirmationReceipt(uniqueId, versionId, receivedFrom); } public void teamMemberAdded(final UUID artifactUniqueId, final Contact teamMember) { handleTeamMemberAdded(artifactUniqueId, teamMember); } public void teamMemberRemoved(final UUID artifactUniqueId, final Contact teamMember) { handleTeamMemberRemoved(artifactUniqueId, teamMember); } }; this.xmppDocumentListener = new XMPPDocumentListener() { public void documentReceived(final JabberId receivedFrom, final UUID uniqueId, final Long versionId, final String name, final byte[] content) { handleDocumentReceived(receivedFrom, uniqueId, versionId, name, content); } }; this.xmppExtensionListener = new XMPPExtensionListener() { public void artifactClosed(final UUID artifactUniqueId, final JabberId artifactClosedBy) { handleArtifactClosed(artifactUniqueId, artifactClosedBy); } public void keyRequestAccepted(final UUID artifactUniqueId, final JabberId acceptedBy) { handleKeyRequestAccepted(artifactUniqueId, acceptedBy); } public void keyRequestDenied(final UUID artifactUniqueId, final JabberId deniedBy) { handleKeyRequestDenied(artifactUniqueId, deniedBy); } public void keyRequested(final UUID artifactUniqueId, final JabberId requestedBy) { handleKeyRequested(artifactUniqueId, requestedBy); } }; this.xmppPresenceListener = new XMPPContactListener() { public void invitationAccepted(final JabberId acceptedBy) { handleInvitationAccepted(acceptedBy); } public void invitationDeclined(final JabberId declinedBy) { handleInvitationDeclined(declinedBy); } public void invitationExtended(final JabberId invitedBy) { handleInvitationExtended(invitedBy); } }; this.xmppSessionListener = new XMPPSessionListener() { public void sessionEstablished() { handleSessionEstablished(); } public void sessionTerminated() { handleSessionTerminated(); } public void sessionTerminated(final Exception x) { handleSessionTerminated(x); } }; xmppSession.addListener(xmppArtifactListener); xmppSession.addListener(xmppDocumentListener); xmppSession.addListener(xmppExtensionListener); xmppSession.addListener(xmppPresenceListener); xmppSession.addListener(xmppSessionListener); }
public User(final JabberId id) { super(); this.id = id; }
public User() { super(); }
public User(final JabberId id) { super(); this.id = id; }
session.prepareStatement(SQL_CREATE_PUBLISHED_TO); session.setLong(1, containerId); session.setLong(2, versionId);
public void createPublishedTo(final Long containerId, final Long versionId, final List<User> publishedTo) { final Session session = openSession(); try { session.prepareStatement(SQL_CREATE_PUBLISHED_TO); session.setLong(1, containerId); session.setLong(2, versionId); for (final User publishedToUser : publishedTo) { session.setLong(3, publishedToUser.getLocalId()); if (1 != session.executeUpdate()) throw new HypersonicException("Could not create published to entry."); } session.commit(); } catch (final HypersonicException hx) { session.rollback(); throw hx; } finally { session.close(); } }
session.setLong(3, publishedToUser.getLocalId()); if (1 != session.executeUpdate()) throw new HypersonicException("Could not create published to entry.");
createPublishedTo(session, containerId, versionId, publishedToUser);
public void createPublishedTo(final Long containerId, final Long versionId, final List<User> publishedTo) { final Session session = openSession(); try { session.prepareStatement(SQL_CREATE_PUBLISHED_TO); session.setLong(1, containerId); session.setLong(2, versionId); for (final User publishedToUser : publishedTo) { session.setLong(3, publishedToUser.getLocalId()); if (1 != session.executeUpdate()) throw new HypersonicException("Could not create published to entry."); } session.commit(); } catch (final HypersonicException hx) { session.rollback(); throw hx; } finally { session.close(); } }
assertOpen("prepareStatement(String)"); logger.logVariable("sql", sql);
assertConnectionIsOpen(); logStatement(sql);
public PreparedStatement prepareStatement(final String sql) { assertOpen("prepareStatement(String)"); logger.logVariable("sql", sql); try { preparedStatement = connection.prepareStatement(sql); return preparedStatement; } catch(final SQLException sqlx) { throw new HypersonicException(sqlx); } }
catch(final SQLException sqlx) { throw new HypersonicException(sqlx); }
public PreparedStatement prepareStatement(final String sql) { assertOpen("prepareStatement(String)"); logger.logVariable("sql", sql); try { preparedStatement = connection.prepareStatement(sql); return preparedStatement; } catch(final SQLException sqlx) { throw new HypersonicException(sqlx); } }
assertOpen("setLong(Integer,Long)"); assertPreparedStatement("setLong(Integer,Long)"); logIndexAndValue(index, value); try { preparedStatement.setLong(index, value); } catch(final SQLException sqlx) { throw new HypersonicException(sqlx); }
assertConnectionIsOpen(); assertPreparedStatementIsSet(); logColumnInjection(index, value); try { preparedStatement.setLong(index, value); } catch (final SQLException sqlx) { throw new HypersonicException(sqlx); }
public void setLong(final Integer index, final Long value) { assertOpen("setLong(Integer,Long)"); assertPreparedStatement("setLong(Integer,Long)"); logIndexAndValue(index, value); try { preparedStatement.setLong(index, value); } catch(final SQLException sqlx) { throw new HypersonicException(sqlx); } }
assertOpen("Cannot execute query if the session is not open."); assertPreparedStatement("Cannot execute query if the statement is not prepared."); try { resultSet = preparedStatement.executeQuery(); } catch(final SQLException sqlx) { throw new HypersonicException(sqlx); } }
assertConnectionIsOpen(); assertPreparedStatementIsSet(); try { resultSet = preparedStatement.executeQuery(); } catch (final SQLException sqlx) { throw panic(sqlx); } }
public void executeQuery() { assertOpen("Cannot execute query if the session is not open."); assertPreparedStatement("Cannot execute query if the statement is not prepared."); try { resultSet = preparedStatement.executeQuery(); } catch(final SQLException sqlx) { throw new HypersonicException(sqlx); } }
assertOpen("nextResult()"); assertOpenResult("nextResult()"); try { return resultSet.next(); } catch(final SQLException sqlx) { throw new HypersonicException(sqlx); }
assertConnectionIsOpen(); assertResultSetIsSet(); try { return resultSet.next(); } catch (final SQLException sqlx) { throw new HypersonicException(sqlx); }
public boolean nextResult() { assertOpen("nextResult()"); assertOpenResult("nextResult()"); try { return resultSet.next(); } catch(final SQLException sqlx) { throw new HypersonicException(sqlx); } }
assertOpen("getStateFromString(String)"); assertOpenResult("getStateFromString(String)"); logger.logVariable("columnName", columnName);
assertConnectionIsOpen(); assertResultSetIsSet();
public ContainerDraft.ArtifactState getContainerStateFromString( final String columnName) { assertOpen("getStateFromString(String)"); assertOpenResult("getStateFromString(String)"); logger.logVariable("columnName", columnName); try { final String value = resultSet.getString(columnName); return resultSet.wasNull() ? null : ContainerDraft.ArtifactState.valueOf(value); } catch (final SQLException sqlx) { throw new HypersonicException(sqlx); } }
logColumnExtraction(columnName, value);
public ContainerDraft.ArtifactState getContainerStateFromString( final String columnName) { assertOpen("getStateFromString(String)"); assertOpenResult("getStateFromString(String)"); logger.logVariable("columnName", columnName); try { final String value = resultSet.getString(columnName); return resultSet.wasNull() ? null : ContainerDraft.ArtifactState.valueOf(value); } catch (final SQLException sqlx) { throw new HypersonicException(sqlx); } }
assertOpen("Cannot close a closed session."); try { close(preparedStatement, resultSet); connection.close(); } catch(final SQLException sqlx) { throw new HypersonicException(sqlx); } sessionManager.close(this); }
assertConnectionIsOpen(); try { close(preparedStatement, resultSet); } finally { try { connection.close(); } catch (final SQLException sqlx) { throw panic(sqlx); } finally { sessionManager.close(this); } } }
public void close() { assertOpen("Cannot close a closed session."); try { close(preparedStatement, resultSet); connection.close(); } catch(final SQLException sqlx) { throw new HypersonicException(sqlx); } sessionManager.close(this); }
assertOpen("executeUpdate()"); assertPreparedStatement("executeUpdate()"); try { return preparedStatement.executeUpdate(); } catch(final SQLException sqlx) { throw new HypersonicException(sqlx); } }
assertConnectionIsOpen(); assertPreparedStatementIsSet(); try { return preparedStatement.executeUpdate(); } catch (final SQLException sqlx) { throw panic(sqlx); } }
public int executeUpdate() { assertOpen("executeUpdate()"); assertPreparedStatement("executeUpdate()"); try { return preparedStatement.executeUpdate(); } catch(final SQLException sqlx) { throw new HypersonicException(sqlx); } }
assertOpen("commit()"); try { connection.commit(); } catch(final SQLException sqlx) { throw new HypersonicException(sqlx); } }
assertConnectionIsOpen(); try { connection.commit(); } catch (final SQLException sqlx) { throw panic(sqlx); } }
public void commit() { assertOpen("commit()"); try { connection.commit(); } catch(final SQLException sqlx) { throw new HypersonicException(sqlx); } }
assertOpen("rollbackSession()");
assertConnectionIsOpen();
public void rollback() { assertOpen("rollbackSession()"); try { connection.commit(); } catch(final SQLException sqlx) { throw new HypersonicException(sqlx); } }
ResultSet resultSet = null; try { resultSet = list("CALL IDENTITY()"); resultSet.next(); return resultSet.getLong(1); } catch (final SQLException sqlx) { throw new HypersonicException(sqlx); } finally { close(resultSet); } }
assertConnectionIsOpen(); final String sql = "CALL IDENTITY()"; logStatement(sql); ResultSet resultSet = null; Statement statement = null; try { statement = connection.createStatement(); resultSet = statement.executeQuery(sql); if (resultSet.next()) { return resultSet.getLong(1); } else { return null; } } catch (final SQLException sqlx) { throw panic(sqlx); } finally { close(statement, resultSet); } }
public Long getIdentity() { ResultSet resultSet = null; try { resultSet = list("CALL IDENTITY()"); resultSet.next(); return resultSet.getLong(1); } catch (final SQLException sqlx) { throw new HypersonicException(sqlx); } finally { close(resultSet); } }
assertOpen("setEnumAsString(Integer,Enum<?>)"); assertPreparedStatement("setEnumAsString(Integer,Enum<?>)"); logIndexAndValue(index, value); try { preparedStatement.setString(index, value.toString()); } catch(final SQLException sqlx) { throw new HypersonicException(sqlx); }
assertConnectionIsOpen(); assertPreparedStatementIsSet(); logColumnInjection(index, value); try { preparedStatement.setString(index, value.toString()); } catch (final SQLException sqlx) { throw new HypersonicException(sqlx); }
public void setEnumTypeAsString(final Integer index, final Enum<?> value) { assertOpen("setEnumAsString(Integer,Enum<?>)"); assertPreparedStatement("setEnumAsString(Integer,Enum<?>)"); logIndexAndValue(index, value); try { preparedStatement.setString(index, value.toString()); } catch(final SQLException sqlx) { throw new HypersonicException(sqlx); } }
session.setLong(6, readLocalId(version.getCreatedBy())); session.setCalendar(7, version.getCreatedOn()); session.setLong(8, readLocalId(version.getUpdatedBy())); session.setCalendar(9, version.getUpdatedOn());
session.setString(6, version.getComment()); session.setLong(7, readLocalId(version.getCreatedBy())); session.setCalendar(8, version.getCreatedOn()); session.setLong(9, readLocalId(version.getUpdatedBy())); session.setCalendar(10, version.getUpdatedOn());
void createVersion(final Session session, final ArtifactVersion version) { session.prepareStatement(INSERT_ARTIFACT_VERSION); session.setLong(1, version.getArtifactId()); session.setLong(2, version.getVersionId()); session.setString(3, version.getName()); session.setTypeAsString(4, version.getArtifactType()); session.setUniqueId(5, version.getArtifactUniqueId()); session.setLong(6, readLocalId(version.getCreatedBy())); session.setCalendar(7, version.getCreatedOn()); session.setLong(8, readLocalId(version.getUpdatedBy())); session.setCalendar(9, version.getUpdatedOn()); if(1 != session.executeUpdate()) throw new HypersonicException("Could not create version."); setVersionMetaData(session, version.getArtifactId(), version .getVersionId(), version.getMetaData()); }
assertOpen("getLong(String)"); assertOpenResult("getLong(String)"); logger.logVariable("columnName", columnName);
assertConnectionIsOpen(); assertResultSetIsSet();
public Long getLong(final String columnName) { assertOpen("getLong(String)"); assertOpenResult("getLong(String)"); logger.logVariable("columnName", columnName); try { final Long value = resultSet.getLong(columnName); return resultSet.wasNull() ? null : value; } catch (final SQLException sqlx) { throw new HypersonicException(sqlx); } }
logColumnExtraction(columnName, value);
public Long getLong(final String columnName) { assertOpen("getLong(String)"); assertOpenResult("getLong(String)"); logger.logVariable("columnName", columnName); try { final Long value = resultSet.getLong(columnName); return resultSet.wasNull() ? null : value; } catch (final SQLException sqlx) { throw new HypersonicException(sqlx); } }
assertOpen("getString(String)"); assertOpenResult("getString(String)"); logger.logVariable("columnName", columnName);
assertConnectionIsOpen(); assertResultSetIsSet();
public String getString(final String columnName) { assertOpen("getString(String)"); assertOpenResult("getString(String)"); logger.logVariable("columnName", columnName); try { final String value = resultSet.getString(columnName); return resultSet.wasNull() ? null : value; } catch (final SQLException sqlx) { throw new HypersonicException(sqlx); } }
logColumnExtraction(columnName, value);
public String getString(final String columnName) { assertOpen("getString(String)"); assertOpenResult("getString(String)"); logger.logVariable("columnName", columnName); try { final String value = resultSet.getString(columnName); return resultSet.wasNull() ? null : value; } catch (final SQLException sqlx) { throw new HypersonicException(sqlx); } }
assertOpen("Cannot get values if the session is not open."); assertOpenResult("Cannot get values if the result is not open."); logger.logVariable("columnName", columnName);
assertConnectionIsOpen(); assertResultSetIsSet();
public JabberId getQualifiedUsername(final String columnName) { assertOpen("Cannot get values if the session is not open."); assertOpenResult("Cannot get values if the result is not open."); logger.logVariable("columnName", columnName); try { final String value = resultSet.getString(columnName); if (resultSet.wasNull()) { return null; } else { return JabberIdBuilder.parse(value); } } catch (final SQLException sqlx) { throw new HypersonicException(sqlx); } catch (final IllegalArgumentException iax) { throw new HypersonicException(iax); } }
logColumnExtraction(columnName, value);
public JabberId getQualifiedUsername(final String columnName) { assertOpen("Cannot get values if the session is not open."); assertOpenResult("Cannot get values if the result is not open."); logger.logVariable("columnName", columnName); try { final String value = resultSet.getString(columnName); if (resultSet.wasNull()) { return null; } else { return JabberIdBuilder.parse(value); } } catch (final SQLException sqlx) { throw new HypersonicException(sqlx); } catch (final IllegalArgumentException iax) { throw new HypersonicException(iax); } }
assertOpen("getCalendar(String)"); assertOpenResult("getCalendar(String)");
assertConnectionIsOpen(); assertResultSetIsSet();
public Calendar getCalendar(final String columnName) { assertOpen("getCalendar(String)"); assertOpenResult("getCalendar(String)"); try { final Calendar calendar = DateUtil.getInstance(); final Timestamp timestamp = resultSet.getTimestamp(columnName, calendar); if (resultSet.wasNull()) { return null; } else { calendar.setTime(timestamp); return calendar; } } catch (final SQLException sqlx) { throw new HypersonicException(sqlx); } }
final Calendar calendar = DateUtil.getInstance(); final Timestamp timestamp = resultSet.getTimestamp(columnName, calendar); if (resultSet.wasNull()) { return null; }
final Calendar value = DateUtil.getInstance(); final Timestamp timestamp = resultSet.getTimestamp(columnName, value); if (resultSet.wasNull()) { logColumnExtraction(columnName, null); return null; }
public Calendar getCalendar(final String columnName) { assertOpen("getCalendar(String)"); assertOpenResult("getCalendar(String)"); try { final Calendar calendar = DateUtil.getInstance(); final Timestamp timestamp = resultSet.getTimestamp(columnName, calendar); if (resultSet.wasNull()) { return null; } else { calendar.setTime(timestamp); return calendar; } } catch (final SQLException sqlx) { throw new HypersonicException(sqlx); } }
calendar.setTime(timestamp); return calendar;
value.setTime(timestamp); logColumnExtraction(columnName, value); return value;
public Calendar getCalendar(final String columnName) { assertOpen("getCalendar(String)"); assertOpenResult("getCalendar(String)"); try { final Calendar calendar = DateUtil.getInstance(); final Timestamp timestamp = resultSet.getTimestamp(columnName, calendar); if (resultSet.wasNull()) { return null; } else { calendar.setTime(timestamp); return calendar; } } catch (final SQLException sqlx) { throw new HypersonicException(sqlx); } }
assertOpen("getStateFromInteger(String)"); assertOpenResult("getStateFromInteger(String)"); logger.logVariable("columnName", columnName);
assertConnectionIsOpen(); assertResultSetIsSet();
public ArtifactState getStateFromInteger(final String columnName) { assertOpen("getStateFromInteger(String)"); assertOpenResult("getStateFromInteger(String)"); logger.logVariable("columnName", columnName); try { final Integer value = resultSet.getInt(columnName); return resultSet.wasNull() ? null : ArtifactState.fromId(value); } catch (final SQLException sqlx) { throw new HypersonicException(sqlx); } }
logColumnExtraction(columnName, value);
public ArtifactState getStateFromInteger(final String columnName) { assertOpen("getStateFromInteger(String)"); assertOpenResult("getStateFromInteger(String)"); logger.logVariable("columnName", columnName); try { final Integer value = resultSet.getInt(columnName); return resultSet.wasNull() ? null : ArtifactState.fromId(value); } catch (final SQLException sqlx) { throw new HypersonicException(sqlx); } }
assertOpen("getTypeFromInteger(String)"); assertOpenResult("getTypeFromInteger(String)"); logger.logVariable("columnName", columnName);
assertConnectionIsOpen(); assertResultSetIsSet();
public ArtifactType getTypeFromInteger(final String columnName) { assertOpen("getTypeFromInteger(String)"); assertOpenResult("getTypeFromInteger(String)"); logger.logVariable("columnName", columnName); try { final Integer value = resultSet.getInt(columnName); return resultSet.wasNull() ? null : ArtifactType.fromId(value); } catch (final SQLException sqlx) { throw new HypersonicException(sqlx); } }
logColumnExtraction(columnName, value);
public ArtifactType getTypeFromInteger(final String columnName) { assertOpen("getTypeFromInteger(String)"); assertOpenResult("getTypeFromInteger(String)"); logger.logVariable("columnName", columnName); try { final Integer value = resultSet.getInt(columnName); return resultSet.wasNull() ? null : ArtifactType.fromId(value); } catch (final SQLException sqlx) { throw new HypersonicException(sqlx); } }
assertOpen("getString(String)"); assertOpenResult("getString(String)"); final String value = getString(columnName); return null == value ? null : UUID.fromString(value); }
assertConnectionIsOpen(); assertResultSetIsSet(); try { final String value = resultSet.getString(columnName); logColumnExtraction(columnName, value); return resultSet.wasNull() ? null : UUID.fromString(value); } catch (final SQLException sqlx) { throw panic(sqlx); } }
public UUID getUniqueId(final String columnName) { assertOpen("getString(String)"); assertOpenResult("getString(String)"); final String value = getString(columnName); return null == value ? null : UUID.fromString(value); }
assertOpen("[LMODEL] [IO] [HSQL] [GET INTEGER]"); assertOpenResult("[LMODEL] [IO] [HSQL] [GET INTEGER]"); logger.logVariable("columnName", columnName);
assertConnectionIsOpen(); assertResultSetIsSet();
public Integer getInteger(final String columnName) { assertOpen("[LMODEL] [IO] [HSQL] [GET INTEGER]"); assertOpenResult("[LMODEL] [IO] [HSQL] [GET INTEGER]"); logger.logVariable("columnName", columnName); try { final Integer value = resultSet.getInt(columnName); return resultSet.wasNull() ? null : value; } catch (final SQLException sqlx) { throw new HypersonicException(sqlx); } }
logColumnExtraction(columnName, value);
public Integer getInteger(final String columnName) { assertOpen("[LMODEL] [IO] [HSQL] [GET INTEGER]"); assertOpenResult("[LMODEL] [IO] [HSQL] [GET INTEGER]"); logger.logVariable("columnName", columnName); try { final Integer value = resultSet.getInt(columnName); return resultSet.wasNull() ? null : value; } catch (final SQLException sqlx) { throw new HypersonicException(sqlx); } }
assertOpen("setString(Integer,String)"); assertPreparedStatement("setString(Integer,String)"); logIndexAndValue(index, value); try { preparedStatement.setString(index, value); } catch(final SQLException sqlx) { throw new HypersonicException(sqlx); }
assertConnectionIsOpen(); assertPreparedStatementIsSet(); logColumnInjection(index, value); try { if (null == value) { preparedStatement.setNull(index, Types.VARCHAR); } else { preparedStatement.setString(index, value); } } catch (final SQLException sqlx) { throw new HypersonicException(sqlx); }
public void setString(final Integer index, final String value) { assertOpen("setString(Integer,String)"); assertPreparedStatement("setString(Integer,String)"); logIndexAndValue(index, value); try { preparedStatement.setString(index, value); } catch(final SQLException sqlx) { throw new HypersonicException(sqlx); } }
assertOpen("setCalendar(Integer,Calendar)"); assertPreparedStatement("setCalendar(Integer,Calendar)"); logIndexAndValue(index, value);
assertConnectionIsOpen(); assertPreparedStatementIsSet(); logColumnInjection(index, value);
public void setCalendar(final Integer index, final Calendar value) { assertOpen("setCalendar(Integer,Calendar)"); assertPreparedStatement("setCalendar(Integer,Calendar)"); logIndexAndValue(index, value); try { preparedStatement.setTimestamp(index, new Timestamp(value.getTimeInMillis()), value); } catch(final SQLException sqlx) { throw new HypersonicException(sqlx); } }
catch(final SQLException sqlx) { throw new HypersonicException(sqlx); }
public void setCalendar(final Integer index, final Calendar value) { assertOpen("setCalendar(Integer,Calendar)"); assertPreparedStatement("setCalendar(Integer,Calendar)"); logIndexAndValue(index, value); try { preparedStatement.setTimestamp(index, new Timestamp(value.getTimeInMillis()), value); } catch(final SQLException sqlx) { throw new HypersonicException(sqlx); } }
System.setProperty("swing.aatext", "true"); try { javax.swing.UIManager.setLookAndFeel(javax.swing.UIManager.getSystemLookAndFeelClassName()); } catch(Exception e) {}
System.out.println("Starting...");
public static void notmain(String[] args) throws Exception { System.setProperty("swing.aatext", "true"); //Antialiased text try { javax.swing.UIManager.setLookAndFeel(javax.swing.UIManager.getSystemLookAndFeelClassName()); } catch(Exception e) {} if(DEBUG) verbose = true; parseArgs(args); printlnVerbose("Processing: " + dmgFile); RandomAccessFile dmgRaf = new RandomAccessFile(dmgFile, "r"); RandomAccessFile isoRaf = null; boolean testOnly = false; if(isoFile != null) { isoRaf = new RandomAccessFile(isoFile, "rw"); isoRaf.setLength(0); printlnVerbose("Extracting to: " + isoFile); } else { testOnly = true; printlnVerbose("Simulating extraction..."); } dmgRaf.seek(dmgRaf.length()-PLIST_ADDRESS_1); long plistBegin1 = dmgRaf.readLong(); long plistEnd = dmgRaf.readLong(); dmgRaf.seek(dmgRaf.length()-PLIST_ADDRESS_2); long plistBegin2 = dmgRaf.readLong(); long plistSize = dmgRaf.readLong(); if(DEBUG) { println("Read addresses:", " " + plistBegin1, " " + plistBegin2); } if(plistBegin1 != plistBegin2) { println("Addresses not equal! Assumption broken... =/", plistBegin1 + " != " + plistBegin2); System.exit(0); } if(plistSize != (plistEnd-plistBegin1)) { println("plistSize field does not match plistEnd marker!", "plistSize=" + plistSize + " plistBegin1=" + plistBegin1 + " plistEnd=" + plistEnd + " plistEnd-plistBegin1=" + (plistEnd-plistBegin1)); } printlnVerbose("Jumping to address..."); dmgRaf.seek(plistBegin1); byte[] buffer = new byte[(int)plistSize]; dmgRaf.read(buffer); InputStream is = new ByteArrayInputStream(buffer); NodeBuilder handler = new NodeBuilder(); SAXParser saxParser = SAXParserFactory.newInstance().newSAXParser(); try {// System.out.println("validation: " + saxParser.getProperty("validation"));// System.out.println("external-general-entities: " + saxParser.getProperty("external-general-entities"));// System.out.println("external-parameter-entities: " + saxParser.getProperty("external-parameter-entities"));// System.out.println("is-standalone: " + saxParser.getProperty("is-standalone"));// System.out.println("lexical-handler: " + saxParser.getProperty("lexical-handler"));// System.out.println("parameter-entities: " + saxParser.getProperty("parameter-entities"));// System.out.println("namespaces: " + saxParser.getProperty("namespaces"));// System.out.println("namespace-prefixes: " + saxParser.getProperty("namespace-prefixes"));// System.out.println(": " + saxParser.getProperty(""));// System.out.println(": " + saxParser.getProperty(""));// System.out.println(": " + saxParser.getProperty(""));// System.out.println(": " + saxParser.getProperty(""));// System.out.println("" + saxParser.getProperty(""));// System.out.println("" + saxParser.getProperty(""));// System.out.println("" + saxParser.getProperty(""));// System.out.println("" + saxParser.getProperty(""));// System.out.println("" + saxParser.getProperty(""));// System.out.println("" + saxParser.getProperty(""));// System.out.println("" + saxParser.getProperty(""));// System.out.println("" + saxParser.getProperty("")); System.out.println("isValidating: " + saxParser.isValidating()); saxParser.parse(is, handler); } catch(SAXException se) { se.printStackTrace(); System.err.println("Could not read the partition list... exiting."); System.exit(1); } XMLNode[] rootNodes = handler.getRoots(); if(rootNodes.length != 1) { println("Could not parse DMG-file!"); System.exit(0); } /* Ok, now we have a tree built from the XML-document. Let's walk to the right place. */ /* cd plist cd dict cdkey resource-fork (type:dict) cdkey blkx (type:array) */ XMLNode current; XMLElement[] children; boolean keyFound; current = rootNodes[0]; //We are at plist... probably (there should be only one root node) current = current.cd("dict"); current = current.cdkey("resource-fork"); current = current.cdkey("blkx"); printlnVerbose("Found " + current.getChildren().length + " partitions:"); byte[] tmp = new byte[0x40000]; byte[] otmp = new byte[0x40000]; byte[] zeroblock = new byte[4096]; /* I think java always zeroes its arrays on creation... but let's play safe. */ for(int y = 0; y < zeroblock.length; ++y) zeroblock[y] = 0; LinkedList<DMGBlock> blocks = new LinkedList<DMGBlock>(); //long lastOffs = 0; long lastOutOffset = 0; long lastInOffset = 0; long totalSize = 0; boolean errorsFound = false; reportProgress(0); for(XMLElement xe : current.getChildren()) { if(progmon != null && progmon.isCanceled()) System.exit(0); if(xe instanceof XMLNode) { XMLNode xn = (XMLNode)xe; byte[] data = Base64.decode(xn.getKeyValue("Data")); long partitionSize = calculatePartitionSize(data); totalSize += partitionSize; printlnVerbose(" " + xn.getKeyValue("Name")); printlnVerbose(" ID: " + xn.getKeyValue("ID")); printlnVerbose(" Attributes: " + xn.getKeyValue("Attributes")); printlnVerbose(" Partition map data length: " + data.length + " bytes"); printlnVerbose(" Partition size: " + partitionSize + " bytes"); if(verbose) { printlnVerbose(" Dumping blkx..."); FileOutputStream fos = new FileOutputStream(xn.getKeyValue("ID") + ".blkx"); fos.write(data); fos.close(); } if(DEBUG) { File dumpFile = new File("data " + xn.getKeyValue("ID") + ".bin"); println(" Dumping partition map to file: " + dumpFile); FileOutputStream dump = new FileOutputStream(dumpFile); dump.write(data); dump.close(); } int offset = 0xCC; int blockType = 0; /* Offset of the input data for the current block in the input file */ long inOffset = 0; /* Size of the input data for the current block */ long inSize = 0; /* Offset of the output data for the current block in the output file */ long outOffset = 0; /* Size of the output data (possibly larger than inSize because of decompression, zero expansion...) */ long outSize = 0; long lastByteReadInBlock = -1; boolean addInOffset = false; //, lastInOffs = 0; int blockCount = 0; long previousPercentage = -1; while(blockType != BT_END) { if(progmon != null && progmon.isCanceled()) System.exit(0); DataInputStream dis = new DataInputStream(new ByteArrayInputStream(data)); int bytesSkipped = 0; while(bytesSkipped < offset) bytesSkipped += dis.skipBytes(offset-bytesSkipped); blockType = dis.readInt(); int skipped = dis.readInt(); //Skip 4 bytes forward outOffset = dis.readLong()*0x200;//(dis.readInt() & 0xffffffffL)*0x200; //unsigned int -> long //dis.readInt(); //Skip 4 bytes forward outSize = dis.readLong()*0x200;//(dis.readInt() & 0xffffffffL)*0x200; //unsigned int -> long inOffset = dis.readLong();// & 0xffffffffL; //unsigned int -> long //dis.readInt(); //Skip 4 bytes forward inSize = dis.readLong();//dis.readInt() & 0xffffffffL; //unsigned int -> long blocks.add(new DMGBlock(blockType, skipped, outOffset, outSize, inOffset, inSize)); if(lastByteReadInBlock == -1) lastByteReadInBlock = inOffset; lastByteReadInBlock += inSize; /* The lines below are a "hack" that I had to do to make dmgx work with certain dmg-files. I don't understand the issue at all, which is why this hack is here, but sometimes inOffset == 0 means that it is 0 relative to the previous partition's last inOffset. And sometimes it doesn't (meaning the actual position 0 in the dmg file). */ if(addInOffset) inOffset += lastInOffset; else if(inOffset == 0) { addInOffset = true; inOffset += lastInOffset; } outOffset += lastOutOffset; if(DEBUG) { println("outOffset=" + outOffset + " outSize=" + outSize + " inOffset=" + inOffset + " inSize=" + inSize + " lastOutOffset=" + lastOutOffset + " lastInOffset=" + lastInOffset /*+ " lastInOffs=" + lastInOffs + " lastOffs=" + lastOffs*/); } if(blockType == BT_ADC) { println(" " + blockCount + ". BT_ADC not supported."); if(!testOnly) System.exit(0); } else if(blockType == BT_ZLIB) { if(DEBUG) println(" " + blockCount + ". BT_ZLIB processing..."); if(!testOnly && isoRaf.getFilePointer() != outOffset) println(" " + blockCount + ". BT_ZLIB FP != outOffset (" + isoRaf.getFilePointer() + " != " + outOffset + ")"); dmgRaf.seek(/*lastOffs+*/inOffset); if(tmp.length < inSize) tmp = new byte[(int)inSize]; long totalBytesRead = 0; while(totalBytesRead < inSize) { totalBytesRead += dmgRaf.read(tmp, (int)totalBytesRead, Math.min((int)(inSize-totalBytesRead), tmp.length)); } long progressPercentage = dmgRaf.getFilePointer()*100/dmgRaf.length(); if(progressPercentage != previousPercentage) { reportProgress(progressPercentage); previousPercentage = progressPercentage; } Inflater inflater = new Inflater(); inflater.setInput(tmp, 0, (int)totalBytesRead); if(otmp.length < outSize) otmp = new byte[(int)outSize]; int bytesInflated = 0; while(true) { try { int counter = 0; while(bytesInflated < outSize && counter++ < 10) { int old = bytesInflated; bytesInflated += inflater.inflate(otmp, bytesInflated, (int)(outSize-bytesInflated)); if(old == bytesInflated) println("Nothing new! finished()=" + inflater.finished() + " needsInput()=" + inflater.needsInput() + " needsDictionary()=" + inflater.needsDictionary() + " getAdler()=" + inflater.getAdler() + " getBytesRead()=" + inflater.getBytesRead() + " getBytesWritten()=" + inflater.getBytesWritten() + " getRemaining()=" + inflater.getRemaining()); } //System.out.println(" Inflated " + bytesInflated + " bytes. Left in buffer: " + inflater.getRemaining() + " bytes inSize="+inSize+" outSize="+outSize); if(inflater.getRemaining() == 0) { //System.out.println(" done!"); break; } else { println(" " + blockCount + ". BT_ZLIB ERROR: otmp contents lost! (should not happen...)", " outSize=" + outSize + " inSize=" + inSize + " tmp.length=" + tmp.length + " otmp.length=" + otmp.length + " bytesInflated=" + bytesInflated + " inflater.getRemaining()=" + inflater.getRemaining());// if(bytesInflated == 0) throw new RuntimeException("WTF"); } } catch(DataFormatException dfe) { println(" " + blockCount + ". BT_ZLIB Could not decode..."); if(!DEBUG) { println("outOffset=" + outOffset + " outSize=" + outSize + " inOffset=" + inOffset + " inSize=" + inSize + " lastOutOffset=" + lastOutOffset + " lastInOffset=" + lastInOffset); } dfe.printStackTrace(); if(!testOnly) System.exit(0); else { println(" Testing mode, so continuing..."); //System.exit(0); errorsFound = true; break; } } } inflater.end(); if(!testOnly) isoRaf.write(otmp, 0, (int)outSize); //lastInOffs = inOffset+inSize; } else if(blockType == BT_BZIP2) { println(" " + blockCount + ". BT_BZIP2 not currently supported."); if(!testOnly) System.exit(0); } else if(blockType == BT_COPY) { if(DEBUG) println(" " + blockCount + ". BT_COPY processing..."); if(!testOnly && isoRaf.getFilePointer() != outOffset) println(" " + blockCount + ". BT_COPY FP != outOffset (" + isoRaf.getFilePointer() + " != " + outOffset + ")"); dmgRaf.seek(/*lastOffs+*/inOffset); int bytesRead = dmgRaf.read(tmp, 0, Math.min((int)inSize, tmp.length)); long totalBytesRead = bytesRead; while(bytesRead != -1) { long progressPercentage = dmgRaf.getFilePointer()*100/dmgRaf.length(); if(progressPercentage != previousPercentage) { reportProgress(progressPercentage); previousPercentage = progressPercentage; } if(!testOnly) isoRaf.write(tmp, 0, bytesRead); if(totalBytesRead >= inSize) break; bytesRead = dmgRaf.read(tmp, 0, Math.min((int)(inSize-totalBytesRead), tmp.length)); if(bytesRead > 0) totalBytesRead += bytesRead; } //lastInOffs = inOffset+inSize; } else if(blockType == BT_ZERO) { if(DEBUG) println(" " + blockCount + ". BT_ZERO processing..."); if(!testOnly && isoRaf.getFilePointer() != outOffset) println(" " + blockCount + ". BT_ZERO FP != outOffset (" + isoRaf.getFilePointer() + " != " + outOffset + ")"); long progressPercentage = dmgRaf.getFilePointer()*100/dmgRaf.length(); if(progressPercentage != previousPercentage) { reportProgress(progressPercentage); previousPercentage = progressPercentage; } long numberOfZeroBlocks = outSize/zeroblock.length; int numberOfRemainingBytes = (int)(outSize%zeroblock.length); for(int j = 0; j < numberOfZeroBlocks; ++j) { if(!testOnly) isoRaf.write(zeroblock); } if(!testOnly) isoRaf.write(zeroblock, 0, numberOfRemainingBytes); //lastInOffs = inOffset+inSize; } else if(blockType == BT_UNKNOWN) { /* I have no idea what this blocktype is... but it's common, and usually doesn't appear more than 2-3 times in a dmg. As long as its input and output sizes are 0, there's no reason to complain... is there? */ if(DEBUG) println(" " + blockCount + ". BT_UNKNOWN processing..."); if(!(inSize == 0 && outSize == 0)) { println(" " + blockCount + ". WARNING! Blocktype BT_UNKNOWN had non-zero sizes...", " inSize=" + inSize + ", outSize=" + outSize); //println(" The author of the program would be pleased if you contacted him about this."); // ...or would I? } } else if(blockType == BT_END) { if(DEBUG) println(" " + blockCount + ". BT_END processing..."); if(!testOnly && isoRaf.getFilePointer() != outOffset) println(" " + blockCount + ". BT_END FP != outOffset (" + isoRaf.getFilePointer() + " != " + outOffset + ")"); //lastOffs += lastInOffs; lastOutOffset = outOffset; lastInOffset += lastByteReadInBlock; } else { println(" " + blockCount + ". WARNING: previously unseen blocktype " + blockType + " [0x" + Integer.toHexString(blockType) + "]", " " + blockCount + ". outOffset=" + outOffset + " outSize=" + outSize + " inOffset=" + inOffset + " inSize=" + inSize); if(!testOnly && isoRaf.getFilePointer() != outOffset) println(" " + blockCount + ". unknown blocktype FP != outOffset (" + isoRaf.getFilePointer() + " != " + outOffset + ")"); } offset += 0x28; ++blockCount; } } } //printlnVerbose("Progress: 100% Done!"); reportProgress(100); String errors = errorsFound?"There were errors...":"No errors reported."; if(!graphical) { newline(); println(errors); printlnVerbose("Total extracted bytes: " + totalSize + " B"); } else { progmon.close(); JOptionPane.showMessageDialog(null, "Extraction complete! " + errors + "\n" + "Total extracted bytes: " + totalSize + " B", "Information", JOptionPane.INFORMATION_MESSAGE); System.exit(0); }// System.out.println("blocks.size()=" + blocks.size());// for(DMGBlock b : blocks)// System.out.println(" " + b.toString()); LinkedList<DMGBlock> merged = mergeBlocks(blocks);// System.out.println("merged.size()=" + merged.size());// for(DMGBlock b : merged)// System.out.println(" " + b.toString()); System.out.println("Extracting all the parts not containing block data from source file:"); int i = 1; DMGBlock previous = null; for(DMGBlock b : merged) { if(previous == null && b.inOffset > 0) { String filename = i++ + ".block"; System.out.print(" " + filename + "..."); FileOutputStream curFos = new FileOutputStream(new File(filename)); dmgRaf.seek(0); byte[] data = new byte[(int)(b.inOffset)]; dmgRaf.read(data); curFos.write(data); curFos.close(); } else if(previous != null) { String filename = i++ + ".block"; System.out.print(" " + filename + "..."); FileOutputStream curFos = new FileOutputStream(new File(filename)); dmgRaf.seek(previous.inOffset+previous.inSize); byte[] data = new byte[(int)(b.inOffset-(previous.inOffset+previous.inSize))]; dmgRaf.read(data); curFos.write(data); curFos.close(); } previous = b; } if(previous.inOffset+previous.inSize != dmgRaf.length()) { String filename = i++ + ".block"; System.out.print(" " + filename + "..."); FileOutputStream curFos = new FileOutputStream(new File(filename)); dmgRaf.seek(previous.inOffset+previous.inSize); byte[] data = new byte[(int)(dmgRaf.length()-(previous.inOffset+previous.inSize))]; dmgRaf.read(data); curFos.write(data); curFos.close(); } dmgRaf.close(); System.out.println("done!"); }
byte[] tmp = new byte[0x40000]; byte[] otmp = new byte[0x40000];
byte[] inBuffer = new byte[0x40000]; byte[] outBuffer = new byte[0x40000];
public static void notmain(String[] args) throws Exception { System.setProperty("swing.aatext", "true"); //Antialiased text try { javax.swing.UIManager.setLookAndFeel(javax.swing.UIManager.getSystemLookAndFeelClassName()); } catch(Exception e) {} if(DEBUG) verbose = true; parseArgs(args); printlnVerbose("Processing: " + dmgFile); RandomAccessFile dmgRaf = new RandomAccessFile(dmgFile, "r"); RandomAccessFile isoRaf = null; boolean testOnly = false; if(isoFile != null) { isoRaf = new RandomAccessFile(isoFile, "rw"); isoRaf.setLength(0); printlnVerbose("Extracting to: " + isoFile); } else { testOnly = true; printlnVerbose("Simulating extraction..."); } dmgRaf.seek(dmgRaf.length()-PLIST_ADDRESS_1); long plistBegin1 = dmgRaf.readLong(); long plistEnd = dmgRaf.readLong(); dmgRaf.seek(dmgRaf.length()-PLIST_ADDRESS_2); long plistBegin2 = dmgRaf.readLong(); long plistSize = dmgRaf.readLong(); if(DEBUG) { println("Read addresses:", " " + plistBegin1, " " + plistBegin2); } if(plistBegin1 != plistBegin2) { println("Addresses not equal! Assumption broken... =/", plistBegin1 + " != " + plistBegin2); System.exit(0); } if(plistSize != (plistEnd-plistBegin1)) { println("plistSize field does not match plistEnd marker!", "plistSize=" + plistSize + " plistBegin1=" + plistBegin1 + " plistEnd=" + plistEnd + " plistEnd-plistBegin1=" + (plistEnd-plistBegin1)); } printlnVerbose("Jumping to address..."); dmgRaf.seek(plistBegin1); byte[] buffer = new byte[(int)plistSize]; dmgRaf.read(buffer); InputStream is = new ByteArrayInputStream(buffer); NodeBuilder handler = new NodeBuilder(); SAXParser saxParser = SAXParserFactory.newInstance().newSAXParser(); try {// System.out.println("validation: " + saxParser.getProperty("validation"));// System.out.println("external-general-entities: " + saxParser.getProperty("external-general-entities"));// System.out.println("external-parameter-entities: " + saxParser.getProperty("external-parameter-entities"));// System.out.println("is-standalone: " + saxParser.getProperty("is-standalone"));// System.out.println("lexical-handler: " + saxParser.getProperty("lexical-handler"));// System.out.println("parameter-entities: " + saxParser.getProperty("parameter-entities"));// System.out.println("namespaces: " + saxParser.getProperty("namespaces"));// System.out.println("namespace-prefixes: " + saxParser.getProperty("namespace-prefixes"));// System.out.println(": " + saxParser.getProperty(""));// System.out.println(": " + saxParser.getProperty(""));// System.out.println(": " + saxParser.getProperty(""));// System.out.println(": " + saxParser.getProperty(""));// System.out.println("" + saxParser.getProperty(""));// System.out.println("" + saxParser.getProperty(""));// System.out.println("" + saxParser.getProperty(""));// System.out.println("" + saxParser.getProperty(""));// System.out.println("" + saxParser.getProperty(""));// System.out.println("" + saxParser.getProperty(""));// System.out.println("" + saxParser.getProperty(""));// System.out.println("" + saxParser.getProperty("")); System.out.println("isValidating: " + saxParser.isValidating()); saxParser.parse(is, handler); } catch(SAXException se) { se.printStackTrace(); System.err.println("Could not read the partition list... exiting."); System.exit(1); } XMLNode[] rootNodes = handler.getRoots(); if(rootNodes.length != 1) { println("Could not parse DMG-file!"); System.exit(0); } /* Ok, now we have a tree built from the XML-document. Let's walk to the right place. */ /* cd plist cd dict cdkey resource-fork (type:dict) cdkey blkx (type:array) */ XMLNode current; XMLElement[] children; boolean keyFound; current = rootNodes[0]; //We are at plist... probably (there should be only one root node) current = current.cd("dict"); current = current.cdkey("resource-fork"); current = current.cdkey("blkx"); printlnVerbose("Found " + current.getChildren().length + " partitions:"); byte[] tmp = new byte[0x40000]; byte[] otmp = new byte[0x40000]; byte[] zeroblock = new byte[4096]; /* I think java always zeroes its arrays on creation... but let's play safe. */ for(int y = 0; y < zeroblock.length; ++y) zeroblock[y] = 0; LinkedList<DMGBlock> blocks = new LinkedList<DMGBlock>(); //long lastOffs = 0; long lastOutOffset = 0; long lastInOffset = 0; long totalSize = 0; boolean errorsFound = false; reportProgress(0); for(XMLElement xe : current.getChildren()) { if(progmon != null && progmon.isCanceled()) System.exit(0); if(xe instanceof XMLNode) { XMLNode xn = (XMLNode)xe; byte[] data = Base64.decode(xn.getKeyValue("Data")); long partitionSize = calculatePartitionSize(data); totalSize += partitionSize; printlnVerbose(" " + xn.getKeyValue("Name")); printlnVerbose(" ID: " + xn.getKeyValue("ID")); printlnVerbose(" Attributes: " + xn.getKeyValue("Attributes")); printlnVerbose(" Partition map data length: " + data.length + " bytes"); printlnVerbose(" Partition size: " + partitionSize + " bytes"); if(verbose) { printlnVerbose(" Dumping blkx..."); FileOutputStream fos = new FileOutputStream(xn.getKeyValue("ID") + ".blkx"); fos.write(data); fos.close(); } if(DEBUG) { File dumpFile = new File("data " + xn.getKeyValue("ID") + ".bin"); println(" Dumping partition map to file: " + dumpFile); FileOutputStream dump = new FileOutputStream(dumpFile); dump.write(data); dump.close(); } int offset = 0xCC; int blockType = 0; /* Offset of the input data for the current block in the input file */ long inOffset = 0; /* Size of the input data for the current block */ long inSize = 0; /* Offset of the output data for the current block in the output file */ long outOffset = 0; /* Size of the output data (possibly larger than inSize because of decompression, zero expansion...) */ long outSize = 0; long lastByteReadInBlock = -1; boolean addInOffset = false; //, lastInOffs = 0; int blockCount = 0; long previousPercentage = -1; while(blockType != BT_END) { if(progmon != null && progmon.isCanceled()) System.exit(0); DataInputStream dis = new DataInputStream(new ByteArrayInputStream(data)); int bytesSkipped = 0; while(bytesSkipped < offset) bytesSkipped += dis.skipBytes(offset-bytesSkipped); blockType = dis.readInt(); int skipped = dis.readInt(); //Skip 4 bytes forward outOffset = dis.readLong()*0x200;//(dis.readInt() & 0xffffffffL)*0x200; //unsigned int -> long //dis.readInt(); //Skip 4 bytes forward outSize = dis.readLong()*0x200;//(dis.readInt() & 0xffffffffL)*0x200; //unsigned int -> long inOffset = dis.readLong();// & 0xffffffffL; //unsigned int -> long //dis.readInt(); //Skip 4 bytes forward inSize = dis.readLong();//dis.readInt() & 0xffffffffL; //unsigned int -> long blocks.add(new DMGBlock(blockType, skipped, outOffset, outSize, inOffset, inSize)); if(lastByteReadInBlock == -1) lastByteReadInBlock = inOffset; lastByteReadInBlock += inSize; /* The lines below are a "hack" that I had to do to make dmgx work with certain dmg-files. I don't understand the issue at all, which is why this hack is here, but sometimes inOffset == 0 means that it is 0 relative to the previous partition's last inOffset. And sometimes it doesn't (meaning the actual position 0 in the dmg file). */ if(addInOffset) inOffset += lastInOffset; else if(inOffset == 0) { addInOffset = true; inOffset += lastInOffset; } outOffset += lastOutOffset; if(DEBUG) { println("outOffset=" + outOffset + " outSize=" + outSize + " inOffset=" + inOffset + " inSize=" + inSize + " lastOutOffset=" + lastOutOffset + " lastInOffset=" + lastInOffset /*+ " lastInOffs=" + lastInOffs + " lastOffs=" + lastOffs*/); } if(blockType == BT_ADC) { println(" " + blockCount + ". BT_ADC not supported."); if(!testOnly) System.exit(0); } else if(blockType == BT_ZLIB) { if(DEBUG) println(" " + blockCount + ". BT_ZLIB processing..."); if(!testOnly && isoRaf.getFilePointer() != outOffset) println(" " + blockCount + ". BT_ZLIB FP != outOffset (" + isoRaf.getFilePointer() + " != " + outOffset + ")"); dmgRaf.seek(/*lastOffs+*/inOffset); if(tmp.length < inSize) tmp = new byte[(int)inSize]; long totalBytesRead = 0; while(totalBytesRead < inSize) { totalBytesRead += dmgRaf.read(tmp, (int)totalBytesRead, Math.min((int)(inSize-totalBytesRead), tmp.length)); } long progressPercentage = dmgRaf.getFilePointer()*100/dmgRaf.length(); if(progressPercentage != previousPercentage) { reportProgress(progressPercentage); previousPercentage = progressPercentage; } Inflater inflater = new Inflater(); inflater.setInput(tmp, 0, (int)totalBytesRead); if(otmp.length < outSize) otmp = new byte[(int)outSize]; int bytesInflated = 0; while(true) { try { int counter = 0; while(bytesInflated < outSize && counter++ < 10) { int old = bytesInflated; bytesInflated += inflater.inflate(otmp, bytesInflated, (int)(outSize-bytesInflated)); if(old == bytesInflated) println("Nothing new! finished()=" + inflater.finished() + " needsInput()=" + inflater.needsInput() + " needsDictionary()=" + inflater.needsDictionary() + " getAdler()=" + inflater.getAdler() + " getBytesRead()=" + inflater.getBytesRead() + " getBytesWritten()=" + inflater.getBytesWritten() + " getRemaining()=" + inflater.getRemaining()); } //System.out.println(" Inflated " + bytesInflated + " bytes. Left in buffer: " + inflater.getRemaining() + " bytes inSize="+inSize+" outSize="+outSize); if(inflater.getRemaining() == 0) { //System.out.println(" done!"); break; } else { println(" " + blockCount + ". BT_ZLIB ERROR: otmp contents lost! (should not happen...)", " outSize=" + outSize + " inSize=" + inSize + " tmp.length=" + tmp.length + " otmp.length=" + otmp.length + " bytesInflated=" + bytesInflated + " inflater.getRemaining()=" + inflater.getRemaining());// if(bytesInflated == 0) throw new RuntimeException("WTF"); } } catch(DataFormatException dfe) { println(" " + blockCount + ". BT_ZLIB Could not decode..."); if(!DEBUG) { println("outOffset=" + outOffset + " outSize=" + outSize + " inOffset=" + inOffset + " inSize=" + inSize + " lastOutOffset=" + lastOutOffset + " lastInOffset=" + lastInOffset); } dfe.printStackTrace(); if(!testOnly) System.exit(0); else { println(" Testing mode, so continuing..."); //System.exit(0); errorsFound = true; break; } } } inflater.end(); if(!testOnly) isoRaf.write(otmp, 0, (int)outSize); //lastInOffs = inOffset+inSize; } else if(blockType == BT_BZIP2) { println(" " + blockCount + ". BT_BZIP2 not currently supported."); if(!testOnly) System.exit(0); } else if(blockType == BT_COPY) { if(DEBUG) println(" " + blockCount + ". BT_COPY processing..."); if(!testOnly && isoRaf.getFilePointer() != outOffset) println(" " + blockCount + ". BT_COPY FP != outOffset (" + isoRaf.getFilePointer() + " != " + outOffset + ")"); dmgRaf.seek(/*lastOffs+*/inOffset); int bytesRead = dmgRaf.read(tmp, 0, Math.min((int)inSize, tmp.length)); long totalBytesRead = bytesRead; while(bytesRead != -1) { long progressPercentage = dmgRaf.getFilePointer()*100/dmgRaf.length(); if(progressPercentage != previousPercentage) { reportProgress(progressPercentage); previousPercentage = progressPercentage; } if(!testOnly) isoRaf.write(tmp, 0, bytesRead); if(totalBytesRead >= inSize) break; bytesRead = dmgRaf.read(tmp, 0, Math.min((int)(inSize-totalBytesRead), tmp.length)); if(bytesRead > 0) totalBytesRead += bytesRead; } //lastInOffs = inOffset+inSize; } else if(blockType == BT_ZERO) { if(DEBUG) println(" " + blockCount + ". BT_ZERO processing..."); if(!testOnly && isoRaf.getFilePointer() != outOffset) println(" " + blockCount + ". BT_ZERO FP != outOffset (" + isoRaf.getFilePointer() + " != " + outOffset + ")"); long progressPercentage = dmgRaf.getFilePointer()*100/dmgRaf.length(); if(progressPercentage != previousPercentage) { reportProgress(progressPercentage); previousPercentage = progressPercentage; } long numberOfZeroBlocks = outSize/zeroblock.length; int numberOfRemainingBytes = (int)(outSize%zeroblock.length); for(int j = 0; j < numberOfZeroBlocks; ++j) { if(!testOnly) isoRaf.write(zeroblock); } if(!testOnly) isoRaf.write(zeroblock, 0, numberOfRemainingBytes); //lastInOffs = inOffset+inSize; } else if(blockType == BT_UNKNOWN) { /* I have no idea what this blocktype is... but it's common, and usually doesn't appear more than 2-3 times in a dmg. As long as its input and output sizes are 0, there's no reason to complain... is there? */ if(DEBUG) println(" " + blockCount + ". BT_UNKNOWN processing..."); if(!(inSize == 0 && outSize == 0)) { println(" " + blockCount + ". WARNING! Blocktype BT_UNKNOWN had non-zero sizes...", " inSize=" + inSize + ", outSize=" + outSize); //println(" The author of the program would be pleased if you contacted him about this."); // ...or would I? } } else if(blockType == BT_END) { if(DEBUG) println(" " + blockCount + ". BT_END processing..."); if(!testOnly && isoRaf.getFilePointer() != outOffset) println(" " + blockCount + ". BT_END FP != outOffset (" + isoRaf.getFilePointer() + " != " + outOffset + ")"); //lastOffs += lastInOffs; lastOutOffset = outOffset; lastInOffset += lastByteReadInBlock; } else { println(" " + blockCount + ". WARNING: previously unseen blocktype " + blockType + " [0x" + Integer.toHexString(blockType) + "]", " " + blockCount + ". outOffset=" + outOffset + " outSize=" + outSize + " inOffset=" + inOffset + " inSize=" + inSize); if(!testOnly && isoRaf.getFilePointer() != outOffset) println(" " + blockCount + ". unknown blocktype FP != outOffset (" + isoRaf.getFilePointer() + " != " + outOffset + ")"); } offset += 0x28; ++blockCount; } } } //printlnVerbose("Progress: 100% Done!"); reportProgress(100); String errors = errorsFound?"There were errors...":"No errors reported."; if(!graphical) { newline(); println(errors); printlnVerbose("Total extracted bytes: " + totalSize + " B"); } else { progmon.close(); JOptionPane.showMessageDialog(null, "Extraction complete! " + errors + "\n" + "Total extracted bytes: " + totalSize + " B", "Information", JOptionPane.INFORMATION_MESSAGE); System.exit(0); }// System.out.println("blocks.size()=" + blocks.size());// for(DMGBlock b : blocks)// System.out.println(" " + b.toString()); LinkedList<DMGBlock> merged = mergeBlocks(blocks);// System.out.println("merged.size()=" + merged.size());// for(DMGBlock b : merged)// System.out.println(" " + b.toString()); System.out.println("Extracting all the parts not containing block data from source file:"); int i = 1; DMGBlock previous = null; for(DMGBlock b : merged) { if(previous == null && b.inOffset > 0) { String filename = i++ + ".block"; System.out.print(" " + filename + "..."); FileOutputStream curFos = new FileOutputStream(new File(filename)); dmgRaf.seek(0); byte[] data = new byte[(int)(b.inOffset)]; dmgRaf.read(data); curFos.write(data); curFos.close(); } else if(previous != null) { String filename = i++ + ".block"; System.out.print(" " + filename + "..."); FileOutputStream curFos = new FileOutputStream(new File(filename)); dmgRaf.seek(previous.inOffset+previous.inSize); byte[] data = new byte[(int)(b.inOffset-(previous.inOffset+previous.inSize))]; dmgRaf.read(data); curFos.write(data); curFos.close(); } previous = b; } if(previous.inOffset+previous.inSize != dmgRaf.length()) { String filename = i++ + ".block"; System.out.print(" " + filename + "..."); FileOutputStream curFos = new FileOutputStream(new File(filename)); dmgRaf.seek(previous.inOffset+previous.inSize); byte[] data = new byte[(int)(dmgRaf.length()-(previous.inOffset+previous.inSize))]; dmgRaf.read(data); curFos.write(data); curFos.close(); } dmgRaf.close(); System.out.println("done!"); }
long previousPercentage = -1;
public static void notmain(String[] args) throws Exception { System.setProperty("swing.aatext", "true"); //Antialiased text try { javax.swing.UIManager.setLookAndFeel(javax.swing.UIManager.getSystemLookAndFeelClassName()); } catch(Exception e) {} if(DEBUG) verbose = true; parseArgs(args); printlnVerbose("Processing: " + dmgFile); RandomAccessFile dmgRaf = new RandomAccessFile(dmgFile, "r"); RandomAccessFile isoRaf = null; boolean testOnly = false; if(isoFile != null) { isoRaf = new RandomAccessFile(isoFile, "rw"); isoRaf.setLength(0); printlnVerbose("Extracting to: " + isoFile); } else { testOnly = true; printlnVerbose("Simulating extraction..."); } dmgRaf.seek(dmgRaf.length()-PLIST_ADDRESS_1); long plistBegin1 = dmgRaf.readLong(); long plistEnd = dmgRaf.readLong(); dmgRaf.seek(dmgRaf.length()-PLIST_ADDRESS_2); long plistBegin2 = dmgRaf.readLong(); long plistSize = dmgRaf.readLong(); if(DEBUG) { println("Read addresses:", " " + plistBegin1, " " + plistBegin2); } if(plistBegin1 != plistBegin2) { println("Addresses not equal! Assumption broken... =/", plistBegin1 + " != " + plistBegin2); System.exit(0); } if(plistSize != (plistEnd-plistBegin1)) { println("plistSize field does not match plistEnd marker!", "plistSize=" + plistSize + " plistBegin1=" + plistBegin1 + " plistEnd=" + plistEnd + " plistEnd-plistBegin1=" + (plistEnd-plistBegin1)); } printlnVerbose("Jumping to address..."); dmgRaf.seek(plistBegin1); byte[] buffer = new byte[(int)plistSize]; dmgRaf.read(buffer); InputStream is = new ByteArrayInputStream(buffer); NodeBuilder handler = new NodeBuilder(); SAXParser saxParser = SAXParserFactory.newInstance().newSAXParser(); try {// System.out.println("validation: " + saxParser.getProperty("validation"));// System.out.println("external-general-entities: " + saxParser.getProperty("external-general-entities"));// System.out.println("external-parameter-entities: " + saxParser.getProperty("external-parameter-entities"));// System.out.println("is-standalone: " + saxParser.getProperty("is-standalone"));// System.out.println("lexical-handler: " + saxParser.getProperty("lexical-handler"));// System.out.println("parameter-entities: " + saxParser.getProperty("parameter-entities"));// System.out.println("namespaces: " + saxParser.getProperty("namespaces"));// System.out.println("namespace-prefixes: " + saxParser.getProperty("namespace-prefixes"));// System.out.println(": " + saxParser.getProperty(""));// System.out.println(": " + saxParser.getProperty(""));// System.out.println(": " + saxParser.getProperty(""));// System.out.println(": " + saxParser.getProperty(""));// System.out.println("" + saxParser.getProperty(""));// System.out.println("" + saxParser.getProperty(""));// System.out.println("" + saxParser.getProperty(""));// System.out.println("" + saxParser.getProperty(""));// System.out.println("" + saxParser.getProperty(""));// System.out.println("" + saxParser.getProperty(""));// System.out.println("" + saxParser.getProperty(""));// System.out.println("" + saxParser.getProperty("")); System.out.println("isValidating: " + saxParser.isValidating()); saxParser.parse(is, handler); } catch(SAXException se) { se.printStackTrace(); System.err.println("Could not read the partition list... exiting."); System.exit(1); } XMLNode[] rootNodes = handler.getRoots(); if(rootNodes.length != 1) { println("Could not parse DMG-file!"); System.exit(0); } /* Ok, now we have a tree built from the XML-document. Let's walk to the right place. */ /* cd plist cd dict cdkey resource-fork (type:dict) cdkey blkx (type:array) */ XMLNode current; XMLElement[] children; boolean keyFound; current = rootNodes[0]; //We are at plist... probably (there should be only one root node) current = current.cd("dict"); current = current.cdkey("resource-fork"); current = current.cdkey("blkx"); printlnVerbose("Found " + current.getChildren().length + " partitions:"); byte[] tmp = new byte[0x40000]; byte[] otmp = new byte[0x40000]; byte[] zeroblock = new byte[4096]; /* I think java always zeroes its arrays on creation... but let's play safe. */ for(int y = 0; y < zeroblock.length; ++y) zeroblock[y] = 0; LinkedList<DMGBlock> blocks = new LinkedList<DMGBlock>(); //long lastOffs = 0; long lastOutOffset = 0; long lastInOffset = 0; long totalSize = 0; boolean errorsFound = false; reportProgress(0); for(XMLElement xe : current.getChildren()) { if(progmon != null && progmon.isCanceled()) System.exit(0); if(xe instanceof XMLNode) { XMLNode xn = (XMLNode)xe; byte[] data = Base64.decode(xn.getKeyValue("Data")); long partitionSize = calculatePartitionSize(data); totalSize += partitionSize; printlnVerbose(" " + xn.getKeyValue("Name")); printlnVerbose(" ID: " + xn.getKeyValue("ID")); printlnVerbose(" Attributes: " + xn.getKeyValue("Attributes")); printlnVerbose(" Partition map data length: " + data.length + " bytes"); printlnVerbose(" Partition size: " + partitionSize + " bytes"); if(verbose) { printlnVerbose(" Dumping blkx..."); FileOutputStream fos = new FileOutputStream(xn.getKeyValue("ID") + ".blkx"); fos.write(data); fos.close(); } if(DEBUG) { File dumpFile = new File("data " + xn.getKeyValue("ID") + ".bin"); println(" Dumping partition map to file: " + dumpFile); FileOutputStream dump = new FileOutputStream(dumpFile); dump.write(data); dump.close(); } int offset = 0xCC; int blockType = 0; /* Offset of the input data for the current block in the input file */ long inOffset = 0; /* Size of the input data for the current block */ long inSize = 0; /* Offset of the output data for the current block in the output file */ long outOffset = 0; /* Size of the output data (possibly larger than inSize because of decompression, zero expansion...) */ long outSize = 0; long lastByteReadInBlock = -1; boolean addInOffset = false; //, lastInOffs = 0; int blockCount = 0; long previousPercentage = -1; while(blockType != BT_END) { if(progmon != null && progmon.isCanceled()) System.exit(0); DataInputStream dis = new DataInputStream(new ByteArrayInputStream(data)); int bytesSkipped = 0; while(bytesSkipped < offset) bytesSkipped += dis.skipBytes(offset-bytesSkipped); blockType = dis.readInt(); int skipped = dis.readInt(); //Skip 4 bytes forward outOffset = dis.readLong()*0x200;//(dis.readInt() & 0xffffffffL)*0x200; //unsigned int -> long //dis.readInt(); //Skip 4 bytes forward outSize = dis.readLong()*0x200;//(dis.readInt() & 0xffffffffL)*0x200; //unsigned int -> long inOffset = dis.readLong();// & 0xffffffffL; //unsigned int -> long //dis.readInt(); //Skip 4 bytes forward inSize = dis.readLong();//dis.readInt() & 0xffffffffL; //unsigned int -> long blocks.add(new DMGBlock(blockType, skipped, outOffset, outSize, inOffset, inSize)); if(lastByteReadInBlock == -1) lastByteReadInBlock = inOffset; lastByteReadInBlock += inSize; /* The lines below are a "hack" that I had to do to make dmgx work with certain dmg-files. I don't understand the issue at all, which is why this hack is here, but sometimes inOffset == 0 means that it is 0 relative to the previous partition's last inOffset. And sometimes it doesn't (meaning the actual position 0 in the dmg file). */ if(addInOffset) inOffset += lastInOffset; else if(inOffset == 0) { addInOffset = true; inOffset += lastInOffset; } outOffset += lastOutOffset; if(DEBUG) { println("outOffset=" + outOffset + " outSize=" + outSize + " inOffset=" + inOffset + " inSize=" + inSize + " lastOutOffset=" + lastOutOffset + " lastInOffset=" + lastInOffset /*+ " lastInOffs=" + lastInOffs + " lastOffs=" + lastOffs*/); } if(blockType == BT_ADC) { println(" " + blockCount + ". BT_ADC not supported."); if(!testOnly) System.exit(0); } else if(blockType == BT_ZLIB) { if(DEBUG) println(" " + blockCount + ". BT_ZLIB processing..."); if(!testOnly && isoRaf.getFilePointer() != outOffset) println(" " + blockCount + ". BT_ZLIB FP != outOffset (" + isoRaf.getFilePointer() + " != " + outOffset + ")"); dmgRaf.seek(/*lastOffs+*/inOffset); if(tmp.length < inSize) tmp = new byte[(int)inSize]; long totalBytesRead = 0; while(totalBytesRead < inSize) { totalBytesRead += dmgRaf.read(tmp, (int)totalBytesRead, Math.min((int)(inSize-totalBytesRead), tmp.length)); } long progressPercentage = dmgRaf.getFilePointer()*100/dmgRaf.length(); if(progressPercentage != previousPercentage) { reportProgress(progressPercentage); previousPercentage = progressPercentage; } Inflater inflater = new Inflater(); inflater.setInput(tmp, 0, (int)totalBytesRead); if(otmp.length < outSize) otmp = new byte[(int)outSize]; int bytesInflated = 0; while(true) { try { int counter = 0; while(bytesInflated < outSize && counter++ < 10) { int old = bytesInflated; bytesInflated += inflater.inflate(otmp, bytesInflated, (int)(outSize-bytesInflated)); if(old == bytesInflated) println("Nothing new! finished()=" + inflater.finished() + " needsInput()=" + inflater.needsInput() + " needsDictionary()=" + inflater.needsDictionary() + " getAdler()=" + inflater.getAdler() + " getBytesRead()=" + inflater.getBytesRead() + " getBytesWritten()=" + inflater.getBytesWritten() + " getRemaining()=" + inflater.getRemaining()); } //System.out.println(" Inflated " + bytesInflated + " bytes. Left in buffer: " + inflater.getRemaining() + " bytes inSize="+inSize+" outSize="+outSize); if(inflater.getRemaining() == 0) { //System.out.println(" done!"); break; } else { println(" " + blockCount + ". BT_ZLIB ERROR: otmp contents lost! (should not happen...)", " outSize=" + outSize + " inSize=" + inSize + " tmp.length=" + tmp.length + " otmp.length=" + otmp.length + " bytesInflated=" + bytesInflated + " inflater.getRemaining()=" + inflater.getRemaining());// if(bytesInflated == 0) throw new RuntimeException("WTF"); } } catch(DataFormatException dfe) { println(" " + blockCount + ". BT_ZLIB Could not decode..."); if(!DEBUG) { println("outOffset=" + outOffset + " outSize=" + outSize + " inOffset=" + inOffset + " inSize=" + inSize + " lastOutOffset=" + lastOutOffset + " lastInOffset=" + lastInOffset); } dfe.printStackTrace(); if(!testOnly) System.exit(0); else { println(" Testing mode, so continuing..."); //System.exit(0); errorsFound = true; break; } } } inflater.end(); if(!testOnly) isoRaf.write(otmp, 0, (int)outSize); //lastInOffs = inOffset+inSize; } else if(blockType == BT_BZIP2) { println(" " + blockCount + ". BT_BZIP2 not currently supported."); if(!testOnly) System.exit(0); } else if(blockType == BT_COPY) { if(DEBUG) println(" " + blockCount + ". BT_COPY processing..."); if(!testOnly && isoRaf.getFilePointer() != outOffset) println(" " + blockCount + ". BT_COPY FP != outOffset (" + isoRaf.getFilePointer() + " != " + outOffset + ")"); dmgRaf.seek(/*lastOffs+*/inOffset); int bytesRead = dmgRaf.read(tmp, 0, Math.min((int)inSize, tmp.length)); long totalBytesRead = bytesRead; while(bytesRead != -1) { long progressPercentage = dmgRaf.getFilePointer()*100/dmgRaf.length(); if(progressPercentage != previousPercentage) { reportProgress(progressPercentage); previousPercentage = progressPercentage; } if(!testOnly) isoRaf.write(tmp, 0, bytesRead); if(totalBytesRead >= inSize) break; bytesRead = dmgRaf.read(tmp, 0, Math.min((int)(inSize-totalBytesRead), tmp.length)); if(bytesRead > 0) totalBytesRead += bytesRead; } //lastInOffs = inOffset+inSize; } else if(blockType == BT_ZERO) { if(DEBUG) println(" " + blockCount + ". BT_ZERO processing..."); if(!testOnly && isoRaf.getFilePointer() != outOffset) println(" " + blockCount + ". BT_ZERO FP != outOffset (" + isoRaf.getFilePointer() + " != " + outOffset + ")"); long progressPercentage = dmgRaf.getFilePointer()*100/dmgRaf.length(); if(progressPercentage != previousPercentage) { reportProgress(progressPercentage); previousPercentage = progressPercentage; } long numberOfZeroBlocks = outSize/zeroblock.length; int numberOfRemainingBytes = (int)(outSize%zeroblock.length); for(int j = 0; j < numberOfZeroBlocks; ++j) { if(!testOnly) isoRaf.write(zeroblock); } if(!testOnly) isoRaf.write(zeroblock, 0, numberOfRemainingBytes); //lastInOffs = inOffset+inSize; } else if(blockType == BT_UNKNOWN) { /* I have no idea what this blocktype is... but it's common, and usually doesn't appear more than 2-3 times in a dmg. As long as its input and output sizes are 0, there's no reason to complain... is there? */ if(DEBUG) println(" " + blockCount + ". BT_UNKNOWN processing..."); if(!(inSize == 0 && outSize == 0)) { println(" " + blockCount + ". WARNING! Blocktype BT_UNKNOWN had non-zero sizes...", " inSize=" + inSize + ", outSize=" + outSize); //println(" The author of the program would be pleased if you contacted him about this."); // ...or would I? } } else if(blockType == BT_END) { if(DEBUG) println(" " + blockCount + ". BT_END processing..."); if(!testOnly && isoRaf.getFilePointer() != outOffset) println(" " + blockCount + ". BT_END FP != outOffset (" + isoRaf.getFilePointer() + " != " + outOffset + ")"); //lastOffs += lastInOffs; lastOutOffset = outOffset; lastInOffset += lastByteReadInBlock; } else { println(" " + blockCount + ". WARNING: previously unseen blocktype " + blockType + " [0x" + Integer.toHexString(blockType) + "]", " " + blockCount + ". outOffset=" + outOffset + " outSize=" + outSize + " inOffset=" + inOffset + " inSize=" + inSize); if(!testOnly && isoRaf.getFilePointer() != outOffset) println(" " + blockCount + ". unknown blocktype FP != outOffset (" + isoRaf.getFilePointer() + " != " + outOffset + ")"); } offset += 0x28; ++blockCount; } } } //printlnVerbose("Progress: 100% Done!"); reportProgress(100); String errors = errorsFound?"There were errors...":"No errors reported."; if(!graphical) { newline(); println(errors); printlnVerbose("Total extracted bytes: " + totalSize + " B"); } else { progmon.close(); JOptionPane.showMessageDialog(null, "Extraction complete! " + errors + "\n" + "Total extracted bytes: " + totalSize + " B", "Information", JOptionPane.INFORMATION_MESSAGE); System.exit(0); }// System.out.println("blocks.size()=" + blocks.size());// for(DMGBlock b : blocks)// System.out.println(" " + b.toString()); LinkedList<DMGBlock> merged = mergeBlocks(blocks);// System.out.println("merged.size()=" + merged.size());// for(DMGBlock b : merged)// System.out.println(" " + b.toString()); System.out.println("Extracting all the parts not containing block data from source file:"); int i = 1; DMGBlock previous = null; for(DMGBlock b : merged) { if(previous == null && b.inOffset > 0) { String filename = i++ + ".block"; System.out.print(" " + filename + "..."); FileOutputStream curFos = new FileOutputStream(new File(filename)); dmgRaf.seek(0); byte[] data = new byte[(int)(b.inOffset)]; dmgRaf.read(data); curFos.write(data); curFos.close(); } else if(previous != null) { String filename = i++ + ".block"; System.out.print(" " + filename + "..."); FileOutputStream curFos = new FileOutputStream(new File(filename)); dmgRaf.seek(previous.inOffset+previous.inSize); byte[] data = new byte[(int)(b.inOffset-(previous.inOffset+previous.inSize))]; dmgRaf.read(data); curFos.write(data); curFos.close(); } previous = b; } if(previous.inOffset+previous.inSize != dmgRaf.length()) { String filename = i++ + ".block"; System.out.print(" " + filename + "..."); FileOutputStream curFos = new FileOutputStream(new File(filename)); dmgRaf.seek(previous.inOffset+previous.inSize); byte[] data = new byte[(int)(dmgRaf.length()-(previous.inOffset+previous.inSize))]; dmgRaf.read(data); curFos.write(data); curFos.close(); } dmgRaf.close(); System.out.println("done!"); }
blocks.add(new DMGBlock(blockType, skipped, outOffset, outSize, inOffset, inSize));
DMGBlock currentBlock = new DMGBlock(blockType, skipped, outOffset, outSize, inOffset, inSize); blocks.add(currentBlock);
public static void notmain(String[] args) throws Exception { System.setProperty("swing.aatext", "true"); //Antialiased text try { javax.swing.UIManager.setLookAndFeel(javax.swing.UIManager.getSystemLookAndFeelClassName()); } catch(Exception e) {} if(DEBUG) verbose = true; parseArgs(args); printlnVerbose("Processing: " + dmgFile); RandomAccessFile dmgRaf = new RandomAccessFile(dmgFile, "r"); RandomAccessFile isoRaf = null; boolean testOnly = false; if(isoFile != null) { isoRaf = new RandomAccessFile(isoFile, "rw"); isoRaf.setLength(0); printlnVerbose("Extracting to: " + isoFile); } else { testOnly = true; printlnVerbose("Simulating extraction..."); } dmgRaf.seek(dmgRaf.length()-PLIST_ADDRESS_1); long plistBegin1 = dmgRaf.readLong(); long plistEnd = dmgRaf.readLong(); dmgRaf.seek(dmgRaf.length()-PLIST_ADDRESS_2); long plistBegin2 = dmgRaf.readLong(); long plistSize = dmgRaf.readLong(); if(DEBUG) { println("Read addresses:", " " + plistBegin1, " " + plistBegin2); } if(plistBegin1 != plistBegin2) { println("Addresses not equal! Assumption broken... =/", plistBegin1 + " != " + plistBegin2); System.exit(0); } if(plistSize != (plistEnd-plistBegin1)) { println("plistSize field does not match plistEnd marker!", "plistSize=" + plistSize + " plistBegin1=" + plistBegin1 + " plistEnd=" + plistEnd + " plistEnd-plistBegin1=" + (plistEnd-plistBegin1)); } printlnVerbose("Jumping to address..."); dmgRaf.seek(plistBegin1); byte[] buffer = new byte[(int)plistSize]; dmgRaf.read(buffer); InputStream is = new ByteArrayInputStream(buffer); NodeBuilder handler = new NodeBuilder(); SAXParser saxParser = SAXParserFactory.newInstance().newSAXParser(); try {// System.out.println("validation: " + saxParser.getProperty("validation"));// System.out.println("external-general-entities: " + saxParser.getProperty("external-general-entities"));// System.out.println("external-parameter-entities: " + saxParser.getProperty("external-parameter-entities"));// System.out.println("is-standalone: " + saxParser.getProperty("is-standalone"));// System.out.println("lexical-handler: " + saxParser.getProperty("lexical-handler"));// System.out.println("parameter-entities: " + saxParser.getProperty("parameter-entities"));// System.out.println("namespaces: " + saxParser.getProperty("namespaces"));// System.out.println("namespace-prefixes: " + saxParser.getProperty("namespace-prefixes"));// System.out.println(": " + saxParser.getProperty(""));// System.out.println(": " + saxParser.getProperty(""));// System.out.println(": " + saxParser.getProperty(""));// System.out.println(": " + saxParser.getProperty(""));// System.out.println("" + saxParser.getProperty(""));// System.out.println("" + saxParser.getProperty(""));// System.out.println("" + saxParser.getProperty(""));// System.out.println("" + saxParser.getProperty(""));// System.out.println("" + saxParser.getProperty(""));// System.out.println("" + saxParser.getProperty(""));// System.out.println("" + saxParser.getProperty(""));// System.out.println("" + saxParser.getProperty("")); System.out.println("isValidating: " + saxParser.isValidating()); saxParser.parse(is, handler); } catch(SAXException se) { se.printStackTrace(); System.err.println("Could not read the partition list... exiting."); System.exit(1); } XMLNode[] rootNodes = handler.getRoots(); if(rootNodes.length != 1) { println("Could not parse DMG-file!"); System.exit(0); } /* Ok, now we have a tree built from the XML-document. Let's walk to the right place. */ /* cd plist cd dict cdkey resource-fork (type:dict) cdkey blkx (type:array) */ XMLNode current; XMLElement[] children; boolean keyFound; current = rootNodes[0]; //We are at plist... probably (there should be only one root node) current = current.cd("dict"); current = current.cdkey("resource-fork"); current = current.cdkey("blkx"); printlnVerbose("Found " + current.getChildren().length + " partitions:"); byte[] tmp = new byte[0x40000]; byte[] otmp = new byte[0x40000]; byte[] zeroblock = new byte[4096]; /* I think java always zeroes its arrays on creation... but let's play safe. */ for(int y = 0; y < zeroblock.length; ++y) zeroblock[y] = 0; LinkedList<DMGBlock> blocks = new LinkedList<DMGBlock>(); //long lastOffs = 0; long lastOutOffset = 0; long lastInOffset = 0; long totalSize = 0; boolean errorsFound = false; reportProgress(0); for(XMLElement xe : current.getChildren()) { if(progmon != null && progmon.isCanceled()) System.exit(0); if(xe instanceof XMLNode) { XMLNode xn = (XMLNode)xe; byte[] data = Base64.decode(xn.getKeyValue("Data")); long partitionSize = calculatePartitionSize(data); totalSize += partitionSize; printlnVerbose(" " + xn.getKeyValue("Name")); printlnVerbose(" ID: " + xn.getKeyValue("ID")); printlnVerbose(" Attributes: " + xn.getKeyValue("Attributes")); printlnVerbose(" Partition map data length: " + data.length + " bytes"); printlnVerbose(" Partition size: " + partitionSize + " bytes"); if(verbose) { printlnVerbose(" Dumping blkx..."); FileOutputStream fos = new FileOutputStream(xn.getKeyValue("ID") + ".blkx"); fos.write(data); fos.close(); } if(DEBUG) { File dumpFile = new File("data " + xn.getKeyValue("ID") + ".bin"); println(" Dumping partition map to file: " + dumpFile); FileOutputStream dump = new FileOutputStream(dumpFile); dump.write(data); dump.close(); } int offset = 0xCC; int blockType = 0; /* Offset of the input data for the current block in the input file */ long inOffset = 0; /* Size of the input data for the current block */ long inSize = 0; /* Offset of the output data for the current block in the output file */ long outOffset = 0; /* Size of the output data (possibly larger than inSize because of decompression, zero expansion...) */ long outSize = 0; long lastByteReadInBlock = -1; boolean addInOffset = false; //, lastInOffs = 0; int blockCount = 0; long previousPercentage = -1; while(blockType != BT_END) { if(progmon != null && progmon.isCanceled()) System.exit(0); DataInputStream dis = new DataInputStream(new ByteArrayInputStream(data)); int bytesSkipped = 0; while(bytesSkipped < offset) bytesSkipped += dis.skipBytes(offset-bytesSkipped); blockType = dis.readInt(); int skipped = dis.readInt(); //Skip 4 bytes forward outOffset = dis.readLong()*0x200;//(dis.readInt() & 0xffffffffL)*0x200; //unsigned int -> long //dis.readInt(); //Skip 4 bytes forward outSize = dis.readLong()*0x200;//(dis.readInt() & 0xffffffffL)*0x200; //unsigned int -> long inOffset = dis.readLong();// & 0xffffffffL; //unsigned int -> long //dis.readInt(); //Skip 4 bytes forward inSize = dis.readLong();//dis.readInt() & 0xffffffffL; //unsigned int -> long blocks.add(new DMGBlock(blockType, skipped, outOffset, outSize, inOffset, inSize)); if(lastByteReadInBlock == -1) lastByteReadInBlock = inOffset; lastByteReadInBlock += inSize; /* The lines below are a "hack" that I had to do to make dmgx work with certain dmg-files. I don't understand the issue at all, which is why this hack is here, but sometimes inOffset == 0 means that it is 0 relative to the previous partition's last inOffset. And sometimes it doesn't (meaning the actual position 0 in the dmg file). */ if(addInOffset) inOffset += lastInOffset; else if(inOffset == 0) { addInOffset = true; inOffset += lastInOffset; } outOffset += lastOutOffset; if(DEBUG) { println("outOffset=" + outOffset + " outSize=" + outSize + " inOffset=" + inOffset + " inSize=" + inSize + " lastOutOffset=" + lastOutOffset + " lastInOffset=" + lastInOffset /*+ " lastInOffs=" + lastInOffs + " lastOffs=" + lastOffs*/); } if(blockType == BT_ADC) { println(" " + blockCount + ". BT_ADC not supported."); if(!testOnly) System.exit(0); } else if(blockType == BT_ZLIB) { if(DEBUG) println(" " + blockCount + ". BT_ZLIB processing..."); if(!testOnly && isoRaf.getFilePointer() != outOffset) println(" " + blockCount + ". BT_ZLIB FP != outOffset (" + isoRaf.getFilePointer() + " != " + outOffset + ")"); dmgRaf.seek(/*lastOffs+*/inOffset); if(tmp.length < inSize) tmp = new byte[(int)inSize]; long totalBytesRead = 0; while(totalBytesRead < inSize) { totalBytesRead += dmgRaf.read(tmp, (int)totalBytesRead, Math.min((int)(inSize-totalBytesRead), tmp.length)); } long progressPercentage = dmgRaf.getFilePointer()*100/dmgRaf.length(); if(progressPercentage != previousPercentage) { reportProgress(progressPercentage); previousPercentage = progressPercentage; } Inflater inflater = new Inflater(); inflater.setInput(tmp, 0, (int)totalBytesRead); if(otmp.length < outSize) otmp = new byte[(int)outSize]; int bytesInflated = 0; while(true) { try { int counter = 0; while(bytesInflated < outSize && counter++ < 10) { int old = bytesInflated; bytesInflated += inflater.inflate(otmp, bytesInflated, (int)(outSize-bytesInflated)); if(old == bytesInflated) println("Nothing new! finished()=" + inflater.finished() + " needsInput()=" + inflater.needsInput() + " needsDictionary()=" + inflater.needsDictionary() + " getAdler()=" + inflater.getAdler() + " getBytesRead()=" + inflater.getBytesRead() + " getBytesWritten()=" + inflater.getBytesWritten() + " getRemaining()=" + inflater.getRemaining()); } //System.out.println(" Inflated " + bytesInflated + " bytes. Left in buffer: " + inflater.getRemaining() + " bytes inSize="+inSize+" outSize="+outSize); if(inflater.getRemaining() == 0) { //System.out.println(" done!"); break; } else { println(" " + blockCount + ". BT_ZLIB ERROR: otmp contents lost! (should not happen...)", " outSize=" + outSize + " inSize=" + inSize + " tmp.length=" + tmp.length + " otmp.length=" + otmp.length + " bytesInflated=" + bytesInflated + " inflater.getRemaining()=" + inflater.getRemaining());// if(bytesInflated == 0) throw new RuntimeException("WTF"); } } catch(DataFormatException dfe) { println(" " + blockCount + ". BT_ZLIB Could not decode..."); if(!DEBUG) { println("outOffset=" + outOffset + " outSize=" + outSize + " inOffset=" + inOffset + " inSize=" + inSize + " lastOutOffset=" + lastOutOffset + " lastInOffset=" + lastInOffset); } dfe.printStackTrace(); if(!testOnly) System.exit(0); else { println(" Testing mode, so continuing..."); //System.exit(0); errorsFound = true; break; } } } inflater.end(); if(!testOnly) isoRaf.write(otmp, 0, (int)outSize); //lastInOffs = inOffset+inSize; } else if(blockType == BT_BZIP2) { println(" " + blockCount + ". BT_BZIP2 not currently supported."); if(!testOnly) System.exit(0); } else if(blockType == BT_COPY) { if(DEBUG) println(" " + blockCount + ". BT_COPY processing..."); if(!testOnly && isoRaf.getFilePointer() != outOffset) println(" " + blockCount + ". BT_COPY FP != outOffset (" + isoRaf.getFilePointer() + " != " + outOffset + ")"); dmgRaf.seek(/*lastOffs+*/inOffset); int bytesRead = dmgRaf.read(tmp, 0, Math.min((int)inSize, tmp.length)); long totalBytesRead = bytesRead; while(bytesRead != -1) { long progressPercentage = dmgRaf.getFilePointer()*100/dmgRaf.length(); if(progressPercentage != previousPercentage) { reportProgress(progressPercentage); previousPercentage = progressPercentage; } if(!testOnly) isoRaf.write(tmp, 0, bytesRead); if(totalBytesRead >= inSize) break; bytesRead = dmgRaf.read(tmp, 0, Math.min((int)(inSize-totalBytesRead), tmp.length)); if(bytesRead > 0) totalBytesRead += bytesRead; } //lastInOffs = inOffset+inSize; } else if(blockType == BT_ZERO) { if(DEBUG) println(" " + blockCount + ". BT_ZERO processing..."); if(!testOnly && isoRaf.getFilePointer() != outOffset) println(" " + blockCount + ". BT_ZERO FP != outOffset (" + isoRaf.getFilePointer() + " != " + outOffset + ")"); long progressPercentage = dmgRaf.getFilePointer()*100/dmgRaf.length(); if(progressPercentage != previousPercentage) { reportProgress(progressPercentage); previousPercentage = progressPercentage; } long numberOfZeroBlocks = outSize/zeroblock.length; int numberOfRemainingBytes = (int)(outSize%zeroblock.length); for(int j = 0; j < numberOfZeroBlocks; ++j) { if(!testOnly) isoRaf.write(zeroblock); } if(!testOnly) isoRaf.write(zeroblock, 0, numberOfRemainingBytes); //lastInOffs = inOffset+inSize; } else if(blockType == BT_UNKNOWN) { /* I have no idea what this blocktype is... but it's common, and usually doesn't appear more than 2-3 times in a dmg. As long as its input and output sizes are 0, there's no reason to complain... is there? */ if(DEBUG) println(" " + blockCount + ". BT_UNKNOWN processing..."); if(!(inSize == 0 && outSize == 0)) { println(" " + blockCount + ". WARNING! Blocktype BT_UNKNOWN had non-zero sizes...", " inSize=" + inSize + ", outSize=" + outSize); //println(" The author of the program would be pleased if you contacted him about this."); // ...or would I? } } else if(blockType == BT_END) { if(DEBUG) println(" " + blockCount + ". BT_END processing..."); if(!testOnly && isoRaf.getFilePointer() != outOffset) println(" " + blockCount + ". BT_END FP != outOffset (" + isoRaf.getFilePointer() + " != " + outOffset + ")"); //lastOffs += lastInOffs; lastOutOffset = outOffset; lastInOffset += lastByteReadInBlock; } else { println(" " + blockCount + ". WARNING: previously unseen blocktype " + blockType + " [0x" + Integer.toHexString(blockType) + "]", " " + blockCount + ". outOffset=" + outOffset + " outSize=" + outSize + " inOffset=" + inOffset + " inSize=" + inSize); if(!testOnly && isoRaf.getFilePointer() != outOffset) println(" " + blockCount + ". unknown blocktype FP != outOffset (" + isoRaf.getFilePointer() + " != " + outOffset + ")"); } offset += 0x28; ++blockCount; } } } //printlnVerbose("Progress: 100% Done!"); reportProgress(100); String errors = errorsFound?"There were errors...":"No errors reported."; if(!graphical) { newline(); println(errors); printlnVerbose("Total extracted bytes: " + totalSize + " B"); } else { progmon.close(); JOptionPane.showMessageDialog(null, "Extraction complete! " + errors + "\n" + "Total extracted bytes: " + totalSize + " B", "Information", JOptionPane.INFORMATION_MESSAGE); System.exit(0); }// System.out.println("blocks.size()=" + blocks.size());// for(DMGBlock b : blocks)// System.out.println(" " + b.toString()); LinkedList<DMGBlock> merged = mergeBlocks(blocks);// System.out.println("merged.size()=" + merged.size());// for(DMGBlock b : merged)// System.out.println(" " + b.toString()); System.out.println("Extracting all the parts not containing block data from source file:"); int i = 1; DMGBlock previous = null; for(DMGBlock b : merged) { if(previous == null && b.inOffset > 0) { String filename = i++ + ".block"; System.out.print(" " + filename + "..."); FileOutputStream curFos = new FileOutputStream(new File(filename)); dmgRaf.seek(0); byte[] data = new byte[(int)(b.inOffset)]; dmgRaf.read(data); curFos.write(data); curFos.close(); } else if(previous != null) { String filename = i++ + ".block"; System.out.print(" " + filename + "..."); FileOutputStream curFos = new FileOutputStream(new File(filename)); dmgRaf.seek(previous.inOffset+previous.inSize); byte[] data = new byte[(int)(b.inOffset-(previous.inOffset+previous.inSize))]; dmgRaf.read(data); curFos.write(data); curFos.close(); } previous = b; } if(previous.inOffset+previous.inSize != dmgRaf.length()) { String filename = i++ + ".block"; System.out.print(" " + filename + "..."); FileOutputStream curFos = new FileOutputStream(new File(filename)); dmgRaf.seek(previous.inOffset+previous.inSize); byte[] data = new byte[(int)(dmgRaf.length()-(previous.inOffset+previous.inSize))]; dmgRaf.read(data); curFos.write(data); curFos.close(); } dmgRaf.close(); System.out.println("done!"); }
dmgRaf.seek(inOffset); if(tmp.length < inSize) tmp = new byte[(int)inSize]; long totalBytesRead = 0; while(totalBytesRead < inSize) { totalBytesRead += dmgRaf.read(tmp, (int)totalBytesRead, Math.min((int)(inSize-totalBytesRead), tmp.length)); } long progressPercentage = dmgRaf.getFilePointer()*100/dmgRaf.length(); if(progressPercentage != previousPercentage) { reportProgress(progressPercentage); previousPercentage = progressPercentage; } Inflater inflater = new Inflater(); inflater.setInput(tmp, 0, (int)totalBytesRead); if(otmp.length < outSize) otmp = new byte[(int)outSize]; int bytesInflated = 0; while(true) {
if(true) {
public static void notmain(String[] args) throws Exception { System.setProperty("swing.aatext", "true"); //Antialiased text try { javax.swing.UIManager.setLookAndFeel(javax.swing.UIManager.getSystemLookAndFeelClassName()); } catch(Exception e) {} if(DEBUG) verbose = true; parseArgs(args); printlnVerbose("Processing: " + dmgFile); RandomAccessFile dmgRaf = new RandomAccessFile(dmgFile, "r"); RandomAccessFile isoRaf = null; boolean testOnly = false; if(isoFile != null) { isoRaf = new RandomAccessFile(isoFile, "rw"); isoRaf.setLength(0); printlnVerbose("Extracting to: " + isoFile); } else { testOnly = true; printlnVerbose("Simulating extraction..."); } dmgRaf.seek(dmgRaf.length()-PLIST_ADDRESS_1); long plistBegin1 = dmgRaf.readLong(); long plistEnd = dmgRaf.readLong(); dmgRaf.seek(dmgRaf.length()-PLIST_ADDRESS_2); long plistBegin2 = dmgRaf.readLong(); long plistSize = dmgRaf.readLong(); if(DEBUG) { println("Read addresses:", " " + plistBegin1, " " + plistBegin2); } if(plistBegin1 != plistBegin2) { println("Addresses not equal! Assumption broken... =/", plistBegin1 + " != " + plistBegin2); System.exit(0); } if(plistSize != (plistEnd-plistBegin1)) { println("plistSize field does not match plistEnd marker!", "plistSize=" + plistSize + " plistBegin1=" + plistBegin1 + " plistEnd=" + plistEnd + " plistEnd-plistBegin1=" + (plistEnd-plistBegin1)); } printlnVerbose("Jumping to address..."); dmgRaf.seek(plistBegin1); byte[] buffer = new byte[(int)plistSize]; dmgRaf.read(buffer); InputStream is = new ByteArrayInputStream(buffer); NodeBuilder handler = new NodeBuilder(); SAXParser saxParser = SAXParserFactory.newInstance().newSAXParser(); try {// System.out.println("validation: " + saxParser.getProperty("validation"));// System.out.println("external-general-entities: " + saxParser.getProperty("external-general-entities"));// System.out.println("external-parameter-entities: " + saxParser.getProperty("external-parameter-entities"));// System.out.println("is-standalone: " + saxParser.getProperty("is-standalone"));// System.out.println("lexical-handler: " + saxParser.getProperty("lexical-handler"));// System.out.println("parameter-entities: " + saxParser.getProperty("parameter-entities"));// System.out.println("namespaces: " + saxParser.getProperty("namespaces"));// System.out.println("namespace-prefixes: " + saxParser.getProperty("namespace-prefixes"));// System.out.println(": " + saxParser.getProperty(""));// System.out.println(": " + saxParser.getProperty(""));// System.out.println(": " + saxParser.getProperty(""));// System.out.println(": " + saxParser.getProperty(""));// System.out.println("" + saxParser.getProperty(""));// System.out.println("" + saxParser.getProperty(""));// System.out.println("" + saxParser.getProperty(""));// System.out.println("" + saxParser.getProperty(""));// System.out.println("" + saxParser.getProperty(""));// System.out.println("" + saxParser.getProperty(""));// System.out.println("" + saxParser.getProperty(""));// System.out.println("" + saxParser.getProperty("")); System.out.println("isValidating: " + saxParser.isValidating()); saxParser.parse(is, handler); } catch(SAXException se) { se.printStackTrace(); System.err.println("Could not read the partition list... exiting."); System.exit(1); } XMLNode[] rootNodes = handler.getRoots(); if(rootNodes.length != 1) { println("Could not parse DMG-file!"); System.exit(0); } /* Ok, now we have a tree built from the XML-document. Let's walk to the right place. */ /* cd plist cd dict cdkey resource-fork (type:dict) cdkey blkx (type:array) */ XMLNode current; XMLElement[] children; boolean keyFound; current = rootNodes[0]; //We are at plist... probably (there should be only one root node) current = current.cd("dict"); current = current.cdkey("resource-fork"); current = current.cdkey("blkx"); printlnVerbose("Found " + current.getChildren().length + " partitions:"); byte[] tmp = new byte[0x40000]; byte[] otmp = new byte[0x40000]; byte[] zeroblock = new byte[4096]; /* I think java always zeroes its arrays on creation... but let's play safe. */ for(int y = 0; y < zeroblock.length; ++y) zeroblock[y] = 0; LinkedList<DMGBlock> blocks = new LinkedList<DMGBlock>(); //long lastOffs = 0; long lastOutOffset = 0; long lastInOffset = 0; long totalSize = 0; boolean errorsFound = false; reportProgress(0); for(XMLElement xe : current.getChildren()) { if(progmon != null && progmon.isCanceled()) System.exit(0); if(xe instanceof XMLNode) { XMLNode xn = (XMLNode)xe; byte[] data = Base64.decode(xn.getKeyValue("Data")); long partitionSize = calculatePartitionSize(data); totalSize += partitionSize; printlnVerbose(" " + xn.getKeyValue("Name")); printlnVerbose(" ID: " + xn.getKeyValue("ID")); printlnVerbose(" Attributes: " + xn.getKeyValue("Attributes")); printlnVerbose(" Partition map data length: " + data.length + " bytes"); printlnVerbose(" Partition size: " + partitionSize + " bytes"); if(verbose) { printlnVerbose(" Dumping blkx..."); FileOutputStream fos = new FileOutputStream(xn.getKeyValue("ID") + ".blkx"); fos.write(data); fos.close(); } if(DEBUG) { File dumpFile = new File("data " + xn.getKeyValue("ID") + ".bin"); println(" Dumping partition map to file: " + dumpFile); FileOutputStream dump = new FileOutputStream(dumpFile); dump.write(data); dump.close(); } int offset = 0xCC; int blockType = 0; /* Offset of the input data for the current block in the input file */ long inOffset = 0; /* Size of the input data for the current block */ long inSize = 0; /* Offset of the output data for the current block in the output file */ long outOffset = 0; /* Size of the output data (possibly larger than inSize because of decompression, zero expansion...) */ long outSize = 0; long lastByteReadInBlock = -1; boolean addInOffset = false; //, lastInOffs = 0; int blockCount = 0; long previousPercentage = -1; while(blockType != BT_END) { if(progmon != null && progmon.isCanceled()) System.exit(0); DataInputStream dis = new DataInputStream(new ByteArrayInputStream(data)); int bytesSkipped = 0; while(bytesSkipped < offset) bytesSkipped += dis.skipBytes(offset-bytesSkipped); blockType = dis.readInt(); int skipped = dis.readInt(); //Skip 4 bytes forward outOffset = dis.readLong()*0x200;//(dis.readInt() & 0xffffffffL)*0x200; //unsigned int -> long //dis.readInt(); //Skip 4 bytes forward outSize = dis.readLong()*0x200;//(dis.readInt() & 0xffffffffL)*0x200; //unsigned int -> long inOffset = dis.readLong();// & 0xffffffffL; //unsigned int -> long //dis.readInt(); //Skip 4 bytes forward inSize = dis.readLong();//dis.readInt() & 0xffffffffL; //unsigned int -> long blocks.add(new DMGBlock(blockType, skipped, outOffset, outSize, inOffset, inSize)); if(lastByteReadInBlock == -1) lastByteReadInBlock = inOffset; lastByteReadInBlock += inSize; /* The lines below are a "hack" that I had to do to make dmgx work with certain dmg-files. I don't understand the issue at all, which is why this hack is here, but sometimes inOffset == 0 means that it is 0 relative to the previous partition's last inOffset. And sometimes it doesn't (meaning the actual position 0 in the dmg file). */ if(addInOffset) inOffset += lastInOffset; else if(inOffset == 0) { addInOffset = true; inOffset += lastInOffset; } outOffset += lastOutOffset; if(DEBUG) { println("outOffset=" + outOffset + " outSize=" + outSize + " inOffset=" + inOffset + " inSize=" + inSize + " lastOutOffset=" + lastOutOffset + " lastInOffset=" + lastInOffset /*+ " lastInOffs=" + lastInOffs + " lastOffs=" + lastOffs*/); } if(blockType == BT_ADC) { println(" " + blockCount + ". BT_ADC not supported."); if(!testOnly) System.exit(0); } else if(blockType == BT_ZLIB) { if(DEBUG) println(" " + blockCount + ". BT_ZLIB processing..."); if(!testOnly && isoRaf.getFilePointer() != outOffset) println(" " + blockCount + ". BT_ZLIB FP != outOffset (" + isoRaf.getFilePointer() + " != " + outOffset + ")"); dmgRaf.seek(/*lastOffs+*/inOffset); if(tmp.length < inSize) tmp = new byte[(int)inSize]; long totalBytesRead = 0; while(totalBytesRead < inSize) { totalBytesRead += dmgRaf.read(tmp, (int)totalBytesRead, Math.min((int)(inSize-totalBytesRead), tmp.length)); } long progressPercentage = dmgRaf.getFilePointer()*100/dmgRaf.length(); if(progressPercentage != previousPercentage) { reportProgress(progressPercentage); previousPercentage = progressPercentage; } Inflater inflater = new Inflater(); inflater.setInput(tmp, 0, (int)totalBytesRead); if(otmp.length < outSize) otmp = new byte[(int)outSize]; int bytesInflated = 0; while(true) { try { int counter = 0; while(bytesInflated < outSize && counter++ < 10) { int old = bytesInflated; bytesInflated += inflater.inflate(otmp, bytesInflated, (int)(outSize-bytesInflated)); if(old == bytesInflated) println("Nothing new! finished()=" + inflater.finished() + " needsInput()=" + inflater.needsInput() + " needsDictionary()=" + inflater.needsDictionary() + " getAdler()=" + inflater.getAdler() + " getBytesRead()=" + inflater.getBytesRead() + " getBytesWritten()=" + inflater.getBytesWritten() + " getRemaining()=" + inflater.getRemaining()); } //System.out.println(" Inflated " + bytesInflated + " bytes. Left in buffer: " + inflater.getRemaining() + " bytes inSize="+inSize+" outSize="+outSize); if(inflater.getRemaining() == 0) { //System.out.println(" done!"); break; } else { println(" " + blockCount + ". BT_ZLIB ERROR: otmp contents lost! (should not happen...)", " outSize=" + outSize + " inSize=" + inSize + " tmp.length=" + tmp.length + " otmp.length=" + otmp.length + " bytesInflated=" + bytesInflated + " inflater.getRemaining()=" + inflater.getRemaining());// if(bytesInflated == 0) throw new RuntimeException("WTF"); } } catch(DataFormatException dfe) { println(" " + blockCount + ". BT_ZLIB Could not decode..."); if(!DEBUG) { println("outOffset=" + outOffset + " outSize=" + outSize + " inOffset=" + inOffset + " inSize=" + inSize + " lastOutOffset=" + lastOutOffset + " lastInOffset=" + lastInOffset); } dfe.printStackTrace(); if(!testOnly) System.exit(0); else { println(" Testing mode, so continuing..."); //System.exit(0); errorsFound = true; break; } } } inflater.end(); if(!testOnly) isoRaf.write(otmp, 0, (int)outSize); //lastInOffs = inOffset+inSize; } else if(blockType == BT_BZIP2) { println(" " + blockCount + ". BT_BZIP2 not currently supported."); if(!testOnly) System.exit(0); } else if(blockType == BT_COPY) { if(DEBUG) println(" " + blockCount + ". BT_COPY processing..."); if(!testOnly && isoRaf.getFilePointer() != outOffset) println(" " + blockCount + ". BT_COPY FP != outOffset (" + isoRaf.getFilePointer() + " != " + outOffset + ")"); dmgRaf.seek(/*lastOffs+*/inOffset); int bytesRead = dmgRaf.read(tmp, 0, Math.min((int)inSize, tmp.length)); long totalBytesRead = bytesRead; while(bytesRead != -1) { long progressPercentage = dmgRaf.getFilePointer()*100/dmgRaf.length(); if(progressPercentage != previousPercentage) { reportProgress(progressPercentage); previousPercentage = progressPercentage; } if(!testOnly) isoRaf.write(tmp, 0, bytesRead); if(totalBytesRead >= inSize) break; bytesRead = dmgRaf.read(tmp, 0, Math.min((int)(inSize-totalBytesRead), tmp.length)); if(bytesRead > 0) totalBytesRead += bytesRead; } //lastInOffs = inOffset+inSize; } else if(blockType == BT_ZERO) { if(DEBUG) println(" " + blockCount + ". BT_ZERO processing..."); if(!testOnly && isoRaf.getFilePointer() != outOffset) println(" " + blockCount + ". BT_ZERO FP != outOffset (" + isoRaf.getFilePointer() + " != " + outOffset + ")"); long progressPercentage = dmgRaf.getFilePointer()*100/dmgRaf.length(); if(progressPercentage != previousPercentage) { reportProgress(progressPercentage); previousPercentage = progressPercentage; } long numberOfZeroBlocks = outSize/zeroblock.length; int numberOfRemainingBytes = (int)(outSize%zeroblock.length); for(int j = 0; j < numberOfZeroBlocks; ++j) { if(!testOnly) isoRaf.write(zeroblock); } if(!testOnly) isoRaf.write(zeroblock, 0, numberOfRemainingBytes); //lastInOffs = inOffset+inSize; } else if(blockType == BT_UNKNOWN) { /* I have no idea what this blocktype is... but it's common, and usually doesn't appear more than 2-3 times in a dmg. As long as its input and output sizes are 0, there's no reason to complain... is there? */ if(DEBUG) println(" " + blockCount + ". BT_UNKNOWN processing..."); if(!(inSize == 0 && outSize == 0)) { println(" " + blockCount + ". WARNING! Blocktype BT_UNKNOWN had non-zero sizes...", " inSize=" + inSize + ", outSize=" + outSize); //println(" The author of the program would be pleased if you contacted him about this."); // ...or would I? } } else if(blockType == BT_END) { if(DEBUG) println(" " + blockCount + ". BT_END processing..."); if(!testOnly && isoRaf.getFilePointer() != outOffset) println(" " + blockCount + ". BT_END FP != outOffset (" + isoRaf.getFilePointer() + " != " + outOffset + ")"); //lastOffs += lastInOffs; lastOutOffset = outOffset; lastInOffset += lastByteReadInBlock; } else { println(" " + blockCount + ". WARNING: previously unseen blocktype " + blockType + " [0x" + Integer.toHexString(blockType) + "]", " " + blockCount + ". outOffset=" + outOffset + " outSize=" + outSize + " inOffset=" + inOffset + " inSize=" + inSize); if(!testOnly && isoRaf.getFilePointer() != outOffset) println(" " + blockCount + ". unknown blocktype FP != outOffset (" + isoRaf.getFilePointer() + " != " + outOffset + ")"); } offset += 0x28; ++blockCount; } } } //printlnVerbose("Progress: 100% Done!"); reportProgress(100); String errors = errorsFound?"There were errors...":"No errors reported."; if(!graphical) { newline(); println(errors); printlnVerbose("Total extracted bytes: " + totalSize + " B"); } else { progmon.close(); JOptionPane.showMessageDialog(null, "Extraction complete! " + errors + "\n" + "Total extracted bytes: " + totalSize + " B", "Information", JOptionPane.INFORMATION_MESSAGE); System.exit(0); }// System.out.println("blocks.size()=" + blocks.size());// for(DMGBlock b : blocks)// System.out.println(" " + b.toString()); LinkedList<DMGBlock> merged = mergeBlocks(blocks);// System.out.println("merged.size()=" + merged.size());// for(DMGBlock b : merged)// System.out.println(" " + b.toString()); System.out.println("Extracting all the parts not containing block data from source file:"); int i = 1; DMGBlock previous = null; for(DMGBlock b : merged) { if(previous == null && b.inOffset > 0) { String filename = i++ + ".block"; System.out.print(" " + filename + "..."); FileOutputStream curFos = new FileOutputStream(new File(filename)); dmgRaf.seek(0); byte[] data = new byte[(int)(b.inOffset)]; dmgRaf.read(data); curFos.write(data); curFos.close(); } else if(previous != null) { String filename = i++ + ".block"; System.out.print(" " + filename + "..."); FileOutputStream curFos = new FileOutputStream(new File(filename)); dmgRaf.seek(previous.inOffset+previous.inSize); byte[] data = new byte[(int)(b.inOffset-(previous.inOffset+previous.inSize))]; dmgRaf.read(data); curFos.write(data); curFos.close(); } previous = b; } if(previous.inOffset+previous.inSize != dmgRaf.length()) { String filename = i++ + ".block"; System.out.print(" " + filename + "..."); FileOutputStream curFos = new FileOutputStream(new File(filename)); dmgRaf.seek(previous.inOffset+previous.inSize); byte[] data = new byte[(int)(dmgRaf.length()-(previous.inOffset+previous.inSize))]; dmgRaf.read(data); curFos.write(data); curFos.close(); } dmgRaf.close(); System.out.println("done!"); }
int counter = 0; while(bytesInflated < outSize && counter++ < 10) { int old = bytesInflated; bytesInflated += inflater.inflate(otmp, bytesInflated, (int)(outSize-bytesInflated)); if(old == bytesInflated) println("Nothing new! finished()=" + inflater.finished() + " needsInput()=" + inflater.needsInput() + " needsDictionary()=" + inflater.needsDictionary() + " getAdler()=" + inflater.getAdler() + " getBytesRead()=" + inflater.getBytesRead() + " getBytesWritten()=" + inflater.getBytesWritten() + " getRemaining()=" + inflater.getRemaining()); } if(inflater.getRemaining() == 0) { break; } else { println(" " + blockCount + ". BT_ZLIB ERROR: otmp contents lost! (should not happen...)", " outSize=" + outSize + " inSize=" + inSize + " tmp.length=" + tmp.length + " otmp.length=" + otmp.length + " bytesInflated=" + bytesInflated + " inflater.getRemaining()=" + inflater.getRemaining()); throw new RuntimeException("WTF"); } } catch(DataFormatException dfe) {
DMGBlockHandlers.processZlibBlock(currentBlock, dmgRaf, isoRaf, testOnly, dummyMonitor); } catch(DataFormatException dfe) {
public static void notmain(String[] args) throws Exception { System.setProperty("swing.aatext", "true"); //Antialiased text try { javax.swing.UIManager.setLookAndFeel(javax.swing.UIManager.getSystemLookAndFeelClassName()); } catch(Exception e) {} if(DEBUG) verbose = true; parseArgs(args); printlnVerbose("Processing: " + dmgFile); RandomAccessFile dmgRaf = new RandomAccessFile(dmgFile, "r"); RandomAccessFile isoRaf = null; boolean testOnly = false; if(isoFile != null) { isoRaf = new RandomAccessFile(isoFile, "rw"); isoRaf.setLength(0); printlnVerbose("Extracting to: " + isoFile); } else { testOnly = true; printlnVerbose("Simulating extraction..."); } dmgRaf.seek(dmgRaf.length()-PLIST_ADDRESS_1); long plistBegin1 = dmgRaf.readLong(); long plistEnd = dmgRaf.readLong(); dmgRaf.seek(dmgRaf.length()-PLIST_ADDRESS_2); long plistBegin2 = dmgRaf.readLong(); long plistSize = dmgRaf.readLong(); if(DEBUG) { println("Read addresses:", " " + plistBegin1, " " + plistBegin2); } if(plistBegin1 != plistBegin2) { println("Addresses not equal! Assumption broken... =/", plistBegin1 + " != " + plistBegin2); System.exit(0); } if(plistSize != (plistEnd-plistBegin1)) { println("plistSize field does not match plistEnd marker!", "plistSize=" + plistSize + " plistBegin1=" + plistBegin1 + " plistEnd=" + plistEnd + " plistEnd-plistBegin1=" + (plistEnd-plistBegin1)); } printlnVerbose("Jumping to address..."); dmgRaf.seek(plistBegin1); byte[] buffer = new byte[(int)plistSize]; dmgRaf.read(buffer); InputStream is = new ByteArrayInputStream(buffer); NodeBuilder handler = new NodeBuilder(); SAXParser saxParser = SAXParserFactory.newInstance().newSAXParser(); try {// System.out.println("validation: " + saxParser.getProperty("validation"));// System.out.println("external-general-entities: " + saxParser.getProperty("external-general-entities"));// System.out.println("external-parameter-entities: " + saxParser.getProperty("external-parameter-entities"));// System.out.println("is-standalone: " + saxParser.getProperty("is-standalone"));// System.out.println("lexical-handler: " + saxParser.getProperty("lexical-handler"));// System.out.println("parameter-entities: " + saxParser.getProperty("parameter-entities"));// System.out.println("namespaces: " + saxParser.getProperty("namespaces"));// System.out.println("namespace-prefixes: " + saxParser.getProperty("namespace-prefixes"));// System.out.println(": " + saxParser.getProperty(""));// System.out.println(": " + saxParser.getProperty(""));// System.out.println(": " + saxParser.getProperty(""));// System.out.println(": " + saxParser.getProperty(""));// System.out.println("" + saxParser.getProperty(""));// System.out.println("" + saxParser.getProperty(""));// System.out.println("" + saxParser.getProperty(""));// System.out.println("" + saxParser.getProperty(""));// System.out.println("" + saxParser.getProperty(""));// System.out.println("" + saxParser.getProperty(""));// System.out.println("" + saxParser.getProperty(""));// System.out.println("" + saxParser.getProperty("")); System.out.println("isValidating: " + saxParser.isValidating()); saxParser.parse(is, handler); } catch(SAXException se) { se.printStackTrace(); System.err.println("Could not read the partition list... exiting."); System.exit(1); } XMLNode[] rootNodes = handler.getRoots(); if(rootNodes.length != 1) { println("Could not parse DMG-file!"); System.exit(0); } /* Ok, now we have a tree built from the XML-document. Let's walk to the right place. */ /* cd plist cd dict cdkey resource-fork (type:dict) cdkey blkx (type:array) */ XMLNode current; XMLElement[] children; boolean keyFound; current = rootNodes[0]; //We are at plist... probably (there should be only one root node) current = current.cd("dict"); current = current.cdkey("resource-fork"); current = current.cdkey("blkx"); printlnVerbose("Found " + current.getChildren().length + " partitions:"); byte[] tmp = new byte[0x40000]; byte[] otmp = new byte[0x40000]; byte[] zeroblock = new byte[4096]; /* I think java always zeroes its arrays on creation... but let's play safe. */ for(int y = 0; y < zeroblock.length; ++y) zeroblock[y] = 0; LinkedList<DMGBlock> blocks = new LinkedList<DMGBlock>(); //long lastOffs = 0; long lastOutOffset = 0; long lastInOffset = 0; long totalSize = 0; boolean errorsFound = false; reportProgress(0); for(XMLElement xe : current.getChildren()) { if(progmon != null && progmon.isCanceled()) System.exit(0); if(xe instanceof XMLNode) { XMLNode xn = (XMLNode)xe; byte[] data = Base64.decode(xn.getKeyValue("Data")); long partitionSize = calculatePartitionSize(data); totalSize += partitionSize; printlnVerbose(" " + xn.getKeyValue("Name")); printlnVerbose(" ID: " + xn.getKeyValue("ID")); printlnVerbose(" Attributes: " + xn.getKeyValue("Attributes")); printlnVerbose(" Partition map data length: " + data.length + " bytes"); printlnVerbose(" Partition size: " + partitionSize + " bytes"); if(verbose) { printlnVerbose(" Dumping blkx..."); FileOutputStream fos = new FileOutputStream(xn.getKeyValue("ID") + ".blkx"); fos.write(data); fos.close(); } if(DEBUG) { File dumpFile = new File("data " + xn.getKeyValue("ID") + ".bin"); println(" Dumping partition map to file: " + dumpFile); FileOutputStream dump = new FileOutputStream(dumpFile); dump.write(data); dump.close(); } int offset = 0xCC; int blockType = 0; /* Offset of the input data for the current block in the input file */ long inOffset = 0; /* Size of the input data for the current block */ long inSize = 0; /* Offset of the output data for the current block in the output file */ long outOffset = 0; /* Size of the output data (possibly larger than inSize because of decompression, zero expansion...) */ long outSize = 0; long lastByteReadInBlock = -1; boolean addInOffset = false; //, lastInOffs = 0; int blockCount = 0; long previousPercentage = -1; while(blockType != BT_END) { if(progmon != null && progmon.isCanceled()) System.exit(0); DataInputStream dis = new DataInputStream(new ByteArrayInputStream(data)); int bytesSkipped = 0; while(bytesSkipped < offset) bytesSkipped += dis.skipBytes(offset-bytesSkipped); blockType = dis.readInt(); int skipped = dis.readInt(); //Skip 4 bytes forward outOffset = dis.readLong()*0x200;//(dis.readInt() & 0xffffffffL)*0x200; //unsigned int -> long //dis.readInt(); //Skip 4 bytes forward outSize = dis.readLong()*0x200;//(dis.readInt() & 0xffffffffL)*0x200; //unsigned int -> long inOffset = dis.readLong();// & 0xffffffffL; //unsigned int -> long //dis.readInt(); //Skip 4 bytes forward inSize = dis.readLong();//dis.readInt() & 0xffffffffL; //unsigned int -> long blocks.add(new DMGBlock(blockType, skipped, outOffset, outSize, inOffset, inSize)); if(lastByteReadInBlock == -1) lastByteReadInBlock = inOffset; lastByteReadInBlock += inSize; /* The lines below are a "hack" that I had to do to make dmgx work with certain dmg-files. I don't understand the issue at all, which is why this hack is here, but sometimes inOffset == 0 means that it is 0 relative to the previous partition's last inOffset. And sometimes it doesn't (meaning the actual position 0 in the dmg file). */ if(addInOffset) inOffset += lastInOffset; else if(inOffset == 0) { addInOffset = true; inOffset += lastInOffset; } outOffset += lastOutOffset; if(DEBUG) { println("outOffset=" + outOffset + " outSize=" + outSize + " inOffset=" + inOffset + " inSize=" + inSize + " lastOutOffset=" + lastOutOffset + " lastInOffset=" + lastInOffset /*+ " lastInOffs=" + lastInOffs + " lastOffs=" + lastOffs*/); } if(blockType == BT_ADC) { println(" " + blockCount + ". BT_ADC not supported."); if(!testOnly) System.exit(0); } else if(blockType == BT_ZLIB) { if(DEBUG) println(" " + blockCount + ". BT_ZLIB processing..."); if(!testOnly && isoRaf.getFilePointer() != outOffset) println(" " + blockCount + ". BT_ZLIB FP != outOffset (" + isoRaf.getFilePointer() + " != " + outOffset + ")"); dmgRaf.seek(/*lastOffs+*/inOffset); if(tmp.length < inSize) tmp = new byte[(int)inSize]; long totalBytesRead = 0; while(totalBytesRead < inSize) { totalBytesRead += dmgRaf.read(tmp, (int)totalBytesRead, Math.min((int)(inSize-totalBytesRead), tmp.length)); } long progressPercentage = dmgRaf.getFilePointer()*100/dmgRaf.length(); if(progressPercentage != previousPercentage) { reportProgress(progressPercentage); previousPercentage = progressPercentage; } Inflater inflater = new Inflater(); inflater.setInput(tmp, 0, (int)totalBytesRead); if(otmp.length < outSize) otmp = new byte[(int)outSize]; int bytesInflated = 0; while(true) { try { int counter = 0; while(bytesInflated < outSize && counter++ < 10) { int old = bytesInflated; bytesInflated += inflater.inflate(otmp, bytesInflated, (int)(outSize-bytesInflated)); if(old == bytesInflated) println("Nothing new! finished()=" + inflater.finished() + " needsInput()=" + inflater.needsInput() + " needsDictionary()=" + inflater.needsDictionary() + " getAdler()=" + inflater.getAdler() + " getBytesRead()=" + inflater.getBytesRead() + " getBytesWritten()=" + inflater.getBytesWritten() + " getRemaining()=" + inflater.getRemaining()); } //System.out.println(" Inflated " + bytesInflated + " bytes. Left in buffer: " + inflater.getRemaining() + " bytes inSize="+inSize+" outSize="+outSize); if(inflater.getRemaining() == 0) { //System.out.println(" done!"); break; } else { println(" " + blockCount + ". BT_ZLIB ERROR: otmp contents lost! (should not happen...)", " outSize=" + outSize + " inSize=" + inSize + " tmp.length=" + tmp.length + " otmp.length=" + otmp.length + " bytesInflated=" + bytesInflated + " inflater.getRemaining()=" + inflater.getRemaining());// if(bytesInflated == 0) throw new RuntimeException("WTF"); } } catch(DataFormatException dfe) { println(" " + blockCount + ". BT_ZLIB Could not decode..."); if(!DEBUG) { println("outOffset=" + outOffset + " outSize=" + outSize + " inOffset=" + inOffset + " inSize=" + inSize + " lastOutOffset=" + lastOutOffset + " lastInOffset=" + lastInOffset); } dfe.printStackTrace(); if(!testOnly) System.exit(0); else { println(" Testing mode, so continuing..."); //System.exit(0); errorsFound = true; break; } } } inflater.end(); if(!testOnly) isoRaf.write(otmp, 0, (int)outSize); //lastInOffs = inOffset+inSize; } else if(blockType == BT_BZIP2) { println(" " + blockCount + ". BT_BZIP2 not currently supported."); if(!testOnly) System.exit(0); } else if(blockType == BT_COPY) { if(DEBUG) println(" " + blockCount + ". BT_COPY processing..."); if(!testOnly && isoRaf.getFilePointer() != outOffset) println(" " + blockCount + ". BT_COPY FP != outOffset (" + isoRaf.getFilePointer() + " != " + outOffset + ")"); dmgRaf.seek(/*lastOffs+*/inOffset); int bytesRead = dmgRaf.read(tmp, 0, Math.min((int)inSize, tmp.length)); long totalBytesRead = bytesRead; while(bytesRead != -1) { long progressPercentage = dmgRaf.getFilePointer()*100/dmgRaf.length(); if(progressPercentage != previousPercentage) { reportProgress(progressPercentage); previousPercentage = progressPercentage; } if(!testOnly) isoRaf.write(tmp, 0, bytesRead); if(totalBytesRead >= inSize) break; bytesRead = dmgRaf.read(tmp, 0, Math.min((int)(inSize-totalBytesRead), tmp.length)); if(bytesRead > 0) totalBytesRead += bytesRead; } //lastInOffs = inOffset+inSize; } else if(blockType == BT_ZERO) { if(DEBUG) println(" " + blockCount + ". BT_ZERO processing..."); if(!testOnly && isoRaf.getFilePointer() != outOffset) println(" " + blockCount + ". BT_ZERO FP != outOffset (" + isoRaf.getFilePointer() + " != " + outOffset + ")"); long progressPercentage = dmgRaf.getFilePointer()*100/dmgRaf.length(); if(progressPercentage != previousPercentage) { reportProgress(progressPercentage); previousPercentage = progressPercentage; } long numberOfZeroBlocks = outSize/zeroblock.length; int numberOfRemainingBytes = (int)(outSize%zeroblock.length); for(int j = 0; j < numberOfZeroBlocks; ++j) { if(!testOnly) isoRaf.write(zeroblock); } if(!testOnly) isoRaf.write(zeroblock, 0, numberOfRemainingBytes); //lastInOffs = inOffset+inSize; } else if(blockType == BT_UNKNOWN) { /* I have no idea what this blocktype is... but it's common, and usually doesn't appear more than 2-3 times in a dmg. As long as its input and output sizes are 0, there's no reason to complain... is there? */ if(DEBUG) println(" " + blockCount + ". BT_UNKNOWN processing..."); if(!(inSize == 0 && outSize == 0)) { println(" " + blockCount + ". WARNING! Blocktype BT_UNKNOWN had non-zero sizes...", " inSize=" + inSize + ", outSize=" + outSize); //println(" The author of the program would be pleased if you contacted him about this."); // ...or would I? } } else if(blockType == BT_END) { if(DEBUG) println(" " + blockCount + ". BT_END processing..."); if(!testOnly && isoRaf.getFilePointer() != outOffset) println(" " + blockCount + ". BT_END FP != outOffset (" + isoRaf.getFilePointer() + " != " + outOffset + ")"); //lastOffs += lastInOffs; lastOutOffset = outOffset; lastInOffset += lastByteReadInBlock; } else { println(" " + blockCount + ". WARNING: previously unseen blocktype " + blockType + " [0x" + Integer.toHexString(blockType) + "]", " " + blockCount + ". outOffset=" + outOffset + " outSize=" + outSize + " inOffset=" + inOffset + " inSize=" + inSize); if(!testOnly && isoRaf.getFilePointer() != outOffset) println(" " + blockCount + ". unknown blocktype FP != outOffset (" + isoRaf.getFilePointer() + " != " + outOffset + ")"); } offset += 0x28; ++blockCount; } } } //printlnVerbose("Progress: 100% Done!"); reportProgress(100); String errors = errorsFound?"There were errors...":"No errors reported."; if(!graphical) { newline(); println(errors); printlnVerbose("Total extracted bytes: " + totalSize + " B"); } else { progmon.close(); JOptionPane.showMessageDialog(null, "Extraction complete! " + errors + "\n" + "Total extracted bytes: " + totalSize + " B", "Information", JOptionPane.INFORMATION_MESSAGE); System.exit(0); }// System.out.println("blocks.size()=" + blocks.size());// for(DMGBlock b : blocks)// System.out.println(" " + b.toString()); LinkedList<DMGBlock> merged = mergeBlocks(blocks);// System.out.println("merged.size()=" + merged.size());// for(DMGBlock b : merged)// System.out.println(" " + b.toString()); System.out.println("Extracting all the parts not containing block data from source file:"); int i = 1; DMGBlock previous = null; for(DMGBlock b : merged) { if(previous == null && b.inOffset > 0) { String filename = i++ + ".block"; System.out.print(" " + filename + "..."); FileOutputStream curFos = new FileOutputStream(new File(filename)); dmgRaf.seek(0); byte[] data = new byte[(int)(b.inOffset)]; dmgRaf.read(data); curFos.write(data); curFos.close(); } else if(previous != null) { String filename = i++ + ".block"; System.out.print(" " + filename + "..."); FileOutputStream curFos = new FileOutputStream(new File(filename)); dmgRaf.seek(previous.inOffset+previous.inSize); byte[] data = new byte[(int)(b.inOffset-(previous.inOffset+previous.inSize))]; dmgRaf.read(data); curFos.write(data); curFos.close(); } previous = b; } if(previous.inOffset+previous.inSize != dmgRaf.length()) { String filename = i++ + ".block"; System.out.print(" " + filename + "..."); FileOutputStream curFos = new FileOutputStream(new File(filename)); dmgRaf.seek(previous.inOffset+previous.inSize); byte[] data = new byte[(int)(dmgRaf.length()-(previous.inOffset+previous.inSize))]; dmgRaf.read(data); curFos.write(data); curFos.close(); } dmgRaf.close(); System.out.println("done!"); }
inflater.end(); if(!testOnly) isoRaf.write(otmp, 0, (int)outSize);
public static void notmain(String[] args) throws Exception { System.setProperty("swing.aatext", "true"); //Antialiased text try { javax.swing.UIManager.setLookAndFeel(javax.swing.UIManager.getSystemLookAndFeelClassName()); } catch(Exception e) {} if(DEBUG) verbose = true; parseArgs(args); printlnVerbose("Processing: " + dmgFile); RandomAccessFile dmgRaf = new RandomAccessFile(dmgFile, "r"); RandomAccessFile isoRaf = null; boolean testOnly = false; if(isoFile != null) { isoRaf = new RandomAccessFile(isoFile, "rw"); isoRaf.setLength(0); printlnVerbose("Extracting to: " + isoFile); } else { testOnly = true; printlnVerbose("Simulating extraction..."); } dmgRaf.seek(dmgRaf.length()-PLIST_ADDRESS_1); long plistBegin1 = dmgRaf.readLong(); long plistEnd = dmgRaf.readLong(); dmgRaf.seek(dmgRaf.length()-PLIST_ADDRESS_2); long plistBegin2 = dmgRaf.readLong(); long plistSize = dmgRaf.readLong(); if(DEBUG) { println("Read addresses:", " " + plistBegin1, " " + plistBegin2); } if(plistBegin1 != plistBegin2) { println("Addresses not equal! Assumption broken... =/", plistBegin1 + " != " + plistBegin2); System.exit(0); } if(plistSize != (plistEnd-plistBegin1)) { println("plistSize field does not match plistEnd marker!", "plistSize=" + plistSize + " plistBegin1=" + plistBegin1 + " plistEnd=" + plistEnd + " plistEnd-plistBegin1=" + (plistEnd-plistBegin1)); } printlnVerbose("Jumping to address..."); dmgRaf.seek(plistBegin1); byte[] buffer = new byte[(int)plistSize]; dmgRaf.read(buffer); InputStream is = new ByteArrayInputStream(buffer); NodeBuilder handler = new NodeBuilder(); SAXParser saxParser = SAXParserFactory.newInstance().newSAXParser(); try {// System.out.println("validation: " + saxParser.getProperty("validation"));// System.out.println("external-general-entities: " + saxParser.getProperty("external-general-entities"));// System.out.println("external-parameter-entities: " + saxParser.getProperty("external-parameter-entities"));// System.out.println("is-standalone: " + saxParser.getProperty("is-standalone"));// System.out.println("lexical-handler: " + saxParser.getProperty("lexical-handler"));// System.out.println("parameter-entities: " + saxParser.getProperty("parameter-entities"));// System.out.println("namespaces: " + saxParser.getProperty("namespaces"));// System.out.println("namespace-prefixes: " + saxParser.getProperty("namespace-prefixes"));// System.out.println(": " + saxParser.getProperty(""));// System.out.println(": " + saxParser.getProperty(""));// System.out.println(": " + saxParser.getProperty(""));// System.out.println(": " + saxParser.getProperty(""));// System.out.println("" + saxParser.getProperty(""));// System.out.println("" + saxParser.getProperty(""));// System.out.println("" + saxParser.getProperty(""));// System.out.println("" + saxParser.getProperty(""));// System.out.println("" + saxParser.getProperty(""));// System.out.println("" + saxParser.getProperty(""));// System.out.println("" + saxParser.getProperty(""));// System.out.println("" + saxParser.getProperty("")); System.out.println("isValidating: " + saxParser.isValidating()); saxParser.parse(is, handler); } catch(SAXException se) { se.printStackTrace(); System.err.println("Could not read the partition list... exiting."); System.exit(1); } XMLNode[] rootNodes = handler.getRoots(); if(rootNodes.length != 1) { println("Could not parse DMG-file!"); System.exit(0); } /* Ok, now we have a tree built from the XML-document. Let's walk to the right place. */ /* cd plist cd dict cdkey resource-fork (type:dict) cdkey blkx (type:array) */ XMLNode current; XMLElement[] children; boolean keyFound; current = rootNodes[0]; //We are at plist... probably (there should be only one root node) current = current.cd("dict"); current = current.cdkey("resource-fork"); current = current.cdkey("blkx"); printlnVerbose("Found " + current.getChildren().length + " partitions:"); byte[] tmp = new byte[0x40000]; byte[] otmp = new byte[0x40000]; byte[] zeroblock = new byte[4096]; /* I think java always zeroes its arrays on creation... but let's play safe. */ for(int y = 0; y < zeroblock.length; ++y) zeroblock[y] = 0; LinkedList<DMGBlock> blocks = new LinkedList<DMGBlock>(); //long lastOffs = 0; long lastOutOffset = 0; long lastInOffset = 0; long totalSize = 0; boolean errorsFound = false; reportProgress(0); for(XMLElement xe : current.getChildren()) { if(progmon != null && progmon.isCanceled()) System.exit(0); if(xe instanceof XMLNode) { XMLNode xn = (XMLNode)xe; byte[] data = Base64.decode(xn.getKeyValue("Data")); long partitionSize = calculatePartitionSize(data); totalSize += partitionSize; printlnVerbose(" " + xn.getKeyValue("Name")); printlnVerbose(" ID: " + xn.getKeyValue("ID")); printlnVerbose(" Attributes: " + xn.getKeyValue("Attributes")); printlnVerbose(" Partition map data length: " + data.length + " bytes"); printlnVerbose(" Partition size: " + partitionSize + " bytes"); if(verbose) { printlnVerbose(" Dumping blkx..."); FileOutputStream fos = new FileOutputStream(xn.getKeyValue("ID") + ".blkx"); fos.write(data); fos.close(); } if(DEBUG) { File dumpFile = new File("data " + xn.getKeyValue("ID") + ".bin"); println(" Dumping partition map to file: " + dumpFile); FileOutputStream dump = new FileOutputStream(dumpFile); dump.write(data); dump.close(); } int offset = 0xCC; int blockType = 0; /* Offset of the input data for the current block in the input file */ long inOffset = 0; /* Size of the input data for the current block */ long inSize = 0; /* Offset of the output data for the current block in the output file */ long outOffset = 0; /* Size of the output data (possibly larger than inSize because of decompression, zero expansion...) */ long outSize = 0; long lastByteReadInBlock = -1; boolean addInOffset = false; //, lastInOffs = 0; int blockCount = 0; long previousPercentage = -1; while(blockType != BT_END) { if(progmon != null && progmon.isCanceled()) System.exit(0); DataInputStream dis = new DataInputStream(new ByteArrayInputStream(data)); int bytesSkipped = 0; while(bytesSkipped < offset) bytesSkipped += dis.skipBytes(offset-bytesSkipped); blockType = dis.readInt(); int skipped = dis.readInt(); //Skip 4 bytes forward outOffset = dis.readLong()*0x200;//(dis.readInt() & 0xffffffffL)*0x200; //unsigned int -> long //dis.readInt(); //Skip 4 bytes forward outSize = dis.readLong()*0x200;//(dis.readInt() & 0xffffffffL)*0x200; //unsigned int -> long inOffset = dis.readLong();// & 0xffffffffL; //unsigned int -> long //dis.readInt(); //Skip 4 bytes forward inSize = dis.readLong();//dis.readInt() & 0xffffffffL; //unsigned int -> long blocks.add(new DMGBlock(blockType, skipped, outOffset, outSize, inOffset, inSize)); if(lastByteReadInBlock == -1) lastByteReadInBlock = inOffset; lastByteReadInBlock += inSize; /* The lines below are a "hack" that I had to do to make dmgx work with certain dmg-files. I don't understand the issue at all, which is why this hack is here, but sometimes inOffset == 0 means that it is 0 relative to the previous partition's last inOffset. And sometimes it doesn't (meaning the actual position 0 in the dmg file). */ if(addInOffset) inOffset += lastInOffset; else if(inOffset == 0) { addInOffset = true; inOffset += lastInOffset; } outOffset += lastOutOffset; if(DEBUG) { println("outOffset=" + outOffset + " outSize=" + outSize + " inOffset=" + inOffset + " inSize=" + inSize + " lastOutOffset=" + lastOutOffset + " lastInOffset=" + lastInOffset /*+ " lastInOffs=" + lastInOffs + " lastOffs=" + lastOffs*/); } if(blockType == BT_ADC) { println(" " + blockCount + ". BT_ADC not supported."); if(!testOnly) System.exit(0); } else if(blockType == BT_ZLIB) { if(DEBUG) println(" " + blockCount + ". BT_ZLIB processing..."); if(!testOnly && isoRaf.getFilePointer() != outOffset) println(" " + blockCount + ". BT_ZLIB FP != outOffset (" + isoRaf.getFilePointer() + " != " + outOffset + ")"); dmgRaf.seek(/*lastOffs+*/inOffset); if(tmp.length < inSize) tmp = new byte[(int)inSize]; long totalBytesRead = 0; while(totalBytesRead < inSize) { totalBytesRead += dmgRaf.read(tmp, (int)totalBytesRead, Math.min((int)(inSize-totalBytesRead), tmp.length)); } long progressPercentage = dmgRaf.getFilePointer()*100/dmgRaf.length(); if(progressPercentage != previousPercentage) { reportProgress(progressPercentage); previousPercentage = progressPercentage; } Inflater inflater = new Inflater(); inflater.setInput(tmp, 0, (int)totalBytesRead); if(otmp.length < outSize) otmp = new byte[(int)outSize]; int bytesInflated = 0; while(true) { try { int counter = 0; while(bytesInflated < outSize && counter++ < 10) { int old = bytesInflated; bytesInflated += inflater.inflate(otmp, bytesInflated, (int)(outSize-bytesInflated)); if(old == bytesInflated) println("Nothing new! finished()=" + inflater.finished() + " needsInput()=" + inflater.needsInput() + " needsDictionary()=" + inflater.needsDictionary() + " getAdler()=" + inflater.getAdler() + " getBytesRead()=" + inflater.getBytesRead() + " getBytesWritten()=" + inflater.getBytesWritten() + " getRemaining()=" + inflater.getRemaining()); } //System.out.println(" Inflated " + bytesInflated + " bytes. Left in buffer: " + inflater.getRemaining() + " bytes inSize="+inSize+" outSize="+outSize); if(inflater.getRemaining() == 0) { //System.out.println(" done!"); break; } else { println(" " + blockCount + ". BT_ZLIB ERROR: otmp contents lost! (should not happen...)", " outSize=" + outSize + " inSize=" + inSize + " tmp.length=" + tmp.length + " otmp.length=" + otmp.length + " bytesInflated=" + bytesInflated + " inflater.getRemaining()=" + inflater.getRemaining());// if(bytesInflated == 0) throw new RuntimeException("WTF"); } } catch(DataFormatException dfe) { println(" " + blockCount + ". BT_ZLIB Could not decode..."); if(!DEBUG) { println("outOffset=" + outOffset + " outSize=" + outSize + " inOffset=" + inOffset + " inSize=" + inSize + " lastOutOffset=" + lastOutOffset + " lastInOffset=" + lastInOffset); } dfe.printStackTrace(); if(!testOnly) System.exit(0); else { println(" Testing mode, so continuing..."); //System.exit(0); errorsFound = true; break; } } } inflater.end(); if(!testOnly) isoRaf.write(otmp, 0, (int)outSize); //lastInOffs = inOffset+inSize; } else if(blockType == BT_BZIP2) { println(" " + blockCount + ". BT_BZIP2 not currently supported."); if(!testOnly) System.exit(0); } else if(blockType == BT_COPY) { if(DEBUG) println(" " + blockCount + ". BT_COPY processing..."); if(!testOnly && isoRaf.getFilePointer() != outOffset) println(" " + blockCount + ". BT_COPY FP != outOffset (" + isoRaf.getFilePointer() + " != " + outOffset + ")"); dmgRaf.seek(/*lastOffs+*/inOffset); int bytesRead = dmgRaf.read(tmp, 0, Math.min((int)inSize, tmp.length)); long totalBytesRead = bytesRead; while(bytesRead != -1) { long progressPercentage = dmgRaf.getFilePointer()*100/dmgRaf.length(); if(progressPercentage != previousPercentage) { reportProgress(progressPercentage); previousPercentage = progressPercentage; } if(!testOnly) isoRaf.write(tmp, 0, bytesRead); if(totalBytesRead >= inSize) break; bytesRead = dmgRaf.read(tmp, 0, Math.min((int)(inSize-totalBytesRead), tmp.length)); if(bytesRead > 0) totalBytesRead += bytesRead; } //lastInOffs = inOffset+inSize; } else if(blockType == BT_ZERO) { if(DEBUG) println(" " + blockCount + ". BT_ZERO processing..."); if(!testOnly && isoRaf.getFilePointer() != outOffset) println(" " + blockCount + ". BT_ZERO FP != outOffset (" + isoRaf.getFilePointer() + " != " + outOffset + ")"); long progressPercentage = dmgRaf.getFilePointer()*100/dmgRaf.length(); if(progressPercentage != previousPercentage) { reportProgress(progressPercentage); previousPercentage = progressPercentage; } long numberOfZeroBlocks = outSize/zeroblock.length; int numberOfRemainingBytes = (int)(outSize%zeroblock.length); for(int j = 0; j < numberOfZeroBlocks; ++j) { if(!testOnly) isoRaf.write(zeroblock); } if(!testOnly) isoRaf.write(zeroblock, 0, numberOfRemainingBytes); //lastInOffs = inOffset+inSize; } else if(blockType == BT_UNKNOWN) { /* I have no idea what this blocktype is... but it's common, and usually doesn't appear more than 2-3 times in a dmg. As long as its input and output sizes are 0, there's no reason to complain... is there? */ if(DEBUG) println(" " + blockCount + ". BT_UNKNOWN processing..."); if(!(inSize == 0 && outSize == 0)) { println(" " + blockCount + ". WARNING! Blocktype BT_UNKNOWN had non-zero sizes...", " inSize=" + inSize + ", outSize=" + outSize); //println(" The author of the program would be pleased if you contacted him about this."); // ...or would I? } } else if(blockType == BT_END) { if(DEBUG) println(" " + blockCount + ". BT_END processing..."); if(!testOnly && isoRaf.getFilePointer() != outOffset) println(" " + blockCount + ". BT_END FP != outOffset (" + isoRaf.getFilePointer() + " != " + outOffset + ")"); //lastOffs += lastInOffs; lastOutOffset = outOffset; lastInOffset += lastByteReadInBlock; } else { println(" " + blockCount + ". WARNING: previously unseen blocktype " + blockType + " [0x" + Integer.toHexString(blockType) + "]", " " + blockCount + ". outOffset=" + outOffset + " outSize=" + outSize + " inOffset=" + inOffset + " inSize=" + inSize); if(!testOnly && isoRaf.getFilePointer() != outOffset) println(" " + blockCount + ". unknown blocktype FP != outOffset (" + isoRaf.getFilePointer() + " != " + outOffset + ")"); } offset += 0x28; ++blockCount; } } } //printlnVerbose("Progress: 100% Done!"); reportProgress(100); String errors = errorsFound?"There were errors...":"No errors reported."; if(!graphical) { newline(); println(errors); printlnVerbose("Total extracted bytes: " + totalSize + " B"); } else { progmon.close(); JOptionPane.showMessageDialog(null, "Extraction complete! " + errors + "\n" + "Total extracted bytes: " + totalSize + " B", "Information", JOptionPane.INFORMATION_MESSAGE); System.exit(0); }// System.out.println("blocks.size()=" + blocks.size());// for(DMGBlock b : blocks)// System.out.println(" " + b.toString()); LinkedList<DMGBlock> merged = mergeBlocks(blocks);// System.out.println("merged.size()=" + merged.size());// for(DMGBlock b : merged)// System.out.println(" " + b.toString()); System.out.println("Extracting all the parts not containing block data from source file:"); int i = 1; DMGBlock previous = null; for(DMGBlock b : merged) { if(previous == null && b.inOffset > 0) { String filename = i++ + ".block"; System.out.print(" " + filename + "..."); FileOutputStream curFos = new FileOutputStream(new File(filename)); dmgRaf.seek(0); byte[] data = new byte[(int)(b.inOffset)]; dmgRaf.read(data); curFos.write(data); curFos.close(); } else if(previous != null) { String filename = i++ + ".block"; System.out.print(" " + filename + "..."); FileOutputStream curFos = new FileOutputStream(new File(filename)); dmgRaf.seek(previous.inOffset+previous.inSize); byte[] data = new byte[(int)(b.inOffset-(previous.inOffset+previous.inSize))]; dmgRaf.read(data); curFos.write(data); curFos.close(); } previous = b; } if(previous.inOffset+previous.inSize != dmgRaf.length()) { String filename = i++ + ".block"; System.out.print(" " + filename + "..."); FileOutputStream curFos = new FileOutputStream(new File(filename)); dmgRaf.seek(previous.inOffset+previous.inSize); byte[] data = new byte[(int)(dmgRaf.length()-(previous.inOffset+previous.inSize))]; dmgRaf.read(data); curFos.write(data); curFos.close(); } dmgRaf.close(); System.out.println("done!"); }
int bytesRead = dmgRaf.read(tmp, 0, Math.min((int)inSize, tmp.length));
int bytesRead = dmgRaf.read(inBuffer, 0, Math.min((int)inSize, inBuffer.length));
public static void notmain(String[] args) throws Exception { System.setProperty("swing.aatext", "true"); //Antialiased text try { javax.swing.UIManager.setLookAndFeel(javax.swing.UIManager.getSystemLookAndFeelClassName()); } catch(Exception e) {} if(DEBUG) verbose = true; parseArgs(args); printlnVerbose("Processing: " + dmgFile); RandomAccessFile dmgRaf = new RandomAccessFile(dmgFile, "r"); RandomAccessFile isoRaf = null; boolean testOnly = false; if(isoFile != null) { isoRaf = new RandomAccessFile(isoFile, "rw"); isoRaf.setLength(0); printlnVerbose("Extracting to: " + isoFile); } else { testOnly = true; printlnVerbose("Simulating extraction..."); } dmgRaf.seek(dmgRaf.length()-PLIST_ADDRESS_1); long plistBegin1 = dmgRaf.readLong(); long plistEnd = dmgRaf.readLong(); dmgRaf.seek(dmgRaf.length()-PLIST_ADDRESS_2); long plistBegin2 = dmgRaf.readLong(); long plistSize = dmgRaf.readLong(); if(DEBUG) { println("Read addresses:", " " + plistBegin1, " " + plistBegin2); } if(plistBegin1 != plistBegin2) { println("Addresses not equal! Assumption broken... =/", plistBegin1 + " != " + plistBegin2); System.exit(0); } if(plistSize != (plistEnd-plistBegin1)) { println("plistSize field does not match plistEnd marker!", "plistSize=" + plistSize + " plistBegin1=" + plistBegin1 + " plistEnd=" + plistEnd + " plistEnd-plistBegin1=" + (plistEnd-plistBegin1)); } printlnVerbose("Jumping to address..."); dmgRaf.seek(plistBegin1); byte[] buffer = new byte[(int)plistSize]; dmgRaf.read(buffer); InputStream is = new ByteArrayInputStream(buffer); NodeBuilder handler = new NodeBuilder(); SAXParser saxParser = SAXParserFactory.newInstance().newSAXParser(); try {// System.out.println("validation: " + saxParser.getProperty("validation"));// System.out.println("external-general-entities: " + saxParser.getProperty("external-general-entities"));// System.out.println("external-parameter-entities: " + saxParser.getProperty("external-parameter-entities"));// System.out.println("is-standalone: " + saxParser.getProperty("is-standalone"));// System.out.println("lexical-handler: " + saxParser.getProperty("lexical-handler"));// System.out.println("parameter-entities: " + saxParser.getProperty("parameter-entities"));// System.out.println("namespaces: " + saxParser.getProperty("namespaces"));// System.out.println("namespace-prefixes: " + saxParser.getProperty("namespace-prefixes"));// System.out.println(": " + saxParser.getProperty(""));// System.out.println(": " + saxParser.getProperty(""));// System.out.println(": " + saxParser.getProperty(""));// System.out.println(": " + saxParser.getProperty(""));// System.out.println("" + saxParser.getProperty(""));// System.out.println("" + saxParser.getProperty(""));// System.out.println("" + saxParser.getProperty(""));// System.out.println("" + saxParser.getProperty(""));// System.out.println("" + saxParser.getProperty(""));// System.out.println("" + saxParser.getProperty(""));// System.out.println("" + saxParser.getProperty(""));// System.out.println("" + saxParser.getProperty("")); System.out.println("isValidating: " + saxParser.isValidating()); saxParser.parse(is, handler); } catch(SAXException se) { se.printStackTrace(); System.err.println("Could not read the partition list... exiting."); System.exit(1); } XMLNode[] rootNodes = handler.getRoots(); if(rootNodes.length != 1) { println("Could not parse DMG-file!"); System.exit(0); } /* Ok, now we have a tree built from the XML-document. Let's walk to the right place. */ /* cd plist cd dict cdkey resource-fork (type:dict) cdkey blkx (type:array) */ XMLNode current; XMLElement[] children; boolean keyFound; current = rootNodes[0]; //We are at plist... probably (there should be only one root node) current = current.cd("dict"); current = current.cdkey("resource-fork"); current = current.cdkey("blkx"); printlnVerbose("Found " + current.getChildren().length + " partitions:"); byte[] tmp = new byte[0x40000]; byte[] otmp = new byte[0x40000]; byte[] zeroblock = new byte[4096]; /* I think java always zeroes its arrays on creation... but let's play safe. */ for(int y = 0; y < zeroblock.length; ++y) zeroblock[y] = 0; LinkedList<DMGBlock> blocks = new LinkedList<DMGBlock>(); //long lastOffs = 0; long lastOutOffset = 0; long lastInOffset = 0; long totalSize = 0; boolean errorsFound = false; reportProgress(0); for(XMLElement xe : current.getChildren()) { if(progmon != null && progmon.isCanceled()) System.exit(0); if(xe instanceof XMLNode) { XMLNode xn = (XMLNode)xe; byte[] data = Base64.decode(xn.getKeyValue("Data")); long partitionSize = calculatePartitionSize(data); totalSize += partitionSize; printlnVerbose(" " + xn.getKeyValue("Name")); printlnVerbose(" ID: " + xn.getKeyValue("ID")); printlnVerbose(" Attributes: " + xn.getKeyValue("Attributes")); printlnVerbose(" Partition map data length: " + data.length + " bytes"); printlnVerbose(" Partition size: " + partitionSize + " bytes"); if(verbose) { printlnVerbose(" Dumping blkx..."); FileOutputStream fos = new FileOutputStream(xn.getKeyValue("ID") + ".blkx"); fos.write(data); fos.close(); } if(DEBUG) { File dumpFile = new File("data " + xn.getKeyValue("ID") + ".bin"); println(" Dumping partition map to file: " + dumpFile); FileOutputStream dump = new FileOutputStream(dumpFile); dump.write(data); dump.close(); } int offset = 0xCC; int blockType = 0; /* Offset of the input data for the current block in the input file */ long inOffset = 0; /* Size of the input data for the current block */ long inSize = 0; /* Offset of the output data for the current block in the output file */ long outOffset = 0; /* Size of the output data (possibly larger than inSize because of decompression, zero expansion...) */ long outSize = 0; long lastByteReadInBlock = -1; boolean addInOffset = false; //, lastInOffs = 0; int blockCount = 0; long previousPercentage = -1; while(blockType != BT_END) { if(progmon != null && progmon.isCanceled()) System.exit(0); DataInputStream dis = new DataInputStream(new ByteArrayInputStream(data)); int bytesSkipped = 0; while(bytesSkipped < offset) bytesSkipped += dis.skipBytes(offset-bytesSkipped); blockType = dis.readInt(); int skipped = dis.readInt(); //Skip 4 bytes forward outOffset = dis.readLong()*0x200;//(dis.readInt() & 0xffffffffL)*0x200; //unsigned int -> long //dis.readInt(); //Skip 4 bytes forward outSize = dis.readLong()*0x200;//(dis.readInt() & 0xffffffffL)*0x200; //unsigned int -> long inOffset = dis.readLong();// & 0xffffffffL; //unsigned int -> long //dis.readInt(); //Skip 4 bytes forward inSize = dis.readLong();//dis.readInt() & 0xffffffffL; //unsigned int -> long blocks.add(new DMGBlock(blockType, skipped, outOffset, outSize, inOffset, inSize)); if(lastByteReadInBlock == -1) lastByteReadInBlock = inOffset; lastByteReadInBlock += inSize; /* The lines below are a "hack" that I had to do to make dmgx work with certain dmg-files. I don't understand the issue at all, which is why this hack is here, but sometimes inOffset == 0 means that it is 0 relative to the previous partition's last inOffset. And sometimes it doesn't (meaning the actual position 0 in the dmg file). */ if(addInOffset) inOffset += lastInOffset; else if(inOffset == 0) { addInOffset = true; inOffset += lastInOffset; } outOffset += lastOutOffset; if(DEBUG) { println("outOffset=" + outOffset + " outSize=" + outSize + " inOffset=" + inOffset + " inSize=" + inSize + " lastOutOffset=" + lastOutOffset + " lastInOffset=" + lastInOffset /*+ " lastInOffs=" + lastInOffs + " lastOffs=" + lastOffs*/); } if(blockType == BT_ADC) { println(" " + blockCount + ". BT_ADC not supported."); if(!testOnly) System.exit(0); } else if(blockType == BT_ZLIB) { if(DEBUG) println(" " + blockCount + ". BT_ZLIB processing..."); if(!testOnly && isoRaf.getFilePointer() != outOffset) println(" " + blockCount + ". BT_ZLIB FP != outOffset (" + isoRaf.getFilePointer() + " != " + outOffset + ")"); dmgRaf.seek(/*lastOffs+*/inOffset); if(tmp.length < inSize) tmp = new byte[(int)inSize]; long totalBytesRead = 0; while(totalBytesRead < inSize) { totalBytesRead += dmgRaf.read(tmp, (int)totalBytesRead, Math.min((int)(inSize-totalBytesRead), tmp.length)); } long progressPercentage = dmgRaf.getFilePointer()*100/dmgRaf.length(); if(progressPercentage != previousPercentage) { reportProgress(progressPercentage); previousPercentage = progressPercentage; } Inflater inflater = new Inflater(); inflater.setInput(tmp, 0, (int)totalBytesRead); if(otmp.length < outSize) otmp = new byte[(int)outSize]; int bytesInflated = 0; while(true) { try { int counter = 0; while(bytesInflated < outSize && counter++ < 10) { int old = bytesInflated; bytesInflated += inflater.inflate(otmp, bytesInflated, (int)(outSize-bytesInflated)); if(old == bytesInflated) println("Nothing new! finished()=" + inflater.finished() + " needsInput()=" + inflater.needsInput() + " needsDictionary()=" + inflater.needsDictionary() + " getAdler()=" + inflater.getAdler() + " getBytesRead()=" + inflater.getBytesRead() + " getBytesWritten()=" + inflater.getBytesWritten() + " getRemaining()=" + inflater.getRemaining()); } //System.out.println(" Inflated " + bytesInflated + " bytes. Left in buffer: " + inflater.getRemaining() + " bytes inSize="+inSize+" outSize="+outSize); if(inflater.getRemaining() == 0) { //System.out.println(" done!"); break; } else { println(" " + blockCount + ". BT_ZLIB ERROR: otmp contents lost! (should not happen...)", " outSize=" + outSize + " inSize=" + inSize + " tmp.length=" + tmp.length + " otmp.length=" + otmp.length + " bytesInflated=" + bytesInflated + " inflater.getRemaining()=" + inflater.getRemaining());// if(bytesInflated == 0) throw new RuntimeException("WTF"); } } catch(DataFormatException dfe) { println(" " + blockCount + ". BT_ZLIB Could not decode..."); if(!DEBUG) { println("outOffset=" + outOffset + " outSize=" + outSize + " inOffset=" + inOffset + " inSize=" + inSize + " lastOutOffset=" + lastOutOffset + " lastInOffset=" + lastInOffset); } dfe.printStackTrace(); if(!testOnly) System.exit(0); else { println(" Testing mode, so continuing..."); //System.exit(0); errorsFound = true; break; } } } inflater.end(); if(!testOnly) isoRaf.write(otmp, 0, (int)outSize); //lastInOffs = inOffset+inSize; } else if(blockType == BT_BZIP2) { println(" " + blockCount + ". BT_BZIP2 not currently supported."); if(!testOnly) System.exit(0); } else if(blockType == BT_COPY) { if(DEBUG) println(" " + blockCount + ". BT_COPY processing..."); if(!testOnly && isoRaf.getFilePointer() != outOffset) println(" " + blockCount + ". BT_COPY FP != outOffset (" + isoRaf.getFilePointer() + " != " + outOffset + ")"); dmgRaf.seek(/*lastOffs+*/inOffset); int bytesRead = dmgRaf.read(tmp, 0, Math.min((int)inSize, tmp.length)); long totalBytesRead = bytesRead; while(bytesRead != -1) { long progressPercentage = dmgRaf.getFilePointer()*100/dmgRaf.length(); if(progressPercentage != previousPercentage) { reportProgress(progressPercentage); previousPercentage = progressPercentage; } if(!testOnly) isoRaf.write(tmp, 0, bytesRead); if(totalBytesRead >= inSize) break; bytesRead = dmgRaf.read(tmp, 0, Math.min((int)(inSize-totalBytesRead), tmp.length)); if(bytesRead > 0) totalBytesRead += bytesRead; } //lastInOffs = inOffset+inSize; } else if(blockType == BT_ZERO) { if(DEBUG) println(" " + blockCount + ". BT_ZERO processing..."); if(!testOnly && isoRaf.getFilePointer() != outOffset) println(" " + blockCount + ". BT_ZERO FP != outOffset (" + isoRaf.getFilePointer() + " != " + outOffset + ")"); long progressPercentage = dmgRaf.getFilePointer()*100/dmgRaf.length(); if(progressPercentage != previousPercentage) { reportProgress(progressPercentage); previousPercentage = progressPercentage; } long numberOfZeroBlocks = outSize/zeroblock.length; int numberOfRemainingBytes = (int)(outSize%zeroblock.length); for(int j = 0; j < numberOfZeroBlocks; ++j) { if(!testOnly) isoRaf.write(zeroblock); } if(!testOnly) isoRaf.write(zeroblock, 0, numberOfRemainingBytes); //lastInOffs = inOffset+inSize; } else if(blockType == BT_UNKNOWN) { /* I have no idea what this blocktype is... but it's common, and usually doesn't appear more than 2-3 times in a dmg. As long as its input and output sizes are 0, there's no reason to complain... is there? */ if(DEBUG) println(" " + blockCount + ". BT_UNKNOWN processing..."); if(!(inSize == 0 && outSize == 0)) { println(" " + blockCount + ". WARNING! Blocktype BT_UNKNOWN had non-zero sizes...", " inSize=" + inSize + ", outSize=" + outSize); //println(" The author of the program would be pleased if you contacted him about this."); // ...or would I? } } else if(blockType == BT_END) { if(DEBUG) println(" " + blockCount + ". BT_END processing..."); if(!testOnly && isoRaf.getFilePointer() != outOffset) println(" " + blockCount + ". BT_END FP != outOffset (" + isoRaf.getFilePointer() + " != " + outOffset + ")"); //lastOffs += lastInOffs; lastOutOffset = outOffset; lastInOffset += lastByteReadInBlock; } else { println(" " + blockCount + ". WARNING: previously unseen blocktype " + blockType + " [0x" + Integer.toHexString(blockType) + "]", " " + blockCount + ". outOffset=" + outOffset + " outSize=" + outSize + " inOffset=" + inOffset + " inSize=" + inSize); if(!testOnly && isoRaf.getFilePointer() != outOffset) println(" " + blockCount + ". unknown blocktype FP != outOffset (" + isoRaf.getFilePointer() + " != " + outOffset + ")"); } offset += 0x28; ++blockCount; } } } //printlnVerbose("Progress: 100% Done!"); reportProgress(100); String errors = errorsFound?"There were errors...":"No errors reported."; if(!graphical) { newline(); println(errors); printlnVerbose("Total extracted bytes: " + totalSize + " B"); } else { progmon.close(); JOptionPane.showMessageDialog(null, "Extraction complete! " + errors + "\n" + "Total extracted bytes: " + totalSize + " B", "Information", JOptionPane.INFORMATION_MESSAGE); System.exit(0); }// System.out.println("blocks.size()=" + blocks.size());// for(DMGBlock b : blocks)// System.out.println(" " + b.toString()); LinkedList<DMGBlock> merged = mergeBlocks(blocks);// System.out.println("merged.size()=" + merged.size());// for(DMGBlock b : merged)// System.out.println(" " + b.toString()); System.out.println("Extracting all the parts not containing block data from source file:"); int i = 1; DMGBlock previous = null; for(DMGBlock b : merged) { if(previous == null && b.inOffset > 0) { String filename = i++ + ".block"; System.out.print(" " + filename + "..."); FileOutputStream curFos = new FileOutputStream(new File(filename)); dmgRaf.seek(0); byte[] data = new byte[(int)(b.inOffset)]; dmgRaf.read(data); curFos.write(data); curFos.close(); } else if(previous != null) { String filename = i++ + ".block"; System.out.print(" " + filename + "..."); FileOutputStream curFos = new FileOutputStream(new File(filename)); dmgRaf.seek(previous.inOffset+previous.inSize); byte[] data = new byte[(int)(b.inOffset-(previous.inOffset+previous.inSize))]; dmgRaf.read(data); curFos.write(data); curFos.close(); } previous = b; } if(previous.inOffset+previous.inSize != dmgRaf.length()) { String filename = i++ + ".block"; System.out.print(" " + filename + "..."); FileOutputStream curFos = new FileOutputStream(new File(filename)); dmgRaf.seek(previous.inOffset+previous.inSize); byte[] data = new byte[(int)(dmgRaf.length()-(previous.inOffset+previous.inSize))]; dmgRaf.read(data); curFos.write(data); curFos.close(); } dmgRaf.close(); System.out.println("done!"); }
long progressPercentage = dmgRaf.getFilePointer()*100/dmgRaf.length(); if(progressPercentage != previousPercentage) { reportProgress(progressPercentage); previousPercentage = progressPercentage; }
reportFilePointerProgress(dmgRaf);
public static void notmain(String[] args) throws Exception { System.setProperty("swing.aatext", "true"); //Antialiased text try { javax.swing.UIManager.setLookAndFeel(javax.swing.UIManager.getSystemLookAndFeelClassName()); } catch(Exception e) {} if(DEBUG) verbose = true; parseArgs(args); printlnVerbose("Processing: " + dmgFile); RandomAccessFile dmgRaf = new RandomAccessFile(dmgFile, "r"); RandomAccessFile isoRaf = null; boolean testOnly = false; if(isoFile != null) { isoRaf = new RandomAccessFile(isoFile, "rw"); isoRaf.setLength(0); printlnVerbose("Extracting to: " + isoFile); } else { testOnly = true; printlnVerbose("Simulating extraction..."); } dmgRaf.seek(dmgRaf.length()-PLIST_ADDRESS_1); long plistBegin1 = dmgRaf.readLong(); long plistEnd = dmgRaf.readLong(); dmgRaf.seek(dmgRaf.length()-PLIST_ADDRESS_2); long plistBegin2 = dmgRaf.readLong(); long plistSize = dmgRaf.readLong(); if(DEBUG) { println("Read addresses:", " " + plistBegin1, " " + plistBegin2); } if(plistBegin1 != plistBegin2) { println("Addresses not equal! Assumption broken... =/", plistBegin1 + " != " + plistBegin2); System.exit(0); } if(plistSize != (plistEnd-plistBegin1)) { println("plistSize field does not match plistEnd marker!", "plistSize=" + plistSize + " plistBegin1=" + plistBegin1 + " plistEnd=" + plistEnd + " plistEnd-plistBegin1=" + (plistEnd-plistBegin1)); } printlnVerbose("Jumping to address..."); dmgRaf.seek(plistBegin1); byte[] buffer = new byte[(int)plistSize]; dmgRaf.read(buffer); InputStream is = new ByteArrayInputStream(buffer); NodeBuilder handler = new NodeBuilder(); SAXParser saxParser = SAXParserFactory.newInstance().newSAXParser(); try {// System.out.println("validation: " + saxParser.getProperty("validation"));// System.out.println("external-general-entities: " + saxParser.getProperty("external-general-entities"));// System.out.println("external-parameter-entities: " + saxParser.getProperty("external-parameter-entities"));// System.out.println("is-standalone: " + saxParser.getProperty("is-standalone"));// System.out.println("lexical-handler: " + saxParser.getProperty("lexical-handler"));// System.out.println("parameter-entities: " + saxParser.getProperty("parameter-entities"));// System.out.println("namespaces: " + saxParser.getProperty("namespaces"));// System.out.println("namespace-prefixes: " + saxParser.getProperty("namespace-prefixes"));// System.out.println(": " + saxParser.getProperty(""));// System.out.println(": " + saxParser.getProperty(""));// System.out.println(": " + saxParser.getProperty(""));// System.out.println(": " + saxParser.getProperty(""));// System.out.println("" + saxParser.getProperty(""));// System.out.println("" + saxParser.getProperty(""));// System.out.println("" + saxParser.getProperty(""));// System.out.println("" + saxParser.getProperty(""));// System.out.println("" + saxParser.getProperty(""));// System.out.println("" + saxParser.getProperty(""));// System.out.println("" + saxParser.getProperty(""));// System.out.println("" + saxParser.getProperty("")); System.out.println("isValidating: " + saxParser.isValidating()); saxParser.parse(is, handler); } catch(SAXException se) { se.printStackTrace(); System.err.println("Could not read the partition list... exiting."); System.exit(1); } XMLNode[] rootNodes = handler.getRoots(); if(rootNodes.length != 1) { println("Could not parse DMG-file!"); System.exit(0); } /* Ok, now we have a tree built from the XML-document. Let's walk to the right place. */ /* cd plist cd dict cdkey resource-fork (type:dict) cdkey blkx (type:array) */ XMLNode current; XMLElement[] children; boolean keyFound; current = rootNodes[0]; //We are at plist... probably (there should be only one root node) current = current.cd("dict"); current = current.cdkey("resource-fork"); current = current.cdkey("blkx"); printlnVerbose("Found " + current.getChildren().length + " partitions:"); byte[] tmp = new byte[0x40000]; byte[] otmp = new byte[0x40000]; byte[] zeroblock = new byte[4096]; /* I think java always zeroes its arrays on creation... but let's play safe. */ for(int y = 0; y < zeroblock.length; ++y) zeroblock[y] = 0; LinkedList<DMGBlock> blocks = new LinkedList<DMGBlock>(); //long lastOffs = 0; long lastOutOffset = 0; long lastInOffset = 0; long totalSize = 0; boolean errorsFound = false; reportProgress(0); for(XMLElement xe : current.getChildren()) { if(progmon != null && progmon.isCanceled()) System.exit(0); if(xe instanceof XMLNode) { XMLNode xn = (XMLNode)xe; byte[] data = Base64.decode(xn.getKeyValue("Data")); long partitionSize = calculatePartitionSize(data); totalSize += partitionSize; printlnVerbose(" " + xn.getKeyValue("Name")); printlnVerbose(" ID: " + xn.getKeyValue("ID")); printlnVerbose(" Attributes: " + xn.getKeyValue("Attributes")); printlnVerbose(" Partition map data length: " + data.length + " bytes"); printlnVerbose(" Partition size: " + partitionSize + " bytes"); if(verbose) { printlnVerbose(" Dumping blkx..."); FileOutputStream fos = new FileOutputStream(xn.getKeyValue("ID") + ".blkx"); fos.write(data); fos.close(); } if(DEBUG) { File dumpFile = new File("data " + xn.getKeyValue("ID") + ".bin"); println(" Dumping partition map to file: " + dumpFile); FileOutputStream dump = new FileOutputStream(dumpFile); dump.write(data); dump.close(); } int offset = 0xCC; int blockType = 0; /* Offset of the input data for the current block in the input file */ long inOffset = 0; /* Size of the input data for the current block */ long inSize = 0; /* Offset of the output data for the current block in the output file */ long outOffset = 0; /* Size of the output data (possibly larger than inSize because of decompression, zero expansion...) */ long outSize = 0; long lastByteReadInBlock = -1; boolean addInOffset = false; //, lastInOffs = 0; int blockCount = 0; long previousPercentage = -1; while(blockType != BT_END) { if(progmon != null && progmon.isCanceled()) System.exit(0); DataInputStream dis = new DataInputStream(new ByteArrayInputStream(data)); int bytesSkipped = 0; while(bytesSkipped < offset) bytesSkipped += dis.skipBytes(offset-bytesSkipped); blockType = dis.readInt(); int skipped = dis.readInt(); //Skip 4 bytes forward outOffset = dis.readLong()*0x200;//(dis.readInt() & 0xffffffffL)*0x200; //unsigned int -> long //dis.readInt(); //Skip 4 bytes forward outSize = dis.readLong()*0x200;//(dis.readInt() & 0xffffffffL)*0x200; //unsigned int -> long inOffset = dis.readLong();// & 0xffffffffL; //unsigned int -> long //dis.readInt(); //Skip 4 bytes forward inSize = dis.readLong();//dis.readInt() & 0xffffffffL; //unsigned int -> long blocks.add(new DMGBlock(blockType, skipped, outOffset, outSize, inOffset, inSize)); if(lastByteReadInBlock == -1) lastByteReadInBlock = inOffset; lastByteReadInBlock += inSize; /* The lines below are a "hack" that I had to do to make dmgx work with certain dmg-files. I don't understand the issue at all, which is why this hack is here, but sometimes inOffset == 0 means that it is 0 relative to the previous partition's last inOffset. And sometimes it doesn't (meaning the actual position 0 in the dmg file). */ if(addInOffset) inOffset += lastInOffset; else if(inOffset == 0) { addInOffset = true; inOffset += lastInOffset; } outOffset += lastOutOffset; if(DEBUG) { println("outOffset=" + outOffset + " outSize=" + outSize + " inOffset=" + inOffset + " inSize=" + inSize + " lastOutOffset=" + lastOutOffset + " lastInOffset=" + lastInOffset /*+ " lastInOffs=" + lastInOffs + " lastOffs=" + lastOffs*/); } if(blockType == BT_ADC) { println(" " + blockCount + ". BT_ADC not supported."); if(!testOnly) System.exit(0); } else if(blockType == BT_ZLIB) { if(DEBUG) println(" " + blockCount + ". BT_ZLIB processing..."); if(!testOnly && isoRaf.getFilePointer() != outOffset) println(" " + blockCount + ". BT_ZLIB FP != outOffset (" + isoRaf.getFilePointer() + " != " + outOffset + ")"); dmgRaf.seek(/*lastOffs+*/inOffset); if(tmp.length < inSize) tmp = new byte[(int)inSize]; long totalBytesRead = 0; while(totalBytesRead < inSize) { totalBytesRead += dmgRaf.read(tmp, (int)totalBytesRead, Math.min((int)(inSize-totalBytesRead), tmp.length)); } long progressPercentage = dmgRaf.getFilePointer()*100/dmgRaf.length(); if(progressPercentage != previousPercentage) { reportProgress(progressPercentage); previousPercentage = progressPercentage; } Inflater inflater = new Inflater(); inflater.setInput(tmp, 0, (int)totalBytesRead); if(otmp.length < outSize) otmp = new byte[(int)outSize]; int bytesInflated = 0; while(true) { try { int counter = 0; while(bytesInflated < outSize && counter++ < 10) { int old = bytesInflated; bytesInflated += inflater.inflate(otmp, bytesInflated, (int)(outSize-bytesInflated)); if(old == bytesInflated) println("Nothing new! finished()=" + inflater.finished() + " needsInput()=" + inflater.needsInput() + " needsDictionary()=" + inflater.needsDictionary() + " getAdler()=" + inflater.getAdler() + " getBytesRead()=" + inflater.getBytesRead() + " getBytesWritten()=" + inflater.getBytesWritten() + " getRemaining()=" + inflater.getRemaining()); } //System.out.println(" Inflated " + bytesInflated + " bytes. Left in buffer: " + inflater.getRemaining() + " bytes inSize="+inSize+" outSize="+outSize); if(inflater.getRemaining() == 0) { //System.out.println(" done!"); break; } else { println(" " + blockCount + ". BT_ZLIB ERROR: otmp contents lost! (should not happen...)", " outSize=" + outSize + " inSize=" + inSize + " tmp.length=" + tmp.length + " otmp.length=" + otmp.length + " bytesInflated=" + bytesInflated + " inflater.getRemaining()=" + inflater.getRemaining());// if(bytesInflated == 0) throw new RuntimeException("WTF"); } } catch(DataFormatException dfe) { println(" " + blockCount + ". BT_ZLIB Could not decode..."); if(!DEBUG) { println("outOffset=" + outOffset + " outSize=" + outSize + " inOffset=" + inOffset + " inSize=" + inSize + " lastOutOffset=" + lastOutOffset + " lastInOffset=" + lastInOffset); } dfe.printStackTrace(); if(!testOnly) System.exit(0); else { println(" Testing mode, so continuing..."); //System.exit(0); errorsFound = true; break; } } } inflater.end(); if(!testOnly) isoRaf.write(otmp, 0, (int)outSize); //lastInOffs = inOffset+inSize; } else if(blockType == BT_BZIP2) { println(" " + blockCount + ". BT_BZIP2 not currently supported."); if(!testOnly) System.exit(0); } else if(blockType == BT_COPY) { if(DEBUG) println(" " + blockCount + ". BT_COPY processing..."); if(!testOnly && isoRaf.getFilePointer() != outOffset) println(" " + blockCount + ". BT_COPY FP != outOffset (" + isoRaf.getFilePointer() + " != " + outOffset + ")"); dmgRaf.seek(/*lastOffs+*/inOffset); int bytesRead = dmgRaf.read(tmp, 0, Math.min((int)inSize, tmp.length)); long totalBytesRead = bytesRead; while(bytesRead != -1) { long progressPercentage = dmgRaf.getFilePointer()*100/dmgRaf.length(); if(progressPercentage != previousPercentage) { reportProgress(progressPercentage); previousPercentage = progressPercentage; } if(!testOnly) isoRaf.write(tmp, 0, bytesRead); if(totalBytesRead >= inSize) break; bytesRead = dmgRaf.read(tmp, 0, Math.min((int)(inSize-totalBytesRead), tmp.length)); if(bytesRead > 0) totalBytesRead += bytesRead; } //lastInOffs = inOffset+inSize; } else if(blockType == BT_ZERO) { if(DEBUG) println(" " + blockCount + ". BT_ZERO processing..."); if(!testOnly && isoRaf.getFilePointer() != outOffset) println(" " + blockCount + ". BT_ZERO FP != outOffset (" + isoRaf.getFilePointer() + " != " + outOffset + ")"); long progressPercentage = dmgRaf.getFilePointer()*100/dmgRaf.length(); if(progressPercentage != previousPercentage) { reportProgress(progressPercentage); previousPercentage = progressPercentage; } long numberOfZeroBlocks = outSize/zeroblock.length; int numberOfRemainingBytes = (int)(outSize%zeroblock.length); for(int j = 0; j < numberOfZeroBlocks; ++j) { if(!testOnly) isoRaf.write(zeroblock); } if(!testOnly) isoRaf.write(zeroblock, 0, numberOfRemainingBytes); //lastInOffs = inOffset+inSize; } else if(blockType == BT_UNKNOWN) { /* I have no idea what this blocktype is... but it's common, and usually doesn't appear more than 2-3 times in a dmg. As long as its input and output sizes are 0, there's no reason to complain... is there? */ if(DEBUG) println(" " + blockCount + ". BT_UNKNOWN processing..."); if(!(inSize == 0 && outSize == 0)) { println(" " + blockCount + ". WARNING! Blocktype BT_UNKNOWN had non-zero sizes...", " inSize=" + inSize + ", outSize=" + outSize); //println(" The author of the program would be pleased if you contacted him about this."); // ...or would I? } } else if(blockType == BT_END) { if(DEBUG) println(" " + blockCount + ". BT_END processing..."); if(!testOnly && isoRaf.getFilePointer() != outOffset) println(" " + blockCount + ". BT_END FP != outOffset (" + isoRaf.getFilePointer() + " != " + outOffset + ")"); //lastOffs += lastInOffs; lastOutOffset = outOffset; lastInOffset += lastByteReadInBlock; } else { println(" " + blockCount + ". WARNING: previously unseen blocktype " + blockType + " [0x" + Integer.toHexString(blockType) + "]", " " + blockCount + ". outOffset=" + outOffset + " outSize=" + outSize + " inOffset=" + inOffset + " inSize=" + inSize); if(!testOnly && isoRaf.getFilePointer() != outOffset) println(" " + blockCount + ". unknown blocktype FP != outOffset (" + isoRaf.getFilePointer() + " != " + outOffset + ")"); } offset += 0x28; ++blockCount; } } } //printlnVerbose("Progress: 100% Done!"); reportProgress(100); String errors = errorsFound?"There were errors...":"No errors reported."; if(!graphical) { newline(); println(errors); printlnVerbose("Total extracted bytes: " + totalSize + " B"); } else { progmon.close(); JOptionPane.showMessageDialog(null, "Extraction complete! " + errors + "\n" + "Total extracted bytes: " + totalSize + " B", "Information", JOptionPane.INFORMATION_MESSAGE); System.exit(0); }// System.out.println("blocks.size()=" + blocks.size());// for(DMGBlock b : blocks)// System.out.println(" " + b.toString()); LinkedList<DMGBlock> merged = mergeBlocks(blocks);// System.out.println("merged.size()=" + merged.size());// for(DMGBlock b : merged)// System.out.println(" " + b.toString()); System.out.println("Extracting all the parts not containing block data from source file:"); int i = 1; DMGBlock previous = null; for(DMGBlock b : merged) { if(previous == null && b.inOffset > 0) { String filename = i++ + ".block"; System.out.print(" " + filename + "..."); FileOutputStream curFos = new FileOutputStream(new File(filename)); dmgRaf.seek(0); byte[] data = new byte[(int)(b.inOffset)]; dmgRaf.read(data); curFos.write(data); curFos.close(); } else if(previous != null) { String filename = i++ + ".block"; System.out.print(" " + filename + "..."); FileOutputStream curFos = new FileOutputStream(new File(filename)); dmgRaf.seek(previous.inOffset+previous.inSize); byte[] data = new byte[(int)(b.inOffset-(previous.inOffset+previous.inSize))]; dmgRaf.read(data); curFos.write(data); curFos.close(); } previous = b; } if(previous.inOffset+previous.inSize != dmgRaf.length()) { String filename = i++ + ".block"; System.out.print(" " + filename + "..."); FileOutputStream curFos = new FileOutputStream(new File(filename)); dmgRaf.seek(previous.inOffset+previous.inSize); byte[] data = new byte[(int)(dmgRaf.length()-(previous.inOffset+previous.inSize))]; dmgRaf.read(data); curFos.write(data); curFos.close(); } dmgRaf.close(); System.out.println("done!"); }
isoRaf.write(tmp, 0, bytesRead);
isoRaf.write(inBuffer, 0, bytesRead);
public static void notmain(String[] args) throws Exception { System.setProperty("swing.aatext", "true"); //Antialiased text try { javax.swing.UIManager.setLookAndFeel(javax.swing.UIManager.getSystemLookAndFeelClassName()); } catch(Exception e) {} if(DEBUG) verbose = true; parseArgs(args); printlnVerbose("Processing: " + dmgFile); RandomAccessFile dmgRaf = new RandomAccessFile(dmgFile, "r"); RandomAccessFile isoRaf = null; boolean testOnly = false; if(isoFile != null) { isoRaf = new RandomAccessFile(isoFile, "rw"); isoRaf.setLength(0); printlnVerbose("Extracting to: " + isoFile); } else { testOnly = true; printlnVerbose("Simulating extraction..."); } dmgRaf.seek(dmgRaf.length()-PLIST_ADDRESS_1); long plistBegin1 = dmgRaf.readLong(); long plistEnd = dmgRaf.readLong(); dmgRaf.seek(dmgRaf.length()-PLIST_ADDRESS_2); long plistBegin2 = dmgRaf.readLong(); long plistSize = dmgRaf.readLong(); if(DEBUG) { println("Read addresses:", " " + plistBegin1, " " + plistBegin2); } if(plistBegin1 != plistBegin2) { println("Addresses not equal! Assumption broken... =/", plistBegin1 + " != " + plistBegin2); System.exit(0); } if(plistSize != (plistEnd-plistBegin1)) { println("plistSize field does not match plistEnd marker!", "plistSize=" + plistSize + " plistBegin1=" + plistBegin1 + " plistEnd=" + plistEnd + " plistEnd-plistBegin1=" + (plistEnd-plistBegin1)); } printlnVerbose("Jumping to address..."); dmgRaf.seek(plistBegin1); byte[] buffer = new byte[(int)plistSize]; dmgRaf.read(buffer); InputStream is = new ByteArrayInputStream(buffer); NodeBuilder handler = new NodeBuilder(); SAXParser saxParser = SAXParserFactory.newInstance().newSAXParser(); try {// System.out.println("validation: " + saxParser.getProperty("validation"));// System.out.println("external-general-entities: " + saxParser.getProperty("external-general-entities"));// System.out.println("external-parameter-entities: " + saxParser.getProperty("external-parameter-entities"));// System.out.println("is-standalone: " + saxParser.getProperty("is-standalone"));// System.out.println("lexical-handler: " + saxParser.getProperty("lexical-handler"));// System.out.println("parameter-entities: " + saxParser.getProperty("parameter-entities"));// System.out.println("namespaces: " + saxParser.getProperty("namespaces"));// System.out.println("namespace-prefixes: " + saxParser.getProperty("namespace-prefixes"));// System.out.println(": " + saxParser.getProperty(""));// System.out.println(": " + saxParser.getProperty(""));// System.out.println(": " + saxParser.getProperty(""));// System.out.println(": " + saxParser.getProperty(""));// System.out.println("" + saxParser.getProperty(""));// System.out.println("" + saxParser.getProperty(""));// System.out.println("" + saxParser.getProperty(""));// System.out.println("" + saxParser.getProperty(""));// System.out.println("" + saxParser.getProperty(""));// System.out.println("" + saxParser.getProperty(""));// System.out.println("" + saxParser.getProperty(""));// System.out.println("" + saxParser.getProperty("")); System.out.println("isValidating: " + saxParser.isValidating()); saxParser.parse(is, handler); } catch(SAXException se) { se.printStackTrace(); System.err.println("Could not read the partition list... exiting."); System.exit(1); } XMLNode[] rootNodes = handler.getRoots(); if(rootNodes.length != 1) { println("Could not parse DMG-file!"); System.exit(0); } /* Ok, now we have a tree built from the XML-document. Let's walk to the right place. */ /* cd plist cd dict cdkey resource-fork (type:dict) cdkey blkx (type:array) */ XMLNode current; XMLElement[] children; boolean keyFound; current = rootNodes[0]; //We are at plist... probably (there should be only one root node) current = current.cd("dict"); current = current.cdkey("resource-fork"); current = current.cdkey("blkx"); printlnVerbose("Found " + current.getChildren().length + " partitions:"); byte[] tmp = new byte[0x40000]; byte[] otmp = new byte[0x40000]; byte[] zeroblock = new byte[4096]; /* I think java always zeroes its arrays on creation... but let's play safe. */ for(int y = 0; y < zeroblock.length; ++y) zeroblock[y] = 0; LinkedList<DMGBlock> blocks = new LinkedList<DMGBlock>(); //long lastOffs = 0; long lastOutOffset = 0; long lastInOffset = 0; long totalSize = 0; boolean errorsFound = false; reportProgress(0); for(XMLElement xe : current.getChildren()) { if(progmon != null && progmon.isCanceled()) System.exit(0); if(xe instanceof XMLNode) { XMLNode xn = (XMLNode)xe; byte[] data = Base64.decode(xn.getKeyValue("Data")); long partitionSize = calculatePartitionSize(data); totalSize += partitionSize; printlnVerbose(" " + xn.getKeyValue("Name")); printlnVerbose(" ID: " + xn.getKeyValue("ID")); printlnVerbose(" Attributes: " + xn.getKeyValue("Attributes")); printlnVerbose(" Partition map data length: " + data.length + " bytes"); printlnVerbose(" Partition size: " + partitionSize + " bytes"); if(verbose) { printlnVerbose(" Dumping blkx..."); FileOutputStream fos = new FileOutputStream(xn.getKeyValue("ID") + ".blkx"); fos.write(data); fos.close(); } if(DEBUG) { File dumpFile = new File("data " + xn.getKeyValue("ID") + ".bin"); println(" Dumping partition map to file: " + dumpFile); FileOutputStream dump = new FileOutputStream(dumpFile); dump.write(data); dump.close(); } int offset = 0xCC; int blockType = 0; /* Offset of the input data for the current block in the input file */ long inOffset = 0; /* Size of the input data for the current block */ long inSize = 0; /* Offset of the output data for the current block in the output file */ long outOffset = 0; /* Size of the output data (possibly larger than inSize because of decompression, zero expansion...) */ long outSize = 0; long lastByteReadInBlock = -1; boolean addInOffset = false; //, lastInOffs = 0; int blockCount = 0; long previousPercentage = -1; while(blockType != BT_END) { if(progmon != null && progmon.isCanceled()) System.exit(0); DataInputStream dis = new DataInputStream(new ByteArrayInputStream(data)); int bytesSkipped = 0; while(bytesSkipped < offset) bytesSkipped += dis.skipBytes(offset-bytesSkipped); blockType = dis.readInt(); int skipped = dis.readInt(); //Skip 4 bytes forward outOffset = dis.readLong()*0x200;//(dis.readInt() & 0xffffffffL)*0x200; //unsigned int -> long //dis.readInt(); //Skip 4 bytes forward outSize = dis.readLong()*0x200;//(dis.readInt() & 0xffffffffL)*0x200; //unsigned int -> long inOffset = dis.readLong();// & 0xffffffffL; //unsigned int -> long //dis.readInt(); //Skip 4 bytes forward inSize = dis.readLong();//dis.readInt() & 0xffffffffL; //unsigned int -> long blocks.add(new DMGBlock(blockType, skipped, outOffset, outSize, inOffset, inSize)); if(lastByteReadInBlock == -1) lastByteReadInBlock = inOffset; lastByteReadInBlock += inSize; /* The lines below are a "hack" that I had to do to make dmgx work with certain dmg-files. I don't understand the issue at all, which is why this hack is here, but sometimes inOffset == 0 means that it is 0 relative to the previous partition's last inOffset. And sometimes it doesn't (meaning the actual position 0 in the dmg file). */ if(addInOffset) inOffset += lastInOffset; else if(inOffset == 0) { addInOffset = true; inOffset += lastInOffset; } outOffset += lastOutOffset; if(DEBUG) { println("outOffset=" + outOffset + " outSize=" + outSize + " inOffset=" + inOffset + " inSize=" + inSize + " lastOutOffset=" + lastOutOffset + " lastInOffset=" + lastInOffset /*+ " lastInOffs=" + lastInOffs + " lastOffs=" + lastOffs*/); } if(blockType == BT_ADC) { println(" " + blockCount + ". BT_ADC not supported."); if(!testOnly) System.exit(0); } else if(blockType == BT_ZLIB) { if(DEBUG) println(" " + blockCount + ". BT_ZLIB processing..."); if(!testOnly && isoRaf.getFilePointer() != outOffset) println(" " + blockCount + ". BT_ZLIB FP != outOffset (" + isoRaf.getFilePointer() + " != " + outOffset + ")"); dmgRaf.seek(/*lastOffs+*/inOffset); if(tmp.length < inSize) tmp = new byte[(int)inSize]; long totalBytesRead = 0; while(totalBytesRead < inSize) { totalBytesRead += dmgRaf.read(tmp, (int)totalBytesRead, Math.min((int)(inSize-totalBytesRead), tmp.length)); } long progressPercentage = dmgRaf.getFilePointer()*100/dmgRaf.length(); if(progressPercentage != previousPercentage) { reportProgress(progressPercentage); previousPercentage = progressPercentage; } Inflater inflater = new Inflater(); inflater.setInput(tmp, 0, (int)totalBytesRead); if(otmp.length < outSize) otmp = new byte[(int)outSize]; int bytesInflated = 0; while(true) { try { int counter = 0; while(bytesInflated < outSize && counter++ < 10) { int old = bytesInflated; bytesInflated += inflater.inflate(otmp, bytesInflated, (int)(outSize-bytesInflated)); if(old == bytesInflated) println("Nothing new! finished()=" + inflater.finished() + " needsInput()=" + inflater.needsInput() + " needsDictionary()=" + inflater.needsDictionary() + " getAdler()=" + inflater.getAdler() + " getBytesRead()=" + inflater.getBytesRead() + " getBytesWritten()=" + inflater.getBytesWritten() + " getRemaining()=" + inflater.getRemaining()); } //System.out.println(" Inflated " + bytesInflated + " bytes. Left in buffer: " + inflater.getRemaining() + " bytes inSize="+inSize+" outSize="+outSize); if(inflater.getRemaining() == 0) { //System.out.println(" done!"); break; } else { println(" " + blockCount + ". BT_ZLIB ERROR: otmp contents lost! (should not happen...)", " outSize=" + outSize + " inSize=" + inSize + " tmp.length=" + tmp.length + " otmp.length=" + otmp.length + " bytesInflated=" + bytesInflated + " inflater.getRemaining()=" + inflater.getRemaining());// if(bytesInflated == 0) throw new RuntimeException("WTF"); } } catch(DataFormatException dfe) { println(" " + blockCount + ". BT_ZLIB Could not decode..."); if(!DEBUG) { println("outOffset=" + outOffset + " outSize=" + outSize + " inOffset=" + inOffset + " inSize=" + inSize + " lastOutOffset=" + lastOutOffset + " lastInOffset=" + lastInOffset); } dfe.printStackTrace(); if(!testOnly) System.exit(0); else { println(" Testing mode, so continuing..."); //System.exit(0); errorsFound = true; break; } } } inflater.end(); if(!testOnly) isoRaf.write(otmp, 0, (int)outSize); //lastInOffs = inOffset+inSize; } else if(blockType == BT_BZIP2) { println(" " + blockCount + ". BT_BZIP2 not currently supported."); if(!testOnly) System.exit(0); } else if(blockType == BT_COPY) { if(DEBUG) println(" " + blockCount + ". BT_COPY processing..."); if(!testOnly && isoRaf.getFilePointer() != outOffset) println(" " + blockCount + ". BT_COPY FP != outOffset (" + isoRaf.getFilePointer() + " != " + outOffset + ")"); dmgRaf.seek(/*lastOffs+*/inOffset); int bytesRead = dmgRaf.read(tmp, 0, Math.min((int)inSize, tmp.length)); long totalBytesRead = bytesRead; while(bytesRead != -1) { long progressPercentage = dmgRaf.getFilePointer()*100/dmgRaf.length(); if(progressPercentage != previousPercentage) { reportProgress(progressPercentage); previousPercentage = progressPercentage; } if(!testOnly) isoRaf.write(tmp, 0, bytesRead); if(totalBytesRead >= inSize) break; bytesRead = dmgRaf.read(tmp, 0, Math.min((int)(inSize-totalBytesRead), tmp.length)); if(bytesRead > 0) totalBytesRead += bytesRead; } //lastInOffs = inOffset+inSize; } else if(blockType == BT_ZERO) { if(DEBUG) println(" " + blockCount + ". BT_ZERO processing..."); if(!testOnly && isoRaf.getFilePointer() != outOffset) println(" " + blockCount + ". BT_ZERO FP != outOffset (" + isoRaf.getFilePointer() + " != " + outOffset + ")"); long progressPercentage = dmgRaf.getFilePointer()*100/dmgRaf.length(); if(progressPercentage != previousPercentage) { reportProgress(progressPercentage); previousPercentage = progressPercentage; } long numberOfZeroBlocks = outSize/zeroblock.length; int numberOfRemainingBytes = (int)(outSize%zeroblock.length); for(int j = 0; j < numberOfZeroBlocks; ++j) { if(!testOnly) isoRaf.write(zeroblock); } if(!testOnly) isoRaf.write(zeroblock, 0, numberOfRemainingBytes); //lastInOffs = inOffset+inSize; } else if(blockType == BT_UNKNOWN) { /* I have no idea what this blocktype is... but it's common, and usually doesn't appear more than 2-3 times in a dmg. As long as its input and output sizes are 0, there's no reason to complain... is there? */ if(DEBUG) println(" " + blockCount + ". BT_UNKNOWN processing..."); if(!(inSize == 0 && outSize == 0)) { println(" " + blockCount + ". WARNING! Blocktype BT_UNKNOWN had non-zero sizes...", " inSize=" + inSize + ", outSize=" + outSize); //println(" The author of the program would be pleased if you contacted him about this."); // ...or would I? } } else if(blockType == BT_END) { if(DEBUG) println(" " + blockCount + ". BT_END processing..."); if(!testOnly && isoRaf.getFilePointer() != outOffset) println(" " + blockCount + ". BT_END FP != outOffset (" + isoRaf.getFilePointer() + " != " + outOffset + ")"); //lastOffs += lastInOffs; lastOutOffset = outOffset; lastInOffset += lastByteReadInBlock; } else { println(" " + blockCount + ". WARNING: previously unseen blocktype " + blockType + " [0x" + Integer.toHexString(blockType) + "]", " " + blockCount + ". outOffset=" + outOffset + " outSize=" + outSize + " inOffset=" + inOffset + " inSize=" + inSize); if(!testOnly && isoRaf.getFilePointer() != outOffset) println(" " + blockCount + ". unknown blocktype FP != outOffset (" + isoRaf.getFilePointer() + " != " + outOffset + ")"); } offset += 0x28; ++blockCount; } } } //printlnVerbose("Progress: 100% Done!"); reportProgress(100); String errors = errorsFound?"There were errors...":"No errors reported."; if(!graphical) { newline(); println(errors); printlnVerbose("Total extracted bytes: " + totalSize + " B"); } else { progmon.close(); JOptionPane.showMessageDialog(null, "Extraction complete! " + errors + "\n" + "Total extracted bytes: " + totalSize + " B", "Information", JOptionPane.INFORMATION_MESSAGE); System.exit(0); }// System.out.println("blocks.size()=" + blocks.size());// for(DMGBlock b : blocks)// System.out.println(" " + b.toString()); LinkedList<DMGBlock> merged = mergeBlocks(blocks);// System.out.println("merged.size()=" + merged.size());// for(DMGBlock b : merged)// System.out.println(" " + b.toString()); System.out.println("Extracting all the parts not containing block data from source file:"); int i = 1; DMGBlock previous = null; for(DMGBlock b : merged) { if(previous == null && b.inOffset > 0) { String filename = i++ + ".block"; System.out.print(" " + filename + "..."); FileOutputStream curFos = new FileOutputStream(new File(filename)); dmgRaf.seek(0); byte[] data = new byte[(int)(b.inOffset)]; dmgRaf.read(data); curFos.write(data); curFos.close(); } else if(previous != null) { String filename = i++ + ".block"; System.out.print(" " + filename + "..."); FileOutputStream curFos = new FileOutputStream(new File(filename)); dmgRaf.seek(previous.inOffset+previous.inSize); byte[] data = new byte[(int)(b.inOffset-(previous.inOffset+previous.inSize))]; dmgRaf.read(data); curFos.write(data); curFos.close(); } previous = b; } if(previous.inOffset+previous.inSize != dmgRaf.length()) { String filename = i++ + ".block"; System.out.print(" " + filename + "..."); FileOutputStream curFos = new FileOutputStream(new File(filename)); dmgRaf.seek(previous.inOffset+previous.inSize); byte[] data = new byte[(int)(dmgRaf.length()-(previous.inOffset+previous.inSize))]; dmgRaf.read(data); curFos.write(data); curFos.close(); } dmgRaf.close(); System.out.println("done!"); }
bytesRead = dmgRaf.read(tmp, 0, Math.min((int)(inSize-totalBytesRead), tmp.length));
bytesRead = dmgRaf.read(inBuffer, 0, Math.min((int)(inSize-totalBytesRead), inBuffer.length));
public static void notmain(String[] args) throws Exception { System.setProperty("swing.aatext", "true"); //Antialiased text try { javax.swing.UIManager.setLookAndFeel(javax.swing.UIManager.getSystemLookAndFeelClassName()); } catch(Exception e) {} if(DEBUG) verbose = true; parseArgs(args); printlnVerbose("Processing: " + dmgFile); RandomAccessFile dmgRaf = new RandomAccessFile(dmgFile, "r"); RandomAccessFile isoRaf = null; boolean testOnly = false; if(isoFile != null) { isoRaf = new RandomAccessFile(isoFile, "rw"); isoRaf.setLength(0); printlnVerbose("Extracting to: " + isoFile); } else { testOnly = true; printlnVerbose("Simulating extraction..."); } dmgRaf.seek(dmgRaf.length()-PLIST_ADDRESS_1); long plistBegin1 = dmgRaf.readLong(); long plistEnd = dmgRaf.readLong(); dmgRaf.seek(dmgRaf.length()-PLIST_ADDRESS_2); long plistBegin2 = dmgRaf.readLong(); long plistSize = dmgRaf.readLong(); if(DEBUG) { println("Read addresses:", " " + plistBegin1, " " + plistBegin2); } if(plistBegin1 != plistBegin2) { println("Addresses not equal! Assumption broken... =/", plistBegin1 + " != " + plistBegin2); System.exit(0); } if(plistSize != (plistEnd-plistBegin1)) { println("plistSize field does not match plistEnd marker!", "plistSize=" + plistSize + " plistBegin1=" + plistBegin1 + " plistEnd=" + plistEnd + " plistEnd-plistBegin1=" + (plistEnd-plistBegin1)); } printlnVerbose("Jumping to address..."); dmgRaf.seek(plistBegin1); byte[] buffer = new byte[(int)plistSize]; dmgRaf.read(buffer); InputStream is = new ByteArrayInputStream(buffer); NodeBuilder handler = new NodeBuilder(); SAXParser saxParser = SAXParserFactory.newInstance().newSAXParser(); try {// System.out.println("validation: " + saxParser.getProperty("validation"));// System.out.println("external-general-entities: " + saxParser.getProperty("external-general-entities"));// System.out.println("external-parameter-entities: " + saxParser.getProperty("external-parameter-entities"));// System.out.println("is-standalone: " + saxParser.getProperty("is-standalone"));// System.out.println("lexical-handler: " + saxParser.getProperty("lexical-handler"));// System.out.println("parameter-entities: " + saxParser.getProperty("parameter-entities"));// System.out.println("namespaces: " + saxParser.getProperty("namespaces"));// System.out.println("namespace-prefixes: " + saxParser.getProperty("namespace-prefixes"));// System.out.println(": " + saxParser.getProperty(""));// System.out.println(": " + saxParser.getProperty(""));// System.out.println(": " + saxParser.getProperty(""));// System.out.println(": " + saxParser.getProperty(""));// System.out.println("" + saxParser.getProperty(""));// System.out.println("" + saxParser.getProperty(""));// System.out.println("" + saxParser.getProperty(""));// System.out.println("" + saxParser.getProperty(""));// System.out.println("" + saxParser.getProperty(""));// System.out.println("" + saxParser.getProperty(""));// System.out.println("" + saxParser.getProperty(""));// System.out.println("" + saxParser.getProperty("")); System.out.println("isValidating: " + saxParser.isValidating()); saxParser.parse(is, handler); } catch(SAXException se) { se.printStackTrace(); System.err.println("Could not read the partition list... exiting."); System.exit(1); } XMLNode[] rootNodes = handler.getRoots(); if(rootNodes.length != 1) { println("Could not parse DMG-file!"); System.exit(0); } /* Ok, now we have a tree built from the XML-document. Let's walk to the right place. */ /* cd plist cd dict cdkey resource-fork (type:dict) cdkey blkx (type:array) */ XMLNode current; XMLElement[] children; boolean keyFound; current = rootNodes[0]; //We are at plist... probably (there should be only one root node) current = current.cd("dict"); current = current.cdkey("resource-fork"); current = current.cdkey("blkx"); printlnVerbose("Found " + current.getChildren().length + " partitions:"); byte[] tmp = new byte[0x40000]; byte[] otmp = new byte[0x40000]; byte[] zeroblock = new byte[4096]; /* I think java always zeroes its arrays on creation... but let's play safe. */ for(int y = 0; y < zeroblock.length; ++y) zeroblock[y] = 0; LinkedList<DMGBlock> blocks = new LinkedList<DMGBlock>(); //long lastOffs = 0; long lastOutOffset = 0; long lastInOffset = 0; long totalSize = 0; boolean errorsFound = false; reportProgress(0); for(XMLElement xe : current.getChildren()) { if(progmon != null && progmon.isCanceled()) System.exit(0); if(xe instanceof XMLNode) { XMLNode xn = (XMLNode)xe; byte[] data = Base64.decode(xn.getKeyValue("Data")); long partitionSize = calculatePartitionSize(data); totalSize += partitionSize; printlnVerbose(" " + xn.getKeyValue("Name")); printlnVerbose(" ID: " + xn.getKeyValue("ID")); printlnVerbose(" Attributes: " + xn.getKeyValue("Attributes")); printlnVerbose(" Partition map data length: " + data.length + " bytes"); printlnVerbose(" Partition size: " + partitionSize + " bytes"); if(verbose) { printlnVerbose(" Dumping blkx..."); FileOutputStream fos = new FileOutputStream(xn.getKeyValue("ID") + ".blkx"); fos.write(data); fos.close(); } if(DEBUG) { File dumpFile = new File("data " + xn.getKeyValue("ID") + ".bin"); println(" Dumping partition map to file: " + dumpFile); FileOutputStream dump = new FileOutputStream(dumpFile); dump.write(data); dump.close(); } int offset = 0xCC; int blockType = 0; /* Offset of the input data for the current block in the input file */ long inOffset = 0; /* Size of the input data for the current block */ long inSize = 0; /* Offset of the output data for the current block in the output file */ long outOffset = 0; /* Size of the output data (possibly larger than inSize because of decompression, zero expansion...) */ long outSize = 0; long lastByteReadInBlock = -1; boolean addInOffset = false; //, lastInOffs = 0; int blockCount = 0; long previousPercentage = -1; while(blockType != BT_END) { if(progmon != null && progmon.isCanceled()) System.exit(0); DataInputStream dis = new DataInputStream(new ByteArrayInputStream(data)); int bytesSkipped = 0; while(bytesSkipped < offset) bytesSkipped += dis.skipBytes(offset-bytesSkipped); blockType = dis.readInt(); int skipped = dis.readInt(); //Skip 4 bytes forward outOffset = dis.readLong()*0x200;//(dis.readInt() & 0xffffffffL)*0x200; //unsigned int -> long //dis.readInt(); //Skip 4 bytes forward outSize = dis.readLong()*0x200;//(dis.readInt() & 0xffffffffL)*0x200; //unsigned int -> long inOffset = dis.readLong();// & 0xffffffffL; //unsigned int -> long //dis.readInt(); //Skip 4 bytes forward inSize = dis.readLong();//dis.readInt() & 0xffffffffL; //unsigned int -> long blocks.add(new DMGBlock(blockType, skipped, outOffset, outSize, inOffset, inSize)); if(lastByteReadInBlock == -1) lastByteReadInBlock = inOffset; lastByteReadInBlock += inSize; /* The lines below are a "hack" that I had to do to make dmgx work with certain dmg-files. I don't understand the issue at all, which is why this hack is here, but sometimes inOffset == 0 means that it is 0 relative to the previous partition's last inOffset. And sometimes it doesn't (meaning the actual position 0 in the dmg file). */ if(addInOffset) inOffset += lastInOffset; else if(inOffset == 0) { addInOffset = true; inOffset += lastInOffset; } outOffset += lastOutOffset; if(DEBUG) { println("outOffset=" + outOffset + " outSize=" + outSize + " inOffset=" + inOffset + " inSize=" + inSize + " lastOutOffset=" + lastOutOffset + " lastInOffset=" + lastInOffset /*+ " lastInOffs=" + lastInOffs + " lastOffs=" + lastOffs*/); } if(blockType == BT_ADC) { println(" " + blockCount + ". BT_ADC not supported."); if(!testOnly) System.exit(0); } else if(blockType == BT_ZLIB) { if(DEBUG) println(" " + blockCount + ". BT_ZLIB processing..."); if(!testOnly && isoRaf.getFilePointer() != outOffset) println(" " + blockCount + ". BT_ZLIB FP != outOffset (" + isoRaf.getFilePointer() + " != " + outOffset + ")"); dmgRaf.seek(/*lastOffs+*/inOffset); if(tmp.length < inSize) tmp = new byte[(int)inSize]; long totalBytesRead = 0; while(totalBytesRead < inSize) { totalBytesRead += dmgRaf.read(tmp, (int)totalBytesRead, Math.min((int)(inSize-totalBytesRead), tmp.length)); } long progressPercentage = dmgRaf.getFilePointer()*100/dmgRaf.length(); if(progressPercentage != previousPercentage) { reportProgress(progressPercentage); previousPercentage = progressPercentage; } Inflater inflater = new Inflater(); inflater.setInput(tmp, 0, (int)totalBytesRead); if(otmp.length < outSize) otmp = new byte[(int)outSize]; int bytesInflated = 0; while(true) { try { int counter = 0; while(bytesInflated < outSize && counter++ < 10) { int old = bytesInflated; bytesInflated += inflater.inflate(otmp, bytesInflated, (int)(outSize-bytesInflated)); if(old == bytesInflated) println("Nothing new! finished()=" + inflater.finished() + " needsInput()=" + inflater.needsInput() + " needsDictionary()=" + inflater.needsDictionary() + " getAdler()=" + inflater.getAdler() + " getBytesRead()=" + inflater.getBytesRead() + " getBytesWritten()=" + inflater.getBytesWritten() + " getRemaining()=" + inflater.getRemaining()); } //System.out.println(" Inflated " + bytesInflated + " bytes. Left in buffer: " + inflater.getRemaining() + " bytes inSize="+inSize+" outSize="+outSize); if(inflater.getRemaining() == 0) { //System.out.println(" done!"); break; } else { println(" " + blockCount + ". BT_ZLIB ERROR: otmp contents lost! (should not happen...)", " outSize=" + outSize + " inSize=" + inSize + " tmp.length=" + tmp.length + " otmp.length=" + otmp.length + " bytesInflated=" + bytesInflated + " inflater.getRemaining()=" + inflater.getRemaining());// if(bytesInflated == 0) throw new RuntimeException("WTF"); } } catch(DataFormatException dfe) { println(" " + blockCount + ". BT_ZLIB Could not decode..."); if(!DEBUG) { println("outOffset=" + outOffset + " outSize=" + outSize + " inOffset=" + inOffset + " inSize=" + inSize + " lastOutOffset=" + lastOutOffset + " lastInOffset=" + lastInOffset); } dfe.printStackTrace(); if(!testOnly) System.exit(0); else { println(" Testing mode, so continuing..."); //System.exit(0); errorsFound = true; break; } } } inflater.end(); if(!testOnly) isoRaf.write(otmp, 0, (int)outSize); //lastInOffs = inOffset+inSize; } else if(blockType == BT_BZIP2) { println(" " + blockCount + ". BT_BZIP2 not currently supported."); if(!testOnly) System.exit(0); } else if(blockType == BT_COPY) { if(DEBUG) println(" " + blockCount + ". BT_COPY processing..."); if(!testOnly && isoRaf.getFilePointer() != outOffset) println(" " + blockCount + ". BT_COPY FP != outOffset (" + isoRaf.getFilePointer() + " != " + outOffset + ")"); dmgRaf.seek(/*lastOffs+*/inOffset); int bytesRead = dmgRaf.read(tmp, 0, Math.min((int)inSize, tmp.length)); long totalBytesRead = bytesRead; while(bytesRead != -1) { long progressPercentage = dmgRaf.getFilePointer()*100/dmgRaf.length(); if(progressPercentage != previousPercentage) { reportProgress(progressPercentage); previousPercentage = progressPercentage; } if(!testOnly) isoRaf.write(tmp, 0, bytesRead); if(totalBytesRead >= inSize) break; bytesRead = dmgRaf.read(tmp, 0, Math.min((int)(inSize-totalBytesRead), tmp.length)); if(bytesRead > 0) totalBytesRead += bytesRead; } //lastInOffs = inOffset+inSize; } else if(blockType == BT_ZERO) { if(DEBUG) println(" " + blockCount + ". BT_ZERO processing..."); if(!testOnly && isoRaf.getFilePointer() != outOffset) println(" " + blockCount + ". BT_ZERO FP != outOffset (" + isoRaf.getFilePointer() + " != " + outOffset + ")"); long progressPercentage = dmgRaf.getFilePointer()*100/dmgRaf.length(); if(progressPercentage != previousPercentage) { reportProgress(progressPercentage); previousPercentage = progressPercentage; } long numberOfZeroBlocks = outSize/zeroblock.length; int numberOfRemainingBytes = (int)(outSize%zeroblock.length); for(int j = 0; j < numberOfZeroBlocks; ++j) { if(!testOnly) isoRaf.write(zeroblock); } if(!testOnly) isoRaf.write(zeroblock, 0, numberOfRemainingBytes); //lastInOffs = inOffset+inSize; } else if(blockType == BT_UNKNOWN) { /* I have no idea what this blocktype is... but it's common, and usually doesn't appear more than 2-3 times in a dmg. As long as its input and output sizes are 0, there's no reason to complain... is there? */ if(DEBUG) println(" " + blockCount + ". BT_UNKNOWN processing..."); if(!(inSize == 0 && outSize == 0)) { println(" " + blockCount + ". WARNING! Blocktype BT_UNKNOWN had non-zero sizes...", " inSize=" + inSize + ", outSize=" + outSize); //println(" The author of the program would be pleased if you contacted him about this."); // ...or would I? } } else if(blockType == BT_END) { if(DEBUG) println(" " + blockCount + ". BT_END processing..."); if(!testOnly && isoRaf.getFilePointer() != outOffset) println(" " + blockCount + ". BT_END FP != outOffset (" + isoRaf.getFilePointer() + " != " + outOffset + ")"); //lastOffs += lastInOffs; lastOutOffset = outOffset; lastInOffset += lastByteReadInBlock; } else { println(" " + blockCount + ". WARNING: previously unseen blocktype " + blockType + " [0x" + Integer.toHexString(blockType) + "]", " " + blockCount + ". outOffset=" + outOffset + " outSize=" + outSize + " inOffset=" + inOffset + " inSize=" + inSize); if(!testOnly && isoRaf.getFilePointer() != outOffset) println(" " + blockCount + ". unknown blocktype FP != outOffset (" + isoRaf.getFilePointer() + " != " + outOffset + ")"); } offset += 0x28; ++blockCount; } } } //printlnVerbose("Progress: 100% Done!"); reportProgress(100); String errors = errorsFound?"There were errors...":"No errors reported."; if(!graphical) { newline(); println(errors); printlnVerbose("Total extracted bytes: " + totalSize + " B"); } else { progmon.close(); JOptionPane.showMessageDialog(null, "Extraction complete! " + errors + "\n" + "Total extracted bytes: " + totalSize + " B", "Information", JOptionPane.INFORMATION_MESSAGE); System.exit(0); }// System.out.println("blocks.size()=" + blocks.size());// for(DMGBlock b : blocks)// System.out.println(" " + b.toString()); LinkedList<DMGBlock> merged = mergeBlocks(blocks);// System.out.println("merged.size()=" + merged.size());// for(DMGBlock b : merged)// System.out.println(" " + b.toString()); System.out.println("Extracting all the parts not containing block data from source file:"); int i = 1; DMGBlock previous = null; for(DMGBlock b : merged) { if(previous == null && b.inOffset > 0) { String filename = i++ + ".block"; System.out.print(" " + filename + "..."); FileOutputStream curFos = new FileOutputStream(new File(filename)); dmgRaf.seek(0); byte[] data = new byte[(int)(b.inOffset)]; dmgRaf.read(data); curFos.write(data); curFos.close(); } else if(previous != null) { String filename = i++ + ".block"; System.out.print(" " + filename + "..."); FileOutputStream curFos = new FileOutputStream(new File(filename)); dmgRaf.seek(previous.inOffset+previous.inSize); byte[] data = new byte[(int)(b.inOffset-(previous.inOffset+previous.inSize))]; dmgRaf.read(data); curFos.write(data); curFos.close(); } previous = b; } if(previous.inOffset+previous.inSize != dmgRaf.length()) { String filename = i++ + ".block"; System.out.print(" " + filename + "..."); FileOutputStream curFos = new FileOutputStream(new File(filename)); dmgRaf.seek(previous.inOffset+previous.inSize); byte[] data = new byte[(int)(dmgRaf.length()-(previous.inOffset+previous.inSize))]; dmgRaf.read(data); curFos.write(data); curFos.close(); } dmgRaf.close(); System.out.println("done!"); }
public static void reportProgress(long progressPercentage) { if(!graphical) { printCurrentLine("--->Progress: " + progressPercentage + "%"); } else { if(progmon == null) { progmon = new ProgressMonitor(null, "Extracting dmg to iso...", "0%", 0, 100); progmon.setProgress(0); progmon.setMillisToPopup(0);
public static void reportProgress(int progressPercentage) { if(progressPercentage != previousPercentage) { previousPercentage = progressPercentage; if(!graphical) { printCurrentLine("--->Progress: " + progressPercentage + "%");
public static void reportProgress(long progressPercentage) { if(!graphical) { printCurrentLine("--->Progress: " + progressPercentage + "%"); } else { if(progmon == null) { progmon = new ProgressMonitor(null, "Extracting dmg to iso...", "0%", 0, 100); progmon.setProgress(0); progmon.setMillisToPopup(0); } progmon.setProgress((int)progressPercentage); progmon.setNote(progressPercentage + "%"); } }
progmon.setProgress((int)progressPercentage); progmon.setNote(progressPercentage + "%");
else { if(progmon == null) { progmon = new ProgressMonitor(null, "Extracting dmg to iso...", "0%", 0, 100); progmon.setProgress(0); progmon.setMillisToPopup(0); } progmon.setProgress((int)progressPercentage); progmon.setNote(progressPercentage + "%"); }
public static void reportProgress(long progressPercentage) { if(!graphical) { printCurrentLine("--->Progress: " + progressPercentage + "%"); } else { if(progmon == null) { progmon = new ProgressMonitor(null, "Extracting dmg to iso...", "0%", 0, 100); progmon.setProgress(0); progmon.setMillisToPopup(0); } progmon.setProgress((int)progressPercentage); progmon.setNote(progressPercentage + "%"); } }
login(OpheliaTestUser.JUNIT_X);
protected void setUp() throws Exception { super.setUp(); login(OpheliaTestUser.JUNIT); login(OpheliaTestUser.JUNIT_X); final ContainerModel containerModel = getContainerModel(OpheliaTestUser.JUNIT); final Container container = createContainer(OpheliaTestUser.JUNIT, NAME); addDocuments(OpheliaTestUser.JUNIT, container); final List<Contact> contacts = readContacts(OpheliaTestUser.JUNIT); datum = new Fixture(contacts, container, containerModel); containerModel.addListener(datum); }
logout(OpheliaTestUser.JUNIT_X);
logger.logTraceId();
protected void tearDown() throws Exception { datum.containerModel.removeListener(datum); datum = null; logout(OpheliaTestUser.JUNIT); logout(OpheliaTestUser.JUNIT_X); super.tearDown(); }
logger.logTraceId();
protected void tearDown() throws Exception { datum.containerModel.removeListener(datum); datum = null; logout(OpheliaTestUser.JUNIT); logout(OpheliaTestUser.JUNIT_X); super.tearDown(); }
logger.logTraceId();
public void testPublish() { datum.containerModel.publish( datum.container.getId(), datum.contacts, datum.teamMembers); assertTrue("The draft published event was not fired.", datum.didNotify); // ensure the system is the key holder again final JabberId keyHolder = getArtifactModel(OpheliaTestUser.JUNIT).readKeyHolder(datum.container.getId()); assertEquals("Local artifact key holder does not match expectation.", User.THINK_PARITY.getId(), keyHolder); assertTrue("Local key flag is still mistakenly applied.", !getArtifactModel(OpheliaTestUser.JUNIT).isFlagApplied(datum.container.getId(), ArtifactFlag.KEY)); // ensure the local and remote team jive final List<TeamMember> localTeam = getArtifactModel(OpheliaTestUser.JUNIT).readTeam2(datum.container.getId()); final List<JabberId> remoteTeam = getSessionModel(OpheliaTestUser.JUNIT).readArtifactTeamIds(datum.container.getUniqueId()); for (final TeamMember localTeamMember : localTeam) { Boolean didFindLocal = Boolean.FALSE; for (final JabberId remoteTeamMemberId : remoteTeam) { if (localTeamMember.getId().equals(remoteTeamMemberId)) { didFindLocal = Boolean.TRUE; break; } } assertTrue(MessageFormat.format( "Could not find local team member {0} in remote team.", localTeamMember), didFindLocal); } for (final JabberId remoteTeamMemberId : remoteTeam) { Boolean didFindRemote = Boolean.FALSE; for (final TeamMember localTeamMember : localTeam) { if (remoteTeamMemberId.equals(localTeamMember.getId())) { didFindRemote = Boolean.TRUE; break; } } assertTrue(MessageFormat.format( "Could not find remote team member {0} in local team.", remoteTeamMemberId), didFindRemote); } }
logger.logTraceId();
protected void logout(final OpheliaTestUser testUser) { getSessionModel(testUser).logout(); }
cellNameJLabel.setFont(listItem.getNameFont());
public Component getListCellRendererComponent(final JList list, final Object value, final int index, final boolean isSelected, final boolean cellHasFocus) { if(0 == index) { setBorder(BorderFactory.createEmptyBorder()); } else { setBorder(CELL_BORDER); } if(isSelected) { setBackground(listItemBackgroundSelect); } else { setBackground(listItemBackground); } final ListItem listItem = (ListItem) value; cellIconJLabel.setIcon(listItem.getMenuIcon()); cellNameJLabel.setText(listItem.getName()); cellNameJLabel.setForeground(listItem.getNameForeground()); cellInfoIconJLabel.setIcon(listItem.getInfoIcon()); return this; }
c.insets.right = 15;
private void initBrowserMainCellComponents() { final GridBagConstraints c = new GridBagConstraints(); c.anchor = GridBagConstraints.WEST; c.fill = GridBagConstraints.BOTH; c.weighty = 1; cellIconJLabel = LabelFactory.create(); c.insets.bottom = 1; c.insets.left = 13; add(cellIconJLabel, c.clone()); cellNameJLabel = LabelFactory.create(); c.gridx = 1; c.weightx = 1; add(cellNameJLabel, c.clone()); cellInfoIconJLabel = LabelFactory.create(); c.gridx = 2; c.weightx = 0; add(cellInfoIconJLabel, c.clone()); }
setText((HistoryItem) value);
setText((DisplayHistoryItem) value);
public Component getListCellRendererComponent(final JList list, final Object value, final int index, final boolean isSelected, final boolean cellHasFocus) { setBackground(isSelected ? BG_SEL : BG); setText((HistoryItem) value); return this; }
protected void setText(final HistoryItem historyItem) { setDateText(historyItem); setEventText(historyItem); setVersionText(historyItem);
protected void setText(final DisplayHistoryItem displayHistoryItem) { itemJLabel.setText(displayHistoryItem.getDisplay());
protected void setText(final HistoryItem historyItem) { setDateText(historyItem); setEventText(historyItem); setVersionText(historyItem); }
setName(new StringBuffer(document.getName()).append(" - ").append(document.getId()).toString());
setName(document.getName());
DocumentListItem(final Document document, final Boolean isKeyHolder) { super("DocumentListItem"); this.isKeyHolder = isKeyHolder; setDocumentId(document.getId()); if(isClosed(document.getId())) { setMenuIcon(MENU_ICON_CLOSED); setNameForeground(NAME_FOREGROUND_CLOSED); } else { setMenuIcon(MENU_ICON); setNameForeground(NAME_FOREGROUND); } setName(new StringBuffer(document.getName()).append(" - ").append(document.getId()).toString()); if(isKeyHolder) { setInfoIcon(KEY_ICON); } }
getMnemonic("CloseMnemonic"),
getMnemonic("Close"),
private JMenuItem getCloseMenuItem() { if(null == closeMenuItem) { closeMenuItem = createJMenuItem(getString("Close"), getMnemonic("CloseMnemonic"), getCloseMenuItemActionListener()); } return closeMenuItem; }
getMnemonic("DeleteMnemonic"),
getMnemonic("Delete"),
private JMenuItem getDeleteMenuItem() { if(null == deleteMenuItem) { deleteMenuItem = createJMenuItem(getString("Delete"), getMnemonic("DeleteMnemonic"), getDeleteMenuItemActionListener()); } return deleteMenuItem; }
getMnemonic("OpenMnemonic"),
getMnemonic("Open"),
private JMenuItem getOpenMenuItem() { if(null == openMenuItem) { openMenuItem = createJMenuItem(getString("Open"), getMnemonic("OpenMnemonic"), getOpenMenuItemActionListener()); } return openMenuItem; }
getMnemonic("RequestKeyMnemonic"),
getMnemonic("RequestKey"),
private JMenuItem getRequestKeyMenuItem() { if(null == requestKeyMenuItem) { requestKeyMenuItem = createJMenuItem(getString("RequestKey"), getMnemonic("RequestKeyMnemonic"), getRequestKeyMenuItemActionListener()); } return requestKeyMenuItem; }
getMnemonic("SendKeyMnemonic"),
getMnemonic("SendKey"),
private JMenuItem getSendKeyMenuItem() { if(null == sendKeyMenuItem) { sendKeyMenuItem = createJMenuItem(getString("SendKey"), getMnemonic("SendKeyMnemonic"), getSendKeyMenuItemActionListener()); } return sendKeyMenuItem; }
getMnemonic("SendMnemonic"), getSendMenuItemActionListener());
getMnemonic("Send"), getSendMenuItemActionListener());
private JMenuItem getSendMenuItem() { if(null == sendMenuItem) { sendMenuItem = createJMenuItem(getString("Send"), getMnemonic("SendMnemonic"), getSendMenuItemActionListener()); } return sendMenuItem; }
this.logger = LoggerFactory.getLogger(getClass());
protected ListItem(final String l18nContext) { super(); this.localization = new ListItemLocalization(l18nContext); this.propertyMap = new Hashtable<Object,Object>(7, 0.75F); }
logger.debug("ListItem.MnemonicString:" + mnemonicString + "]");
protected Integer getMnemonic(final String localKey) { final String mnemonicString = getString(localKey + "Mnemonic"); return new Integer(mnemonicString.charAt(0)); }
super(workspace, L18nContext.SYSTEM_MESSAGE);
super(workspace);
SystemMessageModelImpl(final Workspace workspace) { super(workspace, L18nContext.SYSTEM_MESSAGE); this.defaultComparator = new ComparatorBuilder().createSystemMessageDefault(); this.systemMessageIO = IOFactory.getDefault().createSystemMessageHandler(); }
protected String getString(final String localKey, final Object[] arguments) { return l18n.getString(localKey, arguments);
protected String getString(final String localKey) { return l18n.getString(localKey);
protected String getString(final String localKey, final Object[] arguments) { return l18n.getString(localKey, arguments); }
this.logger = new Log4JWrapper();
Session(final SessionManager sessionManager, final Connection connection) { super(); this.connection = connection; this.logger = new Log4JWrapper(); this.id = JVMUniqueId.nextId(); this.sessionManager = sessionManager; }
assertOpen("execute(String)"); logger.logVariable("sql", sql); try { final Statement s = connection.createStatement(); s.execute(sql); commit(); } catch(final SQLException sqlx) { rollback(); throw new HypersonicException(sqlx); } }
assertConnectionIsOpen(); logStatement(sql); try { final Statement s = connection.createStatement(); s.execute(sql); commit(); } catch (final SQLException sqlx) { rollback(); throw panic(sqlx); } }
public void execute(final String sql) { assertOpen("execute(String)"); logger.logVariable("sql", sql); try { final Statement s = connection.createStatement(); s.execute(sql); commit(); } catch(final SQLException sqlx) { rollback(); throw new HypersonicException(sqlx); } }
assertOpen("getAuditEventTypeFromInteger(String)"); assertOpenResult("getAuditEventTypeFromInteger(String)"); logger.logVariable("columnName", columnName);
assertConnectionIsOpen(); assertResultSetIsSet();
public AuditEventType getAuditEventTypeFromInteger(final String columnName) { assertOpen("getAuditEventTypeFromInteger(String)"); assertOpenResult("getAuditEventTypeFromInteger(String)"); logger.logVariable("columnName", columnName); try { final Integer value = resultSet.getInt(columnName); return resultSet.wasNull() ? null : AuditEventType.fromId(value); } catch (final SQLException sqlx) { throw new HypersonicException(sqlx); } }
logColumnExtraction(columnName, value);
public AuditEventType getAuditEventTypeFromInteger(final String columnName) { assertOpen("getAuditEventTypeFromInteger(String)"); assertOpenResult("getAuditEventTypeFromInteger(String)"); logger.logVariable("columnName", columnName); try { final Integer value = resultSet.getInt(columnName); return resultSet.wasNull() ? null : AuditEventType.fromId(value); } catch (final SQLException sqlx) { throw new HypersonicException(sqlx); } }
assertOpen("[GET BOOLEAN]"); assertOpenResult("[GET BOOLEAN]"); logger.logVariable("columnName", columnName);
assertConnectionIsOpen(); assertResultSetIsSet();
public Boolean getBoolean(final String columnName) { assertOpen("[GET BOOLEAN]"); assertOpenResult("[GET BOOLEAN]"); logger.logVariable("columnName", columnName); try { final Boolean value = resultSet.getBoolean(columnName); return resultSet.wasNull() ? null : value; } catch(final SQLException sqlx) { throw new HypersonicException(sqlx); } }
logColumnExtraction(columnName, value);
public Boolean getBoolean(final String columnName) { assertOpen("[GET BOOLEAN]"); assertOpenResult("[GET BOOLEAN]"); logger.logVariable("columnName", columnName); try { final Boolean value = resultSet.getBoolean(columnName); return resultSet.wasNull() ? null : value; } catch(final SQLException sqlx) { throw new HypersonicException(sqlx); } }
assertOpen("getBytes(String)"); assertOpenResult("getBytes(String)");
assertConnectionIsOpen(); assertResultSetIsSet();
public byte[] getBytes(final String columnName) { assertOpen("getBytes(String)"); assertOpenResult("getBytes(String)"); try { final byte[] value = resultSet.getBytes(columnName); return resultSet.wasNull() ? null : value; } catch (final SQLException sqlx) { throw new HypersonicException(sqlx); } }
logColumnExtraction(columnName, value);
public byte[] getBytes(final String columnName) { assertOpen("getBytes(String)"); assertOpenResult("getBytes(String)"); try { final byte[] value = resultSet.getBytes(columnName); return resultSet.wasNull() ? null : value; } catch (final SQLException sqlx) { throw new HypersonicException(sqlx); } }
assertOpen("getCalendar(String)"); assertOpenResult("getCalendar(String)");
assertConnectionIsOpen(); assertResultSetIsSet();
public EMail getEMail(final String columnName) { assertOpen("getCalendar(String)"); assertOpenResult("getCalendar(String)"); try { final String value = resultSet.getString(columnName); if (resultSet.wasNull()) { return null; } else { return EMailBuilder.parse(value); } } catch (final EMailFormatException efx) { throw new HypersonicException(efx); } catch (final SQLException sqlx) { throw new HypersonicException(sqlx); } }
if (resultSet.wasNull()) { return null; } else {
if (resultSet.wasNull()) { logColumnExtraction(columnName, null); return null; } else { logColumnExtraction(columnName, value);
public EMail getEMail(final String columnName) { assertOpen("getCalendar(String)"); assertOpenResult("getCalendar(String)"); try { final String value = resultSet.getString(columnName); if (resultSet.wasNull()) { return null; } else { return EMailBuilder.parse(value); } } catch (final EMailFormatException efx) { throw new HypersonicException(efx); } catch (final SQLException sqlx) { throw new HypersonicException(sqlx); } }
assertOpen("getFlagFromInteger(String)"); assertOpenResult("getFlagFromInteger(String)"); logger.logVariable("columnName", columnName);
assertConnectionIsOpen(); assertResultSetIsSet();
public ArtifactFlag getFlagFromInteger(final String columnName) { assertOpen("getFlagFromInteger(String)"); assertOpenResult("getFlagFromInteger(String)"); logger.logVariable("columnName", columnName); try { final Integer value = resultSet.getInt(columnName); return resultSet.wasNull() ? null : ArtifactFlag.fromId(value); } catch (final SQLException sqlx) { throw new HypersonicException(sqlx); } }
logColumnExtraction(columnName, value);
public ArtifactFlag getFlagFromInteger(final String columnName) { assertOpen("getFlagFromInteger(String)"); assertOpenResult("getFlagFromInteger(String)"); logger.logVariable("columnName", columnName); try { final Integer value = resultSet.getInt(columnName); return resultSet.wasNull() ? null : ArtifactFlag.fromId(value); } catch (final SQLException sqlx) { throw new HypersonicException(sqlx); } }
assertOpen("getFlagFromString(String)"); assertOpenResult("getFlagFromString(String)"); logger.logVariable("columnName", columnName);
assertConnectionIsOpen(); assertResultSetIsSet();
public ArtifactFlag getFlagFromString(final String columnName) { assertOpen("getFlagFromString(String)"); assertOpenResult("getFlagFromString(String)"); logger.logVariable("columnName", columnName); try { final String value = resultSet.getString(columnName); return resultSet.wasNull() ? null : ArtifactFlag.valueOf(value); } catch (final SQLException sqlx) { throw new HypersonicException(sqlx); } }