rem
stringlengths 0
477k
| add
stringlengths 0
313k
| context
stringlengths 6
599k
|
---|---|---|
versionId, documentUniqueId); | versionId); | public List<DocumentVersion> readDocumentVersions( final UUID uniqueId, final Long versionId, final UUID documentUniqueId) { return archiveModel.readDocumentVersions(uniqueId, versionId, documentUniqueId); } |
final UUID uniqueId, final Long versionId, final UUID documentUniqueId) { | final UUID uniqueId, final Long versionId) { | void restoreBackup() { logger.logApiId(); try { final List<Container> containers = read(); if (0 < containers.size()) { logger.logWarning("{0} containers will be deleted.", containers.size()); for (final Container container : containers) { delete(container.getId()); } } final InternalBackupModel backupModel = getBackupModel(); final List<Container> backupContainers = backupModel.readContainers(); logger.logVariable("backupContainers.size()", backupContainers.size()); for (final Container backupContainer : backupContainers) { restore(backupContainer, new RestoreModel() { public InputStream openDocumentVersion(final UUID uniqueId, final Long versionId) { return backupModel.openDocumentVersion(uniqueId, versionId); } public List<ContainerVersion> readContainerVersions( final UUID uniqueId) { return backupModel.readContainerVersions(uniqueId); } public List<Document> readDocuments(final UUID uniqueId, final Long versionId) { return backupModel.readDocuments(uniqueId, versionId); } public List<DocumentVersion> readDocumentVersions( final UUID uniqueId, final Long versionId, final UUID documentUniqueId) { return backupModel.readDocumentVersions(uniqueId, versionId, documentUniqueId); } public List<JabberId> readTeamIds(final UUID uniqueId) { return backupModel.readTeamIds(uniqueId); } }); } } catch (final Throwable t) { throw translateError(t); } } |
versionId, documentUniqueId); | versionId); | void restoreBackup() { logger.logApiId(); try { final List<Container> containers = read(); if (0 < containers.size()) { logger.logWarning("{0} containers will be deleted.", containers.size()); for (final Container container : containers) { delete(container.getId()); } } final InternalBackupModel backupModel = getBackupModel(); final List<Container> backupContainers = backupModel.readContainers(); logger.logVariable("backupContainers.size()", backupContainers.size()); for (final Container backupContainer : backupContainers) { restore(backupContainer, new RestoreModel() { public InputStream openDocumentVersion(final UUID uniqueId, final Long versionId) { return backupModel.openDocumentVersion(uniqueId, versionId); } public List<ContainerVersion> readContainerVersions( final UUID uniqueId) { return backupModel.readContainerVersions(uniqueId); } public List<Document> readDocuments(final UUID uniqueId, final Long versionId) { return backupModel.readDocuments(uniqueId, versionId); } public List<DocumentVersion> readDocumentVersions( final UUID uniqueId, final Long versionId, final UUID documentUniqueId) { return backupModel.readDocumentVersions(uniqueId, versionId, documentUniqueId); } public List<JabberId> readTeamIds(final UUID uniqueId) { return backupModel.readTeamIds(uniqueId); } }); } } catch (final Throwable t) { throw translateError(t); } } |
final UUID uniqueId, final Long versionId, final UUID documentUniqueId) { | final UUID uniqueId, final Long versionId) { | public List<DocumentVersion> readDocumentVersions( final UUID uniqueId, final Long versionId, final UUID documentUniqueId) { return backupModel.readDocumentVersions(uniqueId, versionId, documentUniqueId); } |
versionId, documentUniqueId); | versionId); | public List<DocumentVersion> readDocumentVersions( final UUID uniqueId, final Long versionId, final UUID documentUniqueId) { return backupModel.readDocumentVersions(uniqueId, versionId, documentUniqueId); } |
final InternalSessionModel iSModel = getInternalSessionModel(); iSModel.sendDelete(documentId); | void close(final Long documentId) throws ParityException { logger.info("[LMODEL] [DOCUMENT MODE] [CLOSE]"); logger.debug(documentId); assertOnline("[LMODEL] [DOCUMENT MODE] [CLOSE] [USER IS NOT ONLINE]"); assertIsKeyHolder("[LMODEL] [DOCUMENT MODE] [CLOSE] [USER IS NOT KEY HOLDER]", documentId); // update state final Document d = get(documentId); assertStateTransition(d.getState(), ArtifactState.CLOSED); documentIO.updateState(d.getId(), ArtifactState.CLOSED); // lock lock(documentId); // call the server's close api getInternalSessionModel().sendClose(documentId); // delete remote team subscription final InternalSessionModel iSModel = getInternalSessionModel(); iSModel.sendDelete(documentId); // audit auditor.close( documentId, currentUserId(), currentDateTime(), currentUserId()); // fire event notifyDocumentClosed(get(documentId), localEventGen); } |
|
final Long documentId) { | final Long documentId, final Integer eTeamSize) { | private Fixture(final ArtifactModel aModel, final JabberId closedBy, final DocumentModelImpl dMImpl, final DocumentModel dModel, final Long documentId) { this.aModel = aModel; this.closedBy = closedBy; this.dMImpl = dMImpl; this.dModel = dModel; this.documentId = documentId; } |
this.eTeamSize = eTeamSize; | private Fixture(final ArtifactModel aModel, final JabberId closedBy, final DocumentModelImpl dMImpl, final DocumentModel dModel, final Long documentId) { this.aModel = aModel; this.closedBy = closedBy; this.dMImpl = dMImpl; this.dModel = dModel; this.documentId = documentId; } |
|
data.add(new Fixture(aModel, userX.getJabberId(), dMImpl, dModel, d0.getId())); | data.add(new Fixture(aModel, userX.getJabberId(), dMImpl, dModel, d0.getId(), aModel.readTeam(d0.getId()).size())); | protected void setUp() throws Exception { super.setUp(); data = new LinkedList<Fixture>(); final ArtifactModel aModel = getArtifactModel(); final DocumentModel dModel = getDocumentModel(); final DocumentModelImpl dMImpl = getImpl(); final SessionModel sModel = getSessionModel(); final ModelTestUser userX = ModelTestUser.getX(); // 1 scenario final File file0 = getInputFiles()[0]; final Document d0 = dModel.create(file0.getName(), file0.getName(), file0); addTeam(d0); modifyDocument(d0); dModel.publish(d0.getId()); sModel.sendKeyResponse(d0.getId(), userX.getJabberId(), KeyResponse.ACCEPT); data.add(new Fixture(aModel, userX.getJabberId(), dMImpl, dModel, d0.getId())); } |
assertEquals("[LMODEL] [DOCUMENT] [TEST CLOSE] [NON-ZERO TEAM SIZE]", team.size(), 0); | assertEquals("[LMODEL] [DOCUMENT] [TEST CLOSE] [NON-ZERO TEAM SIZE]", datum.eTeamSize.intValue(), team.size()); | public void testHandleClose() { testLogger.info("[LMODEL] [DOCUMENT] [TEST HANDLE CLOSE]"); Document document; Set<User> team; for(final Fixture datum : data) { try { datum.dMImpl.handleClose(datum.documentId, datum.closedBy); } catch(final ParityException px) { fail(createFailMessage(px)); } document = null; try { document = datum.dModel.get(datum.documentId); } catch(final ParityException px) { fail(createFailMessage(px)); } assertNotNull("[LMODEL] [DOCUMENT] [TEST CLOSE] [DOCUMENT IS NULL]", document); assertEquals("[LMODEL] [DOCUMENT] [TEST CLOSE] [NON-CLOSED DOCUMENT STATE]", document.getState(), ArtifactState.CLOSED); team = datum.aModel.readTeam(datum.documentId); assertNotNull("[LMODEL] [DOCUMENT] [TEST CLOSE] [TEAM IS NULL]", team); assertEquals("[LMODEL] [DOCUMENT] [TEST CLOSE] [NON-ZERO TEAM SIZE]", team.size(), 0); } } |
final ConfirmSynchronize confirmSynchronize = new ConfirmSynchronize(); openWindow(confirmSynchronize); return confirmSynchronize.didConfirm(); | final ConfirmSynchronizeWindow confirmWindow = new ConfirmSynchronizeWindow(); confirmWindow.setVisibleAndWait(); return confirmWindow.didConfirm(); | public Boolean confirmSynchronize() { final ConfirmSynchronize confirmSynchronize = new ConfirmSynchronize(); openWindow(confirmSynchronize); return confirmSynchronize.didConfirm(); } |
synchronized(this) { notifyAll(); | synchronized (OpheliaJFrame.this) { OpheliaJFrame.this.notifyAll(); | public final void setVisibleAndWait() { addWindowListener(new WindowAdapter() { public void windowClosed(final WindowEvent e) { synchronized(this) { notifyAll(); } } }); try { SwingUtilities.invokeAndWait(new Runnable() { public void run() { setVisible(true); } }); } catch (final Throwable t) { throw new BrowserException( "Error opening the thinkParity Ophelia JFrame.", t); } synchronized (this) { try { wait(); } catch (final Throwable t) { throw new BrowserException( "Error opening the thinkParity Ophelia JFrame.", t); } } } |
synchronized (this) { | synchronized (OpheliaJFrame.this) { | public final void setVisibleAndWait() { addWindowListener(new WindowAdapter() { public void windowClosed(final WindowEvent e) { synchronized(this) { notifyAll(); } } }); try { SwingUtilities.invokeAndWait(new Runnable() { public void run() { setVisible(true); } }); } catch (final Throwable t) { throw new BrowserException( "Error opening the thinkParity Ophelia JFrame.", t); } synchronized (this) { try { wait(); } catch (final Throwable t) { throw new BrowserException( "Error opening the thinkParity Ophelia JFrame.", t); } } } |
wait(); | OpheliaJFrame.this.wait(); | public final void setVisibleAndWait() { addWindowListener(new WindowAdapter() { public void windowClosed(final WindowEvent e) { synchronized(this) { notifyAll(); } } }); try { SwingUtilities.invokeAndWait(new Runnable() { public void run() { setVisible(true); } }); } catch (final Throwable t) { throw new BrowserException( "Error opening the thinkParity Ophelia JFrame.", t); } synchronized (this) { try { wait(); } catch (final Throwable t) { throw new BrowserException( "Error opening the thinkParity Ophelia JFrame.", t); } } } |
data.add(new Fixture(null, documentModel, new Long(-1L))); | data.add(new Fixture(null, documentModel, -1L)); | protected void setUp() throws Exception { super.setUp(); data = new Vector<Fixture>(getInputFilesLength()); final DocumentModel documentModel = getDocumentModel(OpheliaTestUser.JUNIT); Document document; Long documentId; for(File testFile : getInputFiles()) { document = create(OpheliaTestUser.JUNIT, testFile); documentId = document.getId(); data.add(new Fixture(document, documentModel, documentId)); } // add an element where no document is found data.add(new Fixture(null, documentModel, new Long(-1L))); } |
public static final int pow (int base, int power) { return base^power; } | public static final int pow (int base, int power) { return (int)java.lang.Math.pow(base, power); } | public static final int pow (int base, int power) { return base^power; } |
getContainerModel(datum.junit_z).delete(c.getId()); | public void testRestore() { // test final Container c = createContainer(datum.junit_z, "Backup Test: Restore backup 1"); addDocument(datum.junit_z, c.getId(), "JUnitTestFramework.doc"); addDocument(datum.junit_z, c.getId(), "JUnitTestFramework.pdf"); addDocument(datum.junit_z, c.getId(), "JUnitTestFramework.png"); publishToContacts(datum.junit_z, c.getId(), "JUnit.X thinkParity"); datum.waitForEvents(); // postconditions // ensure backed up remotely final Container c_backup = getBackupModel(datum.junit_z).readContainer(c.getUniqueId()); assertNotNull("Container has not been properly backed up.", c_backup); final List<ContainerVersion> cv_list_backup = getBackupModel(datum.junit_z).readContainerVersions(c.getUniqueId()); Map<User, ArtifactReceipt> pt_backup; List<JabberId> t_id_list_backup; List<Document> d_list_backup; List<DocumentVersion> dv_list_backup; for (final ContainerVersion cv_backup : cv_list_backup) { t_id_list_backup = getBackupModel(datum.junit_z).readTeamIds(c.getUniqueId()); for (final JabberId t_id_backup : t_id_list_backup) { assertNotNull("Team member id has not been properly backed up.", t_id_backup); } pt_backup = getBackupModel(datum.junit_z).readPublishedTo(c.getUniqueId(), cv_backup.getVersionId()); for (final Entry<User, ArtifactReceipt> entry : pt_backup.entrySet()) { assertNotNull("Published to user has not been properly backed up.", entry.getKey()); assertNotNull("Published to receipt has not been properly backed up.", entry.getValue()); } d_list_backup = getBackupModel(datum.junit_z).readDocuments(c.getUniqueId(), cv_backup.getVersionId()); for (final Document d_backup : d_list_backup) { assertNotNull("Document has not been properly backed up.", d_backup); } dv_list_backup = getBackupModel(datum.junit_z).readDocumentVersions(c.getUniqueId(), cv_backup.getVersionId()); for (final DocumentVersion dv_backup : dv_list_backup) { assertNotNull("Document version has not been properly backed up.", dv_backup); } } getContainerModel(datum.junit_z).delete(c.getId()); getContainerModel(datum.junit_z).restoreBackup(); } |
|
for(final Iterator<TrayNotification> i = queue.iterator(); i.hasNext();) { notification = i.next(); sysTray.display(notification); i.remove(); | synchronized(this) { for(final Iterator<TrayNotification> i = queue.iterator(); i.hasNext();) { notification = i.next(); sysTray.display(notification); i.remove(); } | private void processQueue() { sysApp.logger.info("[LBROWSER] [APPLICATION] [SYSTEM] [PROCESS QUEUE (" + getQueueTotal() + ")]"); if(0 < getQueueTotal()) { TrayNotification notification; for(final Iterator<TrayNotification> i = queue.iterator(); i.hasNext();) { notification = i.next(); sysTray.display(notification); i.remove(); } } } |
this.listeners = new ArrayList<T>(); | protected AbstractXMPP(final XMPPCore xmppCore) { super(); this.listeners = new ArrayList<T>(); this.xmppCore = xmppCore; this.xmppEventManager = XMPPEventManager.getInstance(xmppCore); this.xstream = new XStream(); } |
|
this.xmppEventManager = XMPPEventManager.getInstance(xmppCore); | protected AbstractXMPP(final XMPPCore xmppCore) { super(); this.listeners = new ArrayList<T>(); this.xmppCore = xmppCore; this.xmppEventManager = XMPPEventManager.getInstance(xmppCore); this.xstream = new XStream(); } |
|
systemTrayIcon.addBalloonActionListener(new ActionListener() { public void actionPerformed(final ActionEvent e) { if(systemApplication.isBrowserRunning()) systemApplication.runMoveBrowserToFront(); else systemApplication.runRestoreBrowser(); } }); | public void install() { systemTrayIcon = new TrayIcon(readTrayIcon()); systemTrayIcon.addActionListener(new ActionListener() { public void actionPerformed(final ActionEvent e) { if(systemApplication.isBrowserRunning()) systemApplication.runMoveBrowserToFront(); else systemApplication.runRestoreBrowser(); } }); systemTrayIcon.setPopupMenu(menuBuilder.createPopup()); systemTrayIcon.setIconAutoSize(true); systemTray = SystemTray.getDefaultSystemTray(); systemTray.addTrayIcon(systemTrayIcon); isInstalled = Boolean.TRUE; reloadConnectionStatus(systemApplication.getConnectionStatus()); } |
|
void run() throws IOException { final HeaderReader headerReader = new HeaderReader(); final StreamHeader sessionId = headerReader.readNext(); if (null != sessionId) { final StreamSession streamSession = streamServer.authenticate(sessionId.getValue(), ((InetSocketAddress) socket.getRemoteSocketAddress()).getAddress()); final StreamHeader sessionType = headerReader.readNext(); final StreamHeader streamId = headerReader.readNext(); if(null != streamSession) { if ("UPSTREAM".equals(sessionType.getValue())) { new UpstreamHandler(streamServer, streamSession, streamId.getValue(), socket.getInputStream()).run(); } else if ("DOWNSTREAM".equals(sessionType.getValue())) { new DownstreamHandler(streamServer, streamSession, streamId.getValue(), socket.getOutputStream()).run(); } else { Assert.assertUnreachable("Unkown stream transfer."); | public void run() { try { final HeaderReader headerReader = new HeaderReader(); final StreamHeader sessionId = headerReader.readNext(); if (null != sessionId) { final StreamSession streamSession = streamServer.authenticate(sessionId.getValue(), ((InetSocketAddress) socket.getRemoteSocketAddress()).getAddress()); final StreamHeader sessionType = headerReader.readNext(); final StreamHeader streamId = headerReader.readNext(); if(null != streamSession) { if ("UPSTREAM".equals(sessionType.getValue())) { final StreamHeader streamSize = headerReader.readNext(); new UpstreamHandler(streamServer, streamSession, streamId.getValue(), Long.valueOf(streamSize.getValue()), socket.getInputStream()).run(); } else if ("DOWNSTREAM".equals(sessionType.getValue())) { new DownstreamHandler(streamServer, streamSession, streamId.getValue(), socket.getOutputStream()).run(); } else { Assert.assertUnreachable("Unkown stream transfer."); } | void run() throws IOException { final HeaderReader headerReader = new HeaderReader(); final StreamHeader sessionId = headerReader.readNext(); if (null != sessionId) { final StreamSession streamSession = streamServer.authenticate(sessionId.getValue(), ((InetSocketAddress) socket.getRemoteSocketAddress()).getAddress()); final StreamHeader sessionType = headerReader.readNext(); final StreamHeader streamId = headerReader.readNext(); if(null != streamSession) { if ("UPSTREAM".equals(sessionType.getValue())) { new UpstreamHandler(streamServer, streamSession, streamId.getValue(), socket.getInputStream()).run(); } else if ("DOWNSTREAM".equals(sessionType.getValue())) { new DownstreamHandler(streamServer, streamSession, streamId.getValue(), socket.getOutputStream()).run(); } else { Assert.assertUnreachable("Unkown stream transfer."); } } } socket.close(); } |
socket.close(); | void run() throws IOException { final HeaderReader headerReader = new HeaderReader(); final StreamHeader sessionId = headerReader.readNext(); if (null != sessionId) { final StreamSession streamSession = streamServer.authenticate(sessionId.getValue(), ((InetSocketAddress) socket.getRemoteSocketAddress()).getAddress()); final StreamHeader sessionType = headerReader.readNext(); final StreamHeader streamId = headerReader.readNext(); if(null != streamSession) { if ("UPSTREAM".equals(sessionType.getValue())) { new UpstreamHandler(streamServer, streamSession, streamId.getValue(), socket.getInputStream()).run(); } else if ("DOWNSTREAM".equals(sessionType.getValue())) { new DownstreamHandler(streamServer, streamSession, streamId.getValue(), socket.getOutputStream()).run(); } else { Assert.assertUnreachable("Unkown stream transfer."); } } } socket.close(); } |
|
Velocity.setProperty(RuntimeConstants.RUNTIME_LOG_LOGSYSTEM_CLASS, ServletLogger.class.getName()); Velocity.setApplicationAttribute(SERVLET_CONTEXT_KEY, getServletContext()); Velocity.setProperty(RuntimeConstants.RESOURCE_LOADER, "webapp"); Velocity.setProperty("webapp.resource.loader.class", WebappLoader.class.getName()); | protected void initVelocity( ServletConfig config ) throws ServletException { // Try reading Velocity configuration try { Properties p = super.loadConfiguration(config); Velocity.setExtendedProperties(ExtendedProperties.convertProperties(p)); } catch(Exception e) { getServletContext().log("Unable to read Velocity configuration file: " + e); getServletContext().log("Using default Velocity configuration."); } // define servletlogger, which logs to the servlet engines log ServletLogger sl = new ServletLogger( getServletContext() ); Velocity.setProperty( RuntimeConstants.RUNTIME_LOG_LOGSYSTEM, sl ); // load resources with webapp resource loader VelocityStrutsServletAppContext vssac = new VelocityStrutsServletAppContext( getServletContext() ); Velocity.setApplicationAttribute( "org.apache.velocity.tools.view.servlet.WebappLoader", vssac ); Velocity.setProperty( "resource.loader", "webapp" ); Velocity.setProperty( "webapp.resource.loader.class", "org.apache.velocity.tools.view.servlet.WebappLoader" ); // now all is ready - init Velocity try { Velocity.init(); } catch( Exception e ) { getServletContext().log("VELOCITY PANIC : unable to init() : " + e ); throw new ServletException ( e ); } } |
|
ServletLogger sl = new ServletLogger( getServletContext() ); Velocity.setProperty( RuntimeConstants.RUNTIME_LOG_LOGSYSTEM, sl ); VelocityStrutsServletAppContext vssac = new VelocityStrutsServletAppContext( getServletContext() ); Velocity.setApplicationAttribute( "org.apache.velocity.tools.view.servlet.WebappLoader", vssac ); Velocity.setProperty( "resource.loader", "webapp" ); Velocity.setProperty( "webapp.resource.loader.class", "org.apache.velocity.tools.view.servlet.WebappLoader" ); | protected void initVelocity( ServletConfig config ) throws ServletException { // Try reading Velocity configuration try { Properties p = super.loadConfiguration(config); Velocity.setExtendedProperties(ExtendedProperties.convertProperties(p)); } catch(Exception e) { getServletContext().log("Unable to read Velocity configuration file: " + e); getServletContext().log("Using default Velocity configuration."); } // define servletlogger, which logs to the servlet engines log ServletLogger sl = new ServletLogger( getServletContext() ); Velocity.setProperty( RuntimeConstants.RUNTIME_LOG_LOGSYSTEM, sl ); // load resources with webapp resource loader VelocityStrutsServletAppContext vssac = new VelocityStrutsServletAppContext( getServletContext() ); Velocity.setApplicationAttribute( "org.apache.velocity.tools.view.servlet.WebappLoader", vssac ); Velocity.setProperty( "resource.loader", "webapp" ); Velocity.setProperty( "webapp.resource.loader.class", "org.apache.velocity.tools.view.servlet.WebappLoader" ); // now all is ready - init Velocity try { Velocity.init(); } catch( Exception e ) { getServletContext().log("VELOCITY PANIC : unable to init() : " + e ); throw new ServletException ( e ); } } |
|
Ancestor ancestor = (Ancestor) persistenceManager.getObject(Ancestor.class,"/test"); assertTrue("Invalid object instance", ancestor instanceof Descendant ); assertEquals("Ancestor path is invalid", ancestor.getPath(), "/test"); assertEquals("Ancestor ancestorField is invalid", ancestor.getAncestorField(), "anotherAncestorValue"); | public void testRetrieveSingleton() { try { PersistenceManager persistenceManager = this.getPersistenceManager(); //--------------------------------------------------------------------------------------------------------- // Insert a descendant object //--------------------------------------------------------------------------------------------------------- Descendant descendant = new Descendant(); descendant.setDescendantField("descendantValue"); descendant.setAncestorField("ancestorValue"); descendant.setPath("/test"); persistenceManager.insert(descendant); persistenceManager.save(); //--------------------------------------------------------------------------------------------------------- // Retrieve a descendant object //--------------------------------------------------------------------------------------------------------- descendant = null; descendant = (Descendant) persistenceManager.getObject( Descendant.class, "/test"); assertEquals("Descendant path is invalid", descendant.getPath(), "/test"); assertEquals("Descendant ancestorField is invalid", descendant.getAncestorField(), "ancestorValue"); assertEquals("Descendant descendantField is invalid", descendant .getDescendantField(), "descendantValue"); //--------------------------------------------------------------------------------------------------------- // Update a descendant object //--------------------------------------------------------------------------------------------------------- descendant.setAncestorField("anotherAncestorValue"); persistenceManager.update(descendant); persistenceManager.save(); //--------------------------------------------------------------------------------------------------------- // Retrieve the updated descendant object //--------------------------------------------------------------------------------------------------------- descendant = null; descendant = (Descendant) persistenceManager.getObject( Descendant.class, "/test"); assertEquals("Descendant path is invalid", descendant.getPath(), "/test"); assertEquals("Descendant ancestorField is invalid", descendant.getAncestorField(), "anotherAncestorValue"); assertEquals("Descendant descendantField is invalid", descendant .getDescendantField(), "descendantValue");// UNCOMMENT// Ancestor ancestor = (Ancestor) persistenceManager.getObject(Ancestor.class,"/test");// assertTrue("Invalid object instance", ancestor instanceof Descendant );// assertEquals("ancestor path is invalid", ancestor.getPath(), "/test");// assertEquals("Desancestorcendant ancestorField is invalid", ancestor.getAncestorField(), "ancestorValue"); } catch (Exception e) { e.printStackTrace(); fail(); } } |
|
return new StringBuffer(PREFIX) .append(IRendererConstants.NULL) .append(IRendererConstants.SUFFIX).toString(); | return "null"; | public String doRender(Object o) { if(null == o) { return new StringBuffer(PREFIX) .append(IRendererConstants.NULL) .append(IRendererConstants.SUFFIX).toString(); } else { final Packet p = (Packet) o; return new StringBuffer(PREFIX) .append(IRendererConstants.ID).append(p.getPacketID()) .append(TO).append(p.getTo()) .append(FROM).append(p.getFrom()) .append(XML).append(p.toXML()) .append(IRendererConstants.SUFFIX) .toString(); } } |
final Packet p = (Packet) o; return new StringBuffer(PREFIX) .append(IRendererConstants.ID).append(p.getPacketID()) .append(TO).append(p.getTo()) .append(FROM).append(p.getFrom()) .append(XML).append(p.toXML()) .append(IRendererConstants.SUFFIX) .toString(); | return ((Packet) o).toXML(); | public String doRender(Object o) { if(null == o) { return new StringBuffer(PREFIX) .append(IRendererConstants.NULL) .append(IRendererConstants.SUFFIX).toString(); } else { final Packet p = (Packet) o; return new StringBuffer(PREFIX) .append(IRendererConstants.ID).append(p.getPacketID()) .append(TO).append(p.getTo()) .append(FROM).append(p.getFrom()) .append(XML).append(p.toXML()) .append(IRendererConstants.SUFFIX) .toString(); } } |
documentModel.createDraft(document.getId()); | ContainerDraft createDraft(final Long containerId) { logger.logApiId(); logger.logVariable("containerId", containerId); try { assertContainerDraftDoesNotExist(containerId); if (isFirstDraft(containerId)) { createFirstDraft(containerId, localTeamMember(containerId)); } else { final InternalArtifactModel artifactModel = getInternalArtifactModel(); assertOnline("The user is not online."); final Container container = read(containerId); if (!isDistributed(container.getId())) { createDistributed(container); } final ContainerVersion latestVersion = readLatestVersion(container.getId()); final List<Document> documents = readDocuments( latestVersion.getArtifactId(), latestVersion.getVersionId()); // create final ContainerDraft draft = new ContainerDraft(); draft.setOwner(localTeamMember(containerId)); draft.setContainerId(containerId); for (final Document document : documents) { draft.addDocument(document); draft.putState(document, ContainerDraft.ArtifactState.NONE); } containerIO.createDraft(draft); artifactModel.applyFlagKey(container.getId()); // remote create final List<JabberId> team = artifactModel.readTeamIds(containerId); team.remove(localUserId()); getSessionModel().createDraft(team, container.getUniqueId()); } // fire event final Container postCreation = read(containerId); final ContainerDraft postCreationDraft = readDraft(containerId); notifyDraftCreated(postCreation, postCreationDraft, localEventGenerator); return postCreationDraft; } catch (final Throwable t) { throw translateError(t); } } |
|
if (1 == e.getClickCount()) { if (e.getButton()==MouseEvent.BUTTON1) { if (isMouseEventWithinCell(e)) { triggerExpand(getSelectedCell()); | if (!MenuFactory.isPopupMenu()) { if (1 == e.getClickCount()) { if (e.getButton()==MouseEvent.BUTTON1) { if (isMouseEventWithinCell(e)) { triggerExpand(getSelectedCell()); } | private void tabJListMouseClicked(java.awt.event.MouseEvent e) {//GEN-FIRST:event_tabJListMouseClicked if (1 == e.getClickCount()) { if (e.getButton()==MouseEvent.BUTTON1) { if (isMouseEventWithinCell(e)) { triggerExpand(getSelectedCell()); } } } else if (2 == e.getClickCount()) { if (isMouseEventWithinCell(e)) { triggerDoubleClick(getSelectedCell()); } else { triggerDoubleClick(); } } }//GEN-LAST:event_tabJListMouseClicked |
} } else if (2 == e.getClickCount()) { if (isMouseEventWithinCell(e)) { triggerDoubleClick(getSelectedCell()); } else { triggerDoubleClick(); | } else if (2 == e.getClickCount()) { if (isMouseEventWithinCell(e)) { triggerDoubleClick(getSelectedCell()); } else { triggerDoubleClick(); } | private void tabJListMouseClicked(java.awt.event.MouseEvent e) {//GEN-FIRST:event_tabJListMouseClicked if (1 == e.getClickCount()) { if (e.getButton()==MouseEvent.BUTTON1) { if (isMouseEventWithinCell(e)) { triggerExpand(getSelectedCell()); } } } else if (2 == e.getClickCount()) { if (isMouseEventWithinCell(e)) { triggerDoubleClick(getSelectedCell()); } else { triggerDoubleClick(); } } }//GEN-LAST:event_tabJListMouseClicked |
if(e.isPopupTrigger()) { | if (!MenuFactory.isPopupMenu() && e.isPopupTrigger()) { | private void tabJListMouseReleased(java.awt.event.MouseEvent e) {//GEN-FIRST:event_tabJListMouseReleased if(e.isPopupTrigger()) { // Desired behavior: if click on an entry in the list then trigger a popup for that entry. // If click in the blank area below the last entry in the list then trigger a popup that // allows the user to create a container. // If there are no containers then expect getSelectedIndex() to return -1. // If there are 1 or more containers and the user clicks below the final entry then expect // locationToIndex() to return the last entry. if (isMouseEventWithinCell(e)) { setSelectedIndex(tabJList.locationToIndex(e.getPoint())); triggerPopup(getSelectedCell(), e); } else { triggerPopup(tabJList, e); } } }//GEN-LAST:event_tabJListMouseReleased |
addContainerPanel(containerPanels.size() == 0 ? 0 : containerPanels .size() - 1, container); | addContainerPanel(panels.size() == 0 ? 0 : panels.size() - 1, container); | private void addContainerPanel(final Container container) { addContainerPanel(containerPanels.size() == 0 ? 0 : containerPanels .size() - 1, container); } |
this.searchResults = readSearchResults(); | applySearchResults(); | public void applySearch(final String searchExpression) { debug(); if (searchExpression.equals(this.searchExpression)) { return; } else { this.searchExpression = searchExpression; this.searchResults = readSearchResults(); synchronize(); } } |
containerPanels.clear(); | panels.clear(); | private void clearPanels() { containerPanels.clear(); } |
logger.logDebug("{0} container panels.", containerPanels.size()); | logger.logDebug("{0} container panels.", panels.size()); | public void debug() { logger.logDebug("{0} container panels.", containerPanels.size()); logger.logDebug("{0} visible panels.", visiblePanels.size()); for (final TabPanel visiblePanel : visiblePanels) { logger.logVariable("visiblePanel.getId()", visiblePanel.getId()); } logger.logDebug("{0} model elements.", listModel.size()); final TabPanel[] listModelPanels = new TabPanel[listModel.size()]; listModel.copyInto(listModelPanels); for (final TabPanel listModelPanel : listModelPanels) { logger.logVariable("listModelPanel.getId()", listModelPanel.getId()); } } |
for (int i = 0; i < containerPanels.size(); i++) if (((ContainerPanel) containerPanels.get(i)).getContainer() | for (int i = 0; i < panels.size(); i++) if (((ContainerPanel) panels.get(i)).getContainer() | private int lookupIndex(final Long containerId) { for (int i = 0; i < containerPanels.size(); i++) if (((ContainerPanel) containerPanels.get(i)).getContainer() .getId().equals(containerId)) return i; return -1; } |
final TabPanel containerPanel = containerPanels.remove(panelIndex); | final TabPanel containerPanel = panels.remove(panelIndex); | private void removeContainerPanel(final Long containerId, final boolean removeExpandedState) { Long lookupContainerId; for (final Iterator<Long> iLookupValues = containerIdLookup.values().iterator(); iLookupValues.hasNext(); ) { lookupContainerId = iLookupValues.next(); if (lookupContainerId.equals(containerId)) { iLookupValues.remove(); } } final int panelIndex = lookupIndex(containerId); if (removeExpandedState) { final TabPanel containerPanel = containerPanels.remove(panelIndex); expandedState.remove(containerPanel); } else { containerPanels.remove(panelIndex); } } |
containerPanels.remove(panelIndex); | panels.remove(panelIndex); | private void removeContainerPanel(final Long containerId, final boolean removeExpandedState) { Long lookupContainerId; for (final Iterator<Long> iLookupValues = containerIdLookup.values().iterator(); iLookupValues.hasNext(); ) { lookupContainerId = iLookupValues.next(); if (lookupContainerId.equals(containerId)) { iLookupValues.remove(); } } final int panelIndex = lookupIndex(containerId); if (removeExpandedState) { final TabPanel containerPanel = containerPanels.remove(panelIndex); expandedState.remove(containerPanel); } else { containerPanels.remove(panelIndex); } } |
searchResults = null; | searchResults.clear(); | public void removeSearch() { debug(); // if the member search expression is already null; then there is no // search applied -> do nothing if (null == searchExpression) { return; } else { searchExpression = null; searchResults = null; synchronize(); } } |
applyFilters(); | protected void synchronize() { debug(); /* add container panels and container version panels to the visibility list */ visiblePanels.clear(); for (final TabPanel containerPanel : containerPanels) { visiblePanels.add(containerPanel); } // add newly visible panels to the model; and set other panels int listModelIndex; for (int i = 0; i < visiblePanels.size(); i++) { if (listModel.contains(visiblePanels.get(i))) { listModelIndex = listModel.indexOf(visiblePanels.get(i)); /* the position of the panel in the model is identical to that * of the panel the list */ if (i == listModelIndex) { listModel.set(i, visiblePanels.get(i)); } else { listModel.remove(listModelIndex); listModel.add(i, visiblePanels.get(i)); } } else { listModel.add(i, visiblePanels.get(i)); } } // prune newly invisible panels from the model final TabPanel[] invisiblePanels = new TabPanel[listModel.size()]; listModel.copyInto(invisiblePanels); for (int i = 0; i < invisiblePanels.length; i++) { if (!visiblePanels.contains(invisiblePanels[i])) { listModel.removeElement(invisiblePanels[i]); } } debug(); } |
|
for (final TabPanel containerPanel : containerPanels) { visiblePanels.add(containerPanel); | for (final TabPanel panel : filteredPanels) { visiblePanels.add(panel); | protected void synchronize() { debug(); /* add container panels and container version panels to the visibility list */ visiblePanels.clear(); for (final TabPanel containerPanel : containerPanels) { visiblePanels.add(containerPanel); } // add newly visible panels to the model; and set other panels int listModelIndex; for (int i = 0; i < visiblePanels.size(); i++) { if (listModel.contains(visiblePanels.get(i))) { listModelIndex = listModel.indexOf(visiblePanels.get(i)); /* the position of the panel in the model is identical to that * of the panel the list */ if (i == listModelIndex) { listModel.set(i, visiblePanels.get(i)); } else { listModel.remove(listModelIndex); listModel.add(i, visiblePanels.get(i)); } } else { listModel.add(i, visiblePanels.get(i)); } } // prune newly invisible panels from the model final TabPanel[] invisiblePanels = new TabPanel[listModel.size()]; listModel.copyInto(invisiblePanels); for (int i = 0; i < invisiblePanels.length; i++) { if (!visiblePanels.contains(invisiblePanels[i])) { listModel.removeElement(invisiblePanels[i]); } } debug(); } |
mainCellDocument.setExpanded(documents.get(index).isExpanded()); | private void syncDocumentInternal(final Long documentId, final Boolean remote) { final MainCellDocument mainCellDocument = readDocument(documentId); // if the document is null; we can assume the document has been // deleted (it's not longer being created by the provider); so we find // the document and remove it if(null == mainCellDocument) { for(int i = 0; i < documents.size(); i++) { if(documents.get(i).getId().equals(documentId)) { documents.remove(i); break; } } final MainCellDocument[] historyKeys = (MainCellDocument[]) documentHistory.keySet().toArray(new MainCellDocument[] {}); for(int i = 0; i < historyKeys.length; i++) { if(historyKeys[i].getId().equals(documentId)) { documentHistory.remove(historyKeys[i]); break; } } } // the document is not null; therefore it is either new; or updated else { // the document is new if(!documents.contains(mainCellDocument)) { documents.add(0, mainCellDocument); documentHistory.put(mainCellDocument, readHistory(mainCellDocument)); } // the document has been updated else { final int index = documents.indexOf(mainCellDocument); documents.remove(index); // if the reload is the result of a remote event add the document // at the top of the list; otherwise add it in the same location // it previously existed if(remote) { documents.add(0, mainCellDocument); } else { documents.add(index, mainCellDocument); } documentHistory.put(mainCellDocument, readHistory(mainCellDocument)); dirtyCells.add(mainCellDocument); dirtyCells.addAll(documentHistory.get(mainCellDocument)); } } } |
|
case KEY_RESPONSE_DENIED: return extractKeyResponseDenied(session); case KEY_REQUEST_DENIED: return extractKeyRequestDenied(session); | private AuditEvent extract(final Session session) { final AuditEventType eventType = session.getAuditEventTypeFromInteger("ARTIFACT_AUDIT_TYPE_ID"); switch(eventType) { case ARCHIVE: return extractArchive(session); case CLOSE: return extractClose(session); case CREATE: return extractCreate(session); case RECEIVE: return extractReceive(session); case RECEIVE_KEY: return extractReceiveKey(session); case REQUEST_KEY: return extractRequestKey(session); case SEND: return extractSend(session); case SEND_KEY: return extractSendKey(session); default: throw Assert.createUnreachable("Unknown event type: " + eventType); } } |
|
final StreamSession streamSession) { | final StreamSession streamSession, final Long streamSize) { | private Fixture(final InputStream stream, final String streamId, final StreamSession streamSession) { super(); this.stream = stream; this.streamId = streamId; this.streamSession = streamSession; } |
this.streamSize = streamSize; | private Fixture(final InputStream stream, final String streamId, final StreamSession streamSession) { super(); this.stream = stream; this.streamId = streamId; this.streamSession = streamSession; } |
|
datum = new Fixture(stream, streamId, session); | datum = new Fixture(stream, streamId, session, streamFile.length()); | protected void setUp() throws Exception { super.setUp(); final File workingDirectory = new File(getOutputDirectory(), "working"); Assert.assertTrue(workingDirectory.mkdir(), "Could not create directory {0}.", workingDirectory); final File streamFile = getInputFiles()[3]; final StreamServer server = startStreamServer(DesdemonaTestUser.JUNIT, workingDirectory); final StreamSession session = createSession(DesdemonaTestUser.JUNIT, server); final String streamId = createStream(server, session, streamFile.getName()); final InputStream stream = new FileInputStream(streamFile); datum = new Fixture(stream, streamId, session); } |
writer.write(datum.streamId, datum.stream); | writer.write(datum.streamId, datum.stream, datum.streamSize); } catch (final IOException iox) { fail(createFailMessage(iox)); | public void testWriter() { final StreamWriter writer = new StreamWriter(datum.streamSession); try { writer.open(); writer.write(datum.streamId, datum.stream); } finally { writer.close(); } } |
writer.close(); | try { datum.stream.close(); writer.close(); } catch (final IOException iox2) { fail(createFailMessage(iox2)); } | public void testWriter() { final StreamWriter writer = new StreamWriter(datum.streamSession); try { writer.open(); writer.write(datum.streamId, datum.stream); } finally { writer.close(); } } |
this(workspace, null); | super(); this.context = new Context(getClass()); this.l18n = new Localization(LocalizationContext.MODEL); this.logger = LoggerFactory.getLogger(getClass()); this.workspace = workspace; this.preferences = (null == workspace ? null : workspace.getPreferences()); | protected AbstractModelImpl(final Workspace workspace) { this(workspace, null); } |
public BooleanTypeConverterImpl(ValueFactory factory) { super(factory); } | public BooleanTypeConverterImpl() { super(); } | public BooleanTypeConverterImpl(ValueFactory factory) { super(factory); } |
System.out.println("Creating connection with Psyclone at " + hostname + ":" + port + " with service name " + plugname); | public void connect(String plugname, String hostname, Integer port) { plug = new JavaAIRPlug(plugname, hostname, port); } |
|
callback.airBrushReceiveMessage(message); | if (!callback.airBrushReceiveMessage(message)) { System.out.println("Note: Unhandled callback for: " + message.type + " to: " + message.to); } | public void run() { Message message; while (Thread.currentThread() == thread) { if ((message = plug.waitForNewMessage(100)) != null) { callback.airBrushReceiveMessage(message); } } } |
if(DEBUG) verbose = true; | if(debug) verbose = true; | public static void notmain(String[] args) throws Exception { 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[] inBuffer = new byte[0x40000]; byte[] outBuffer = 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 elementNumber = 0; //long lastOffs = 0; long lastOutOffset = 0; long lastInOffset = 0; long totalSize = 0; int errorsReported = 0; int warningsReported = 0; 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; 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 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) { if(DEBUG) println("!-----addInOffset mode: inOffset tranformation " + inOffset + "->" + (inOffset+lastInOffset)); inOffset += lastInOffset; } else if(inOffset == 0) { if(DEBUG) println("!-----Detected inOffset == 0, setting to " + lastInOffset); addInOffset = true; inOffset = lastInOffset; } outOffset += lastOutOffset; DMGBlock currentBlock = new DMGBlock(blockType, skipped, outOffset, outSize, inOffset, inSize); blocks.add(currentBlock); if(DEBUG) { println("outOffset=" + outOffset + " outSize=" + outSize + " inOffset=" + inOffset + " inSize=" + inSize + " lastOutOffset=" + lastOutOffset + " lastInOffset=" + lastInOffset /*+ " lastInOffs=" + lastInOffs + " lastOffs=" + lastOffs*/); } if(blockType == BT_ADC) { println(" " + elementNumber + ":" + blockCount + ". ERROR: BT_ADC not supported."); ++errorsReported; if(!testOnly) System.exit(0); } else if(blockType == BT_ZLIB) { if(DEBUG) println(" " + elementNumber + ":" + blockCount + ". BT_ZLIB processing..."); if(!testOnly && isoRaf.getFilePointer() != outOffset) println(" " + elementNumber + ":" + blockCount + ". WARNING: BT_ZLIB FP != outOffset (" + isoRaf.getFilePointer() + " != " + outOffset + ")"); try { DMGBlockHandlers.processZlibBlock(currentBlock, dmgRaf, isoRaf, testOnly, dummyMonitor); } catch(DataFormatException dfe) { println(" " + elementNumber + ":" + blockCount + ". ERROR: BT_ZLIB Could not decode..."); ++errorsReported; 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); break; } } } else if(blockType == BT_BZIP2) { println(" " + elementNumber + ":" + blockCount + ". ERROR: BT_BZIP2 not currently supported."); ++errorsReported; if(!testOnly) System.exit(0); } else if(blockType == BT_COPY) { if(DEBUG) println(" " + elementNumber + ":" + blockCount + ". BT_COPY processing..."); if(!testOnly && isoRaf.getFilePointer() != outOffset) { println(" " + elementNumber + ":" + blockCount + ". WARNING: BT_COPY FP != outOffset (" + isoRaf.getFilePointer() + " != " + outOffset + ")"); ++warningsReported; } dmgRaf.seek(/*lastOffs+*/inOffset); int bytesRead = dmgRaf.read(inBuffer, 0, Math.min((int)inSize, inBuffer.length)); long totalBytesRead = bytesRead; while(bytesRead != -1) { reportFilePointerProgress(dmgRaf); if(!testOnly) isoRaf.write(inBuffer, 0, bytesRead); if(totalBytesRead >= inSize) break; bytesRead = dmgRaf.read(inBuffer, 0, Math.min((int)(inSize-totalBytesRead), inBuffer.length)); if(bytesRead > 0) totalBytesRead += bytesRead; } //lastInOffs = inOffset+inSize; } else if(blockType == BT_ZERO) { if(DEBUG) println(" " + elementNumber + ":" + blockCount + ". BT_ZERO processing..."); if(!testOnly && isoRaf.getFilePointer() != outOffset) { println(" " + elementNumber + ":" + blockCount + ". WARNING: BT_ZERO FP != outOffset (" + isoRaf.getFilePointer() + " != " + outOffset + ")"); ++warningsReported; } reportFilePointerProgress(dmgRaf); 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_ZERO2) { if(DEBUG) println(" " + elementNumber + ":" + blockCount + ". BT_ZERO2 processing..."); if(!testOnly && isoRaf.getFilePointer() != outOffset) { println(" " + elementNumber + ":" + blockCount + ". WARNING: BT_ZERO2 FP != outOffset (" + isoRaf.getFilePointer() + " != " + outOffset + ")"); ++warningsReported; } reportFilePointerProgress(dmgRaf); 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(" " + elementNumber + ":" + blockCount + ". BT_UNKNOWN processing..."); if(!(inSize == 0 && outSize == 0)) { println(" " + elementNumber + ":" + blockCount + ". WARNING: Blocktype BT_UNKNOWN had non-zero sizes...", " inSize=" + inSize + ", outSize=" + outSize); ++warningsReported; //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(" " + elementNumber + ":" + blockCount + ". BT_END processing..."); if(!testOnly && isoRaf.getFilePointer() != outOffset) println(" " + elementNumber + ":" + blockCount + ". WARNING: BT_END FP != outOffset (" + isoRaf.getFilePointer() + " != " + outOffset + ")"); //lastOffs += lastInOffs; lastOutOffset = outOffset; lastInOffset += lastByteReadInBlock; } else { println(" " + elementNumber + ":" + blockCount + ". WARNING: previously unseen blocktype " + blockType + " [0x" + Integer.toHexString(blockType) + "]", " " + elementNumber + ":" + blockCount + ". outOffset=" + outOffset + " outSize=" + outSize + " inOffset=" + inOffset + " inSize=" + inSize); ++warningsReported; if(!testOnly && isoRaf.getFilePointer() != outOffset) println(" " + elementNumber + ":" + blockCount + ". unknown blocktype FP != outOffset (" + isoRaf.getFilePointer() + " != " + outOffset + ")"); } offset += 0x28; ++blockCount; } } ++elementNumber; } //printlnVerbose("Progress: 100% Done!"); reportProgress(100); String summary = (errorsReported != 0)?errorsReported+" errors reported":"No errors reported"; summary += (warningsReported != 0)?" ("+warningsReported+" warnings emitted).":"."; if(!graphical) { newline(); println(summary); printlnVerbose("Total extracted bytes: " + totalSize + " B"); } else { progmon.close(); JOptionPane.showMessageDialog(null, "Extraction complete! " + summary + "\n" + "Total extracted bytes: " + totalSize + " B", "Information", JOptionPane.INFORMATION_MESSAGE); System.exit(0); } if(!DEBUG) { if(isoRaf != null) isoRaf.close(); dmgRaf.close(); } else { if(isoRaf != null) isoRaf.close();// 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()); 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"; println(" " + new File(filename).getCanonicalPath() + "..."); 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"; println(" " + new File(filename).getCanonicalPath() + "..."); 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"; println(" " + new File(filename).getCanonicalPath() + "..."); 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!"); } } |
if(DEBUG) { | if(debug) { | public static void notmain(String[] args) throws Exception { 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[] inBuffer = new byte[0x40000]; byte[] outBuffer = 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 elementNumber = 0; //long lastOffs = 0; long lastOutOffset = 0; long lastInOffset = 0; long totalSize = 0; int errorsReported = 0; int warningsReported = 0; 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; 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 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) { if(DEBUG) println("!-----addInOffset mode: inOffset tranformation " + inOffset + "->" + (inOffset+lastInOffset)); inOffset += lastInOffset; } else if(inOffset == 0) { if(DEBUG) println("!-----Detected inOffset == 0, setting to " + lastInOffset); addInOffset = true; inOffset = lastInOffset; } outOffset += lastOutOffset; DMGBlock currentBlock = new DMGBlock(blockType, skipped, outOffset, outSize, inOffset, inSize); blocks.add(currentBlock); if(DEBUG) { println("outOffset=" + outOffset + " outSize=" + outSize + " inOffset=" + inOffset + " inSize=" + inSize + " lastOutOffset=" + lastOutOffset + " lastInOffset=" + lastInOffset /*+ " lastInOffs=" + lastInOffs + " lastOffs=" + lastOffs*/); } if(blockType == BT_ADC) { println(" " + elementNumber + ":" + blockCount + ". ERROR: BT_ADC not supported."); ++errorsReported; if(!testOnly) System.exit(0); } else if(blockType == BT_ZLIB) { if(DEBUG) println(" " + elementNumber + ":" + blockCount + ". BT_ZLIB processing..."); if(!testOnly && isoRaf.getFilePointer() != outOffset) println(" " + elementNumber + ":" + blockCount + ". WARNING: BT_ZLIB FP != outOffset (" + isoRaf.getFilePointer() + " != " + outOffset + ")"); try { DMGBlockHandlers.processZlibBlock(currentBlock, dmgRaf, isoRaf, testOnly, dummyMonitor); } catch(DataFormatException dfe) { println(" " + elementNumber + ":" + blockCount + ". ERROR: BT_ZLIB Could not decode..."); ++errorsReported; 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); break; } } } else if(blockType == BT_BZIP2) { println(" " + elementNumber + ":" + blockCount + ". ERROR: BT_BZIP2 not currently supported."); ++errorsReported; if(!testOnly) System.exit(0); } else if(blockType == BT_COPY) { if(DEBUG) println(" " + elementNumber + ":" + blockCount + ". BT_COPY processing..."); if(!testOnly && isoRaf.getFilePointer() != outOffset) { println(" " + elementNumber + ":" + blockCount + ". WARNING: BT_COPY FP != outOffset (" + isoRaf.getFilePointer() + " != " + outOffset + ")"); ++warningsReported; } dmgRaf.seek(/*lastOffs+*/inOffset); int bytesRead = dmgRaf.read(inBuffer, 0, Math.min((int)inSize, inBuffer.length)); long totalBytesRead = bytesRead; while(bytesRead != -1) { reportFilePointerProgress(dmgRaf); if(!testOnly) isoRaf.write(inBuffer, 0, bytesRead); if(totalBytesRead >= inSize) break; bytesRead = dmgRaf.read(inBuffer, 0, Math.min((int)(inSize-totalBytesRead), inBuffer.length)); if(bytesRead > 0) totalBytesRead += bytesRead; } //lastInOffs = inOffset+inSize; } else if(blockType == BT_ZERO) { if(DEBUG) println(" " + elementNumber + ":" + blockCount + ". BT_ZERO processing..."); if(!testOnly && isoRaf.getFilePointer() != outOffset) { println(" " + elementNumber + ":" + blockCount + ". WARNING: BT_ZERO FP != outOffset (" + isoRaf.getFilePointer() + " != " + outOffset + ")"); ++warningsReported; } reportFilePointerProgress(dmgRaf); 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_ZERO2) { if(DEBUG) println(" " + elementNumber + ":" + blockCount + ". BT_ZERO2 processing..."); if(!testOnly && isoRaf.getFilePointer() != outOffset) { println(" " + elementNumber + ":" + blockCount + ". WARNING: BT_ZERO2 FP != outOffset (" + isoRaf.getFilePointer() + " != " + outOffset + ")"); ++warningsReported; } reportFilePointerProgress(dmgRaf); 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(" " + elementNumber + ":" + blockCount + ". BT_UNKNOWN processing..."); if(!(inSize == 0 && outSize == 0)) { println(" " + elementNumber + ":" + blockCount + ". WARNING: Blocktype BT_UNKNOWN had non-zero sizes...", " inSize=" + inSize + ", outSize=" + outSize); ++warningsReported; //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(" " + elementNumber + ":" + blockCount + ". BT_END processing..."); if(!testOnly && isoRaf.getFilePointer() != outOffset) println(" " + elementNumber + ":" + blockCount + ". WARNING: BT_END FP != outOffset (" + isoRaf.getFilePointer() + " != " + outOffset + ")"); //lastOffs += lastInOffs; lastOutOffset = outOffset; lastInOffset += lastByteReadInBlock; } else { println(" " + elementNumber + ":" + blockCount + ". WARNING: previously unseen blocktype " + blockType + " [0x" + Integer.toHexString(blockType) + "]", " " + elementNumber + ":" + blockCount + ". outOffset=" + outOffset + " outSize=" + outSize + " inOffset=" + inOffset + " inSize=" + inSize); ++warningsReported; if(!testOnly && isoRaf.getFilePointer() != outOffset) println(" " + elementNumber + ":" + blockCount + ". unknown blocktype FP != outOffset (" + isoRaf.getFilePointer() + " != " + outOffset + ")"); } offset += 0x28; ++blockCount; } } ++elementNumber; } //printlnVerbose("Progress: 100% Done!"); reportProgress(100); String summary = (errorsReported != 0)?errorsReported+" errors reported":"No errors reported"; summary += (warningsReported != 0)?" ("+warningsReported+" warnings emitted).":"."; if(!graphical) { newline(); println(summary); printlnVerbose("Total extracted bytes: " + totalSize + " B"); } else { progmon.close(); JOptionPane.showMessageDialog(null, "Extraction complete! " + summary + "\n" + "Total extracted bytes: " + totalSize + " B", "Information", JOptionPane.INFORMATION_MESSAGE); System.exit(0); } if(!DEBUG) { if(isoRaf != null) isoRaf.close(); dmgRaf.close(); } else { if(isoRaf != null) isoRaf.close();// 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()); 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"; println(" " + new File(filename).getCanonicalPath() + "..."); 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"; println(" " + new File(filename).getCanonicalPath() + "..."); 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"; println(" " + new File(filename).getCanonicalPath() + "..."); 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!"); } } |
println("Addresses not equal! Assumption broken... =/", | println("ERROR: Addresses not equal! Assumption false.", | public static void notmain(String[] args) throws Exception { 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[] inBuffer = new byte[0x40000]; byte[] outBuffer = 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 elementNumber = 0; //long lastOffs = 0; long lastOutOffset = 0; long lastInOffset = 0; long totalSize = 0; int errorsReported = 0; int warningsReported = 0; 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; 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 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) { if(DEBUG) println("!-----addInOffset mode: inOffset tranformation " + inOffset + "->" + (inOffset+lastInOffset)); inOffset += lastInOffset; } else if(inOffset == 0) { if(DEBUG) println("!-----Detected inOffset == 0, setting to " + lastInOffset); addInOffset = true; inOffset = lastInOffset; } outOffset += lastOutOffset; DMGBlock currentBlock = new DMGBlock(blockType, skipped, outOffset, outSize, inOffset, inSize); blocks.add(currentBlock); if(DEBUG) { println("outOffset=" + outOffset + " outSize=" + outSize + " inOffset=" + inOffset + " inSize=" + inSize + " lastOutOffset=" + lastOutOffset + " lastInOffset=" + lastInOffset /*+ " lastInOffs=" + lastInOffs + " lastOffs=" + lastOffs*/); } if(blockType == BT_ADC) { println(" " + elementNumber + ":" + blockCount + ". ERROR: BT_ADC not supported."); ++errorsReported; if(!testOnly) System.exit(0); } else if(blockType == BT_ZLIB) { if(DEBUG) println(" " + elementNumber + ":" + blockCount + ". BT_ZLIB processing..."); if(!testOnly && isoRaf.getFilePointer() != outOffset) println(" " + elementNumber + ":" + blockCount + ". WARNING: BT_ZLIB FP != outOffset (" + isoRaf.getFilePointer() + " != " + outOffset + ")"); try { DMGBlockHandlers.processZlibBlock(currentBlock, dmgRaf, isoRaf, testOnly, dummyMonitor); } catch(DataFormatException dfe) { println(" " + elementNumber + ":" + blockCount + ". ERROR: BT_ZLIB Could not decode..."); ++errorsReported; 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); break; } } } else if(blockType == BT_BZIP2) { println(" " + elementNumber + ":" + blockCount + ". ERROR: BT_BZIP2 not currently supported."); ++errorsReported; if(!testOnly) System.exit(0); } else if(blockType == BT_COPY) { if(DEBUG) println(" " + elementNumber + ":" + blockCount + ". BT_COPY processing..."); if(!testOnly && isoRaf.getFilePointer() != outOffset) { println(" " + elementNumber + ":" + blockCount + ". WARNING: BT_COPY FP != outOffset (" + isoRaf.getFilePointer() + " != " + outOffset + ")"); ++warningsReported; } dmgRaf.seek(/*lastOffs+*/inOffset); int bytesRead = dmgRaf.read(inBuffer, 0, Math.min((int)inSize, inBuffer.length)); long totalBytesRead = bytesRead; while(bytesRead != -1) { reportFilePointerProgress(dmgRaf); if(!testOnly) isoRaf.write(inBuffer, 0, bytesRead); if(totalBytesRead >= inSize) break; bytesRead = dmgRaf.read(inBuffer, 0, Math.min((int)(inSize-totalBytesRead), inBuffer.length)); if(bytesRead > 0) totalBytesRead += bytesRead; } //lastInOffs = inOffset+inSize; } else if(blockType == BT_ZERO) { if(DEBUG) println(" " + elementNumber + ":" + blockCount + ". BT_ZERO processing..."); if(!testOnly && isoRaf.getFilePointer() != outOffset) { println(" " + elementNumber + ":" + blockCount + ". WARNING: BT_ZERO FP != outOffset (" + isoRaf.getFilePointer() + " != " + outOffset + ")"); ++warningsReported; } reportFilePointerProgress(dmgRaf); 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_ZERO2) { if(DEBUG) println(" " + elementNumber + ":" + blockCount + ". BT_ZERO2 processing..."); if(!testOnly && isoRaf.getFilePointer() != outOffset) { println(" " + elementNumber + ":" + blockCount + ". WARNING: BT_ZERO2 FP != outOffset (" + isoRaf.getFilePointer() + " != " + outOffset + ")"); ++warningsReported; } reportFilePointerProgress(dmgRaf); 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(" " + elementNumber + ":" + blockCount + ". BT_UNKNOWN processing..."); if(!(inSize == 0 && outSize == 0)) { println(" " + elementNumber + ":" + blockCount + ". WARNING: Blocktype BT_UNKNOWN had non-zero sizes...", " inSize=" + inSize + ", outSize=" + outSize); ++warningsReported; //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(" " + elementNumber + ":" + blockCount + ". BT_END processing..."); if(!testOnly && isoRaf.getFilePointer() != outOffset) println(" " + elementNumber + ":" + blockCount + ". WARNING: BT_END FP != outOffset (" + isoRaf.getFilePointer() + " != " + outOffset + ")"); //lastOffs += lastInOffs; lastOutOffset = outOffset; lastInOffset += lastByteReadInBlock; } else { println(" " + elementNumber + ":" + blockCount + ". WARNING: previously unseen blocktype " + blockType + " [0x" + Integer.toHexString(blockType) + "]", " " + elementNumber + ":" + blockCount + ". outOffset=" + outOffset + " outSize=" + outSize + " inOffset=" + inOffset + " inSize=" + inSize); ++warningsReported; if(!testOnly && isoRaf.getFilePointer() != outOffset) println(" " + elementNumber + ":" + blockCount + ". unknown blocktype FP != outOffset (" + isoRaf.getFilePointer() + " != " + outOffset + ")"); } offset += 0x28; ++blockCount; } } ++elementNumber; } //printlnVerbose("Progress: 100% Done!"); reportProgress(100); String summary = (errorsReported != 0)?errorsReported+" errors reported":"No errors reported"; summary += (warningsReported != 0)?" ("+warningsReported+" warnings emitted).":"."; if(!graphical) { newline(); println(summary); printlnVerbose("Total extracted bytes: " + totalSize + " B"); } else { progmon.close(); JOptionPane.showMessageDialog(null, "Extraction complete! " + summary + "\n" + "Total extracted bytes: " + totalSize + " B", "Information", JOptionPane.INFORMATION_MESSAGE); System.exit(0); } if(!DEBUG) { if(isoRaf != null) isoRaf.close(); dmgRaf.close(); } else { if(isoRaf != null) isoRaf.close();// 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()); 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"; println(" " + new File(filename).getCanonicalPath() + "..."); 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"; println(" " + new File(filename).getCanonicalPath() + "..."); 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"; println(" " + new File(filename).getCanonicalPath() + "..."); 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!"); } } |
println("plistSize field does not match plistEnd marker!", | println("NOTE: plistSize field does not match plistEnd marker. Assumption false.", | public static void notmain(String[] args) throws Exception { 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[] inBuffer = new byte[0x40000]; byte[] outBuffer = 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 elementNumber = 0; //long lastOffs = 0; long lastOutOffset = 0; long lastInOffset = 0; long totalSize = 0; int errorsReported = 0; int warningsReported = 0; 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; 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 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) { if(DEBUG) println("!-----addInOffset mode: inOffset tranformation " + inOffset + "->" + (inOffset+lastInOffset)); inOffset += lastInOffset; } else if(inOffset == 0) { if(DEBUG) println("!-----Detected inOffset == 0, setting to " + lastInOffset); addInOffset = true; inOffset = lastInOffset; } outOffset += lastOutOffset; DMGBlock currentBlock = new DMGBlock(blockType, skipped, outOffset, outSize, inOffset, inSize); blocks.add(currentBlock); if(DEBUG) { println("outOffset=" + outOffset + " outSize=" + outSize + " inOffset=" + inOffset + " inSize=" + inSize + " lastOutOffset=" + lastOutOffset + " lastInOffset=" + lastInOffset /*+ " lastInOffs=" + lastInOffs + " lastOffs=" + lastOffs*/); } if(blockType == BT_ADC) { println(" " + elementNumber + ":" + blockCount + ". ERROR: BT_ADC not supported."); ++errorsReported; if(!testOnly) System.exit(0); } else if(blockType == BT_ZLIB) { if(DEBUG) println(" " + elementNumber + ":" + blockCount + ". BT_ZLIB processing..."); if(!testOnly && isoRaf.getFilePointer() != outOffset) println(" " + elementNumber + ":" + blockCount + ". WARNING: BT_ZLIB FP != outOffset (" + isoRaf.getFilePointer() + " != " + outOffset + ")"); try { DMGBlockHandlers.processZlibBlock(currentBlock, dmgRaf, isoRaf, testOnly, dummyMonitor); } catch(DataFormatException dfe) { println(" " + elementNumber + ":" + blockCount + ". ERROR: BT_ZLIB Could not decode..."); ++errorsReported; 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); break; } } } else if(blockType == BT_BZIP2) { println(" " + elementNumber + ":" + blockCount + ". ERROR: BT_BZIP2 not currently supported."); ++errorsReported; if(!testOnly) System.exit(0); } else if(blockType == BT_COPY) { if(DEBUG) println(" " + elementNumber + ":" + blockCount + ". BT_COPY processing..."); if(!testOnly && isoRaf.getFilePointer() != outOffset) { println(" " + elementNumber + ":" + blockCount + ". WARNING: BT_COPY FP != outOffset (" + isoRaf.getFilePointer() + " != " + outOffset + ")"); ++warningsReported; } dmgRaf.seek(/*lastOffs+*/inOffset); int bytesRead = dmgRaf.read(inBuffer, 0, Math.min((int)inSize, inBuffer.length)); long totalBytesRead = bytesRead; while(bytesRead != -1) { reportFilePointerProgress(dmgRaf); if(!testOnly) isoRaf.write(inBuffer, 0, bytesRead); if(totalBytesRead >= inSize) break; bytesRead = dmgRaf.read(inBuffer, 0, Math.min((int)(inSize-totalBytesRead), inBuffer.length)); if(bytesRead > 0) totalBytesRead += bytesRead; } //lastInOffs = inOffset+inSize; } else if(blockType == BT_ZERO) { if(DEBUG) println(" " + elementNumber + ":" + blockCount + ". BT_ZERO processing..."); if(!testOnly && isoRaf.getFilePointer() != outOffset) { println(" " + elementNumber + ":" + blockCount + ". WARNING: BT_ZERO FP != outOffset (" + isoRaf.getFilePointer() + " != " + outOffset + ")"); ++warningsReported; } reportFilePointerProgress(dmgRaf); 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_ZERO2) { if(DEBUG) println(" " + elementNumber + ":" + blockCount + ". BT_ZERO2 processing..."); if(!testOnly && isoRaf.getFilePointer() != outOffset) { println(" " + elementNumber + ":" + blockCount + ". WARNING: BT_ZERO2 FP != outOffset (" + isoRaf.getFilePointer() + " != " + outOffset + ")"); ++warningsReported; } reportFilePointerProgress(dmgRaf); 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(" " + elementNumber + ":" + blockCount + ". BT_UNKNOWN processing..."); if(!(inSize == 0 && outSize == 0)) { println(" " + elementNumber + ":" + blockCount + ". WARNING: Blocktype BT_UNKNOWN had non-zero sizes...", " inSize=" + inSize + ", outSize=" + outSize); ++warningsReported; //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(" " + elementNumber + ":" + blockCount + ". BT_END processing..."); if(!testOnly && isoRaf.getFilePointer() != outOffset) println(" " + elementNumber + ":" + blockCount + ". WARNING: BT_END FP != outOffset (" + isoRaf.getFilePointer() + " != " + outOffset + ")"); //lastOffs += lastInOffs; lastOutOffset = outOffset; lastInOffset += lastByteReadInBlock; } else { println(" " + elementNumber + ":" + blockCount + ". WARNING: previously unseen blocktype " + blockType + " [0x" + Integer.toHexString(blockType) + "]", " " + elementNumber + ":" + blockCount + ". outOffset=" + outOffset + " outSize=" + outSize + " inOffset=" + inOffset + " inSize=" + inSize); ++warningsReported; if(!testOnly && isoRaf.getFilePointer() != outOffset) println(" " + elementNumber + ":" + blockCount + ". unknown blocktype FP != outOffset (" + isoRaf.getFilePointer() + " != " + outOffset + ")"); } offset += 0x28; ++blockCount; } } ++elementNumber; } //printlnVerbose("Progress: 100% Done!"); reportProgress(100); String summary = (errorsReported != 0)?errorsReported+" errors reported":"No errors reported"; summary += (warningsReported != 0)?" ("+warningsReported+" warnings emitted).":"."; if(!graphical) { newline(); println(summary); printlnVerbose("Total extracted bytes: " + totalSize + " B"); } else { progmon.close(); JOptionPane.showMessageDialog(null, "Extraction complete! " + summary + "\n" + "Total extracted bytes: " + totalSize + " B", "Information", JOptionPane.INFORMATION_MESSAGE); System.exit(0); } if(!DEBUG) { if(isoRaf != null) isoRaf.close(); dmgRaf.close(); } else { if(isoRaf != null) isoRaf.close();// 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()); 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"; println(" " + new File(filename).getCanonicalPath() + "..."); 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"; println(" " + new File(filename).getCanonicalPath() + "..."); 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"; println(" " + new File(filename).getCanonicalPath() + "..."); 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!"); } } |
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"); | if(debug) { File dumpFile = new File("data(" + xn.getKeyValue("ID") + ").bin"); | public static void notmain(String[] args) throws Exception { 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[] inBuffer = new byte[0x40000]; byte[] outBuffer = 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 elementNumber = 0; //long lastOffs = 0; long lastOutOffset = 0; long lastInOffset = 0; long totalSize = 0; int errorsReported = 0; int warningsReported = 0; 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; 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 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) { if(DEBUG) println("!-----addInOffset mode: inOffset tranformation " + inOffset + "->" + (inOffset+lastInOffset)); inOffset += lastInOffset; } else if(inOffset == 0) { if(DEBUG) println("!-----Detected inOffset == 0, setting to " + lastInOffset); addInOffset = true; inOffset = lastInOffset; } outOffset += lastOutOffset; DMGBlock currentBlock = new DMGBlock(blockType, skipped, outOffset, outSize, inOffset, inSize); blocks.add(currentBlock); if(DEBUG) { println("outOffset=" + outOffset + " outSize=" + outSize + " inOffset=" + inOffset + " inSize=" + inSize + " lastOutOffset=" + lastOutOffset + " lastInOffset=" + lastInOffset /*+ " lastInOffs=" + lastInOffs + " lastOffs=" + lastOffs*/); } if(blockType == BT_ADC) { println(" " + elementNumber + ":" + blockCount + ". ERROR: BT_ADC not supported."); ++errorsReported; if(!testOnly) System.exit(0); } else if(blockType == BT_ZLIB) { if(DEBUG) println(" " + elementNumber + ":" + blockCount + ". BT_ZLIB processing..."); if(!testOnly && isoRaf.getFilePointer() != outOffset) println(" " + elementNumber + ":" + blockCount + ". WARNING: BT_ZLIB FP != outOffset (" + isoRaf.getFilePointer() + " != " + outOffset + ")"); try { DMGBlockHandlers.processZlibBlock(currentBlock, dmgRaf, isoRaf, testOnly, dummyMonitor); } catch(DataFormatException dfe) { println(" " + elementNumber + ":" + blockCount + ". ERROR: BT_ZLIB Could not decode..."); ++errorsReported; 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); break; } } } else if(blockType == BT_BZIP2) { println(" " + elementNumber + ":" + blockCount + ". ERROR: BT_BZIP2 not currently supported."); ++errorsReported; if(!testOnly) System.exit(0); } else if(blockType == BT_COPY) { if(DEBUG) println(" " + elementNumber + ":" + blockCount + ". BT_COPY processing..."); if(!testOnly && isoRaf.getFilePointer() != outOffset) { println(" " + elementNumber + ":" + blockCount + ". WARNING: BT_COPY FP != outOffset (" + isoRaf.getFilePointer() + " != " + outOffset + ")"); ++warningsReported; } dmgRaf.seek(/*lastOffs+*/inOffset); int bytesRead = dmgRaf.read(inBuffer, 0, Math.min((int)inSize, inBuffer.length)); long totalBytesRead = bytesRead; while(bytesRead != -1) { reportFilePointerProgress(dmgRaf); if(!testOnly) isoRaf.write(inBuffer, 0, bytesRead); if(totalBytesRead >= inSize) break; bytesRead = dmgRaf.read(inBuffer, 0, Math.min((int)(inSize-totalBytesRead), inBuffer.length)); if(bytesRead > 0) totalBytesRead += bytesRead; } //lastInOffs = inOffset+inSize; } else if(blockType == BT_ZERO) { if(DEBUG) println(" " + elementNumber + ":" + blockCount + ". BT_ZERO processing..."); if(!testOnly && isoRaf.getFilePointer() != outOffset) { println(" " + elementNumber + ":" + blockCount + ". WARNING: BT_ZERO FP != outOffset (" + isoRaf.getFilePointer() + " != " + outOffset + ")"); ++warningsReported; } reportFilePointerProgress(dmgRaf); 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_ZERO2) { if(DEBUG) println(" " + elementNumber + ":" + blockCount + ". BT_ZERO2 processing..."); if(!testOnly && isoRaf.getFilePointer() != outOffset) { println(" " + elementNumber + ":" + blockCount + ". WARNING: BT_ZERO2 FP != outOffset (" + isoRaf.getFilePointer() + " != " + outOffset + ")"); ++warningsReported; } reportFilePointerProgress(dmgRaf); 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(" " + elementNumber + ":" + blockCount + ". BT_UNKNOWN processing..."); if(!(inSize == 0 && outSize == 0)) { println(" " + elementNumber + ":" + blockCount + ". WARNING: Blocktype BT_UNKNOWN had non-zero sizes...", " inSize=" + inSize + ", outSize=" + outSize); ++warningsReported; //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(" " + elementNumber + ":" + blockCount + ". BT_END processing..."); if(!testOnly && isoRaf.getFilePointer() != outOffset) println(" " + elementNumber + ":" + blockCount + ". WARNING: BT_END FP != outOffset (" + isoRaf.getFilePointer() + " != " + outOffset + ")"); //lastOffs += lastInOffs; lastOutOffset = outOffset; lastInOffset += lastByteReadInBlock; } else { println(" " + elementNumber + ":" + blockCount + ". WARNING: previously unseen blocktype " + blockType + " [0x" + Integer.toHexString(blockType) + "]", " " + elementNumber + ":" + blockCount + ". outOffset=" + outOffset + " outSize=" + outSize + " inOffset=" + inOffset + " inSize=" + inSize); ++warningsReported; if(!testOnly && isoRaf.getFilePointer() != outOffset) println(" " + elementNumber + ":" + blockCount + ". unknown blocktype FP != outOffset (" + isoRaf.getFilePointer() + " != " + outOffset + ")"); } offset += 0x28; ++blockCount; } } ++elementNumber; } //printlnVerbose("Progress: 100% Done!"); reportProgress(100); String summary = (errorsReported != 0)?errorsReported+" errors reported":"No errors reported"; summary += (warningsReported != 0)?" ("+warningsReported+" warnings emitted).":"."; if(!graphical) { newline(); println(summary); printlnVerbose("Total extracted bytes: " + totalSize + " B"); } else { progmon.close(); JOptionPane.showMessageDialog(null, "Extraction complete! " + summary + "\n" + "Total extracted bytes: " + totalSize + " B", "Information", JOptionPane.INFORMATION_MESSAGE); System.exit(0); } if(!DEBUG) { if(isoRaf != null) isoRaf.close(); dmgRaf.close(); } else { if(isoRaf != null) isoRaf.close();// 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()); 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"; println(" " + new File(filename).getCanonicalPath() + "..."); 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"; println(" " + new File(filename).getCanonicalPath() + "..."); 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"; println(" " + new File(filename).getCanonicalPath() + "..."); 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!"); } } |
if(DEBUG) println("!-----addInOffset mode: inOffset tranformation " + inOffset + "->" + (inOffset+lastInOffset)); | if(debug) println("------->NOTE: addInOffset mode: inOffset tranformation " + inOffset + "->" + (inOffset+lastInOffset)); | public static void notmain(String[] args) throws Exception { 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[] inBuffer = new byte[0x40000]; byte[] outBuffer = 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 elementNumber = 0; //long lastOffs = 0; long lastOutOffset = 0; long lastInOffset = 0; long totalSize = 0; int errorsReported = 0; int warningsReported = 0; 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; 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 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) { if(DEBUG) println("!-----addInOffset mode: inOffset tranformation " + inOffset + "->" + (inOffset+lastInOffset)); inOffset += lastInOffset; } else if(inOffset == 0) { if(DEBUG) println("!-----Detected inOffset == 0, setting to " + lastInOffset); addInOffset = true; inOffset = lastInOffset; } outOffset += lastOutOffset; DMGBlock currentBlock = new DMGBlock(blockType, skipped, outOffset, outSize, inOffset, inSize); blocks.add(currentBlock); if(DEBUG) { println("outOffset=" + outOffset + " outSize=" + outSize + " inOffset=" + inOffset + " inSize=" + inSize + " lastOutOffset=" + lastOutOffset + " lastInOffset=" + lastInOffset /*+ " lastInOffs=" + lastInOffs + " lastOffs=" + lastOffs*/); } if(blockType == BT_ADC) { println(" " + elementNumber + ":" + blockCount + ". ERROR: BT_ADC not supported."); ++errorsReported; if(!testOnly) System.exit(0); } else if(blockType == BT_ZLIB) { if(DEBUG) println(" " + elementNumber + ":" + blockCount + ". BT_ZLIB processing..."); if(!testOnly && isoRaf.getFilePointer() != outOffset) println(" " + elementNumber + ":" + blockCount + ". WARNING: BT_ZLIB FP != outOffset (" + isoRaf.getFilePointer() + " != " + outOffset + ")"); try { DMGBlockHandlers.processZlibBlock(currentBlock, dmgRaf, isoRaf, testOnly, dummyMonitor); } catch(DataFormatException dfe) { println(" " + elementNumber + ":" + blockCount + ". ERROR: BT_ZLIB Could not decode..."); ++errorsReported; 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); break; } } } else if(blockType == BT_BZIP2) { println(" " + elementNumber + ":" + blockCount + ". ERROR: BT_BZIP2 not currently supported."); ++errorsReported; if(!testOnly) System.exit(0); } else if(blockType == BT_COPY) { if(DEBUG) println(" " + elementNumber + ":" + blockCount + ". BT_COPY processing..."); if(!testOnly && isoRaf.getFilePointer() != outOffset) { println(" " + elementNumber + ":" + blockCount + ". WARNING: BT_COPY FP != outOffset (" + isoRaf.getFilePointer() + " != " + outOffset + ")"); ++warningsReported; } dmgRaf.seek(/*lastOffs+*/inOffset); int bytesRead = dmgRaf.read(inBuffer, 0, Math.min((int)inSize, inBuffer.length)); long totalBytesRead = bytesRead; while(bytesRead != -1) { reportFilePointerProgress(dmgRaf); if(!testOnly) isoRaf.write(inBuffer, 0, bytesRead); if(totalBytesRead >= inSize) break; bytesRead = dmgRaf.read(inBuffer, 0, Math.min((int)(inSize-totalBytesRead), inBuffer.length)); if(bytesRead > 0) totalBytesRead += bytesRead; } //lastInOffs = inOffset+inSize; } else if(blockType == BT_ZERO) { if(DEBUG) println(" " + elementNumber + ":" + blockCount + ". BT_ZERO processing..."); if(!testOnly && isoRaf.getFilePointer() != outOffset) { println(" " + elementNumber + ":" + blockCount + ". WARNING: BT_ZERO FP != outOffset (" + isoRaf.getFilePointer() + " != " + outOffset + ")"); ++warningsReported; } reportFilePointerProgress(dmgRaf); 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_ZERO2) { if(DEBUG) println(" " + elementNumber + ":" + blockCount + ". BT_ZERO2 processing..."); if(!testOnly && isoRaf.getFilePointer() != outOffset) { println(" " + elementNumber + ":" + blockCount + ". WARNING: BT_ZERO2 FP != outOffset (" + isoRaf.getFilePointer() + " != " + outOffset + ")"); ++warningsReported; } reportFilePointerProgress(dmgRaf); 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(" " + elementNumber + ":" + blockCount + ". BT_UNKNOWN processing..."); if(!(inSize == 0 && outSize == 0)) { println(" " + elementNumber + ":" + blockCount + ". WARNING: Blocktype BT_UNKNOWN had non-zero sizes...", " inSize=" + inSize + ", outSize=" + outSize); ++warningsReported; //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(" " + elementNumber + ":" + blockCount + ". BT_END processing..."); if(!testOnly && isoRaf.getFilePointer() != outOffset) println(" " + elementNumber + ":" + blockCount + ". WARNING: BT_END FP != outOffset (" + isoRaf.getFilePointer() + " != " + outOffset + ")"); //lastOffs += lastInOffs; lastOutOffset = outOffset; lastInOffset += lastByteReadInBlock; } else { println(" " + elementNumber + ":" + blockCount + ". WARNING: previously unseen blocktype " + blockType + " [0x" + Integer.toHexString(blockType) + "]", " " + elementNumber + ":" + blockCount + ". outOffset=" + outOffset + " outSize=" + outSize + " inOffset=" + inOffset + " inSize=" + inSize); ++warningsReported; if(!testOnly && isoRaf.getFilePointer() != outOffset) println(" " + elementNumber + ":" + blockCount + ". unknown blocktype FP != outOffset (" + isoRaf.getFilePointer() + " != " + outOffset + ")"); } offset += 0x28; ++blockCount; } } ++elementNumber; } //printlnVerbose("Progress: 100% Done!"); reportProgress(100); String summary = (errorsReported != 0)?errorsReported+" errors reported":"No errors reported"; summary += (warningsReported != 0)?" ("+warningsReported+" warnings emitted).":"."; if(!graphical) { newline(); println(summary); printlnVerbose("Total extracted bytes: " + totalSize + " B"); } else { progmon.close(); JOptionPane.showMessageDialog(null, "Extraction complete! " + summary + "\n" + "Total extracted bytes: " + totalSize + " B", "Information", JOptionPane.INFORMATION_MESSAGE); System.exit(0); } if(!DEBUG) { if(isoRaf != null) isoRaf.close(); dmgRaf.close(); } else { if(isoRaf != null) isoRaf.close();// 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()); 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"; println(" " + new File(filename).getCanonicalPath() + "..."); 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"; println(" " + new File(filename).getCanonicalPath() + "..."); 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"; println(" " + new File(filename).getCanonicalPath() + "..."); 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!"); } } |
else if(inOffset == 0) { if(DEBUG) println("!-----Detected inOffset == 0, setting to " + lastInOffset); | else if(inOffset == 0 && blockCount == 0) { if(debug) println("------->NOTE: Detected inOffset == 0, setting to " + lastInOffset); | public static void notmain(String[] args) throws Exception { 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[] inBuffer = new byte[0x40000]; byte[] outBuffer = 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 elementNumber = 0; //long lastOffs = 0; long lastOutOffset = 0; long lastInOffset = 0; long totalSize = 0; int errorsReported = 0; int warningsReported = 0; 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; 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 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) { if(DEBUG) println("!-----addInOffset mode: inOffset tranformation " + inOffset + "->" + (inOffset+lastInOffset)); inOffset += lastInOffset; } else if(inOffset == 0) { if(DEBUG) println("!-----Detected inOffset == 0, setting to " + lastInOffset); addInOffset = true; inOffset = lastInOffset; } outOffset += lastOutOffset; DMGBlock currentBlock = new DMGBlock(blockType, skipped, outOffset, outSize, inOffset, inSize); blocks.add(currentBlock); if(DEBUG) { println("outOffset=" + outOffset + " outSize=" + outSize + " inOffset=" + inOffset + " inSize=" + inSize + " lastOutOffset=" + lastOutOffset + " lastInOffset=" + lastInOffset /*+ " lastInOffs=" + lastInOffs + " lastOffs=" + lastOffs*/); } if(blockType == BT_ADC) { println(" " + elementNumber + ":" + blockCount + ". ERROR: BT_ADC not supported."); ++errorsReported; if(!testOnly) System.exit(0); } else if(blockType == BT_ZLIB) { if(DEBUG) println(" " + elementNumber + ":" + blockCount + ". BT_ZLIB processing..."); if(!testOnly && isoRaf.getFilePointer() != outOffset) println(" " + elementNumber + ":" + blockCount + ". WARNING: BT_ZLIB FP != outOffset (" + isoRaf.getFilePointer() + " != " + outOffset + ")"); try { DMGBlockHandlers.processZlibBlock(currentBlock, dmgRaf, isoRaf, testOnly, dummyMonitor); } catch(DataFormatException dfe) { println(" " + elementNumber + ":" + blockCount + ". ERROR: BT_ZLIB Could not decode..."); ++errorsReported; 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); break; } } } else if(blockType == BT_BZIP2) { println(" " + elementNumber + ":" + blockCount + ". ERROR: BT_BZIP2 not currently supported."); ++errorsReported; if(!testOnly) System.exit(0); } else if(blockType == BT_COPY) { if(DEBUG) println(" " + elementNumber + ":" + blockCount + ". BT_COPY processing..."); if(!testOnly && isoRaf.getFilePointer() != outOffset) { println(" " + elementNumber + ":" + blockCount + ". WARNING: BT_COPY FP != outOffset (" + isoRaf.getFilePointer() + " != " + outOffset + ")"); ++warningsReported; } dmgRaf.seek(/*lastOffs+*/inOffset); int bytesRead = dmgRaf.read(inBuffer, 0, Math.min((int)inSize, inBuffer.length)); long totalBytesRead = bytesRead; while(bytesRead != -1) { reportFilePointerProgress(dmgRaf); if(!testOnly) isoRaf.write(inBuffer, 0, bytesRead); if(totalBytesRead >= inSize) break; bytesRead = dmgRaf.read(inBuffer, 0, Math.min((int)(inSize-totalBytesRead), inBuffer.length)); if(bytesRead > 0) totalBytesRead += bytesRead; } //lastInOffs = inOffset+inSize; } else if(blockType == BT_ZERO) { if(DEBUG) println(" " + elementNumber + ":" + blockCount + ". BT_ZERO processing..."); if(!testOnly && isoRaf.getFilePointer() != outOffset) { println(" " + elementNumber + ":" + blockCount + ". WARNING: BT_ZERO FP != outOffset (" + isoRaf.getFilePointer() + " != " + outOffset + ")"); ++warningsReported; } reportFilePointerProgress(dmgRaf); 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_ZERO2) { if(DEBUG) println(" " + elementNumber + ":" + blockCount + ". BT_ZERO2 processing..."); if(!testOnly && isoRaf.getFilePointer() != outOffset) { println(" " + elementNumber + ":" + blockCount + ". WARNING: BT_ZERO2 FP != outOffset (" + isoRaf.getFilePointer() + " != " + outOffset + ")"); ++warningsReported; } reportFilePointerProgress(dmgRaf); 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(" " + elementNumber + ":" + blockCount + ". BT_UNKNOWN processing..."); if(!(inSize == 0 && outSize == 0)) { println(" " + elementNumber + ":" + blockCount + ". WARNING: Blocktype BT_UNKNOWN had non-zero sizes...", " inSize=" + inSize + ", outSize=" + outSize); ++warningsReported; //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(" " + elementNumber + ":" + blockCount + ". BT_END processing..."); if(!testOnly && isoRaf.getFilePointer() != outOffset) println(" " + elementNumber + ":" + blockCount + ". WARNING: BT_END FP != outOffset (" + isoRaf.getFilePointer() + " != " + outOffset + ")"); //lastOffs += lastInOffs; lastOutOffset = outOffset; lastInOffset += lastByteReadInBlock; } else { println(" " + elementNumber + ":" + blockCount + ". WARNING: previously unseen blocktype " + blockType + " [0x" + Integer.toHexString(blockType) + "]", " " + elementNumber + ":" + blockCount + ". outOffset=" + outOffset + " outSize=" + outSize + " inOffset=" + inOffset + " inSize=" + inSize); ++warningsReported; if(!testOnly && isoRaf.getFilePointer() != outOffset) println(" " + elementNumber + ":" + blockCount + ". unknown blocktype FP != outOffset (" + isoRaf.getFilePointer() + " != " + outOffset + ")"); } offset += 0x28; ++blockCount; } } ++elementNumber; } //printlnVerbose("Progress: 100% Done!"); reportProgress(100); String summary = (errorsReported != 0)?errorsReported+" errors reported":"No errors reported"; summary += (warningsReported != 0)?" ("+warningsReported+" warnings emitted).":"."; if(!graphical) { newline(); println(summary); printlnVerbose("Total extracted bytes: " + totalSize + " B"); } else { progmon.close(); JOptionPane.showMessageDialog(null, "Extraction complete! " + summary + "\n" + "Total extracted bytes: " + totalSize + " B", "Information", JOptionPane.INFORMATION_MESSAGE); System.exit(0); } if(!DEBUG) { if(isoRaf != null) isoRaf.close(); dmgRaf.close(); } else { if(isoRaf != null) isoRaf.close();// 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()); 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"; println(" " + new File(filename).getCanonicalPath() + "..."); 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"; println(" " + new File(filename).getCanonicalPath() + "..."); 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"; println(" " + new File(filename).getCanonicalPath() + "..."); 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!"); } } |
if(DEBUG) { println("outOffset=" + outOffset + " outSize=" + outSize + " inOffset=" + inOffset + " inSize=" + inSize + " lastOutOffset=" + lastOutOffset + " lastInOffset=" + lastInOffset | if(debug) { println(" outOffset=" + outOffset + " outSize=" + outSize + " inOffset=" + inOffset, " inSize=" + inSize + " lastOutOffset=" + lastOutOffset + " lastInOffset=" + lastInOffset | public static void notmain(String[] args) throws Exception { 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[] inBuffer = new byte[0x40000]; byte[] outBuffer = 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 elementNumber = 0; //long lastOffs = 0; long lastOutOffset = 0; long lastInOffset = 0; long totalSize = 0; int errorsReported = 0; int warningsReported = 0; 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; 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 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) { if(DEBUG) println("!-----addInOffset mode: inOffset tranformation " + inOffset + "->" + (inOffset+lastInOffset)); inOffset += lastInOffset; } else if(inOffset == 0) { if(DEBUG) println("!-----Detected inOffset == 0, setting to " + lastInOffset); addInOffset = true; inOffset = lastInOffset; } outOffset += lastOutOffset; DMGBlock currentBlock = new DMGBlock(blockType, skipped, outOffset, outSize, inOffset, inSize); blocks.add(currentBlock); if(DEBUG) { println("outOffset=" + outOffset + " outSize=" + outSize + " inOffset=" + inOffset + " inSize=" + inSize + " lastOutOffset=" + lastOutOffset + " lastInOffset=" + lastInOffset /*+ " lastInOffs=" + lastInOffs + " lastOffs=" + lastOffs*/); } if(blockType == BT_ADC) { println(" " + elementNumber + ":" + blockCount + ". ERROR: BT_ADC not supported."); ++errorsReported; if(!testOnly) System.exit(0); } else if(blockType == BT_ZLIB) { if(DEBUG) println(" " + elementNumber + ":" + blockCount + ". BT_ZLIB processing..."); if(!testOnly && isoRaf.getFilePointer() != outOffset) println(" " + elementNumber + ":" + blockCount + ". WARNING: BT_ZLIB FP != outOffset (" + isoRaf.getFilePointer() + " != " + outOffset + ")"); try { DMGBlockHandlers.processZlibBlock(currentBlock, dmgRaf, isoRaf, testOnly, dummyMonitor); } catch(DataFormatException dfe) { println(" " + elementNumber + ":" + blockCount + ". ERROR: BT_ZLIB Could not decode..."); ++errorsReported; 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); break; } } } else if(blockType == BT_BZIP2) { println(" " + elementNumber + ":" + blockCount + ". ERROR: BT_BZIP2 not currently supported."); ++errorsReported; if(!testOnly) System.exit(0); } else if(blockType == BT_COPY) { if(DEBUG) println(" " + elementNumber + ":" + blockCount + ". BT_COPY processing..."); if(!testOnly && isoRaf.getFilePointer() != outOffset) { println(" " + elementNumber + ":" + blockCount + ". WARNING: BT_COPY FP != outOffset (" + isoRaf.getFilePointer() + " != " + outOffset + ")"); ++warningsReported; } dmgRaf.seek(/*lastOffs+*/inOffset); int bytesRead = dmgRaf.read(inBuffer, 0, Math.min((int)inSize, inBuffer.length)); long totalBytesRead = bytesRead; while(bytesRead != -1) { reportFilePointerProgress(dmgRaf); if(!testOnly) isoRaf.write(inBuffer, 0, bytesRead); if(totalBytesRead >= inSize) break; bytesRead = dmgRaf.read(inBuffer, 0, Math.min((int)(inSize-totalBytesRead), inBuffer.length)); if(bytesRead > 0) totalBytesRead += bytesRead; } //lastInOffs = inOffset+inSize; } else if(blockType == BT_ZERO) { if(DEBUG) println(" " + elementNumber + ":" + blockCount + ". BT_ZERO processing..."); if(!testOnly && isoRaf.getFilePointer() != outOffset) { println(" " + elementNumber + ":" + blockCount + ". WARNING: BT_ZERO FP != outOffset (" + isoRaf.getFilePointer() + " != " + outOffset + ")"); ++warningsReported; } reportFilePointerProgress(dmgRaf); 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_ZERO2) { if(DEBUG) println(" " + elementNumber + ":" + blockCount + ". BT_ZERO2 processing..."); if(!testOnly && isoRaf.getFilePointer() != outOffset) { println(" " + elementNumber + ":" + blockCount + ". WARNING: BT_ZERO2 FP != outOffset (" + isoRaf.getFilePointer() + " != " + outOffset + ")"); ++warningsReported; } reportFilePointerProgress(dmgRaf); 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(" " + elementNumber + ":" + blockCount + ". BT_UNKNOWN processing..."); if(!(inSize == 0 && outSize == 0)) { println(" " + elementNumber + ":" + blockCount + ". WARNING: Blocktype BT_UNKNOWN had non-zero sizes...", " inSize=" + inSize + ", outSize=" + outSize); ++warningsReported; //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(" " + elementNumber + ":" + blockCount + ". BT_END processing..."); if(!testOnly && isoRaf.getFilePointer() != outOffset) println(" " + elementNumber + ":" + blockCount + ". WARNING: BT_END FP != outOffset (" + isoRaf.getFilePointer() + " != " + outOffset + ")"); //lastOffs += lastInOffs; lastOutOffset = outOffset; lastInOffset += lastByteReadInBlock; } else { println(" " + elementNumber + ":" + blockCount + ". WARNING: previously unseen blocktype " + blockType + " [0x" + Integer.toHexString(blockType) + "]", " " + elementNumber + ":" + blockCount + ". outOffset=" + outOffset + " outSize=" + outSize + " inOffset=" + inOffset + " inSize=" + inSize); ++warningsReported; if(!testOnly && isoRaf.getFilePointer() != outOffset) println(" " + elementNumber + ":" + blockCount + ". unknown blocktype FP != outOffset (" + isoRaf.getFilePointer() + " != " + outOffset + ")"); } offset += 0x28; ++blockCount; } } ++elementNumber; } //printlnVerbose("Progress: 100% Done!"); reportProgress(100); String summary = (errorsReported != 0)?errorsReported+" errors reported":"No errors reported"; summary += (warningsReported != 0)?" ("+warningsReported+" warnings emitted).":"."; if(!graphical) { newline(); println(summary); printlnVerbose("Total extracted bytes: " + totalSize + " B"); } else { progmon.close(); JOptionPane.showMessageDialog(null, "Extraction complete! " + summary + "\n" + "Total extracted bytes: " + totalSize + " B", "Information", JOptionPane.INFORMATION_MESSAGE); System.exit(0); } if(!DEBUG) { if(isoRaf != null) isoRaf.close(); dmgRaf.close(); } else { if(isoRaf != null) isoRaf.close();// 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()); 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"; println(" " + new File(filename).getCanonicalPath() + "..."); 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"; println(" " + new File(filename).getCanonicalPath() + "..."); 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"; println(" " + new File(filename).getCanonicalPath() + "..."); 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!"); } } |
println(" " + elementNumber + ":" + blockCount + ". ERROR: BT_ADC not supported."); | println("!------>ERROR: BT_ADC not supported."); | public static void notmain(String[] args) throws Exception { 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[] inBuffer = new byte[0x40000]; byte[] outBuffer = 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 elementNumber = 0; //long lastOffs = 0; long lastOutOffset = 0; long lastInOffset = 0; long totalSize = 0; int errorsReported = 0; int warningsReported = 0; 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; 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 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) { if(DEBUG) println("!-----addInOffset mode: inOffset tranformation " + inOffset + "->" + (inOffset+lastInOffset)); inOffset += lastInOffset; } else if(inOffset == 0) { if(DEBUG) println("!-----Detected inOffset == 0, setting to " + lastInOffset); addInOffset = true; inOffset = lastInOffset; } outOffset += lastOutOffset; DMGBlock currentBlock = new DMGBlock(blockType, skipped, outOffset, outSize, inOffset, inSize); blocks.add(currentBlock); if(DEBUG) { println("outOffset=" + outOffset + " outSize=" + outSize + " inOffset=" + inOffset + " inSize=" + inSize + " lastOutOffset=" + lastOutOffset + " lastInOffset=" + lastInOffset /*+ " lastInOffs=" + lastInOffs + " lastOffs=" + lastOffs*/); } if(blockType == BT_ADC) { println(" " + elementNumber + ":" + blockCount + ". ERROR: BT_ADC not supported."); ++errorsReported; if(!testOnly) System.exit(0); } else if(blockType == BT_ZLIB) { if(DEBUG) println(" " + elementNumber + ":" + blockCount + ". BT_ZLIB processing..."); if(!testOnly && isoRaf.getFilePointer() != outOffset) println(" " + elementNumber + ":" + blockCount + ". WARNING: BT_ZLIB FP != outOffset (" + isoRaf.getFilePointer() + " != " + outOffset + ")"); try { DMGBlockHandlers.processZlibBlock(currentBlock, dmgRaf, isoRaf, testOnly, dummyMonitor); } catch(DataFormatException dfe) { println(" " + elementNumber + ":" + blockCount + ". ERROR: BT_ZLIB Could not decode..."); ++errorsReported; 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); break; } } } else if(blockType == BT_BZIP2) { println(" " + elementNumber + ":" + blockCount + ". ERROR: BT_BZIP2 not currently supported."); ++errorsReported; if(!testOnly) System.exit(0); } else if(blockType == BT_COPY) { if(DEBUG) println(" " + elementNumber + ":" + blockCount + ". BT_COPY processing..."); if(!testOnly && isoRaf.getFilePointer() != outOffset) { println(" " + elementNumber + ":" + blockCount + ". WARNING: BT_COPY FP != outOffset (" + isoRaf.getFilePointer() + " != " + outOffset + ")"); ++warningsReported; } dmgRaf.seek(/*lastOffs+*/inOffset); int bytesRead = dmgRaf.read(inBuffer, 0, Math.min((int)inSize, inBuffer.length)); long totalBytesRead = bytesRead; while(bytesRead != -1) { reportFilePointerProgress(dmgRaf); if(!testOnly) isoRaf.write(inBuffer, 0, bytesRead); if(totalBytesRead >= inSize) break; bytesRead = dmgRaf.read(inBuffer, 0, Math.min((int)(inSize-totalBytesRead), inBuffer.length)); if(bytesRead > 0) totalBytesRead += bytesRead; } //lastInOffs = inOffset+inSize; } else if(blockType == BT_ZERO) { if(DEBUG) println(" " + elementNumber + ":" + blockCount + ". BT_ZERO processing..."); if(!testOnly && isoRaf.getFilePointer() != outOffset) { println(" " + elementNumber + ":" + blockCount + ". WARNING: BT_ZERO FP != outOffset (" + isoRaf.getFilePointer() + " != " + outOffset + ")"); ++warningsReported; } reportFilePointerProgress(dmgRaf); 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_ZERO2) { if(DEBUG) println(" " + elementNumber + ":" + blockCount + ". BT_ZERO2 processing..."); if(!testOnly && isoRaf.getFilePointer() != outOffset) { println(" " + elementNumber + ":" + blockCount + ". WARNING: BT_ZERO2 FP != outOffset (" + isoRaf.getFilePointer() + " != " + outOffset + ")"); ++warningsReported; } reportFilePointerProgress(dmgRaf); 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(" " + elementNumber + ":" + blockCount + ". BT_UNKNOWN processing..."); if(!(inSize == 0 && outSize == 0)) { println(" " + elementNumber + ":" + blockCount + ". WARNING: Blocktype BT_UNKNOWN had non-zero sizes...", " inSize=" + inSize + ", outSize=" + outSize); ++warningsReported; //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(" " + elementNumber + ":" + blockCount + ". BT_END processing..."); if(!testOnly && isoRaf.getFilePointer() != outOffset) println(" " + elementNumber + ":" + blockCount + ". WARNING: BT_END FP != outOffset (" + isoRaf.getFilePointer() + " != " + outOffset + ")"); //lastOffs += lastInOffs; lastOutOffset = outOffset; lastInOffset += lastByteReadInBlock; } else { println(" " + elementNumber + ":" + blockCount + ". WARNING: previously unseen blocktype " + blockType + " [0x" + Integer.toHexString(blockType) + "]", " " + elementNumber + ":" + blockCount + ". outOffset=" + outOffset + " outSize=" + outSize + " inOffset=" + inOffset + " inSize=" + inSize); ++warningsReported; if(!testOnly && isoRaf.getFilePointer() != outOffset) println(" " + elementNumber + ":" + blockCount + ". unknown blocktype FP != outOffset (" + isoRaf.getFilePointer() + " != " + outOffset + ")"); } offset += 0x28; ++blockCount; } } ++elementNumber; } //printlnVerbose("Progress: 100% Done!"); reportProgress(100); String summary = (errorsReported != 0)?errorsReported+" errors reported":"No errors reported"; summary += (warningsReported != 0)?" ("+warningsReported+" warnings emitted).":"."; if(!graphical) { newline(); println(summary); printlnVerbose("Total extracted bytes: " + totalSize + " B"); } else { progmon.close(); JOptionPane.showMessageDialog(null, "Extraction complete! " + summary + "\n" + "Total extracted bytes: " + totalSize + " B", "Information", JOptionPane.INFORMATION_MESSAGE); System.exit(0); } if(!DEBUG) { if(isoRaf != null) isoRaf.close(); dmgRaf.close(); } else { if(isoRaf != null) isoRaf.close();// 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()); 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"; println(" " + new File(filename).getCanonicalPath() + "..."); 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"; println(" " + new File(filename).getCanonicalPath() + "..."); 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"; println(" " + new File(filename).getCanonicalPath() + "..."); 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!"); } } |
if(DEBUG) println(" " + elementNumber + ":" + blockCount + ". BT_ZLIB processing..."); | public static void notmain(String[] args) throws Exception { 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[] inBuffer = new byte[0x40000]; byte[] outBuffer = 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 elementNumber = 0; //long lastOffs = 0; long lastOutOffset = 0; long lastInOffset = 0; long totalSize = 0; int errorsReported = 0; int warningsReported = 0; 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; 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 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) { if(DEBUG) println("!-----addInOffset mode: inOffset tranformation " + inOffset + "->" + (inOffset+lastInOffset)); inOffset += lastInOffset; } else if(inOffset == 0) { if(DEBUG) println("!-----Detected inOffset == 0, setting to " + lastInOffset); addInOffset = true; inOffset = lastInOffset; } outOffset += lastOutOffset; DMGBlock currentBlock = new DMGBlock(blockType, skipped, outOffset, outSize, inOffset, inSize); blocks.add(currentBlock); if(DEBUG) { println("outOffset=" + outOffset + " outSize=" + outSize + " inOffset=" + inOffset + " inSize=" + inSize + " lastOutOffset=" + lastOutOffset + " lastInOffset=" + lastInOffset /*+ " lastInOffs=" + lastInOffs + " lastOffs=" + lastOffs*/); } if(blockType == BT_ADC) { println(" " + elementNumber + ":" + blockCount + ". ERROR: BT_ADC not supported."); ++errorsReported; if(!testOnly) System.exit(0); } else if(blockType == BT_ZLIB) { if(DEBUG) println(" " + elementNumber + ":" + blockCount + ". BT_ZLIB processing..."); if(!testOnly && isoRaf.getFilePointer() != outOffset) println(" " + elementNumber + ":" + blockCount + ". WARNING: BT_ZLIB FP != outOffset (" + isoRaf.getFilePointer() + " != " + outOffset + ")"); try { DMGBlockHandlers.processZlibBlock(currentBlock, dmgRaf, isoRaf, testOnly, dummyMonitor); } catch(DataFormatException dfe) { println(" " + elementNumber + ":" + blockCount + ". ERROR: BT_ZLIB Could not decode..."); ++errorsReported; 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); break; } } } else if(blockType == BT_BZIP2) { println(" " + elementNumber + ":" + blockCount + ". ERROR: BT_BZIP2 not currently supported."); ++errorsReported; if(!testOnly) System.exit(0); } else if(blockType == BT_COPY) { if(DEBUG) println(" " + elementNumber + ":" + blockCount + ". BT_COPY processing..."); if(!testOnly && isoRaf.getFilePointer() != outOffset) { println(" " + elementNumber + ":" + blockCount + ". WARNING: BT_COPY FP != outOffset (" + isoRaf.getFilePointer() + " != " + outOffset + ")"); ++warningsReported; } dmgRaf.seek(/*lastOffs+*/inOffset); int bytesRead = dmgRaf.read(inBuffer, 0, Math.min((int)inSize, inBuffer.length)); long totalBytesRead = bytesRead; while(bytesRead != -1) { reportFilePointerProgress(dmgRaf); if(!testOnly) isoRaf.write(inBuffer, 0, bytesRead); if(totalBytesRead >= inSize) break; bytesRead = dmgRaf.read(inBuffer, 0, Math.min((int)(inSize-totalBytesRead), inBuffer.length)); if(bytesRead > 0) totalBytesRead += bytesRead; } //lastInOffs = inOffset+inSize; } else if(blockType == BT_ZERO) { if(DEBUG) println(" " + elementNumber + ":" + blockCount + ". BT_ZERO processing..."); if(!testOnly && isoRaf.getFilePointer() != outOffset) { println(" " + elementNumber + ":" + blockCount + ". WARNING: BT_ZERO FP != outOffset (" + isoRaf.getFilePointer() + " != " + outOffset + ")"); ++warningsReported; } reportFilePointerProgress(dmgRaf); 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_ZERO2) { if(DEBUG) println(" " + elementNumber + ":" + blockCount + ". BT_ZERO2 processing..."); if(!testOnly && isoRaf.getFilePointer() != outOffset) { println(" " + elementNumber + ":" + blockCount + ". WARNING: BT_ZERO2 FP != outOffset (" + isoRaf.getFilePointer() + " != " + outOffset + ")"); ++warningsReported; } reportFilePointerProgress(dmgRaf); 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(" " + elementNumber + ":" + blockCount + ". BT_UNKNOWN processing..."); if(!(inSize == 0 && outSize == 0)) { println(" " + elementNumber + ":" + blockCount + ". WARNING: Blocktype BT_UNKNOWN had non-zero sizes...", " inSize=" + inSize + ", outSize=" + outSize); ++warningsReported; //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(" " + elementNumber + ":" + blockCount + ". BT_END processing..."); if(!testOnly && isoRaf.getFilePointer() != outOffset) println(" " + elementNumber + ":" + blockCount + ". WARNING: BT_END FP != outOffset (" + isoRaf.getFilePointer() + " != " + outOffset + ")"); //lastOffs += lastInOffs; lastOutOffset = outOffset; lastInOffset += lastByteReadInBlock; } else { println(" " + elementNumber + ":" + blockCount + ". WARNING: previously unseen blocktype " + blockType + " [0x" + Integer.toHexString(blockType) + "]", " " + elementNumber + ":" + blockCount + ". outOffset=" + outOffset + " outSize=" + outSize + " inOffset=" + inOffset + " inSize=" + inSize); ++warningsReported; if(!testOnly && isoRaf.getFilePointer() != outOffset) println(" " + elementNumber + ":" + blockCount + ". unknown blocktype FP != outOffset (" + isoRaf.getFilePointer() + " != " + outOffset + ")"); } offset += 0x28; ++blockCount; } } ++elementNumber; } //printlnVerbose("Progress: 100% Done!"); reportProgress(100); String summary = (errorsReported != 0)?errorsReported+" errors reported":"No errors reported"; summary += (warningsReported != 0)?" ("+warningsReported+" warnings emitted).":"."; if(!graphical) { newline(); println(summary); printlnVerbose("Total extracted bytes: " + totalSize + " B"); } else { progmon.close(); JOptionPane.showMessageDialog(null, "Extraction complete! " + summary + "\n" + "Total extracted bytes: " + totalSize + " B", "Information", JOptionPane.INFORMATION_MESSAGE); System.exit(0); } if(!DEBUG) { if(isoRaf != null) isoRaf.close(); dmgRaf.close(); } else { if(isoRaf != null) isoRaf.close();// 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()); 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"; println(" " + new File(filename).getCanonicalPath() + "..."); 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"; println(" " + new File(filename).getCanonicalPath() + "..."); 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"; println(" " + new File(filename).getCanonicalPath() + "..."); 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!"); } } |
|
println(" " + elementNumber + ":" + blockCount + ". WARNING: BT_ZLIB FP != outOffset (" + | println("!------>WARNING: BT_ZLIB FP != outOffset (" + | public static void notmain(String[] args) throws Exception { 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[] inBuffer = new byte[0x40000]; byte[] outBuffer = 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 elementNumber = 0; //long lastOffs = 0; long lastOutOffset = 0; long lastInOffset = 0; long totalSize = 0; int errorsReported = 0; int warningsReported = 0; 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; 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 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) { if(DEBUG) println("!-----addInOffset mode: inOffset tranformation " + inOffset + "->" + (inOffset+lastInOffset)); inOffset += lastInOffset; } else if(inOffset == 0) { if(DEBUG) println("!-----Detected inOffset == 0, setting to " + lastInOffset); addInOffset = true; inOffset = lastInOffset; } outOffset += lastOutOffset; DMGBlock currentBlock = new DMGBlock(blockType, skipped, outOffset, outSize, inOffset, inSize); blocks.add(currentBlock); if(DEBUG) { println("outOffset=" + outOffset + " outSize=" + outSize + " inOffset=" + inOffset + " inSize=" + inSize + " lastOutOffset=" + lastOutOffset + " lastInOffset=" + lastInOffset /*+ " lastInOffs=" + lastInOffs + " lastOffs=" + lastOffs*/); } if(blockType == BT_ADC) { println(" " + elementNumber + ":" + blockCount + ". ERROR: BT_ADC not supported."); ++errorsReported; if(!testOnly) System.exit(0); } else if(blockType == BT_ZLIB) { if(DEBUG) println(" " + elementNumber + ":" + blockCount + ". BT_ZLIB processing..."); if(!testOnly && isoRaf.getFilePointer() != outOffset) println(" " + elementNumber + ":" + blockCount + ". WARNING: BT_ZLIB FP != outOffset (" + isoRaf.getFilePointer() + " != " + outOffset + ")"); try { DMGBlockHandlers.processZlibBlock(currentBlock, dmgRaf, isoRaf, testOnly, dummyMonitor); } catch(DataFormatException dfe) { println(" " + elementNumber + ":" + blockCount + ". ERROR: BT_ZLIB Could not decode..."); ++errorsReported; 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); break; } } } else if(blockType == BT_BZIP2) { println(" " + elementNumber + ":" + blockCount + ". ERROR: BT_BZIP2 not currently supported."); ++errorsReported; if(!testOnly) System.exit(0); } else if(blockType == BT_COPY) { if(DEBUG) println(" " + elementNumber + ":" + blockCount + ". BT_COPY processing..."); if(!testOnly && isoRaf.getFilePointer() != outOffset) { println(" " + elementNumber + ":" + blockCount + ". WARNING: BT_COPY FP != outOffset (" + isoRaf.getFilePointer() + " != " + outOffset + ")"); ++warningsReported; } dmgRaf.seek(/*lastOffs+*/inOffset); int bytesRead = dmgRaf.read(inBuffer, 0, Math.min((int)inSize, inBuffer.length)); long totalBytesRead = bytesRead; while(bytesRead != -1) { reportFilePointerProgress(dmgRaf); if(!testOnly) isoRaf.write(inBuffer, 0, bytesRead); if(totalBytesRead >= inSize) break; bytesRead = dmgRaf.read(inBuffer, 0, Math.min((int)(inSize-totalBytesRead), inBuffer.length)); if(bytesRead > 0) totalBytesRead += bytesRead; } //lastInOffs = inOffset+inSize; } else if(blockType == BT_ZERO) { if(DEBUG) println(" " + elementNumber + ":" + blockCount + ". BT_ZERO processing..."); if(!testOnly && isoRaf.getFilePointer() != outOffset) { println(" " + elementNumber + ":" + blockCount + ". WARNING: BT_ZERO FP != outOffset (" + isoRaf.getFilePointer() + " != " + outOffset + ")"); ++warningsReported; } reportFilePointerProgress(dmgRaf); 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_ZERO2) { if(DEBUG) println(" " + elementNumber + ":" + blockCount + ". BT_ZERO2 processing..."); if(!testOnly && isoRaf.getFilePointer() != outOffset) { println(" " + elementNumber + ":" + blockCount + ". WARNING: BT_ZERO2 FP != outOffset (" + isoRaf.getFilePointer() + " != " + outOffset + ")"); ++warningsReported; } reportFilePointerProgress(dmgRaf); 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(" " + elementNumber + ":" + blockCount + ". BT_UNKNOWN processing..."); if(!(inSize == 0 && outSize == 0)) { println(" " + elementNumber + ":" + blockCount + ". WARNING: Blocktype BT_UNKNOWN had non-zero sizes...", " inSize=" + inSize + ", outSize=" + outSize); ++warningsReported; //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(" " + elementNumber + ":" + blockCount + ". BT_END processing..."); if(!testOnly && isoRaf.getFilePointer() != outOffset) println(" " + elementNumber + ":" + blockCount + ". WARNING: BT_END FP != outOffset (" + isoRaf.getFilePointer() + " != " + outOffset + ")"); //lastOffs += lastInOffs; lastOutOffset = outOffset; lastInOffset += lastByteReadInBlock; } else { println(" " + elementNumber + ":" + blockCount + ". WARNING: previously unseen blocktype " + blockType + " [0x" + Integer.toHexString(blockType) + "]", " " + elementNumber + ":" + blockCount + ". outOffset=" + outOffset + " outSize=" + outSize + " inOffset=" + inOffset + " inSize=" + inSize); ++warningsReported; if(!testOnly && isoRaf.getFilePointer() != outOffset) println(" " + elementNumber + ":" + blockCount + ". unknown blocktype FP != outOffset (" + isoRaf.getFilePointer() + " != " + outOffset + ")"); } offset += 0x28; ++blockCount; } } ++elementNumber; } //printlnVerbose("Progress: 100% Done!"); reportProgress(100); String summary = (errorsReported != 0)?errorsReported+" errors reported":"No errors reported"; summary += (warningsReported != 0)?" ("+warningsReported+" warnings emitted).":"."; if(!graphical) { newline(); println(summary); printlnVerbose("Total extracted bytes: " + totalSize + " B"); } else { progmon.close(); JOptionPane.showMessageDialog(null, "Extraction complete! " + summary + "\n" + "Total extracted bytes: " + totalSize + " B", "Information", JOptionPane.INFORMATION_MESSAGE); System.exit(0); } if(!DEBUG) { if(isoRaf != null) isoRaf.close(); dmgRaf.close(); } else { if(isoRaf != null) isoRaf.close();// 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()); 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"; println(" " + new File(filename).getCanonicalPath() + "..."); 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"; println(" " + new File(filename).getCanonicalPath() + "..."); 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"; println(" " + new File(filename).getCanonicalPath() + "..."); 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!"); } } |
println(" " + elementNumber + ":" + blockCount + ". ERROR: BT_ZLIB Could not decode..."); | println("!------>ERROR: BT_ZLIB Could not decode..."); | public static void notmain(String[] args) throws Exception { 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[] inBuffer = new byte[0x40000]; byte[] outBuffer = 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 elementNumber = 0; //long lastOffs = 0; long lastOutOffset = 0; long lastInOffset = 0; long totalSize = 0; int errorsReported = 0; int warningsReported = 0; 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; 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 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) { if(DEBUG) println("!-----addInOffset mode: inOffset tranformation " + inOffset + "->" + (inOffset+lastInOffset)); inOffset += lastInOffset; } else if(inOffset == 0) { if(DEBUG) println("!-----Detected inOffset == 0, setting to " + lastInOffset); addInOffset = true; inOffset = lastInOffset; } outOffset += lastOutOffset; DMGBlock currentBlock = new DMGBlock(blockType, skipped, outOffset, outSize, inOffset, inSize); blocks.add(currentBlock); if(DEBUG) { println("outOffset=" + outOffset + " outSize=" + outSize + " inOffset=" + inOffset + " inSize=" + inSize + " lastOutOffset=" + lastOutOffset + " lastInOffset=" + lastInOffset /*+ " lastInOffs=" + lastInOffs + " lastOffs=" + lastOffs*/); } if(blockType == BT_ADC) { println(" " + elementNumber + ":" + blockCount + ". ERROR: BT_ADC not supported."); ++errorsReported; if(!testOnly) System.exit(0); } else if(blockType == BT_ZLIB) { if(DEBUG) println(" " + elementNumber + ":" + blockCount + ". BT_ZLIB processing..."); if(!testOnly && isoRaf.getFilePointer() != outOffset) println(" " + elementNumber + ":" + blockCount + ". WARNING: BT_ZLIB FP != outOffset (" + isoRaf.getFilePointer() + " != " + outOffset + ")"); try { DMGBlockHandlers.processZlibBlock(currentBlock, dmgRaf, isoRaf, testOnly, dummyMonitor); } catch(DataFormatException dfe) { println(" " + elementNumber + ":" + blockCount + ". ERROR: BT_ZLIB Could not decode..."); ++errorsReported; 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); break; } } } else if(blockType == BT_BZIP2) { println(" " + elementNumber + ":" + blockCount + ". ERROR: BT_BZIP2 not currently supported."); ++errorsReported; if(!testOnly) System.exit(0); } else if(blockType == BT_COPY) { if(DEBUG) println(" " + elementNumber + ":" + blockCount + ". BT_COPY processing..."); if(!testOnly && isoRaf.getFilePointer() != outOffset) { println(" " + elementNumber + ":" + blockCount + ". WARNING: BT_COPY FP != outOffset (" + isoRaf.getFilePointer() + " != " + outOffset + ")"); ++warningsReported; } dmgRaf.seek(/*lastOffs+*/inOffset); int bytesRead = dmgRaf.read(inBuffer, 0, Math.min((int)inSize, inBuffer.length)); long totalBytesRead = bytesRead; while(bytesRead != -1) { reportFilePointerProgress(dmgRaf); if(!testOnly) isoRaf.write(inBuffer, 0, bytesRead); if(totalBytesRead >= inSize) break; bytesRead = dmgRaf.read(inBuffer, 0, Math.min((int)(inSize-totalBytesRead), inBuffer.length)); if(bytesRead > 0) totalBytesRead += bytesRead; } //lastInOffs = inOffset+inSize; } else if(blockType == BT_ZERO) { if(DEBUG) println(" " + elementNumber + ":" + blockCount + ". BT_ZERO processing..."); if(!testOnly && isoRaf.getFilePointer() != outOffset) { println(" " + elementNumber + ":" + blockCount + ". WARNING: BT_ZERO FP != outOffset (" + isoRaf.getFilePointer() + " != " + outOffset + ")"); ++warningsReported; } reportFilePointerProgress(dmgRaf); 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_ZERO2) { if(DEBUG) println(" " + elementNumber + ":" + blockCount + ". BT_ZERO2 processing..."); if(!testOnly && isoRaf.getFilePointer() != outOffset) { println(" " + elementNumber + ":" + blockCount + ". WARNING: BT_ZERO2 FP != outOffset (" + isoRaf.getFilePointer() + " != " + outOffset + ")"); ++warningsReported; } reportFilePointerProgress(dmgRaf); 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(" " + elementNumber + ":" + blockCount + ". BT_UNKNOWN processing..."); if(!(inSize == 0 && outSize == 0)) { println(" " + elementNumber + ":" + blockCount + ". WARNING: Blocktype BT_UNKNOWN had non-zero sizes...", " inSize=" + inSize + ", outSize=" + outSize); ++warningsReported; //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(" " + elementNumber + ":" + blockCount + ". BT_END processing..."); if(!testOnly && isoRaf.getFilePointer() != outOffset) println(" " + elementNumber + ":" + blockCount + ". WARNING: BT_END FP != outOffset (" + isoRaf.getFilePointer() + " != " + outOffset + ")"); //lastOffs += lastInOffs; lastOutOffset = outOffset; lastInOffset += lastByteReadInBlock; } else { println(" " + elementNumber + ":" + blockCount + ". WARNING: previously unseen blocktype " + blockType + " [0x" + Integer.toHexString(blockType) + "]", " " + elementNumber + ":" + blockCount + ". outOffset=" + outOffset + " outSize=" + outSize + " inOffset=" + inOffset + " inSize=" + inSize); ++warningsReported; if(!testOnly && isoRaf.getFilePointer() != outOffset) println(" " + elementNumber + ":" + blockCount + ". unknown blocktype FP != outOffset (" + isoRaf.getFilePointer() + " != " + outOffset + ")"); } offset += 0x28; ++blockCount; } } ++elementNumber; } //printlnVerbose("Progress: 100% Done!"); reportProgress(100); String summary = (errorsReported != 0)?errorsReported+" errors reported":"No errors reported"; summary += (warningsReported != 0)?" ("+warningsReported+" warnings emitted).":"."; if(!graphical) { newline(); println(summary); printlnVerbose("Total extracted bytes: " + totalSize + " B"); } else { progmon.close(); JOptionPane.showMessageDialog(null, "Extraction complete! " + summary + "\n" + "Total extracted bytes: " + totalSize + " B", "Information", JOptionPane.INFORMATION_MESSAGE); System.exit(0); } if(!DEBUG) { if(isoRaf != null) isoRaf.close(); dmgRaf.close(); } else { if(isoRaf != null) isoRaf.close();// 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()); 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"; println(" " + new File(filename).getCanonicalPath() + "..."); 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"; println(" " + new File(filename).getCanonicalPath() + "..."); 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"; println(" " + new File(filename).getCanonicalPath() + "..."); 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!"); } } |
if(!DEBUG) { println("outOffset=" + outOffset + " outSize=" + outSize + | if(!debug) { println("!------> outOffset=" + outOffset + " outSize=" + outSize + | public static void notmain(String[] args) throws Exception { 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[] inBuffer = new byte[0x40000]; byte[] outBuffer = 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 elementNumber = 0; //long lastOffs = 0; long lastOutOffset = 0; long lastInOffset = 0; long totalSize = 0; int errorsReported = 0; int warningsReported = 0; 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; 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 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) { if(DEBUG) println("!-----addInOffset mode: inOffset tranformation " + inOffset + "->" + (inOffset+lastInOffset)); inOffset += lastInOffset; } else if(inOffset == 0) { if(DEBUG) println("!-----Detected inOffset == 0, setting to " + lastInOffset); addInOffset = true; inOffset = lastInOffset; } outOffset += lastOutOffset; DMGBlock currentBlock = new DMGBlock(blockType, skipped, outOffset, outSize, inOffset, inSize); blocks.add(currentBlock); if(DEBUG) { println("outOffset=" + outOffset + " outSize=" + outSize + " inOffset=" + inOffset + " inSize=" + inSize + " lastOutOffset=" + lastOutOffset + " lastInOffset=" + lastInOffset /*+ " lastInOffs=" + lastInOffs + " lastOffs=" + lastOffs*/); } if(blockType == BT_ADC) { println(" " + elementNumber + ":" + blockCount + ". ERROR: BT_ADC not supported."); ++errorsReported; if(!testOnly) System.exit(0); } else if(blockType == BT_ZLIB) { if(DEBUG) println(" " + elementNumber + ":" + blockCount + ". BT_ZLIB processing..."); if(!testOnly && isoRaf.getFilePointer() != outOffset) println(" " + elementNumber + ":" + blockCount + ". WARNING: BT_ZLIB FP != outOffset (" + isoRaf.getFilePointer() + " != " + outOffset + ")"); try { DMGBlockHandlers.processZlibBlock(currentBlock, dmgRaf, isoRaf, testOnly, dummyMonitor); } catch(DataFormatException dfe) { println(" " + elementNumber + ":" + blockCount + ". ERROR: BT_ZLIB Could not decode..."); ++errorsReported; 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); break; } } } else if(blockType == BT_BZIP2) { println(" " + elementNumber + ":" + blockCount + ". ERROR: BT_BZIP2 not currently supported."); ++errorsReported; if(!testOnly) System.exit(0); } else if(blockType == BT_COPY) { if(DEBUG) println(" " + elementNumber + ":" + blockCount + ". BT_COPY processing..."); if(!testOnly && isoRaf.getFilePointer() != outOffset) { println(" " + elementNumber + ":" + blockCount + ". WARNING: BT_COPY FP != outOffset (" + isoRaf.getFilePointer() + " != " + outOffset + ")"); ++warningsReported; } dmgRaf.seek(/*lastOffs+*/inOffset); int bytesRead = dmgRaf.read(inBuffer, 0, Math.min((int)inSize, inBuffer.length)); long totalBytesRead = bytesRead; while(bytesRead != -1) { reportFilePointerProgress(dmgRaf); if(!testOnly) isoRaf.write(inBuffer, 0, bytesRead); if(totalBytesRead >= inSize) break; bytesRead = dmgRaf.read(inBuffer, 0, Math.min((int)(inSize-totalBytesRead), inBuffer.length)); if(bytesRead > 0) totalBytesRead += bytesRead; } //lastInOffs = inOffset+inSize; } else if(blockType == BT_ZERO) { if(DEBUG) println(" " + elementNumber + ":" + blockCount + ". BT_ZERO processing..."); if(!testOnly && isoRaf.getFilePointer() != outOffset) { println(" " + elementNumber + ":" + blockCount + ". WARNING: BT_ZERO FP != outOffset (" + isoRaf.getFilePointer() + " != " + outOffset + ")"); ++warningsReported; } reportFilePointerProgress(dmgRaf); 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_ZERO2) { if(DEBUG) println(" " + elementNumber + ":" + blockCount + ". BT_ZERO2 processing..."); if(!testOnly && isoRaf.getFilePointer() != outOffset) { println(" " + elementNumber + ":" + blockCount + ". WARNING: BT_ZERO2 FP != outOffset (" + isoRaf.getFilePointer() + " != " + outOffset + ")"); ++warningsReported; } reportFilePointerProgress(dmgRaf); 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(" " + elementNumber + ":" + blockCount + ". BT_UNKNOWN processing..."); if(!(inSize == 0 && outSize == 0)) { println(" " + elementNumber + ":" + blockCount + ". WARNING: Blocktype BT_UNKNOWN had non-zero sizes...", " inSize=" + inSize + ", outSize=" + outSize); ++warningsReported; //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(" " + elementNumber + ":" + blockCount + ". BT_END processing..."); if(!testOnly && isoRaf.getFilePointer() != outOffset) println(" " + elementNumber + ":" + blockCount + ". WARNING: BT_END FP != outOffset (" + isoRaf.getFilePointer() + " != " + outOffset + ")"); //lastOffs += lastInOffs; lastOutOffset = outOffset; lastInOffset += lastByteReadInBlock; } else { println(" " + elementNumber + ":" + blockCount + ". WARNING: previously unseen blocktype " + blockType + " [0x" + Integer.toHexString(blockType) + "]", " " + elementNumber + ":" + blockCount + ". outOffset=" + outOffset + " outSize=" + outSize + " inOffset=" + inOffset + " inSize=" + inSize); ++warningsReported; if(!testOnly && isoRaf.getFilePointer() != outOffset) println(" " + elementNumber + ":" + blockCount + ". unknown blocktype FP != outOffset (" + isoRaf.getFilePointer() + " != " + outOffset + ")"); } offset += 0x28; ++blockCount; } } ++elementNumber; } //printlnVerbose("Progress: 100% Done!"); reportProgress(100); String summary = (errorsReported != 0)?errorsReported+" errors reported":"No errors reported"; summary += (warningsReported != 0)?" ("+warningsReported+" warnings emitted).":"."; if(!graphical) { newline(); println(summary); printlnVerbose("Total extracted bytes: " + totalSize + " B"); } else { progmon.close(); JOptionPane.showMessageDialog(null, "Extraction complete! " + summary + "\n" + "Total extracted bytes: " + totalSize + " B", "Information", JOptionPane.INFORMATION_MESSAGE); System.exit(0); } if(!DEBUG) { if(isoRaf != null) isoRaf.close(); dmgRaf.close(); } else { if(isoRaf != null) isoRaf.close();// 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()); 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"; println(" " + new File(filename).getCanonicalPath() + "..."); 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"; println(" " + new File(filename).getCanonicalPath() + "..."); 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"; println(" " + new File(filename).getCanonicalPath() + "..."); 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!"); } } |
println(" Testing mode, so continuing..."); | println("!------> Testing mode, so continuing..."); | public static void notmain(String[] args) throws Exception { 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[] inBuffer = new byte[0x40000]; byte[] outBuffer = 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 elementNumber = 0; //long lastOffs = 0; long lastOutOffset = 0; long lastInOffset = 0; long totalSize = 0; int errorsReported = 0; int warningsReported = 0; 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; 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 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) { if(DEBUG) println("!-----addInOffset mode: inOffset tranformation " + inOffset + "->" + (inOffset+lastInOffset)); inOffset += lastInOffset; } else if(inOffset == 0) { if(DEBUG) println("!-----Detected inOffset == 0, setting to " + lastInOffset); addInOffset = true; inOffset = lastInOffset; } outOffset += lastOutOffset; DMGBlock currentBlock = new DMGBlock(blockType, skipped, outOffset, outSize, inOffset, inSize); blocks.add(currentBlock); if(DEBUG) { println("outOffset=" + outOffset + " outSize=" + outSize + " inOffset=" + inOffset + " inSize=" + inSize + " lastOutOffset=" + lastOutOffset + " lastInOffset=" + lastInOffset /*+ " lastInOffs=" + lastInOffs + " lastOffs=" + lastOffs*/); } if(blockType == BT_ADC) { println(" " + elementNumber + ":" + blockCount + ". ERROR: BT_ADC not supported."); ++errorsReported; if(!testOnly) System.exit(0); } else if(blockType == BT_ZLIB) { if(DEBUG) println(" " + elementNumber + ":" + blockCount + ". BT_ZLIB processing..."); if(!testOnly && isoRaf.getFilePointer() != outOffset) println(" " + elementNumber + ":" + blockCount + ". WARNING: BT_ZLIB FP != outOffset (" + isoRaf.getFilePointer() + " != " + outOffset + ")"); try { DMGBlockHandlers.processZlibBlock(currentBlock, dmgRaf, isoRaf, testOnly, dummyMonitor); } catch(DataFormatException dfe) { println(" " + elementNumber + ":" + blockCount + ". ERROR: BT_ZLIB Could not decode..."); ++errorsReported; 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); break; } } } else if(blockType == BT_BZIP2) { println(" " + elementNumber + ":" + blockCount + ". ERROR: BT_BZIP2 not currently supported."); ++errorsReported; if(!testOnly) System.exit(0); } else if(blockType == BT_COPY) { if(DEBUG) println(" " + elementNumber + ":" + blockCount + ". BT_COPY processing..."); if(!testOnly && isoRaf.getFilePointer() != outOffset) { println(" " + elementNumber + ":" + blockCount + ". WARNING: BT_COPY FP != outOffset (" + isoRaf.getFilePointer() + " != " + outOffset + ")"); ++warningsReported; } dmgRaf.seek(/*lastOffs+*/inOffset); int bytesRead = dmgRaf.read(inBuffer, 0, Math.min((int)inSize, inBuffer.length)); long totalBytesRead = bytesRead; while(bytesRead != -1) { reportFilePointerProgress(dmgRaf); if(!testOnly) isoRaf.write(inBuffer, 0, bytesRead); if(totalBytesRead >= inSize) break; bytesRead = dmgRaf.read(inBuffer, 0, Math.min((int)(inSize-totalBytesRead), inBuffer.length)); if(bytesRead > 0) totalBytesRead += bytesRead; } //lastInOffs = inOffset+inSize; } else if(blockType == BT_ZERO) { if(DEBUG) println(" " + elementNumber + ":" + blockCount + ". BT_ZERO processing..."); if(!testOnly && isoRaf.getFilePointer() != outOffset) { println(" " + elementNumber + ":" + blockCount + ". WARNING: BT_ZERO FP != outOffset (" + isoRaf.getFilePointer() + " != " + outOffset + ")"); ++warningsReported; } reportFilePointerProgress(dmgRaf); 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_ZERO2) { if(DEBUG) println(" " + elementNumber + ":" + blockCount + ". BT_ZERO2 processing..."); if(!testOnly && isoRaf.getFilePointer() != outOffset) { println(" " + elementNumber + ":" + blockCount + ". WARNING: BT_ZERO2 FP != outOffset (" + isoRaf.getFilePointer() + " != " + outOffset + ")"); ++warningsReported; } reportFilePointerProgress(dmgRaf); 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(" " + elementNumber + ":" + blockCount + ". BT_UNKNOWN processing..."); if(!(inSize == 0 && outSize == 0)) { println(" " + elementNumber + ":" + blockCount + ". WARNING: Blocktype BT_UNKNOWN had non-zero sizes...", " inSize=" + inSize + ", outSize=" + outSize); ++warningsReported; //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(" " + elementNumber + ":" + blockCount + ". BT_END processing..."); if(!testOnly && isoRaf.getFilePointer() != outOffset) println(" " + elementNumber + ":" + blockCount + ". WARNING: BT_END FP != outOffset (" + isoRaf.getFilePointer() + " != " + outOffset + ")"); //lastOffs += lastInOffs; lastOutOffset = outOffset; lastInOffset += lastByteReadInBlock; } else { println(" " + elementNumber + ":" + blockCount + ". WARNING: previously unseen blocktype " + blockType + " [0x" + Integer.toHexString(blockType) + "]", " " + elementNumber + ":" + blockCount + ". outOffset=" + outOffset + " outSize=" + outSize + " inOffset=" + inOffset + " inSize=" + inSize); ++warningsReported; if(!testOnly && isoRaf.getFilePointer() != outOffset) println(" " + elementNumber + ":" + blockCount + ". unknown blocktype FP != outOffset (" + isoRaf.getFilePointer() + " != " + outOffset + ")"); } offset += 0x28; ++blockCount; } } ++elementNumber; } //printlnVerbose("Progress: 100% Done!"); reportProgress(100); String summary = (errorsReported != 0)?errorsReported+" errors reported":"No errors reported"; summary += (warningsReported != 0)?" ("+warningsReported+" warnings emitted).":"."; if(!graphical) { newline(); println(summary); printlnVerbose("Total extracted bytes: " + totalSize + " B"); } else { progmon.close(); JOptionPane.showMessageDialog(null, "Extraction complete! " + summary + "\n" + "Total extracted bytes: " + totalSize + " B", "Information", JOptionPane.INFORMATION_MESSAGE); System.exit(0); } if(!DEBUG) { if(isoRaf != null) isoRaf.close(); dmgRaf.close(); } else { if(isoRaf != null) isoRaf.close();// 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()); 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"; println(" " + new File(filename).getCanonicalPath() + "..."); 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"; println(" " + new File(filename).getCanonicalPath() + "..."); 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"; println(" " + new File(filename).getCanonicalPath() + "..."); 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!"); } } |
println(" " + elementNumber + ":" + blockCount + ". ERROR: BT_BZIP2 not currently supported."); | println("!------>ERROR: BT_BZIP2 not currently supported."); | public static void notmain(String[] args) throws Exception { 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[] inBuffer = new byte[0x40000]; byte[] outBuffer = 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 elementNumber = 0; //long lastOffs = 0; long lastOutOffset = 0; long lastInOffset = 0; long totalSize = 0; int errorsReported = 0; int warningsReported = 0; 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; 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 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) { if(DEBUG) println("!-----addInOffset mode: inOffset tranformation " + inOffset + "->" + (inOffset+lastInOffset)); inOffset += lastInOffset; } else if(inOffset == 0) { if(DEBUG) println("!-----Detected inOffset == 0, setting to " + lastInOffset); addInOffset = true; inOffset = lastInOffset; } outOffset += lastOutOffset; DMGBlock currentBlock = new DMGBlock(blockType, skipped, outOffset, outSize, inOffset, inSize); blocks.add(currentBlock); if(DEBUG) { println("outOffset=" + outOffset + " outSize=" + outSize + " inOffset=" + inOffset + " inSize=" + inSize + " lastOutOffset=" + lastOutOffset + " lastInOffset=" + lastInOffset /*+ " lastInOffs=" + lastInOffs + " lastOffs=" + lastOffs*/); } if(blockType == BT_ADC) { println(" " + elementNumber + ":" + blockCount + ". ERROR: BT_ADC not supported."); ++errorsReported; if(!testOnly) System.exit(0); } else if(blockType == BT_ZLIB) { if(DEBUG) println(" " + elementNumber + ":" + blockCount + ". BT_ZLIB processing..."); if(!testOnly && isoRaf.getFilePointer() != outOffset) println(" " + elementNumber + ":" + blockCount + ". WARNING: BT_ZLIB FP != outOffset (" + isoRaf.getFilePointer() + " != " + outOffset + ")"); try { DMGBlockHandlers.processZlibBlock(currentBlock, dmgRaf, isoRaf, testOnly, dummyMonitor); } catch(DataFormatException dfe) { println(" " + elementNumber + ":" + blockCount + ". ERROR: BT_ZLIB Could not decode..."); ++errorsReported; 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); break; } } } else if(blockType == BT_BZIP2) { println(" " + elementNumber + ":" + blockCount + ". ERROR: BT_BZIP2 not currently supported."); ++errorsReported; if(!testOnly) System.exit(0); } else if(blockType == BT_COPY) { if(DEBUG) println(" " + elementNumber + ":" + blockCount + ". BT_COPY processing..."); if(!testOnly && isoRaf.getFilePointer() != outOffset) { println(" " + elementNumber + ":" + blockCount + ". WARNING: BT_COPY FP != outOffset (" + isoRaf.getFilePointer() + " != " + outOffset + ")"); ++warningsReported; } dmgRaf.seek(/*lastOffs+*/inOffset); int bytesRead = dmgRaf.read(inBuffer, 0, Math.min((int)inSize, inBuffer.length)); long totalBytesRead = bytesRead; while(bytesRead != -1) { reportFilePointerProgress(dmgRaf); if(!testOnly) isoRaf.write(inBuffer, 0, bytesRead); if(totalBytesRead >= inSize) break; bytesRead = dmgRaf.read(inBuffer, 0, Math.min((int)(inSize-totalBytesRead), inBuffer.length)); if(bytesRead > 0) totalBytesRead += bytesRead; } //lastInOffs = inOffset+inSize; } else if(blockType == BT_ZERO) { if(DEBUG) println(" " + elementNumber + ":" + blockCount + ". BT_ZERO processing..."); if(!testOnly && isoRaf.getFilePointer() != outOffset) { println(" " + elementNumber + ":" + blockCount + ". WARNING: BT_ZERO FP != outOffset (" + isoRaf.getFilePointer() + " != " + outOffset + ")"); ++warningsReported; } reportFilePointerProgress(dmgRaf); 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_ZERO2) { if(DEBUG) println(" " + elementNumber + ":" + blockCount + ". BT_ZERO2 processing..."); if(!testOnly && isoRaf.getFilePointer() != outOffset) { println(" " + elementNumber + ":" + blockCount + ". WARNING: BT_ZERO2 FP != outOffset (" + isoRaf.getFilePointer() + " != " + outOffset + ")"); ++warningsReported; } reportFilePointerProgress(dmgRaf); 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(" " + elementNumber + ":" + blockCount + ". BT_UNKNOWN processing..."); if(!(inSize == 0 && outSize == 0)) { println(" " + elementNumber + ":" + blockCount + ". WARNING: Blocktype BT_UNKNOWN had non-zero sizes...", " inSize=" + inSize + ", outSize=" + outSize); ++warningsReported; //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(" " + elementNumber + ":" + blockCount + ". BT_END processing..."); if(!testOnly && isoRaf.getFilePointer() != outOffset) println(" " + elementNumber + ":" + blockCount + ". WARNING: BT_END FP != outOffset (" + isoRaf.getFilePointer() + " != " + outOffset + ")"); //lastOffs += lastInOffs; lastOutOffset = outOffset; lastInOffset += lastByteReadInBlock; } else { println(" " + elementNumber + ":" + blockCount + ". WARNING: previously unseen blocktype " + blockType + " [0x" + Integer.toHexString(blockType) + "]", " " + elementNumber + ":" + blockCount + ". outOffset=" + outOffset + " outSize=" + outSize + " inOffset=" + inOffset + " inSize=" + inSize); ++warningsReported; if(!testOnly && isoRaf.getFilePointer() != outOffset) println(" " + elementNumber + ":" + blockCount + ". unknown blocktype FP != outOffset (" + isoRaf.getFilePointer() + " != " + outOffset + ")"); } offset += 0x28; ++blockCount; } } ++elementNumber; } //printlnVerbose("Progress: 100% Done!"); reportProgress(100); String summary = (errorsReported != 0)?errorsReported+" errors reported":"No errors reported"; summary += (warningsReported != 0)?" ("+warningsReported+" warnings emitted).":"."; if(!graphical) { newline(); println(summary); printlnVerbose("Total extracted bytes: " + totalSize + " B"); } else { progmon.close(); JOptionPane.showMessageDialog(null, "Extraction complete! " + summary + "\n" + "Total extracted bytes: " + totalSize + " B", "Information", JOptionPane.INFORMATION_MESSAGE); System.exit(0); } if(!DEBUG) { if(isoRaf != null) isoRaf.close(); dmgRaf.close(); } else { if(isoRaf != null) isoRaf.close();// 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()); 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"; println(" " + new File(filename).getCanonicalPath() + "..."); 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"; println(" " + new File(filename).getCanonicalPath() + "..."); 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"; println(" " + new File(filename).getCanonicalPath() + "..."); 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!"); } } |
if(DEBUG) println(" " + elementNumber + ":" + blockCount + ". BT_COPY processing..."); | public static void notmain(String[] args) throws Exception { 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[] inBuffer = new byte[0x40000]; byte[] outBuffer = 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 elementNumber = 0; //long lastOffs = 0; long lastOutOffset = 0; long lastInOffset = 0; long totalSize = 0; int errorsReported = 0; int warningsReported = 0; 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; 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 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) { if(DEBUG) println("!-----addInOffset mode: inOffset tranformation " + inOffset + "->" + (inOffset+lastInOffset)); inOffset += lastInOffset; } else if(inOffset == 0) { if(DEBUG) println("!-----Detected inOffset == 0, setting to " + lastInOffset); addInOffset = true; inOffset = lastInOffset; } outOffset += lastOutOffset; DMGBlock currentBlock = new DMGBlock(blockType, skipped, outOffset, outSize, inOffset, inSize); blocks.add(currentBlock); if(DEBUG) { println("outOffset=" + outOffset + " outSize=" + outSize + " inOffset=" + inOffset + " inSize=" + inSize + " lastOutOffset=" + lastOutOffset + " lastInOffset=" + lastInOffset /*+ " lastInOffs=" + lastInOffs + " lastOffs=" + lastOffs*/); } if(blockType == BT_ADC) { println(" " + elementNumber + ":" + blockCount + ". ERROR: BT_ADC not supported."); ++errorsReported; if(!testOnly) System.exit(0); } else if(blockType == BT_ZLIB) { if(DEBUG) println(" " + elementNumber + ":" + blockCount + ". BT_ZLIB processing..."); if(!testOnly && isoRaf.getFilePointer() != outOffset) println(" " + elementNumber + ":" + blockCount + ". WARNING: BT_ZLIB FP != outOffset (" + isoRaf.getFilePointer() + " != " + outOffset + ")"); try { DMGBlockHandlers.processZlibBlock(currentBlock, dmgRaf, isoRaf, testOnly, dummyMonitor); } catch(DataFormatException dfe) { println(" " + elementNumber + ":" + blockCount + ". ERROR: BT_ZLIB Could not decode..."); ++errorsReported; 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); break; } } } else if(blockType == BT_BZIP2) { println(" " + elementNumber + ":" + blockCount + ". ERROR: BT_BZIP2 not currently supported."); ++errorsReported; if(!testOnly) System.exit(0); } else if(blockType == BT_COPY) { if(DEBUG) println(" " + elementNumber + ":" + blockCount + ". BT_COPY processing..."); if(!testOnly && isoRaf.getFilePointer() != outOffset) { println(" " + elementNumber + ":" + blockCount + ". WARNING: BT_COPY FP != outOffset (" + isoRaf.getFilePointer() + " != " + outOffset + ")"); ++warningsReported; } dmgRaf.seek(/*lastOffs+*/inOffset); int bytesRead = dmgRaf.read(inBuffer, 0, Math.min((int)inSize, inBuffer.length)); long totalBytesRead = bytesRead; while(bytesRead != -1) { reportFilePointerProgress(dmgRaf); if(!testOnly) isoRaf.write(inBuffer, 0, bytesRead); if(totalBytesRead >= inSize) break; bytesRead = dmgRaf.read(inBuffer, 0, Math.min((int)(inSize-totalBytesRead), inBuffer.length)); if(bytesRead > 0) totalBytesRead += bytesRead; } //lastInOffs = inOffset+inSize; } else if(blockType == BT_ZERO) { if(DEBUG) println(" " + elementNumber + ":" + blockCount + ". BT_ZERO processing..."); if(!testOnly && isoRaf.getFilePointer() != outOffset) { println(" " + elementNumber + ":" + blockCount + ". WARNING: BT_ZERO FP != outOffset (" + isoRaf.getFilePointer() + " != " + outOffset + ")"); ++warningsReported; } reportFilePointerProgress(dmgRaf); 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_ZERO2) { if(DEBUG) println(" " + elementNumber + ":" + blockCount + ". BT_ZERO2 processing..."); if(!testOnly && isoRaf.getFilePointer() != outOffset) { println(" " + elementNumber + ":" + blockCount + ". WARNING: BT_ZERO2 FP != outOffset (" + isoRaf.getFilePointer() + " != " + outOffset + ")"); ++warningsReported; } reportFilePointerProgress(dmgRaf); 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(" " + elementNumber + ":" + blockCount + ". BT_UNKNOWN processing..."); if(!(inSize == 0 && outSize == 0)) { println(" " + elementNumber + ":" + blockCount + ". WARNING: Blocktype BT_UNKNOWN had non-zero sizes...", " inSize=" + inSize + ", outSize=" + outSize); ++warningsReported; //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(" " + elementNumber + ":" + blockCount + ". BT_END processing..."); if(!testOnly && isoRaf.getFilePointer() != outOffset) println(" " + elementNumber + ":" + blockCount + ". WARNING: BT_END FP != outOffset (" + isoRaf.getFilePointer() + " != " + outOffset + ")"); //lastOffs += lastInOffs; lastOutOffset = outOffset; lastInOffset += lastByteReadInBlock; } else { println(" " + elementNumber + ":" + blockCount + ". WARNING: previously unseen blocktype " + blockType + " [0x" + Integer.toHexString(blockType) + "]", " " + elementNumber + ":" + blockCount + ". outOffset=" + outOffset + " outSize=" + outSize + " inOffset=" + inOffset + " inSize=" + inSize); ++warningsReported; if(!testOnly && isoRaf.getFilePointer() != outOffset) println(" " + elementNumber + ":" + blockCount + ". unknown blocktype FP != outOffset (" + isoRaf.getFilePointer() + " != " + outOffset + ")"); } offset += 0x28; ++blockCount; } } ++elementNumber; } //printlnVerbose("Progress: 100% Done!"); reportProgress(100); String summary = (errorsReported != 0)?errorsReported+" errors reported":"No errors reported"; summary += (warningsReported != 0)?" ("+warningsReported+" warnings emitted).":"."; if(!graphical) { newline(); println(summary); printlnVerbose("Total extracted bytes: " + totalSize + " B"); } else { progmon.close(); JOptionPane.showMessageDialog(null, "Extraction complete! " + summary + "\n" + "Total extracted bytes: " + totalSize + " B", "Information", JOptionPane.INFORMATION_MESSAGE); System.exit(0); } if(!DEBUG) { if(isoRaf != null) isoRaf.close(); dmgRaf.close(); } else { if(isoRaf != null) isoRaf.close();// 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()); 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"; println(" " + new File(filename).getCanonicalPath() + "..."); 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"; println(" " + new File(filename).getCanonicalPath() + "..."); 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"; println(" " + new File(filename).getCanonicalPath() + "..."); 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!"); } } |
|
println(" " + elementNumber + ":" + blockCount + ". WARNING: BT_COPY FP != outOffset (" + isoRaf.getFilePointer() + " != " + outOffset + ")"); | println("!------>WARNING: BT_COPY FP != outOffset (" + isoRaf.getFilePointer() + " != " + outOffset + ")"); | public static void notmain(String[] args) throws Exception { 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[] inBuffer = new byte[0x40000]; byte[] outBuffer = 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 elementNumber = 0; //long lastOffs = 0; long lastOutOffset = 0; long lastInOffset = 0; long totalSize = 0; int errorsReported = 0; int warningsReported = 0; 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; 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 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) { if(DEBUG) println("!-----addInOffset mode: inOffset tranformation " + inOffset + "->" + (inOffset+lastInOffset)); inOffset += lastInOffset; } else if(inOffset == 0) { if(DEBUG) println("!-----Detected inOffset == 0, setting to " + lastInOffset); addInOffset = true; inOffset = lastInOffset; } outOffset += lastOutOffset; DMGBlock currentBlock = new DMGBlock(blockType, skipped, outOffset, outSize, inOffset, inSize); blocks.add(currentBlock); if(DEBUG) { println("outOffset=" + outOffset + " outSize=" + outSize + " inOffset=" + inOffset + " inSize=" + inSize + " lastOutOffset=" + lastOutOffset + " lastInOffset=" + lastInOffset /*+ " lastInOffs=" + lastInOffs + " lastOffs=" + lastOffs*/); } if(blockType == BT_ADC) { println(" " + elementNumber + ":" + blockCount + ". ERROR: BT_ADC not supported."); ++errorsReported; if(!testOnly) System.exit(0); } else if(blockType == BT_ZLIB) { if(DEBUG) println(" " + elementNumber + ":" + blockCount + ". BT_ZLIB processing..."); if(!testOnly && isoRaf.getFilePointer() != outOffset) println(" " + elementNumber + ":" + blockCount + ". WARNING: BT_ZLIB FP != outOffset (" + isoRaf.getFilePointer() + " != " + outOffset + ")"); try { DMGBlockHandlers.processZlibBlock(currentBlock, dmgRaf, isoRaf, testOnly, dummyMonitor); } catch(DataFormatException dfe) { println(" " + elementNumber + ":" + blockCount + ". ERROR: BT_ZLIB Could not decode..."); ++errorsReported; 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); break; } } } else if(blockType == BT_BZIP2) { println(" " + elementNumber + ":" + blockCount + ". ERROR: BT_BZIP2 not currently supported."); ++errorsReported; if(!testOnly) System.exit(0); } else if(blockType == BT_COPY) { if(DEBUG) println(" " + elementNumber + ":" + blockCount + ". BT_COPY processing..."); if(!testOnly && isoRaf.getFilePointer() != outOffset) { println(" " + elementNumber + ":" + blockCount + ". WARNING: BT_COPY FP != outOffset (" + isoRaf.getFilePointer() + " != " + outOffset + ")"); ++warningsReported; } dmgRaf.seek(/*lastOffs+*/inOffset); int bytesRead = dmgRaf.read(inBuffer, 0, Math.min((int)inSize, inBuffer.length)); long totalBytesRead = bytesRead; while(bytesRead != -1) { reportFilePointerProgress(dmgRaf); if(!testOnly) isoRaf.write(inBuffer, 0, bytesRead); if(totalBytesRead >= inSize) break; bytesRead = dmgRaf.read(inBuffer, 0, Math.min((int)(inSize-totalBytesRead), inBuffer.length)); if(bytesRead > 0) totalBytesRead += bytesRead; } //lastInOffs = inOffset+inSize; } else if(blockType == BT_ZERO) { if(DEBUG) println(" " + elementNumber + ":" + blockCount + ". BT_ZERO processing..."); if(!testOnly && isoRaf.getFilePointer() != outOffset) { println(" " + elementNumber + ":" + blockCount + ". WARNING: BT_ZERO FP != outOffset (" + isoRaf.getFilePointer() + " != " + outOffset + ")"); ++warningsReported; } reportFilePointerProgress(dmgRaf); 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_ZERO2) { if(DEBUG) println(" " + elementNumber + ":" + blockCount + ". BT_ZERO2 processing..."); if(!testOnly && isoRaf.getFilePointer() != outOffset) { println(" " + elementNumber + ":" + blockCount + ". WARNING: BT_ZERO2 FP != outOffset (" + isoRaf.getFilePointer() + " != " + outOffset + ")"); ++warningsReported; } reportFilePointerProgress(dmgRaf); 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(" " + elementNumber + ":" + blockCount + ". BT_UNKNOWN processing..."); if(!(inSize == 0 && outSize == 0)) { println(" " + elementNumber + ":" + blockCount + ". WARNING: Blocktype BT_UNKNOWN had non-zero sizes...", " inSize=" + inSize + ", outSize=" + outSize); ++warningsReported; //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(" " + elementNumber + ":" + blockCount + ". BT_END processing..."); if(!testOnly && isoRaf.getFilePointer() != outOffset) println(" " + elementNumber + ":" + blockCount + ". WARNING: BT_END FP != outOffset (" + isoRaf.getFilePointer() + " != " + outOffset + ")"); //lastOffs += lastInOffs; lastOutOffset = outOffset; lastInOffset += lastByteReadInBlock; } else { println(" " + elementNumber + ":" + blockCount + ". WARNING: previously unseen blocktype " + blockType + " [0x" + Integer.toHexString(blockType) + "]", " " + elementNumber + ":" + blockCount + ". outOffset=" + outOffset + " outSize=" + outSize + " inOffset=" + inOffset + " inSize=" + inSize); ++warningsReported; if(!testOnly && isoRaf.getFilePointer() != outOffset) println(" " + elementNumber + ":" + blockCount + ". unknown blocktype FP != outOffset (" + isoRaf.getFilePointer() + " != " + outOffset + ")"); } offset += 0x28; ++blockCount; } } ++elementNumber; } //printlnVerbose("Progress: 100% Done!"); reportProgress(100); String summary = (errorsReported != 0)?errorsReported+" errors reported":"No errors reported"; summary += (warningsReported != 0)?" ("+warningsReported+" warnings emitted).":"."; if(!graphical) { newline(); println(summary); printlnVerbose("Total extracted bytes: " + totalSize + " B"); } else { progmon.close(); JOptionPane.showMessageDialog(null, "Extraction complete! " + summary + "\n" + "Total extracted bytes: " + totalSize + " B", "Information", JOptionPane.INFORMATION_MESSAGE); System.exit(0); } if(!DEBUG) { if(isoRaf != null) isoRaf.close(); dmgRaf.close(); } else { if(isoRaf != null) isoRaf.close();// 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()); 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"; println(" " + new File(filename).getCanonicalPath() + "..."); 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"; println(" " + new File(filename).getCanonicalPath() + "..."); 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"; println(" " + new File(filename).getCanonicalPath() + "..."); 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!"); } } |
if(DEBUG) println(" " + elementNumber + ":" + blockCount + ". BT_ZERO processing..."); | public static void notmain(String[] args) throws Exception { 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[] inBuffer = new byte[0x40000]; byte[] outBuffer = 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 elementNumber = 0; //long lastOffs = 0; long lastOutOffset = 0; long lastInOffset = 0; long totalSize = 0; int errorsReported = 0; int warningsReported = 0; 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; 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 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) { if(DEBUG) println("!-----addInOffset mode: inOffset tranformation " + inOffset + "->" + (inOffset+lastInOffset)); inOffset += lastInOffset; } else if(inOffset == 0) { if(DEBUG) println("!-----Detected inOffset == 0, setting to " + lastInOffset); addInOffset = true; inOffset = lastInOffset; } outOffset += lastOutOffset; DMGBlock currentBlock = new DMGBlock(blockType, skipped, outOffset, outSize, inOffset, inSize); blocks.add(currentBlock); if(DEBUG) { println("outOffset=" + outOffset + " outSize=" + outSize + " inOffset=" + inOffset + " inSize=" + inSize + " lastOutOffset=" + lastOutOffset + " lastInOffset=" + lastInOffset /*+ " lastInOffs=" + lastInOffs + " lastOffs=" + lastOffs*/); } if(blockType == BT_ADC) { println(" " + elementNumber + ":" + blockCount + ". ERROR: BT_ADC not supported."); ++errorsReported; if(!testOnly) System.exit(0); } else if(blockType == BT_ZLIB) { if(DEBUG) println(" " + elementNumber + ":" + blockCount + ". BT_ZLIB processing..."); if(!testOnly && isoRaf.getFilePointer() != outOffset) println(" " + elementNumber + ":" + blockCount + ". WARNING: BT_ZLIB FP != outOffset (" + isoRaf.getFilePointer() + " != " + outOffset + ")"); try { DMGBlockHandlers.processZlibBlock(currentBlock, dmgRaf, isoRaf, testOnly, dummyMonitor); } catch(DataFormatException dfe) { println(" " + elementNumber + ":" + blockCount + ". ERROR: BT_ZLIB Could not decode..."); ++errorsReported; 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); break; } } } else if(blockType == BT_BZIP2) { println(" " + elementNumber + ":" + blockCount + ". ERROR: BT_BZIP2 not currently supported."); ++errorsReported; if(!testOnly) System.exit(0); } else if(blockType == BT_COPY) { if(DEBUG) println(" " + elementNumber + ":" + blockCount + ". BT_COPY processing..."); if(!testOnly && isoRaf.getFilePointer() != outOffset) { println(" " + elementNumber + ":" + blockCount + ". WARNING: BT_COPY FP != outOffset (" + isoRaf.getFilePointer() + " != " + outOffset + ")"); ++warningsReported; } dmgRaf.seek(/*lastOffs+*/inOffset); int bytesRead = dmgRaf.read(inBuffer, 0, Math.min((int)inSize, inBuffer.length)); long totalBytesRead = bytesRead; while(bytesRead != -1) { reportFilePointerProgress(dmgRaf); if(!testOnly) isoRaf.write(inBuffer, 0, bytesRead); if(totalBytesRead >= inSize) break; bytesRead = dmgRaf.read(inBuffer, 0, Math.min((int)(inSize-totalBytesRead), inBuffer.length)); if(bytesRead > 0) totalBytesRead += bytesRead; } //lastInOffs = inOffset+inSize; } else if(blockType == BT_ZERO) { if(DEBUG) println(" " + elementNumber + ":" + blockCount + ". BT_ZERO processing..."); if(!testOnly && isoRaf.getFilePointer() != outOffset) { println(" " + elementNumber + ":" + blockCount + ". WARNING: BT_ZERO FP != outOffset (" + isoRaf.getFilePointer() + " != " + outOffset + ")"); ++warningsReported; } reportFilePointerProgress(dmgRaf); 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_ZERO2) { if(DEBUG) println(" " + elementNumber + ":" + blockCount + ". BT_ZERO2 processing..."); if(!testOnly && isoRaf.getFilePointer() != outOffset) { println(" " + elementNumber + ":" + blockCount + ". WARNING: BT_ZERO2 FP != outOffset (" + isoRaf.getFilePointer() + " != " + outOffset + ")"); ++warningsReported; } reportFilePointerProgress(dmgRaf); 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(" " + elementNumber + ":" + blockCount + ". BT_UNKNOWN processing..."); if(!(inSize == 0 && outSize == 0)) { println(" " + elementNumber + ":" + blockCount + ". WARNING: Blocktype BT_UNKNOWN had non-zero sizes...", " inSize=" + inSize + ", outSize=" + outSize); ++warningsReported; //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(" " + elementNumber + ":" + blockCount + ". BT_END processing..."); if(!testOnly && isoRaf.getFilePointer() != outOffset) println(" " + elementNumber + ":" + blockCount + ". WARNING: BT_END FP != outOffset (" + isoRaf.getFilePointer() + " != " + outOffset + ")"); //lastOffs += lastInOffs; lastOutOffset = outOffset; lastInOffset += lastByteReadInBlock; } else { println(" " + elementNumber + ":" + blockCount + ". WARNING: previously unseen blocktype " + blockType + " [0x" + Integer.toHexString(blockType) + "]", " " + elementNumber + ":" + blockCount + ". outOffset=" + outOffset + " outSize=" + outSize + " inOffset=" + inOffset + " inSize=" + inSize); ++warningsReported; if(!testOnly && isoRaf.getFilePointer() != outOffset) println(" " + elementNumber + ":" + blockCount + ". unknown blocktype FP != outOffset (" + isoRaf.getFilePointer() + " != " + outOffset + ")"); } offset += 0x28; ++blockCount; } } ++elementNumber; } //printlnVerbose("Progress: 100% Done!"); reportProgress(100); String summary = (errorsReported != 0)?errorsReported+" errors reported":"No errors reported"; summary += (warningsReported != 0)?" ("+warningsReported+" warnings emitted).":"."; if(!graphical) { newline(); println(summary); printlnVerbose("Total extracted bytes: " + totalSize + " B"); } else { progmon.close(); JOptionPane.showMessageDialog(null, "Extraction complete! " + summary + "\n" + "Total extracted bytes: " + totalSize + " B", "Information", JOptionPane.INFORMATION_MESSAGE); System.exit(0); } if(!DEBUG) { if(isoRaf != null) isoRaf.close(); dmgRaf.close(); } else { if(isoRaf != null) isoRaf.close();// 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()); 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"; println(" " + new File(filename).getCanonicalPath() + "..."); 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"; println(" " + new File(filename).getCanonicalPath() + "..."); 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"; println(" " + new File(filename).getCanonicalPath() + "..."); 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!"); } } |
|
println(" " + elementNumber + ":" + blockCount + ". WARNING: BT_ZERO FP != outOffset (" + | println("!------>WARNING: BT_ZERO FP != outOffset (" + | public static void notmain(String[] args) throws Exception { 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[] inBuffer = new byte[0x40000]; byte[] outBuffer = 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 elementNumber = 0; //long lastOffs = 0; long lastOutOffset = 0; long lastInOffset = 0; long totalSize = 0; int errorsReported = 0; int warningsReported = 0; 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; 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 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) { if(DEBUG) println("!-----addInOffset mode: inOffset tranformation " + inOffset + "->" + (inOffset+lastInOffset)); inOffset += lastInOffset; } else if(inOffset == 0) { if(DEBUG) println("!-----Detected inOffset == 0, setting to " + lastInOffset); addInOffset = true; inOffset = lastInOffset; } outOffset += lastOutOffset; DMGBlock currentBlock = new DMGBlock(blockType, skipped, outOffset, outSize, inOffset, inSize); blocks.add(currentBlock); if(DEBUG) { println("outOffset=" + outOffset + " outSize=" + outSize + " inOffset=" + inOffset + " inSize=" + inSize + " lastOutOffset=" + lastOutOffset + " lastInOffset=" + lastInOffset /*+ " lastInOffs=" + lastInOffs + " lastOffs=" + lastOffs*/); } if(blockType == BT_ADC) { println(" " + elementNumber + ":" + blockCount + ". ERROR: BT_ADC not supported."); ++errorsReported; if(!testOnly) System.exit(0); } else if(blockType == BT_ZLIB) { if(DEBUG) println(" " + elementNumber + ":" + blockCount + ". BT_ZLIB processing..."); if(!testOnly && isoRaf.getFilePointer() != outOffset) println(" " + elementNumber + ":" + blockCount + ". WARNING: BT_ZLIB FP != outOffset (" + isoRaf.getFilePointer() + " != " + outOffset + ")"); try { DMGBlockHandlers.processZlibBlock(currentBlock, dmgRaf, isoRaf, testOnly, dummyMonitor); } catch(DataFormatException dfe) { println(" " + elementNumber + ":" + blockCount + ". ERROR: BT_ZLIB Could not decode..."); ++errorsReported; 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); break; } } } else if(blockType == BT_BZIP2) { println(" " + elementNumber + ":" + blockCount + ". ERROR: BT_BZIP2 not currently supported."); ++errorsReported; if(!testOnly) System.exit(0); } else if(blockType == BT_COPY) { if(DEBUG) println(" " + elementNumber + ":" + blockCount + ". BT_COPY processing..."); if(!testOnly && isoRaf.getFilePointer() != outOffset) { println(" " + elementNumber + ":" + blockCount + ". WARNING: BT_COPY FP != outOffset (" + isoRaf.getFilePointer() + " != " + outOffset + ")"); ++warningsReported; } dmgRaf.seek(/*lastOffs+*/inOffset); int bytesRead = dmgRaf.read(inBuffer, 0, Math.min((int)inSize, inBuffer.length)); long totalBytesRead = bytesRead; while(bytesRead != -1) { reportFilePointerProgress(dmgRaf); if(!testOnly) isoRaf.write(inBuffer, 0, bytesRead); if(totalBytesRead >= inSize) break; bytesRead = dmgRaf.read(inBuffer, 0, Math.min((int)(inSize-totalBytesRead), inBuffer.length)); if(bytesRead > 0) totalBytesRead += bytesRead; } //lastInOffs = inOffset+inSize; } else if(blockType == BT_ZERO) { if(DEBUG) println(" " + elementNumber + ":" + blockCount + ". BT_ZERO processing..."); if(!testOnly && isoRaf.getFilePointer() != outOffset) { println(" " + elementNumber + ":" + blockCount + ". WARNING: BT_ZERO FP != outOffset (" + isoRaf.getFilePointer() + " != " + outOffset + ")"); ++warningsReported; } reportFilePointerProgress(dmgRaf); 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_ZERO2) { if(DEBUG) println(" " + elementNumber + ":" + blockCount + ". BT_ZERO2 processing..."); if(!testOnly && isoRaf.getFilePointer() != outOffset) { println(" " + elementNumber + ":" + blockCount + ". WARNING: BT_ZERO2 FP != outOffset (" + isoRaf.getFilePointer() + " != " + outOffset + ")"); ++warningsReported; } reportFilePointerProgress(dmgRaf); 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(" " + elementNumber + ":" + blockCount + ". BT_UNKNOWN processing..."); if(!(inSize == 0 && outSize == 0)) { println(" " + elementNumber + ":" + blockCount + ". WARNING: Blocktype BT_UNKNOWN had non-zero sizes...", " inSize=" + inSize + ", outSize=" + outSize); ++warningsReported; //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(" " + elementNumber + ":" + blockCount + ". BT_END processing..."); if(!testOnly && isoRaf.getFilePointer() != outOffset) println(" " + elementNumber + ":" + blockCount + ". WARNING: BT_END FP != outOffset (" + isoRaf.getFilePointer() + " != " + outOffset + ")"); //lastOffs += lastInOffs; lastOutOffset = outOffset; lastInOffset += lastByteReadInBlock; } else { println(" " + elementNumber + ":" + blockCount + ". WARNING: previously unseen blocktype " + blockType + " [0x" + Integer.toHexString(blockType) + "]", " " + elementNumber + ":" + blockCount + ". outOffset=" + outOffset + " outSize=" + outSize + " inOffset=" + inOffset + " inSize=" + inSize); ++warningsReported; if(!testOnly && isoRaf.getFilePointer() != outOffset) println(" " + elementNumber + ":" + blockCount + ". unknown blocktype FP != outOffset (" + isoRaf.getFilePointer() + " != " + outOffset + ")"); } offset += 0x28; ++blockCount; } } ++elementNumber; } //printlnVerbose("Progress: 100% Done!"); reportProgress(100); String summary = (errorsReported != 0)?errorsReported+" errors reported":"No errors reported"; summary += (warningsReported != 0)?" ("+warningsReported+" warnings emitted).":"."; if(!graphical) { newline(); println(summary); printlnVerbose("Total extracted bytes: " + totalSize + " B"); } else { progmon.close(); JOptionPane.showMessageDialog(null, "Extraction complete! " + summary + "\n" + "Total extracted bytes: " + totalSize + " B", "Information", JOptionPane.INFORMATION_MESSAGE); System.exit(0); } if(!DEBUG) { if(isoRaf != null) isoRaf.close(); dmgRaf.close(); } else { if(isoRaf != null) isoRaf.close();// 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()); 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"; println(" " + new File(filename).getCanonicalPath() + "..."); 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"; println(" " + new File(filename).getCanonicalPath() + "..."); 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"; println(" " + new File(filename).getCanonicalPath() + "..."); 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!"); } } |
if(DEBUG) println(" " + elementNumber + ":" + blockCount + ". BT_ZERO2 processing..."); | public static void notmain(String[] args) throws Exception { 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[] inBuffer = new byte[0x40000]; byte[] outBuffer = 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 elementNumber = 0; //long lastOffs = 0; long lastOutOffset = 0; long lastInOffset = 0; long totalSize = 0; int errorsReported = 0; int warningsReported = 0; 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; 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 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) { if(DEBUG) println("!-----addInOffset mode: inOffset tranformation " + inOffset + "->" + (inOffset+lastInOffset)); inOffset += lastInOffset; } else if(inOffset == 0) { if(DEBUG) println("!-----Detected inOffset == 0, setting to " + lastInOffset); addInOffset = true; inOffset = lastInOffset; } outOffset += lastOutOffset; DMGBlock currentBlock = new DMGBlock(blockType, skipped, outOffset, outSize, inOffset, inSize); blocks.add(currentBlock); if(DEBUG) { println("outOffset=" + outOffset + " outSize=" + outSize + " inOffset=" + inOffset + " inSize=" + inSize + " lastOutOffset=" + lastOutOffset + " lastInOffset=" + lastInOffset /*+ " lastInOffs=" + lastInOffs + " lastOffs=" + lastOffs*/); } if(blockType == BT_ADC) { println(" " + elementNumber + ":" + blockCount + ". ERROR: BT_ADC not supported."); ++errorsReported; if(!testOnly) System.exit(0); } else if(blockType == BT_ZLIB) { if(DEBUG) println(" " + elementNumber + ":" + blockCount + ". BT_ZLIB processing..."); if(!testOnly && isoRaf.getFilePointer() != outOffset) println(" " + elementNumber + ":" + blockCount + ". WARNING: BT_ZLIB FP != outOffset (" + isoRaf.getFilePointer() + " != " + outOffset + ")"); try { DMGBlockHandlers.processZlibBlock(currentBlock, dmgRaf, isoRaf, testOnly, dummyMonitor); } catch(DataFormatException dfe) { println(" " + elementNumber + ":" + blockCount + ". ERROR: BT_ZLIB Could not decode..."); ++errorsReported; 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); break; } } } else if(blockType == BT_BZIP2) { println(" " + elementNumber + ":" + blockCount + ". ERROR: BT_BZIP2 not currently supported."); ++errorsReported; if(!testOnly) System.exit(0); } else if(blockType == BT_COPY) { if(DEBUG) println(" " + elementNumber + ":" + blockCount + ". BT_COPY processing..."); if(!testOnly && isoRaf.getFilePointer() != outOffset) { println(" " + elementNumber + ":" + blockCount + ". WARNING: BT_COPY FP != outOffset (" + isoRaf.getFilePointer() + " != " + outOffset + ")"); ++warningsReported; } dmgRaf.seek(/*lastOffs+*/inOffset); int bytesRead = dmgRaf.read(inBuffer, 0, Math.min((int)inSize, inBuffer.length)); long totalBytesRead = bytesRead; while(bytesRead != -1) { reportFilePointerProgress(dmgRaf); if(!testOnly) isoRaf.write(inBuffer, 0, bytesRead); if(totalBytesRead >= inSize) break; bytesRead = dmgRaf.read(inBuffer, 0, Math.min((int)(inSize-totalBytesRead), inBuffer.length)); if(bytesRead > 0) totalBytesRead += bytesRead; } //lastInOffs = inOffset+inSize; } else if(blockType == BT_ZERO) { if(DEBUG) println(" " + elementNumber + ":" + blockCount + ". BT_ZERO processing..."); if(!testOnly && isoRaf.getFilePointer() != outOffset) { println(" " + elementNumber + ":" + blockCount + ". WARNING: BT_ZERO FP != outOffset (" + isoRaf.getFilePointer() + " != " + outOffset + ")"); ++warningsReported; } reportFilePointerProgress(dmgRaf); 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_ZERO2) { if(DEBUG) println(" " + elementNumber + ":" + blockCount + ". BT_ZERO2 processing..."); if(!testOnly && isoRaf.getFilePointer() != outOffset) { println(" " + elementNumber + ":" + blockCount + ". WARNING: BT_ZERO2 FP != outOffset (" + isoRaf.getFilePointer() + " != " + outOffset + ")"); ++warningsReported; } reportFilePointerProgress(dmgRaf); 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(" " + elementNumber + ":" + blockCount + ". BT_UNKNOWN processing..."); if(!(inSize == 0 && outSize == 0)) { println(" " + elementNumber + ":" + blockCount + ". WARNING: Blocktype BT_UNKNOWN had non-zero sizes...", " inSize=" + inSize + ", outSize=" + outSize); ++warningsReported; //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(" " + elementNumber + ":" + blockCount + ". BT_END processing..."); if(!testOnly && isoRaf.getFilePointer() != outOffset) println(" " + elementNumber + ":" + blockCount + ". WARNING: BT_END FP != outOffset (" + isoRaf.getFilePointer() + " != " + outOffset + ")"); //lastOffs += lastInOffs; lastOutOffset = outOffset; lastInOffset += lastByteReadInBlock; } else { println(" " + elementNumber + ":" + blockCount + ". WARNING: previously unseen blocktype " + blockType + " [0x" + Integer.toHexString(blockType) + "]", " " + elementNumber + ":" + blockCount + ". outOffset=" + outOffset + " outSize=" + outSize + " inOffset=" + inOffset + " inSize=" + inSize); ++warningsReported; if(!testOnly && isoRaf.getFilePointer() != outOffset) println(" " + elementNumber + ":" + blockCount + ". unknown blocktype FP != outOffset (" + isoRaf.getFilePointer() + " != " + outOffset + ")"); } offset += 0x28; ++blockCount; } } ++elementNumber; } //printlnVerbose("Progress: 100% Done!"); reportProgress(100); String summary = (errorsReported != 0)?errorsReported+" errors reported":"No errors reported"; summary += (warningsReported != 0)?" ("+warningsReported+" warnings emitted).":"."; if(!graphical) { newline(); println(summary); printlnVerbose("Total extracted bytes: " + totalSize + " B"); } else { progmon.close(); JOptionPane.showMessageDialog(null, "Extraction complete! " + summary + "\n" + "Total extracted bytes: " + totalSize + " B", "Information", JOptionPane.INFORMATION_MESSAGE); System.exit(0); } if(!DEBUG) { if(isoRaf != null) isoRaf.close(); dmgRaf.close(); } else { if(isoRaf != null) isoRaf.close();// 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()); 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"; println(" " + new File(filename).getCanonicalPath() + "..."); 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"; println(" " + new File(filename).getCanonicalPath() + "..."); 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"; println(" " + new File(filename).getCanonicalPath() + "..."); 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!"); } } |
|
println(" " + elementNumber + ":" + blockCount + ". WARNING: BT_ZERO2 FP != outOffset (" + | println("!------>WARNING: BT_ZERO2 FP != outOffset (" + | public static void notmain(String[] args) throws Exception { 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[] inBuffer = new byte[0x40000]; byte[] outBuffer = 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 elementNumber = 0; //long lastOffs = 0; long lastOutOffset = 0; long lastInOffset = 0; long totalSize = 0; int errorsReported = 0; int warningsReported = 0; 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; 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 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) { if(DEBUG) println("!-----addInOffset mode: inOffset tranformation " + inOffset + "->" + (inOffset+lastInOffset)); inOffset += lastInOffset; } else if(inOffset == 0) { if(DEBUG) println("!-----Detected inOffset == 0, setting to " + lastInOffset); addInOffset = true; inOffset = lastInOffset; } outOffset += lastOutOffset; DMGBlock currentBlock = new DMGBlock(blockType, skipped, outOffset, outSize, inOffset, inSize); blocks.add(currentBlock); if(DEBUG) { println("outOffset=" + outOffset + " outSize=" + outSize + " inOffset=" + inOffset + " inSize=" + inSize + " lastOutOffset=" + lastOutOffset + " lastInOffset=" + lastInOffset /*+ " lastInOffs=" + lastInOffs + " lastOffs=" + lastOffs*/); } if(blockType == BT_ADC) { println(" " + elementNumber + ":" + blockCount + ". ERROR: BT_ADC not supported."); ++errorsReported; if(!testOnly) System.exit(0); } else if(blockType == BT_ZLIB) { if(DEBUG) println(" " + elementNumber + ":" + blockCount + ". BT_ZLIB processing..."); if(!testOnly && isoRaf.getFilePointer() != outOffset) println(" " + elementNumber + ":" + blockCount + ". WARNING: BT_ZLIB FP != outOffset (" + isoRaf.getFilePointer() + " != " + outOffset + ")"); try { DMGBlockHandlers.processZlibBlock(currentBlock, dmgRaf, isoRaf, testOnly, dummyMonitor); } catch(DataFormatException dfe) { println(" " + elementNumber + ":" + blockCount + ". ERROR: BT_ZLIB Could not decode..."); ++errorsReported; 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); break; } } } else if(blockType == BT_BZIP2) { println(" " + elementNumber + ":" + blockCount + ". ERROR: BT_BZIP2 not currently supported."); ++errorsReported; if(!testOnly) System.exit(0); } else if(blockType == BT_COPY) { if(DEBUG) println(" " + elementNumber + ":" + blockCount + ". BT_COPY processing..."); if(!testOnly && isoRaf.getFilePointer() != outOffset) { println(" " + elementNumber + ":" + blockCount + ". WARNING: BT_COPY FP != outOffset (" + isoRaf.getFilePointer() + " != " + outOffset + ")"); ++warningsReported; } dmgRaf.seek(/*lastOffs+*/inOffset); int bytesRead = dmgRaf.read(inBuffer, 0, Math.min((int)inSize, inBuffer.length)); long totalBytesRead = bytesRead; while(bytesRead != -1) { reportFilePointerProgress(dmgRaf); if(!testOnly) isoRaf.write(inBuffer, 0, bytesRead); if(totalBytesRead >= inSize) break; bytesRead = dmgRaf.read(inBuffer, 0, Math.min((int)(inSize-totalBytesRead), inBuffer.length)); if(bytesRead > 0) totalBytesRead += bytesRead; } //lastInOffs = inOffset+inSize; } else if(blockType == BT_ZERO) { if(DEBUG) println(" " + elementNumber + ":" + blockCount + ". BT_ZERO processing..."); if(!testOnly && isoRaf.getFilePointer() != outOffset) { println(" " + elementNumber + ":" + blockCount + ". WARNING: BT_ZERO FP != outOffset (" + isoRaf.getFilePointer() + " != " + outOffset + ")"); ++warningsReported; } reportFilePointerProgress(dmgRaf); 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_ZERO2) { if(DEBUG) println(" " + elementNumber + ":" + blockCount + ". BT_ZERO2 processing..."); if(!testOnly && isoRaf.getFilePointer() != outOffset) { println(" " + elementNumber + ":" + blockCount + ". WARNING: BT_ZERO2 FP != outOffset (" + isoRaf.getFilePointer() + " != " + outOffset + ")"); ++warningsReported; } reportFilePointerProgress(dmgRaf); 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(" " + elementNumber + ":" + blockCount + ". BT_UNKNOWN processing..."); if(!(inSize == 0 && outSize == 0)) { println(" " + elementNumber + ":" + blockCount + ". WARNING: Blocktype BT_UNKNOWN had non-zero sizes...", " inSize=" + inSize + ", outSize=" + outSize); ++warningsReported; //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(" " + elementNumber + ":" + blockCount + ". BT_END processing..."); if(!testOnly && isoRaf.getFilePointer() != outOffset) println(" " + elementNumber + ":" + blockCount + ". WARNING: BT_END FP != outOffset (" + isoRaf.getFilePointer() + " != " + outOffset + ")"); //lastOffs += lastInOffs; lastOutOffset = outOffset; lastInOffset += lastByteReadInBlock; } else { println(" " + elementNumber + ":" + blockCount + ". WARNING: previously unseen blocktype " + blockType + " [0x" + Integer.toHexString(blockType) + "]", " " + elementNumber + ":" + blockCount + ". outOffset=" + outOffset + " outSize=" + outSize + " inOffset=" + inOffset + " inSize=" + inSize); ++warningsReported; if(!testOnly && isoRaf.getFilePointer() != outOffset) println(" " + elementNumber + ":" + blockCount + ". unknown blocktype FP != outOffset (" + isoRaf.getFilePointer() + " != " + outOffset + ")"); } offset += 0x28; ++blockCount; } } ++elementNumber; } //printlnVerbose("Progress: 100% Done!"); reportProgress(100); String summary = (errorsReported != 0)?errorsReported+" errors reported":"No errors reported"; summary += (warningsReported != 0)?" ("+warningsReported+" warnings emitted).":"."; if(!graphical) { newline(); println(summary); printlnVerbose("Total extracted bytes: " + totalSize + " B"); } else { progmon.close(); JOptionPane.showMessageDialog(null, "Extraction complete! " + summary + "\n" + "Total extracted bytes: " + totalSize + " B", "Information", JOptionPane.INFORMATION_MESSAGE); System.exit(0); } if(!DEBUG) { if(isoRaf != null) isoRaf.close(); dmgRaf.close(); } else { if(isoRaf != null) isoRaf.close();// 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()); 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"; println(" " + new File(filename).getCanonicalPath() + "..."); 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"; println(" " + new File(filename).getCanonicalPath() + "..."); 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"; println(" " + new File(filename).getCanonicalPath() + "..."); 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!"); } } |
if(DEBUG) println(" " + elementNumber + ":" + blockCount + ". BT_UNKNOWN processing..."); | public static void notmain(String[] args) throws Exception { 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[] inBuffer = new byte[0x40000]; byte[] outBuffer = 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 elementNumber = 0; //long lastOffs = 0; long lastOutOffset = 0; long lastInOffset = 0; long totalSize = 0; int errorsReported = 0; int warningsReported = 0; 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; 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 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) { if(DEBUG) println("!-----addInOffset mode: inOffset tranformation " + inOffset + "->" + (inOffset+lastInOffset)); inOffset += lastInOffset; } else if(inOffset == 0) { if(DEBUG) println("!-----Detected inOffset == 0, setting to " + lastInOffset); addInOffset = true; inOffset = lastInOffset; } outOffset += lastOutOffset; DMGBlock currentBlock = new DMGBlock(blockType, skipped, outOffset, outSize, inOffset, inSize); blocks.add(currentBlock); if(DEBUG) { println("outOffset=" + outOffset + " outSize=" + outSize + " inOffset=" + inOffset + " inSize=" + inSize + " lastOutOffset=" + lastOutOffset + " lastInOffset=" + lastInOffset /*+ " lastInOffs=" + lastInOffs + " lastOffs=" + lastOffs*/); } if(blockType == BT_ADC) { println(" " + elementNumber + ":" + blockCount + ". ERROR: BT_ADC not supported."); ++errorsReported; if(!testOnly) System.exit(0); } else if(blockType == BT_ZLIB) { if(DEBUG) println(" " + elementNumber + ":" + blockCount + ". BT_ZLIB processing..."); if(!testOnly && isoRaf.getFilePointer() != outOffset) println(" " + elementNumber + ":" + blockCount + ". WARNING: BT_ZLIB FP != outOffset (" + isoRaf.getFilePointer() + " != " + outOffset + ")"); try { DMGBlockHandlers.processZlibBlock(currentBlock, dmgRaf, isoRaf, testOnly, dummyMonitor); } catch(DataFormatException dfe) { println(" " + elementNumber + ":" + blockCount + ". ERROR: BT_ZLIB Could not decode..."); ++errorsReported; 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); break; } } } else if(blockType == BT_BZIP2) { println(" " + elementNumber + ":" + blockCount + ". ERROR: BT_BZIP2 not currently supported."); ++errorsReported; if(!testOnly) System.exit(0); } else if(blockType == BT_COPY) { if(DEBUG) println(" " + elementNumber + ":" + blockCount + ". BT_COPY processing..."); if(!testOnly && isoRaf.getFilePointer() != outOffset) { println(" " + elementNumber + ":" + blockCount + ". WARNING: BT_COPY FP != outOffset (" + isoRaf.getFilePointer() + " != " + outOffset + ")"); ++warningsReported; } dmgRaf.seek(/*lastOffs+*/inOffset); int bytesRead = dmgRaf.read(inBuffer, 0, Math.min((int)inSize, inBuffer.length)); long totalBytesRead = bytesRead; while(bytesRead != -1) { reportFilePointerProgress(dmgRaf); if(!testOnly) isoRaf.write(inBuffer, 0, bytesRead); if(totalBytesRead >= inSize) break; bytesRead = dmgRaf.read(inBuffer, 0, Math.min((int)(inSize-totalBytesRead), inBuffer.length)); if(bytesRead > 0) totalBytesRead += bytesRead; } //lastInOffs = inOffset+inSize; } else if(blockType == BT_ZERO) { if(DEBUG) println(" " + elementNumber + ":" + blockCount + ". BT_ZERO processing..."); if(!testOnly && isoRaf.getFilePointer() != outOffset) { println(" " + elementNumber + ":" + blockCount + ". WARNING: BT_ZERO FP != outOffset (" + isoRaf.getFilePointer() + " != " + outOffset + ")"); ++warningsReported; } reportFilePointerProgress(dmgRaf); 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_ZERO2) { if(DEBUG) println(" " + elementNumber + ":" + blockCount + ". BT_ZERO2 processing..."); if(!testOnly && isoRaf.getFilePointer() != outOffset) { println(" " + elementNumber + ":" + blockCount + ". WARNING: BT_ZERO2 FP != outOffset (" + isoRaf.getFilePointer() + " != " + outOffset + ")"); ++warningsReported; } reportFilePointerProgress(dmgRaf); 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(" " + elementNumber + ":" + blockCount + ". BT_UNKNOWN processing..."); if(!(inSize == 0 && outSize == 0)) { println(" " + elementNumber + ":" + blockCount + ". WARNING: Blocktype BT_UNKNOWN had non-zero sizes...", " inSize=" + inSize + ", outSize=" + outSize); ++warningsReported; //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(" " + elementNumber + ":" + blockCount + ". BT_END processing..."); if(!testOnly && isoRaf.getFilePointer() != outOffset) println(" " + elementNumber + ":" + blockCount + ". WARNING: BT_END FP != outOffset (" + isoRaf.getFilePointer() + " != " + outOffset + ")"); //lastOffs += lastInOffs; lastOutOffset = outOffset; lastInOffset += lastByteReadInBlock; } else { println(" " + elementNumber + ":" + blockCount + ". WARNING: previously unseen blocktype " + blockType + " [0x" + Integer.toHexString(blockType) + "]", " " + elementNumber + ":" + blockCount + ". outOffset=" + outOffset + " outSize=" + outSize + " inOffset=" + inOffset + " inSize=" + inSize); ++warningsReported; if(!testOnly && isoRaf.getFilePointer() != outOffset) println(" " + elementNumber + ":" + blockCount + ". unknown blocktype FP != outOffset (" + isoRaf.getFilePointer() + " != " + outOffset + ")"); } offset += 0x28; ++blockCount; } } ++elementNumber; } //printlnVerbose("Progress: 100% Done!"); reportProgress(100); String summary = (errorsReported != 0)?errorsReported+" errors reported":"No errors reported"; summary += (warningsReported != 0)?" ("+warningsReported+" warnings emitted).":"."; if(!graphical) { newline(); println(summary); printlnVerbose("Total extracted bytes: " + totalSize + " B"); } else { progmon.close(); JOptionPane.showMessageDialog(null, "Extraction complete! " + summary + "\n" + "Total extracted bytes: " + totalSize + " B", "Information", JOptionPane.INFORMATION_MESSAGE); System.exit(0); } if(!DEBUG) { if(isoRaf != null) isoRaf.close(); dmgRaf.close(); } else { if(isoRaf != null) isoRaf.close();// 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()); 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"; println(" " + new File(filename).getCanonicalPath() + "..."); 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"; println(" " + new File(filename).getCanonicalPath() + "..."); 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"; println(" " + new File(filename).getCanonicalPath() + "..."); 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!"); } } |
|
println(" " + elementNumber + ":" + blockCount + ". WARNING: Blocktype BT_UNKNOWN had non-zero sizes...", " inSize=" + inSize + ", outSize=" + outSize); | println("!------>WARNING: Blocktype BT_UNKNOWN had non-zero sizes...", "!------> inSize=" + inSize + ", outSize=" + outSize); | public static void notmain(String[] args) throws Exception { 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[] inBuffer = new byte[0x40000]; byte[] outBuffer = 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 elementNumber = 0; //long lastOffs = 0; long lastOutOffset = 0; long lastInOffset = 0; long totalSize = 0; int errorsReported = 0; int warningsReported = 0; 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; 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 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) { if(DEBUG) println("!-----addInOffset mode: inOffset tranformation " + inOffset + "->" + (inOffset+lastInOffset)); inOffset += lastInOffset; } else if(inOffset == 0) { if(DEBUG) println("!-----Detected inOffset == 0, setting to " + lastInOffset); addInOffset = true; inOffset = lastInOffset; } outOffset += lastOutOffset; DMGBlock currentBlock = new DMGBlock(blockType, skipped, outOffset, outSize, inOffset, inSize); blocks.add(currentBlock); if(DEBUG) { println("outOffset=" + outOffset + " outSize=" + outSize + " inOffset=" + inOffset + " inSize=" + inSize + " lastOutOffset=" + lastOutOffset + " lastInOffset=" + lastInOffset /*+ " lastInOffs=" + lastInOffs + " lastOffs=" + lastOffs*/); } if(blockType == BT_ADC) { println(" " + elementNumber + ":" + blockCount + ". ERROR: BT_ADC not supported."); ++errorsReported; if(!testOnly) System.exit(0); } else if(blockType == BT_ZLIB) { if(DEBUG) println(" " + elementNumber + ":" + blockCount + ". BT_ZLIB processing..."); if(!testOnly && isoRaf.getFilePointer() != outOffset) println(" " + elementNumber + ":" + blockCount + ". WARNING: BT_ZLIB FP != outOffset (" + isoRaf.getFilePointer() + " != " + outOffset + ")"); try { DMGBlockHandlers.processZlibBlock(currentBlock, dmgRaf, isoRaf, testOnly, dummyMonitor); } catch(DataFormatException dfe) { println(" " + elementNumber + ":" + blockCount + ". ERROR: BT_ZLIB Could not decode..."); ++errorsReported; 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); break; } } } else if(blockType == BT_BZIP2) { println(" " + elementNumber + ":" + blockCount + ". ERROR: BT_BZIP2 not currently supported."); ++errorsReported; if(!testOnly) System.exit(0); } else if(blockType == BT_COPY) { if(DEBUG) println(" " + elementNumber + ":" + blockCount + ". BT_COPY processing..."); if(!testOnly && isoRaf.getFilePointer() != outOffset) { println(" " + elementNumber + ":" + blockCount + ". WARNING: BT_COPY FP != outOffset (" + isoRaf.getFilePointer() + " != " + outOffset + ")"); ++warningsReported; } dmgRaf.seek(/*lastOffs+*/inOffset); int bytesRead = dmgRaf.read(inBuffer, 0, Math.min((int)inSize, inBuffer.length)); long totalBytesRead = bytesRead; while(bytesRead != -1) { reportFilePointerProgress(dmgRaf); if(!testOnly) isoRaf.write(inBuffer, 0, bytesRead); if(totalBytesRead >= inSize) break; bytesRead = dmgRaf.read(inBuffer, 0, Math.min((int)(inSize-totalBytesRead), inBuffer.length)); if(bytesRead > 0) totalBytesRead += bytesRead; } //lastInOffs = inOffset+inSize; } else if(blockType == BT_ZERO) { if(DEBUG) println(" " + elementNumber + ":" + blockCount + ". BT_ZERO processing..."); if(!testOnly && isoRaf.getFilePointer() != outOffset) { println(" " + elementNumber + ":" + blockCount + ". WARNING: BT_ZERO FP != outOffset (" + isoRaf.getFilePointer() + " != " + outOffset + ")"); ++warningsReported; } reportFilePointerProgress(dmgRaf); 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_ZERO2) { if(DEBUG) println(" " + elementNumber + ":" + blockCount + ". BT_ZERO2 processing..."); if(!testOnly && isoRaf.getFilePointer() != outOffset) { println(" " + elementNumber + ":" + blockCount + ". WARNING: BT_ZERO2 FP != outOffset (" + isoRaf.getFilePointer() + " != " + outOffset + ")"); ++warningsReported; } reportFilePointerProgress(dmgRaf); 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(" " + elementNumber + ":" + blockCount + ". BT_UNKNOWN processing..."); if(!(inSize == 0 && outSize == 0)) { println(" " + elementNumber + ":" + blockCount + ". WARNING: Blocktype BT_UNKNOWN had non-zero sizes...", " inSize=" + inSize + ", outSize=" + outSize); ++warningsReported; //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(" " + elementNumber + ":" + blockCount + ". BT_END processing..."); if(!testOnly && isoRaf.getFilePointer() != outOffset) println(" " + elementNumber + ":" + blockCount + ". WARNING: BT_END FP != outOffset (" + isoRaf.getFilePointer() + " != " + outOffset + ")"); //lastOffs += lastInOffs; lastOutOffset = outOffset; lastInOffset += lastByteReadInBlock; } else { println(" " + elementNumber + ":" + blockCount + ". WARNING: previously unseen blocktype " + blockType + " [0x" + Integer.toHexString(blockType) + "]", " " + elementNumber + ":" + blockCount + ". outOffset=" + outOffset + " outSize=" + outSize + " inOffset=" + inOffset + " inSize=" + inSize); ++warningsReported; if(!testOnly && isoRaf.getFilePointer() != outOffset) println(" " + elementNumber + ":" + blockCount + ". unknown blocktype FP != outOffset (" + isoRaf.getFilePointer() + " != " + outOffset + ")"); } offset += 0x28; ++blockCount; } } ++elementNumber; } //printlnVerbose("Progress: 100% Done!"); reportProgress(100); String summary = (errorsReported != 0)?errorsReported+" errors reported":"No errors reported"; summary += (warningsReported != 0)?" ("+warningsReported+" warnings emitted).":"."; if(!graphical) { newline(); println(summary); printlnVerbose("Total extracted bytes: " + totalSize + " B"); } else { progmon.close(); JOptionPane.showMessageDialog(null, "Extraction complete! " + summary + "\n" + "Total extracted bytes: " + totalSize + " B", "Information", JOptionPane.INFORMATION_MESSAGE); System.exit(0); } if(!DEBUG) { if(isoRaf != null) isoRaf.close(); dmgRaf.close(); } else { if(isoRaf != null) isoRaf.close();// 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()); 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"; println(" " + new File(filename).getCanonicalPath() + "..."); 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"; println(" " + new File(filename).getCanonicalPath() + "..."); 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"; println(" " + new File(filename).getCanonicalPath() + "..."); 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!"); } } |
if(DEBUG) println(" " + elementNumber + ":" + blockCount + ". BT_END processing..."); if(!testOnly && isoRaf.getFilePointer() != outOffset) println(" " + elementNumber + ":" + blockCount + ". WARNING: BT_END FP != outOffset (" + isoRaf.getFilePointer() + " != " + outOffset + ")"); | if(!testOnly && isoRaf.getFilePointer() != outOffset) { println("!------>WARNING: BT_END FP != outOffset (" + isoRaf.getFilePointer() + " != " + outOffset + ")"); ++warningsReported; } | public static void notmain(String[] args) throws Exception { 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[] inBuffer = new byte[0x40000]; byte[] outBuffer = 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 elementNumber = 0; //long lastOffs = 0; long lastOutOffset = 0; long lastInOffset = 0; long totalSize = 0; int errorsReported = 0; int warningsReported = 0; 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; 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 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) { if(DEBUG) println("!-----addInOffset mode: inOffset tranformation " + inOffset + "->" + (inOffset+lastInOffset)); inOffset += lastInOffset; } else if(inOffset == 0) { if(DEBUG) println("!-----Detected inOffset == 0, setting to " + lastInOffset); addInOffset = true; inOffset = lastInOffset; } outOffset += lastOutOffset; DMGBlock currentBlock = new DMGBlock(blockType, skipped, outOffset, outSize, inOffset, inSize); blocks.add(currentBlock); if(DEBUG) { println("outOffset=" + outOffset + " outSize=" + outSize + " inOffset=" + inOffset + " inSize=" + inSize + " lastOutOffset=" + lastOutOffset + " lastInOffset=" + lastInOffset /*+ " lastInOffs=" + lastInOffs + " lastOffs=" + lastOffs*/); } if(blockType == BT_ADC) { println(" " + elementNumber + ":" + blockCount + ". ERROR: BT_ADC not supported."); ++errorsReported; if(!testOnly) System.exit(0); } else if(blockType == BT_ZLIB) { if(DEBUG) println(" " + elementNumber + ":" + blockCount + ". BT_ZLIB processing..."); if(!testOnly && isoRaf.getFilePointer() != outOffset) println(" " + elementNumber + ":" + blockCount + ". WARNING: BT_ZLIB FP != outOffset (" + isoRaf.getFilePointer() + " != " + outOffset + ")"); try { DMGBlockHandlers.processZlibBlock(currentBlock, dmgRaf, isoRaf, testOnly, dummyMonitor); } catch(DataFormatException dfe) { println(" " + elementNumber + ":" + blockCount + ". ERROR: BT_ZLIB Could not decode..."); ++errorsReported; 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); break; } } } else if(blockType == BT_BZIP2) { println(" " + elementNumber + ":" + blockCount + ". ERROR: BT_BZIP2 not currently supported."); ++errorsReported; if(!testOnly) System.exit(0); } else if(blockType == BT_COPY) { if(DEBUG) println(" " + elementNumber + ":" + blockCount + ". BT_COPY processing..."); if(!testOnly && isoRaf.getFilePointer() != outOffset) { println(" " + elementNumber + ":" + blockCount + ". WARNING: BT_COPY FP != outOffset (" + isoRaf.getFilePointer() + " != " + outOffset + ")"); ++warningsReported; } dmgRaf.seek(/*lastOffs+*/inOffset); int bytesRead = dmgRaf.read(inBuffer, 0, Math.min((int)inSize, inBuffer.length)); long totalBytesRead = bytesRead; while(bytesRead != -1) { reportFilePointerProgress(dmgRaf); if(!testOnly) isoRaf.write(inBuffer, 0, bytesRead); if(totalBytesRead >= inSize) break; bytesRead = dmgRaf.read(inBuffer, 0, Math.min((int)(inSize-totalBytesRead), inBuffer.length)); if(bytesRead > 0) totalBytesRead += bytesRead; } //lastInOffs = inOffset+inSize; } else if(blockType == BT_ZERO) { if(DEBUG) println(" " + elementNumber + ":" + blockCount + ". BT_ZERO processing..."); if(!testOnly && isoRaf.getFilePointer() != outOffset) { println(" " + elementNumber + ":" + blockCount + ". WARNING: BT_ZERO FP != outOffset (" + isoRaf.getFilePointer() + " != " + outOffset + ")"); ++warningsReported; } reportFilePointerProgress(dmgRaf); 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_ZERO2) { if(DEBUG) println(" " + elementNumber + ":" + blockCount + ". BT_ZERO2 processing..."); if(!testOnly && isoRaf.getFilePointer() != outOffset) { println(" " + elementNumber + ":" + blockCount + ". WARNING: BT_ZERO2 FP != outOffset (" + isoRaf.getFilePointer() + " != " + outOffset + ")"); ++warningsReported; } reportFilePointerProgress(dmgRaf); 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(" " + elementNumber + ":" + blockCount + ". BT_UNKNOWN processing..."); if(!(inSize == 0 && outSize == 0)) { println(" " + elementNumber + ":" + blockCount + ". WARNING: Blocktype BT_UNKNOWN had non-zero sizes...", " inSize=" + inSize + ", outSize=" + outSize); ++warningsReported; //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(" " + elementNumber + ":" + blockCount + ". BT_END processing..."); if(!testOnly && isoRaf.getFilePointer() != outOffset) println(" " + elementNumber + ":" + blockCount + ". WARNING: BT_END FP != outOffset (" + isoRaf.getFilePointer() + " != " + outOffset + ")"); //lastOffs += lastInOffs; lastOutOffset = outOffset; lastInOffset += lastByteReadInBlock; } else { println(" " + elementNumber + ":" + blockCount + ". WARNING: previously unseen blocktype " + blockType + " [0x" + Integer.toHexString(blockType) + "]", " " + elementNumber + ":" + blockCount + ". outOffset=" + outOffset + " outSize=" + outSize + " inOffset=" + inOffset + " inSize=" + inSize); ++warningsReported; if(!testOnly && isoRaf.getFilePointer() != outOffset) println(" " + elementNumber + ":" + blockCount + ". unknown blocktype FP != outOffset (" + isoRaf.getFilePointer() + " != " + outOffset + ")"); } offset += 0x28; ++blockCount; } } ++elementNumber; } //printlnVerbose("Progress: 100% Done!"); reportProgress(100); String summary = (errorsReported != 0)?errorsReported+" errors reported":"No errors reported"; summary += (warningsReported != 0)?" ("+warningsReported+" warnings emitted).":"."; if(!graphical) { newline(); println(summary); printlnVerbose("Total extracted bytes: " + totalSize + " B"); } else { progmon.close(); JOptionPane.showMessageDialog(null, "Extraction complete! " + summary + "\n" + "Total extracted bytes: " + totalSize + " B", "Information", JOptionPane.INFORMATION_MESSAGE); System.exit(0); } if(!DEBUG) { if(isoRaf != null) isoRaf.close(); dmgRaf.close(); } else { if(isoRaf != null) isoRaf.close();// 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()); 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"; println(" " + new File(filename).getCanonicalPath() + "..."); 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"; println(" " + new File(filename).getCanonicalPath() + "..."); 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"; println(" " + new File(filename).getCanonicalPath() + "..."); 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!"); } } |
println(" " + elementNumber + ":" + blockCount + ". WARNING: previously unseen blocktype " + blockType + " [0x" + Integer.toHexString(blockType) + "]", " " + elementNumber + ":" + blockCount + ". outOffset=" + outOffset + " outSize=" + outSize + " inOffset=" + inOffset + " inSize=" + inSize); | println("!------>WARNING: previously unseen blocktype " + blockType + " [0x" + Integer.toHexString(blockType) + "]", "!------> outOffset=" + outOffset + " outSize=" + outSize + " inOffset=" + inOffset + " inSize=" + inSize); | public static void notmain(String[] args) throws Exception { 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[] inBuffer = new byte[0x40000]; byte[] outBuffer = 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 elementNumber = 0; //long lastOffs = 0; long lastOutOffset = 0; long lastInOffset = 0; long totalSize = 0; int errorsReported = 0; int warningsReported = 0; 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; 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 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) { if(DEBUG) println("!-----addInOffset mode: inOffset tranformation " + inOffset + "->" + (inOffset+lastInOffset)); inOffset += lastInOffset; } else if(inOffset == 0) { if(DEBUG) println("!-----Detected inOffset == 0, setting to " + lastInOffset); addInOffset = true; inOffset = lastInOffset; } outOffset += lastOutOffset; DMGBlock currentBlock = new DMGBlock(blockType, skipped, outOffset, outSize, inOffset, inSize); blocks.add(currentBlock); if(DEBUG) { println("outOffset=" + outOffset + " outSize=" + outSize + " inOffset=" + inOffset + " inSize=" + inSize + " lastOutOffset=" + lastOutOffset + " lastInOffset=" + lastInOffset /*+ " lastInOffs=" + lastInOffs + " lastOffs=" + lastOffs*/); } if(blockType == BT_ADC) { println(" " + elementNumber + ":" + blockCount + ". ERROR: BT_ADC not supported."); ++errorsReported; if(!testOnly) System.exit(0); } else if(blockType == BT_ZLIB) { if(DEBUG) println(" " + elementNumber + ":" + blockCount + ". BT_ZLIB processing..."); if(!testOnly && isoRaf.getFilePointer() != outOffset) println(" " + elementNumber + ":" + blockCount + ". WARNING: BT_ZLIB FP != outOffset (" + isoRaf.getFilePointer() + " != " + outOffset + ")"); try { DMGBlockHandlers.processZlibBlock(currentBlock, dmgRaf, isoRaf, testOnly, dummyMonitor); } catch(DataFormatException dfe) { println(" " + elementNumber + ":" + blockCount + ". ERROR: BT_ZLIB Could not decode..."); ++errorsReported; 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); break; } } } else if(blockType == BT_BZIP2) { println(" " + elementNumber + ":" + blockCount + ". ERROR: BT_BZIP2 not currently supported."); ++errorsReported; if(!testOnly) System.exit(0); } else if(blockType == BT_COPY) { if(DEBUG) println(" " + elementNumber + ":" + blockCount + ". BT_COPY processing..."); if(!testOnly && isoRaf.getFilePointer() != outOffset) { println(" " + elementNumber + ":" + blockCount + ". WARNING: BT_COPY FP != outOffset (" + isoRaf.getFilePointer() + " != " + outOffset + ")"); ++warningsReported; } dmgRaf.seek(/*lastOffs+*/inOffset); int bytesRead = dmgRaf.read(inBuffer, 0, Math.min((int)inSize, inBuffer.length)); long totalBytesRead = bytesRead; while(bytesRead != -1) { reportFilePointerProgress(dmgRaf); if(!testOnly) isoRaf.write(inBuffer, 0, bytesRead); if(totalBytesRead >= inSize) break; bytesRead = dmgRaf.read(inBuffer, 0, Math.min((int)(inSize-totalBytesRead), inBuffer.length)); if(bytesRead > 0) totalBytesRead += bytesRead; } //lastInOffs = inOffset+inSize; } else if(blockType == BT_ZERO) { if(DEBUG) println(" " + elementNumber + ":" + blockCount + ". BT_ZERO processing..."); if(!testOnly && isoRaf.getFilePointer() != outOffset) { println(" " + elementNumber + ":" + blockCount + ". WARNING: BT_ZERO FP != outOffset (" + isoRaf.getFilePointer() + " != " + outOffset + ")"); ++warningsReported; } reportFilePointerProgress(dmgRaf); 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_ZERO2) { if(DEBUG) println(" " + elementNumber + ":" + blockCount + ". BT_ZERO2 processing..."); if(!testOnly && isoRaf.getFilePointer() != outOffset) { println(" " + elementNumber + ":" + blockCount + ". WARNING: BT_ZERO2 FP != outOffset (" + isoRaf.getFilePointer() + " != " + outOffset + ")"); ++warningsReported; } reportFilePointerProgress(dmgRaf); 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(" " + elementNumber + ":" + blockCount + ". BT_UNKNOWN processing..."); if(!(inSize == 0 && outSize == 0)) { println(" " + elementNumber + ":" + blockCount + ". WARNING: Blocktype BT_UNKNOWN had non-zero sizes...", " inSize=" + inSize + ", outSize=" + outSize); ++warningsReported; //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(" " + elementNumber + ":" + blockCount + ". BT_END processing..."); if(!testOnly && isoRaf.getFilePointer() != outOffset) println(" " + elementNumber + ":" + blockCount + ". WARNING: BT_END FP != outOffset (" + isoRaf.getFilePointer() + " != " + outOffset + ")"); //lastOffs += lastInOffs; lastOutOffset = outOffset; lastInOffset += lastByteReadInBlock; } else { println(" " + elementNumber + ":" + blockCount + ". WARNING: previously unseen blocktype " + blockType + " [0x" + Integer.toHexString(blockType) + "]", " " + elementNumber + ":" + blockCount + ". outOffset=" + outOffset + " outSize=" + outSize + " inOffset=" + inOffset + " inSize=" + inSize); ++warningsReported; if(!testOnly && isoRaf.getFilePointer() != outOffset) println(" " + elementNumber + ":" + blockCount + ". unknown blocktype FP != outOffset (" + isoRaf.getFilePointer() + " != " + outOffset + ")"); } offset += 0x28; ++blockCount; } } ++elementNumber; } //printlnVerbose("Progress: 100% Done!"); reportProgress(100); String summary = (errorsReported != 0)?errorsReported+" errors reported":"No errors reported"; summary += (warningsReported != 0)?" ("+warningsReported+" warnings emitted).":"."; if(!graphical) { newline(); println(summary); printlnVerbose("Total extracted bytes: " + totalSize + " B"); } else { progmon.close(); JOptionPane.showMessageDialog(null, "Extraction complete! " + summary + "\n" + "Total extracted bytes: " + totalSize + " B", "Information", JOptionPane.INFORMATION_MESSAGE); System.exit(0); } if(!DEBUG) { if(isoRaf != null) isoRaf.close(); dmgRaf.close(); } else { if(isoRaf != null) isoRaf.close();// 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()); 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"; println(" " + new File(filename).getCanonicalPath() + "..."); 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"; println(" " + new File(filename).getCanonicalPath() + "..."); 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"; println(" " + new File(filename).getCanonicalPath() + "..."); 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!"); } } |
println(" " + elementNumber + ":" + blockCount + ". unknown blocktype FP != outOffset (" + | println("!------>WARNING: unknown blocktype FP != outOffset (" + | public static void notmain(String[] args) throws Exception { 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[] inBuffer = new byte[0x40000]; byte[] outBuffer = 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 elementNumber = 0; //long lastOffs = 0; long lastOutOffset = 0; long lastInOffset = 0; long totalSize = 0; int errorsReported = 0; int warningsReported = 0; 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; 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 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) { if(DEBUG) println("!-----addInOffset mode: inOffset tranformation " + inOffset + "->" + (inOffset+lastInOffset)); inOffset += lastInOffset; } else if(inOffset == 0) { if(DEBUG) println("!-----Detected inOffset == 0, setting to " + lastInOffset); addInOffset = true; inOffset = lastInOffset; } outOffset += lastOutOffset; DMGBlock currentBlock = new DMGBlock(blockType, skipped, outOffset, outSize, inOffset, inSize); blocks.add(currentBlock); if(DEBUG) { println("outOffset=" + outOffset + " outSize=" + outSize + " inOffset=" + inOffset + " inSize=" + inSize + " lastOutOffset=" + lastOutOffset + " lastInOffset=" + lastInOffset /*+ " lastInOffs=" + lastInOffs + " lastOffs=" + lastOffs*/); } if(blockType == BT_ADC) { println(" " + elementNumber + ":" + blockCount + ". ERROR: BT_ADC not supported."); ++errorsReported; if(!testOnly) System.exit(0); } else if(blockType == BT_ZLIB) { if(DEBUG) println(" " + elementNumber + ":" + blockCount + ". BT_ZLIB processing..."); if(!testOnly && isoRaf.getFilePointer() != outOffset) println(" " + elementNumber + ":" + blockCount + ". WARNING: BT_ZLIB FP != outOffset (" + isoRaf.getFilePointer() + " != " + outOffset + ")"); try { DMGBlockHandlers.processZlibBlock(currentBlock, dmgRaf, isoRaf, testOnly, dummyMonitor); } catch(DataFormatException dfe) { println(" " + elementNumber + ":" + blockCount + ". ERROR: BT_ZLIB Could not decode..."); ++errorsReported; 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); break; } } } else if(blockType == BT_BZIP2) { println(" " + elementNumber + ":" + blockCount + ". ERROR: BT_BZIP2 not currently supported."); ++errorsReported; if(!testOnly) System.exit(0); } else if(blockType == BT_COPY) { if(DEBUG) println(" " + elementNumber + ":" + blockCount + ". BT_COPY processing..."); if(!testOnly && isoRaf.getFilePointer() != outOffset) { println(" " + elementNumber + ":" + blockCount + ". WARNING: BT_COPY FP != outOffset (" + isoRaf.getFilePointer() + " != " + outOffset + ")"); ++warningsReported; } dmgRaf.seek(/*lastOffs+*/inOffset); int bytesRead = dmgRaf.read(inBuffer, 0, Math.min((int)inSize, inBuffer.length)); long totalBytesRead = bytesRead; while(bytesRead != -1) { reportFilePointerProgress(dmgRaf); if(!testOnly) isoRaf.write(inBuffer, 0, bytesRead); if(totalBytesRead >= inSize) break; bytesRead = dmgRaf.read(inBuffer, 0, Math.min((int)(inSize-totalBytesRead), inBuffer.length)); if(bytesRead > 0) totalBytesRead += bytesRead; } //lastInOffs = inOffset+inSize; } else if(blockType == BT_ZERO) { if(DEBUG) println(" " + elementNumber + ":" + blockCount + ". BT_ZERO processing..."); if(!testOnly && isoRaf.getFilePointer() != outOffset) { println(" " + elementNumber + ":" + blockCount + ". WARNING: BT_ZERO FP != outOffset (" + isoRaf.getFilePointer() + " != " + outOffset + ")"); ++warningsReported; } reportFilePointerProgress(dmgRaf); 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_ZERO2) { if(DEBUG) println(" " + elementNumber + ":" + blockCount + ". BT_ZERO2 processing..."); if(!testOnly && isoRaf.getFilePointer() != outOffset) { println(" " + elementNumber + ":" + blockCount + ". WARNING: BT_ZERO2 FP != outOffset (" + isoRaf.getFilePointer() + " != " + outOffset + ")"); ++warningsReported; } reportFilePointerProgress(dmgRaf); 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(" " + elementNumber + ":" + blockCount + ". BT_UNKNOWN processing..."); if(!(inSize == 0 && outSize == 0)) { println(" " + elementNumber + ":" + blockCount + ". WARNING: Blocktype BT_UNKNOWN had non-zero sizes...", " inSize=" + inSize + ", outSize=" + outSize); ++warningsReported; //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(" " + elementNumber + ":" + blockCount + ". BT_END processing..."); if(!testOnly && isoRaf.getFilePointer() != outOffset) println(" " + elementNumber + ":" + blockCount + ". WARNING: BT_END FP != outOffset (" + isoRaf.getFilePointer() + " != " + outOffset + ")"); //lastOffs += lastInOffs; lastOutOffset = outOffset; lastInOffset += lastByteReadInBlock; } else { println(" " + elementNumber + ":" + blockCount + ". WARNING: previously unseen blocktype " + blockType + " [0x" + Integer.toHexString(blockType) + "]", " " + elementNumber + ":" + blockCount + ". outOffset=" + outOffset + " outSize=" + outSize + " inOffset=" + inOffset + " inSize=" + inSize); ++warningsReported; if(!testOnly && isoRaf.getFilePointer() != outOffset) println(" " + elementNumber + ":" + blockCount + ". unknown blocktype FP != outOffset (" + isoRaf.getFilePointer() + " != " + outOffset + ")"); } offset += 0x28; ++blockCount; } } ++elementNumber; } //printlnVerbose("Progress: 100% Done!"); reportProgress(100); String summary = (errorsReported != 0)?errorsReported+" errors reported":"No errors reported"; summary += (warningsReported != 0)?" ("+warningsReported+" warnings emitted).":"."; if(!graphical) { newline(); println(summary); printlnVerbose("Total extracted bytes: " + totalSize + " B"); } else { progmon.close(); JOptionPane.showMessageDialog(null, "Extraction complete! " + summary + "\n" + "Total extracted bytes: " + totalSize + " B", "Information", JOptionPane.INFORMATION_MESSAGE); System.exit(0); } if(!DEBUG) { if(isoRaf != null) isoRaf.close(); dmgRaf.close(); } else { if(isoRaf != null) isoRaf.close();// 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()); 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"; println(" " + new File(filename).getCanonicalPath() + "..."); 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"; println(" " + new File(filename).getCanonicalPath() + "..."); 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"; println(" " + new File(filename).getCanonicalPath() + "..."); 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!"); } } |
if(!DEBUG) { | if(!debug) { | public static void notmain(String[] args) throws Exception { 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[] inBuffer = new byte[0x40000]; byte[] outBuffer = 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 elementNumber = 0; //long lastOffs = 0; long lastOutOffset = 0; long lastInOffset = 0; long totalSize = 0; int errorsReported = 0; int warningsReported = 0; 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; 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 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) { if(DEBUG) println("!-----addInOffset mode: inOffset tranformation " + inOffset + "->" + (inOffset+lastInOffset)); inOffset += lastInOffset; } else if(inOffset == 0) { if(DEBUG) println("!-----Detected inOffset == 0, setting to " + lastInOffset); addInOffset = true; inOffset = lastInOffset; } outOffset += lastOutOffset; DMGBlock currentBlock = new DMGBlock(blockType, skipped, outOffset, outSize, inOffset, inSize); blocks.add(currentBlock); if(DEBUG) { println("outOffset=" + outOffset + " outSize=" + outSize + " inOffset=" + inOffset + " inSize=" + inSize + " lastOutOffset=" + lastOutOffset + " lastInOffset=" + lastInOffset /*+ " lastInOffs=" + lastInOffs + " lastOffs=" + lastOffs*/); } if(blockType == BT_ADC) { println(" " + elementNumber + ":" + blockCount + ". ERROR: BT_ADC not supported."); ++errorsReported; if(!testOnly) System.exit(0); } else if(blockType == BT_ZLIB) { if(DEBUG) println(" " + elementNumber + ":" + blockCount + ". BT_ZLIB processing..."); if(!testOnly && isoRaf.getFilePointer() != outOffset) println(" " + elementNumber + ":" + blockCount + ". WARNING: BT_ZLIB FP != outOffset (" + isoRaf.getFilePointer() + " != " + outOffset + ")"); try { DMGBlockHandlers.processZlibBlock(currentBlock, dmgRaf, isoRaf, testOnly, dummyMonitor); } catch(DataFormatException dfe) { println(" " + elementNumber + ":" + blockCount + ". ERROR: BT_ZLIB Could not decode..."); ++errorsReported; 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); break; } } } else if(blockType == BT_BZIP2) { println(" " + elementNumber + ":" + blockCount + ". ERROR: BT_BZIP2 not currently supported."); ++errorsReported; if(!testOnly) System.exit(0); } else if(blockType == BT_COPY) { if(DEBUG) println(" " + elementNumber + ":" + blockCount + ". BT_COPY processing..."); if(!testOnly && isoRaf.getFilePointer() != outOffset) { println(" " + elementNumber + ":" + blockCount + ". WARNING: BT_COPY FP != outOffset (" + isoRaf.getFilePointer() + " != " + outOffset + ")"); ++warningsReported; } dmgRaf.seek(/*lastOffs+*/inOffset); int bytesRead = dmgRaf.read(inBuffer, 0, Math.min((int)inSize, inBuffer.length)); long totalBytesRead = bytesRead; while(bytesRead != -1) { reportFilePointerProgress(dmgRaf); if(!testOnly) isoRaf.write(inBuffer, 0, bytesRead); if(totalBytesRead >= inSize) break; bytesRead = dmgRaf.read(inBuffer, 0, Math.min((int)(inSize-totalBytesRead), inBuffer.length)); if(bytesRead > 0) totalBytesRead += bytesRead; } //lastInOffs = inOffset+inSize; } else if(blockType == BT_ZERO) { if(DEBUG) println(" " + elementNumber + ":" + blockCount + ". BT_ZERO processing..."); if(!testOnly && isoRaf.getFilePointer() != outOffset) { println(" " + elementNumber + ":" + blockCount + ". WARNING: BT_ZERO FP != outOffset (" + isoRaf.getFilePointer() + " != " + outOffset + ")"); ++warningsReported; } reportFilePointerProgress(dmgRaf); 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_ZERO2) { if(DEBUG) println(" " + elementNumber + ":" + blockCount + ". BT_ZERO2 processing..."); if(!testOnly && isoRaf.getFilePointer() != outOffset) { println(" " + elementNumber + ":" + blockCount + ". WARNING: BT_ZERO2 FP != outOffset (" + isoRaf.getFilePointer() + " != " + outOffset + ")"); ++warningsReported; } reportFilePointerProgress(dmgRaf); 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(" " + elementNumber + ":" + blockCount + ". BT_UNKNOWN processing..."); if(!(inSize == 0 && outSize == 0)) { println(" " + elementNumber + ":" + blockCount + ". WARNING: Blocktype BT_UNKNOWN had non-zero sizes...", " inSize=" + inSize + ", outSize=" + outSize); ++warningsReported; //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(" " + elementNumber + ":" + blockCount + ". BT_END processing..."); if(!testOnly && isoRaf.getFilePointer() != outOffset) println(" " + elementNumber + ":" + blockCount + ". WARNING: BT_END FP != outOffset (" + isoRaf.getFilePointer() + " != " + outOffset + ")"); //lastOffs += lastInOffs; lastOutOffset = outOffset; lastInOffset += lastByteReadInBlock; } else { println(" " + elementNumber + ":" + blockCount + ". WARNING: previously unseen blocktype " + blockType + " [0x" + Integer.toHexString(blockType) + "]", " " + elementNumber + ":" + blockCount + ". outOffset=" + outOffset + " outSize=" + outSize + " inOffset=" + inOffset + " inSize=" + inSize); ++warningsReported; if(!testOnly && isoRaf.getFilePointer() != outOffset) println(" " + elementNumber + ":" + blockCount + ". unknown blocktype FP != outOffset (" + isoRaf.getFilePointer() + " != " + outOffset + ")"); } offset += 0x28; ++blockCount; } } ++elementNumber; } //printlnVerbose("Progress: 100% Done!"); reportProgress(100); String summary = (errorsReported != 0)?errorsReported+" errors reported":"No errors reported"; summary += (warningsReported != 0)?" ("+warningsReported+" warnings emitted).":"."; if(!graphical) { newline(); println(summary); printlnVerbose("Total extracted bytes: " + totalSize + " B"); } else { progmon.close(); JOptionPane.showMessageDialog(null, "Extraction complete! " + summary + "\n" + "Total extracted bytes: " + totalSize + " B", "Information", JOptionPane.INFORMATION_MESSAGE); System.exit(0); } if(!DEBUG) { if(isoRaf != null) isoRaf.close(); dmgRaf.close(); } else { if(isoRaf != null) isoRaf.close();// 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()); 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"; println(" " + new File(filename).getCanonicalPath() + "..."); 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"; println(" " + new File(filename).getCanonicalPath() + "..."); 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"; println(" " + new File(filename).getCanonicalPath() + "..."); 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!"); } } |
" based upon dmg2iso, Copyright (c) 2004 vu1tur <[email protected]>", | " based on dmg2iso, Copyright (c) 2004 vu1tur <[email protected]>", | public static void parseArgs(String[] args) { boolean parseSuccessful = false; try { /* Take care of the options... */ int i; for(i = 0; i < args.length; ++i) { String cur = args[i]; if(!cur.startsWith("-")) break; else if(cur.equals("-gui")) { graphical = true; // This should be moved to UI class in the future. System.setProperty("swing.aatext", "true"); //Antialiased text try { javax.swing.UIManager.setLookAndFeel(javax.swing.UIManager.getSystemLookAndFeelClassName()); } catch(Exception e) {} } else if(cur.equals("-v")) verbose = true; else if(cur.equals("-startupcommand")) { startupCommand = args[i+1]; ++i; } } println(APPNAME + " " + BUILDSTRING, "Copyright (c) 2006 Erik Larsson <[email protected]>", " based upon dmg2iso, Copyright (c) 2004 vu1tur <[email protected]>", " also using the iHarder Base64 Encoder/Decoder <http://iharder.sf.net>", "", "This program is distributed under the GNU General Public License version 2 or", "later. See <http://www.gnu.org/copyleft/gpl.html> for the details.", ""); if(i == args.length) { dmgFile = getInputFileFromUser(); if(dmgFile == null) System.exit(0); if(getOutputConfirmationFromUser()) { isoFile = getOutputFileFromUser(); if(isoFile == null) System.exit(0); } } else { dmgFile = new File(args[i++]); if(!dmgFile.exists()) { println("File \"" + dmgFile + "\" could not be found!"); System.exit(0); } if(i == args.length-1) isoFile = new File(args[i]); else if(i != args.length) throw new Exception(); } parseSuccessful = true; } catch(Exception e) { println(); println(" usage: " + startupCommand + " [options] <dmgFile> [<isoFile>]"); println(" if an iso-file is not supplied, the program will simulate an extraction"); println(" (useful for detecting errors in dmg-files)"); println(); System.exit(0); } } |
final InternalDocumentModel iDocumentModel = | final InternalDocumentModel iDModel = | static void notifyKeyRequestAccepted(final UUID artifactUniqueId, final JabberId acceptedBy) { final InternalDocumentModel iDocumentModel = DocumentModel.getInternalModel(sContext); try { final Document document = iDocumentModel.get(artifactUniqueId); iDocumentModel.unlock(document.getId()); SystemMessageModel.getInternalModel(sContext). createKeyResponse(document.getId(), Boolean.TRUE, acceptedBy); } catch(ParityException px) { sLogger.fatal("Could not accept key request.", px); return; } } |
final Document document = iDocumentModel.get(artifactUniqueId); iDocumentModel.unlock(document.getId()); | final Document document = iDModel.get(artifactUniqueId); iDModel.unlock(document.getId()); | static void notifyKeyRequestAccepted(final UUID artifactUniqueId, final JabberId acceptedBy) { final InternalDocumentModel iDocumentModel = DocumentModel.getInternalModel(sContext); try { final Document document = iDocumentModel.get(artifactUniqueId); iDocumentModel.unlock(document.getId()); SystemMessageModel.getInternalModel(sContext). createKeyResponse(document.getId(), Boolean.TRUE, acceptedBy); } catch(ParityException px) { sLogger.fatal("Could not accept key request.", px); return; } } |
final User loggedInUser; synchronized(xmppHelperLock) { loggedInUser = xmppHelper.getUser(); } iDModel.auditRecieveKey(document.getId(), loggedInUser.getId(), currentDateTime(), acceptedBy); } catch(final SmackException sx) { sLogger.fatal("Could not accept key request.", sx); return; | static void notifyKeyRequestAccepted(final UUID artifactUniqueId, final JabberId acceptedBy) { final InternalDocumentModel iDocumentModel = DocumentModel.getInternalModel(sContext); try { final Document document = iDocumentModel.get(artifactUniqueId); iDocumentModel.unlock(document.getId()); SystemMessageModel.getInternalModel(sContext). createKeyResponse(document.getId(), Boolean.TRUE, acceptedBy); } catch(ParityException px) { sLogger.fatal("Could not accept key request.", px); return; } } |
|
final DocumentVersion version = iDModel.createVersion(documentId); | final DocumentVersion version; if(iDModel.isWorkingVersionEqual(documentId)) { version = iDModel.getLatestVersion(documentId); } else { version = iDModel.createVersion(documentId); } | void sendKeyResponse(final Long documentId, final JabberId requestedBy, final KeyResponse keyResponse) throws ParityException { logger.info("sendKeyResponse(UUID,User,KeyResponse)"); logger.debug(documentId); logger.debug(requestedBy); logger.debug(keyResponse); assertLoggedInUserIsKeyHolder(documentId); synchronized(SessionModelImpl.xmppHelperLock) { try { // NOTE This should be refactored when the session can be changed. final User requestedByUser = new User(requestedBy.getQualifiedJabberId()); final InternalDocumentModel iDModel = getInternalDocumentModel(); final Document document = iDModel.get(documentId); // if the user sends an acceptance of the key request; we // want to send the latest version to the requesting user switch(keyResponse) { case ACCEPT: // create the new version final DocumentVersion version = iDModel.createVersion(documentId); // send the key change to the server xmppHelper.sendKeyResponse( document.getUniqueId(), keyResponse, requestedByUser); // send new version final Collection<User> users = new Vector<User>(1); users.add(requestedByUser); send(users, documentId, version.getVersionId()); // lock the local document iDModel.lock(documentId); // audit send key final DocumentVersion dv = iDModel.getVersion( version.getArtifactId(), version.getVersionId()); auditor.sendKey(dv.getArtifactId(), dv.getVersionId(), xmppHelper.getUser().getId(), version.getUpdatedOn(), requestedBy); break; case DENY: // send the declination to the server xmppHelper.sendKeyResponse( document.getUniqueId(), KeyResponse.DENY, requestedByUser); break; default: throw Assert.createUnreachable("Unknown key response: " + keyResponse); } } catch(final SmackException sx) { logger.error("sendKeyResponse(Document,User,KeyResponse)", sx); throw ParityErrorTranslator.translate(sx); } catch(final RuntimeException rx) { logger.error("sendKeyResponse(Document,User,KeyResponse)", rx); throw ParityErrorTranslator.translate(rx); } } } |
xmppHelper.getUser().getId(), version.getUpdatedOn(), | xmppHelper.getUser().getId(), currentDateTime(), | void sendKeyResponse(final Long documentId, final JabberId requestedBy, final KeyResponse keyResponse) throws ParityException { logger.info("sendKeyResponse(UUID,User,KeyResponse)"); logger.debug(documentId); logger.debug(requestedBy); logger.debug(keyResponse); assertLoggedInUserIsKeyHolder(documentId); synchronized(SessionModelImpl.xmppHelperLock) { try { // NOTE This should be refactored when the session can be changed. final User requestedByUser = new User(requestedBy.getQualifiedJabberId()); final InternalDocumentModel iDModel = getInternalDocumentModel(); final Document document = iDModel.get(documentId); // if the user sends an acceptance of the key request; we // want to send the latest version to the requesting user switch(keyResponse) { case ACCEPT: // create the new version final DocumentVersion version = iDModel.createVersion(documentId); // send the key change to the server xmppHelper.sendKeyResponse( document.getUniqueId(), keyResponse, requestedByUser); // send new version final Collection<User> users = new Vector<User>(1); users.add(requestedByUser); send(users, documentId, version.getVersionId()); // lock the local document iDModel.lock(documentId); // audit send key final DocumentVersion dv = iDModel.getVersion( version.getArtifactId(), version.getVersionId()); auditor.sendKey(dv.getArtifactId(), dv.getVersionId(), xmppHelper.getUser().getId(), version.getUpdatedOn(), requestedBy); break; case DENY: // send the declination to the server xmppHelper.sendKeyResponse( document.getUniqueId(), KeyResponse.DENY, requestedByUser); break; default: throw Assert.createUnreachable("Unknown key response: " + keyResponse); } } catch(final SmackException sx) { logger.error("sendKeyResponse(Document,User,KeyResponse)", sx); throw ParityErrorTranslator.translate(sx); } catch(final RuntimeException rx) { logger.error("sendKeyResponse(Document,User,KeyResponse)", rx); throw ParityErrorTranslator.translate(rx); } } } |
ServletContext servletContext = config.getServletContext(); | public void init( ServletConfig config ) throws ServletException { super.init( config ); /* * setup the toolbox if there is one */ String key = config.getInitParameter( TOOLBOX_PARAM ); if ( key != null ) { InputStream is = null; try { /* * little fix up */ if ( !key.startsWith("/") ) { key = "/" + key; } /* * get the bits */ is = getServletContext().getResourceAsStream( key ); if ( is != null) { Velocity.info("Using toolbox configuration file '" + key +"'"); toolboxManager = new ServletToolboxManager(getServletContext()); toolboxManager.load( is ); Velocity.info("Toolbox setup complete."); } } catch( Exception e ) { Velocity.error("Problem reading toolbox file properties file '" + key +"' : " + e ); } finally { try { if ( is != null) is.close(); } catch(Exception ee ) {} } } else { Velocity.info("No toolbox entry in configuration."); } } |
|
if ( key != null ) | if (key == null || key.length() == 0) | public void init( ServletConfig config ) throws ServletException { super.init( config ); /* * setup the toolbox if there is one */ String key = config.getInitParameter( TOOLBOX_PARAM ); if ( key != null ) { InputStream is = null; try { /* * little fix up */ if ( !key.startsWith("/") ) { key = "/" + key; } /* * get the bits */ is = getServletContext().getResourceAsStream( key ); if ( is != null) { Velocity.info("Using toolbox configuration file '" + key +"'"); toolboxManager = new ServletToolboxManager(getServletContext()); toolboxManager.load( is ); Velocity.info("Toolbox setup complete."); } } catch( Exception e ) { Velocity.error("Problem reading toolbox file properties file '" + key +"' : " + e ); } finally { try { if ( is != null) is.close(); } catch(Exception ee ) {} } } else { Velocity.info("No toolbox entry in configuration."); } } |
InputStream is = null; | key = servletContext.getInitParameter(TOOLBOX_PARAM); } | public void init( ServletConfig config ) throws ServletException { super.init( config ); /* * setup the toolbox if there is one */ String key = config.getInitParameter( TOOLBOX_PARAM ); if ( key != null ) { InputStream is = null; try { /* * little fix up */ if ( !key.startsWith("/") ) { key = "/" + key; } /* * get the bits */ is = getServletContext().getResourceAsStream( key ); if ( is != null) { Velocity.info("Using toolbox configuration file '" + key +"'"); toolboxManager = new ServletToolboxManager(getServletContext()); toolboxManager.load( is ); Velocity.info("Toolbox setup complete."); } } catch( Exception e ) { Velocity.error("Problem reading toolbox file properties file '" + key +"' : " + e ); } finally { try { if ( is != null) is.close(); } catch(Exception ee ) {} } } else { Velocity.info("No toolbox entry in configuration."); } } |
try { if ( !key.startsWith("/") ) { key = "/" + key; } is = getServletContext().getResourceAsStream( key ); if ( is != null) { Velocity.info("Using toolbox configuration file '" + key +"'"); toolboxManager = new ServletToolboxManager(getServletContext()); toolboxManager.load( is ); Velocity.info("Toolbox setup complete."); } } catch( Exception e ) { Velocity.error("Problem reading toolbox file properties file '" + key +"' : " + e ); } finally { try { if ( is != null) is.close(); } catch(Exception ee ) {} } } else { | if (key != null) { toolboxManager = ServletToolboxManager.getInstance(servletContext, key); } else { | public void init( ServletConfig config ) throws ServletException { super.init( config ); /* * setup the toolbox if there is one */ String key = config.getInitParameter( TOOLBOX_PARAM ); if ( key != null ) { InputStream is = null; try { /* * little fix up */ if ( !key.startsWith("/") ) { key = "/" + key; } /* * get the bits */ is = getServletContext().getResourceAsStream( key ); if ( is != null) { Velocity.info("Using toolbox configuration file '" + key +"'"); toolboxManager = new ServletToolboxManager(getServletContext()); toolboxManager.load( is ); Velocity.info("Toolbox setup complete."); } } catch( Exception e ) { Velocity.error("Problem reading toolbox file properties file '" + key +"' : " + e ); } finally { try { if ( is != null) is.close(); } catch(Exception ee ) {} } } else { Velocity.info("No toolbox entry in configuration."); } } |
public ServletToolboxManager(ServletContext servletContext) | private ServletToolboxManager(ServletContext servletContext) | public ServletToolboxManager(ServletContext servletContext) { this.servletContext = servletContext; appTools = new HashMap(); sessionToolInfo = new ArrayList(); requestToolInfo = new ArrayList(); createSession = true; } |
final OutputStream stream, final String streamId, final StreamSession streamSession) { | final StreamSession streamSession, final String streamId, final File inputFile, final File outputFile) { | private Fixture(final StreamServer streamServer, final OutputStream stream, final String streamId, final StreamSession streamSession) { super(); this.streamServer = streamServer; this.stream = stream; this.streamId = streamId; this.streamSession = streamSession; } |
this.stream = stream; | private Fixture(final StreamServer streamServer, final OutputStream stream, final String streamId, final StreamSession streamSession) { super(); this.streamServer = streamServer; this.stream = stream; this.streamId = streamId; this.streamSession = streamSession; } |
|
this.inputFile = inputFile; this.outputFile = outputFile; | private Fixture(final StreamServer streamServer, final OutputStream stream, final String streamId, final StreamSession streamSession) { super(); this.streamServer = streamServer; this.stream = stream; this.streamId = streamId; this.streamSession = streamSession; } |
|
final File streamFile = getInputFiles()[0]; | final File inputFile = getInputFiles()[0]; final File outputFile = new File(getOutputDirectory(), inputFile.getName()); | protected void setUp() throws Exception { super.setUp(); final File workingDirectory = new File(getOutputDirectory(), "working"); Assert.assertTrue(workingDirectory.mkdir(), "Could not create directory {0}.", workingDirectory); final File streamFile = getInputFiles()[0]; final StreamServer server = startStreamServer(DesdemonaTestUser.JUNIT, workingDirectory); final StreamSession session = createSession(DesdemonaTestUser.JUNIT, server); final String streamId = createStream(server, session, streamFile.getName()); final OutputStream stream = new FileOutputStream(new File(getOutputDirectory(), streamFile.getName())); seedServer(server, session, streamId, 0L, streamFile); datum = new Fixture(server, stream, streamId, session); } |
final String streamId = createStream(server, session, streamFile.getName()); final OutputStream stream = new FileOutputStream(new File(getOutputDirectory(), streamFile.getName())); seedServer(server, session, streamId, 0L, streamFile); datum = new Fixture(server, stream, streamId, session); | final String streamId = createStream(server, session, inputFile.getName()); seedServer(server, session, streamId, 0L, inputFile); datum = new Fixture(server, session, streamId, inputFile, outputFile); | protected void setUp() throws Exception { super.setUp(); final File workingDirectory = new File(getOutputDirectory(), "working"); Assert.assertTrue(workingDirectory.mkdir(), "Could not create directory {0}.", workingDirectory); final File streamFile = getInputFiles()[0]; final StreamServer server = startStreamServer(DesdemonaTestUser.JUNIT, workingDirectory); final StreamSession session = createSession(DesdemonaTestUser.JUNIT, server); final String streamId = createStream(server, session, streamFile.getName()); final OutputStream stream = new FileOutputStream(new File(getOutputDirectory(), streamFile.getName())); seedServer(server, session, streamId, 0L, streamFile); datum = new Fixture(server, stream, streamId, session); } |
reader.open(); reader.read(datum.streamId, datum.stream); | final OutputStream outputStream = new FileOutputStream(datum.outputFile); try { reader.open(); reader.read(datum.streamId, outputStream, 0L); } catch (final IOException iox) { fail(createFailMessage(iox)); } finally { try { outputStream.close(); reader.close(); } catch (final IOException iox2) { fail(createFailMessage(iox2)); } } | public void testReader() { final StreamReader reader = new StreamReader(datum.streamSession); try { reader.open(); reader.read(datum.streamId, datum.stream); } catch (final IOException iox) { fail(createFailMessage(iox)); } finally { try { datum.stream.close(); reader.close(); } catch (final IOException iox2) { fail(createFailMessage(iox2)); } } } |
} finally { | } assertEquals(datum.outputFile.length(), datum.inputFile.length()); try { final InputStream downloadInputStream = new FileInputStream(datum.outputFile); String downloadChecksum; | public void testReader() { final StreamReader reader = new StreamReader(datum.streamSession); try { reader.open(); reader.read(datum.streamId, datum.stream); } catch (final IOException iox) { fail(createFailMessage(iox)); } finally { try { datum.stream.close(); reader.close(); } catch (final IOException iox2) { fail(createFailMessage(iox2)); } } } |
datum.stream.close(); reader.close(); } catch (final IOException iox2) { fail(createFailMessage(iox2)); | downloadChecksum = MD5Util.md5Hex(downloadInputStream); } catch (final Throwable t) { downloadChecksum = null; } finally { downloadInputStream.close(); | public void testReader() { final StreamReader reader = new StreamReader(datum.streamSession); try { reader.open(); reader.read(datum.streamId, datum.stream); } catch (final IOException iox) { fail(createFailMessage(iox)); } finally { try { datum.stream.close(); reader.close(); } catch (final IOException iox2) { fail(createFailMessage(iox2)); } } } |
final InputStream uploadInputStream = new FileInputStream(datum.inputFile); String uploadChecksum; try { uploadChecksum = MD5Util.md5Hex(uploadInputStream); } catch (final Throwable t) { uploadChecksum = null; } finally { uploadInputStream.close(); } assertEquals(downloadChecksum, uploadChecksum); } catch (final IOException iox) { fail(createFailMessage(iox)); | public void testReader() { final StreamReader reader = new StreamReader(datum.streamSession); try { reader.open(); reader.read(datum.streamId, datum.stream); } catch (final IOException iox) { fail(createFailMessage(iox)); } finally { try { datum.stream.close(); reader.close(); } catch (final IOException iox2) { fail(createFailMessage(iox2)); } } } |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.