bugged
stringlengths 6
599k
| fixed
stringlengths 10
599k
| __index_level_0__
int64 0
1.13M
|
|---|---|---|
StreamSession authenticate(final String sessionId, final InetAddress sessionAddress) { synchronized (SESSIONS) { final ServerSession session = SESSIONS.get(sessionId); if (session.getInetAddress().equals(sessionAddress)) { return session; } else { logger.logWarning("Session address {0} does not match original.", sessionAddress); return null; } } }
|
StreamSession authenticate(final String sessionId, final InetAddress sessionAddress) { synchronized (SESSIONS) { final ServerSession session = SESSIONS.get(sessionId); final InetAddress inetAddress = session.getInetAddress(); if (null == inetAddress) { return session; } else { logger.logWarning("Session address {0} does not match original.", sessionAddress); return null; } } }
| 1,114,560
|
StreamSession authenticate(final String sessionId, final InetAddress sessionAddress) { synchronized (SESSIONS) { final ServerSession session = SESSIONS.get(sessionId); if (session.getInetAddress().equals(sessionAddress)) { return session; } else { logger.logWarning("Session address {0} does not match original.", sessionAddress); return null; } } }
|
StreamSession authenticate(final String sessionId, final InetAddress sessionAddress) { synchronized (SESSIONS) { final ServerSession session = SESSIONS.get(sessionId); if (session.getInetAddress().equals(sessionAddress)) { return session; } else { logger.logWarning("Session address {0} does not match original.", sessionAddress); return null; } } }
| 1,114,561
|
void initialize(final ServerSession session) { Assert.assertNotNull("Session is null.", session); Assert.assertNotNull("Session buffer size is null.", session.getBufferSize()); Assert.assertNotNull("Session charset is null.", session.getCharset()); Assert.assertNotNull("Session environment is null.", session.getEnvironment()); Assert.assertNotNull("Session id is null.", session.getId()); Assert.assertNotNull("Session inet address is null.", session.getInetAddress()); synchronized (SESSIONS) { SESSIONS.put(session.getId(), session); fileServer.initialize(session); socketServer.initialize(session); } }
|
void initialize(final ServerSession session) { Assert.assertNotNull("Session is null.", session); Assert.assertNotNull("Session buffer size is null.", session.getBufferSize()); Assert.assertNotNull("Session charset is null.", session.getCharset()); Assert.assertNotNull("Session environment is null.", session.getEnvironment()); Assert.assertNotNull("Session id is null.", session.getId()); synchronized (SESSIONS) { SESSIONS.put(session.getId(), session); fileServer.initialize(session); socketServer.initialize(session); } }
| 1,114,562
|
public void procesarEvento(){ String claveAlumno= (String)this.getSesion().getAttribute("claveAlumno"); ObjetoBean alumnoEdicion= (ObjetoBean)(this.getSesion().getAttribute("beanAlumno")); alumnoEdicion.cambiaValor(Constantes.ID_ISALUMNO_ISUSUARIO_DNI,claveAlumno); this.getSesion().setAttribute("beanAlumno",alumnoEdicion); GestorAlumnos GA= new GestorAlumnos(); ListaObjetoBean camposErroneos= GA.comprobar(alumnoEdicion); if(claveAlumno!=null && camposErroneos.esVacio()){ this.setResuladooperacion("OK"); this.getSesion().removeAttribute("claveAlumno"); } else{ this.getSesion().setAttribute("error",camposErroneos); this.setResuladooperacion("ERROR"); } }
|
public void procesarEvento(){ String claveAlumno= (String)this.getSesion().getAttribute("claveAlumno"); ObjetoBean alumnoEdicion= (ObjetoBean)(this.getSesion().getAttribute("beanAlumno")); alumnoEdicion.cambiaValor(Constantes.ID_ISALUMNO_ISUSUARIO_DNI,claveAlumno); this.getSesion().setAttribute("beanAlumno",alumnoEdicion); GestorAlumnos GA= new GestorAlumnos(); ListaObjetoBean camposErroneos= GA.comprobar(alumnoEdicion); if(claveAlumno!=null && camposErroneos.esVacio()){ this.setResuladooperacion("OK"); } else{ this.getSesion().setAttribute("error",camposErroneos); this.setResuladooperacion("ERROR"); } }
| 1,114,563
|
public Object getElement(final Object input) { // TODO Create a statistics model to obtain and build // reports try { return dModel.list().size(); } catch(final ParityException px) { throw new RuntimeException(px); } }
|
public Object getElement(final Object input) { // TODO Create a statistics model to obtain and build // reports try { return sModel.readContact(); } catch(final ParityException px) { throw new RuntimeException(px); } }
| 1,114,564
|
public Object getElement(final Object input) { return countProvider.getElement(input); }
|
public Object getElement(final Object input) { return countProvider.getElement(input); }
| 1,114,565
|
private void syncDocuments() { // sync the documents with the visible documents visibleDocuments.clear(); visibleDocuments.addAll(documents); ModelFilterManager.filter(visibleDocuments, documentFilter); // sync visible documents with the swing list's model ListItem li; for(int i = 0; i < visibleDocuments.size(); i++) { li = ListItem.create(visibleDocuments.get(i)); if(!jListModel.contains(li)) { jListModel.add(i, li); } } final ListItem[] modelItems = new ListItem[jListModel.size()]; jListModel.copyInto(modelItems); DocumentListItem dli; int touchedIndex; for(int i = 0; i < modelItems.length; i++) { li = modelItems[i]; if(li instanceof DocumentListItem) { dli = (DocumentListItem) li; // remove documents that are no longer visible if(!visibleDocuments.contains(dli.getDisplayDocument())) jListModel.removeElement(li); // re-create the list item of those that have been touched if(touchedDocuments.contains(dli.getDisplayDocument())) { touchedIndex = touchedDocuments.indexOf(dli.getDisplayDocument()); jListModel.remove(i); jListModel.add(i, ListItem.create(touchedDocuments.get(touchedIndex))); } } } touchedDocuments.clear(); if(1 > visibleDocuments.size()) { browser.disableHistory(); } else { browser.enableHistory(); } }
|
private void syncDocuments() { // sync the documents with the visible documents visibleDocuments.clear(); visibleDocuments.addAll(documents); ModelFilterManager.filter(visibleDocuments, documentFilter); // sync visible documents with the swing list's model ListItem li; for(int i = 0; i < visibleDocuments.size(); i++) { li = ListItem.create(visibleDocuments.get(i)); if(!jListModel.contains(li)) { jListModel.add(i, li); } } final ListItem[] modelItems = new ListItem[jListModel.size()]; jListModel.copyInto(modelItems); DocumentListItem dli; int visibleIndex; for(int i = 0; i < modelItems.length; i++) { li = modelItems[i]; if(li instanceof DocumentListItem) { dli = (DocumentListItem) li; // remove documents that are no longer visible if(!visibleDocuments.contains(dli.getDisplayDocument())) jListModel.removeElement(li); // re-create the list item of those that have been touched if(touchedDocuments.contains(dli.getDisplayDocument())) { touchedIndex = touchedDocuments.indexOf(dli.getDisplayDocument()); jListModel.remove(i); jListModel.add(i, ListItem.create(touchedDocuments.get(touchedIndex))); } } } touchedDocuments.clear(); if(1 > visibleDocuments.size()) { browser.disableHistory(); } else { browser.enableHistory(); } }
| 1,114,566
|
private void syncDocuments() { // sync the documents with the visible documents visibleDocuments.clear(); visibleDocuments.addAll(documents); ModelFilterManager.filter(visibleDocuments, documentFilter); // sync visible documents with the swing list's model ListItem li; for(int i = 0; i < visibleDocuments.size(); i++) { li = ListItem.create(visibleDocuments.get(i)); if(!jListModel.contains(li)) { jListModel.add(i, li); } } final ListItem[] modelItems = new ListItem[jListModel.size()]; jListModel.copyInto(modelItems); DocumentListItem dli; int touchedIndex; for(int i = 0; i < modelItems.length; i++) { li = modelItems[i]; if(li instanceof DocumentListItem) { dli = (DocumentListItem) li; // remove documents that are no longer visible if(!visibleDocuments.contains(dli.getDisplayDocument())) jListModel.removeElement(li); // re-create the list item of those that have been touched if(touchedDocuments.contains(dli.getDisplayDocument())) { touchedIndex = touchedDocuments.indexOf(dli.getDisplayDocument()); jListModel.remove(i); jListModel.add(i, ListItem.create(touchedDocuments.get(touchedIndex))); } } } touchedDocuments.clear(); if(1 > visibleDocuments.size()) { browser.disableHistory(); } else { browser.enableHistory(); } }
|
private void syncDocuments() { // sync the documents with the visible documents visibleDocuments.clear(); visibleDocuments.addAll(documents); ModelFilterManager.filter(visibleDocuments, documentFilter); // sync visible documents with the swing list's model ListItem li; for(int i = 0; i < visibleDocuments.size(); i++) { li = ListItem.create(visibleDocuments.get(i)); if(!jListModel.contains(li)) { jListModel.add(i, li); } } final ListItem[] modelItems = new ListItem[jListModel.size()]; jListModel.copyInto(modelItems); DocumentListItem dli; int touchedIndex; for(int i = 0; i < modelItems.length; i++) { li = modelItems[i]; if(li instanceof DocumentListItem) { dli = (DocumentListItem) li; // remove documents that are no longer visible if(!visibleDocuments.contains(dli.getDisplayDocument())) jListModel.removeElement(li); // re-create the list item of those that have been touched if(touchedDocuments.contains(dli.getDisplayDocument())) { visibleIndex = visibleDocuments.indexOf(dli.getDisplayDocument()); jListModel.remove(i); jListModel.add(i, ListItem.create(touchedDocuments.get(touchedIndex))); } } } touchedDocuments.clear(); if(1 > visibleDocuments.size()) { browser.disableHistory(); } else { browser.enableHistory(); } }
| 1,114,567
|
private void syncDocuments() { // sync the documents with the visible documents visibleDocuments.clear(); visibleDocuments.addAll(documents); ModelFilterManager.filter(visibleDocuments, documentFilter); // sync visible documents with the swing list's model ListItem li; for(int i = 0; i < visibleDocuments.size(); i++) { li = ListItem.create(visibleDocuments.get(i)); if(!jListModel.contains(li)) { jListModel.add(i, li); } } final ListItem[] modelItems = new ListItem[jListModel.size()]; jListModel.copyInto(modelItems); DocumentListItem dli; int touchedIndex; for(int i = 0; i < modelItems.length; i++) { li = modelItems[i]; if(li instanceof DocumentListItem) { dli = (DocumentListItem) li; // remove documents that are no longer visible if(!visibleDocuments.contains(dli.getDisplayDocument())) jListModel.removeElement(li); // re-create the list item of those that have been touched if(touchedDocuments.contains(dli.getDisplayDocument())) { touchedIndex = touchedDocuments.indexOf(dli.getDisplayDocument()); jListModel.remove(i); jListModel.add(i, ListItem.create(touchedDocuments.get(touchedIndex))); } } } touchedDocuments.clear(); if(1 > visibleDocuments.size()) { browser.disableHistory(); } else { browser.enableHistory(); } }
|
private void syncDocuments() { // sync the documents with the visible documents visibleDocuments.clear(); visibleDocuments.addAll(documents); ModelFilterManager.filter(visibleDocuments, documentFilter); // sync visible documents with the swing list's model ListItem li; for(int i = 0; i < visibleDocuments.size(); i++) { li = ListItem.create(visibleDocuments.get(i)); if(!jListModel.contains(li)) { jListModel.add(i, li); } } final ListItem[] modelItems = new ListItem[jListModel.size()]; jListModel.copyInto(modelItems); DocumentListItem dli; int touchedIndex; for(int i = 0; i < modelItems.length; i++) { li = modelItems[i]; if(li instanceof DocumentListItem) { dli = (DocumentListItem) li; // remove documents that are no longer visible if(!visibleDocuments.contains(dli.getDisplayDocument())) jListModel.removeElement(li); // re-create the list item of those that have been touched if(touchedDocuments.contains(dli.getDisplayDocument())) { touchedIndex = touchedDocuments.indexOf(dli.getDisplayDocument()); jListModel.remove(i); jListModel.add(visibleIndex, ListItem.create(visibleDocuments.get(visibleIndex))); } } } touchedDocuments.clear(); if(1 > visibleDocuments.size()) { browser.disableHistory(); } else { browser.enableHistory(); } }
| 1,114,568
|
void login(final String username, final String password) throws ParityException { final String host = preferences.getServerHost(); final Integer port = preferences.getServerPort(); synchronized(xmppHelperLock) { try { xmppHelper.login(host, port, username, password); preferences.setUsername(xmppHelper.getUser().getUsername()); } catch(SmackException sx) { logger.error("login(String,String)", sx); throw ParityErrorTranslator.translate(sx); } catch(RuntimeException rx) { logger.error("login(String,String)", rx); throw ParityErrorTranslator.translate(rx); } } }
|
void login(final String username, final String password) throws ParityException { final String host = preferences.getServerHost(); final Integer port = preferences.getServerPort(); synchronized(xmppHelperLock) { try { xmppHelper.login(host, port, username, password); if(!preferences.isSetUsername()) { preferences.setUsername(usernameAtHost); } } catch(SmackException sx) { logger.error("login(String,String)", sx); throw ParityErrorTranslator.translate(sx); } catch(RuntimeException rx) { logger.error("login(String,String)", rx); throw ParityErrorTranslator.translate(rx); } } }
| 1,114,569
|
public static JMenuItem createCheckBox(final String text, final Integer mnemonic) { synchronized(singletonLock) { return singleton.doCreateCheckBox(text, mnemonic); } }
|
public static JMenuItem createCheckBox(final String text, final Integer mnemonic) { synchronized(singletonLock) { return singleton.doCreateCheckBox(text, mnemonic); } }
| 1,114,570
|
private JMenuItem doCreateCheckBox(final String text, final Integer mnemonic) { logger.debug(text); final JMenuItem jMenuItem = new JCheckBoxMenuItem(text); applyDefaultFont(jMenuItem); applyMnemonic(jMenuItem, mnemonic); return jMenuItem; }
|
private JMenuItem doCreateCheckBox(final String text, final Integer mnemonic) { logger.debug(text); final JMenuItem jMenuItem = new JCheckBoxMenuItem(text); applyDefaultFont(jMenuItem); applyMnemonic(jMenuItem, mnemonic); return jMenuItem; }
| 1,114,571
|
public void bind() { bound = true; color = new Color(255, 255, 255); }
|
public void bind() { bound = true; color = new Color(255, 255, 127); }
| 1,114,573
|
private Double keplerRotation(Double r) { return (1 / Math.sqrt(r * r * r)) * 1000.0; }
|
private Double keplerRotation(Double r) { Double r2 = r * 1.5; return (1 / Math.sqrt(r2 * r2 * r2)) * 1000.0; }
| 1,114,574
|
public Component getListCellRendererComponent(final JList list, final Object value, final int index, final boolean isSelected, final boolean cellHasFocus) { final AbstractContentCell cell = (AbstractContentCell) value; textJLabel.setText(cell.getText()); final Icon icon = cell.getIcon(); if (null!=icon) { iconJLabel.setIcon(icon); } if (isSelected && list.isFocusOwner()) { textJLabel.setForeground(Colors.Browser.List.INNER_LIST_SELECTION_FG); setBackground(Colors.Browser.List.INNER_LIST_SELECTION_BG); } else { textJLabel.setForeground(Colors.Browser.List.LIST_FG); if (0 == index % 2) { setBackground(Colors.Browser.List.LIST_EVEN_BG); } else { setBackground(Colors.Browser.List.LIST_ODD_BG); } } return this; }
|
public Component getListCellRendererComponent(final JList list, final Object value, final int index, final boolean isSelected, final boolean cellHasFocus) { final AbstractContentCell cell = (AbstractContentCell) value; textJLabel.setText(cell.getText()); final Icon icon = cell.getIcon(); if (null!=icon) { iconJLabel.setIcon(icon); } if (isSelected && list.isFocusOwner()) { textJLabel.setForeground(Colors.Browser.List.INNER_LIST_SELECTION_FG); setBackground(Colors.Browser.List.INNER_LIST_SELECTION_BG); } else { textJLabel.setForeground(Colors.Browser.List.LIST_FG); if (0 == index % 2) { setBackground(Colors.Browser.List.LIST_EVEN_BG); } else { setBackground(Colors.Browser.List.LIST_ODD_BG); } } return this; }
| 1,114,575
|
protected StreamClient(final StreamSession session) { super(); this.logger = new Log4JWrapper(); this.session = session; final Environment environment = session.getEnvironment(); this.socketAddress = new InetSocketAddress( environment.getStreamHost(), environment.getStreamPort()); if (environment.isStreamTLSEnabled()) { logger.logInfo("Stream Client - {0}:{1} - Secure", environment.getStreamHost(), environment.getStreamPort()); final String keyStorePath = "security/stream_client_keystore"; final char[] keyStorePassword = "password".toCharArray(); try { socketFactory = com.thinkparity.codebase.net.SocketFactory.getSecureInstance(keyStorePath, keyStorePassword, keyStorePath, keyStorePassword); } catch (final Exception x) { throw new StreamException(x); } } else { logger.logInfo("Stream Client - {0}:{1}", environment.getStreamHost(), environment.getStreamPort()); socketFactory = com.thinkparity.codebase.net.SocketFactory.getInstance(); } }
|
protected StreamClient(final StreamSession session) { super(); this.session = session; final Environment environment = session.getEnvironment(); this.socketAddress = new InetSocketAddress( environment.getStreamHost(), environment.getStreamPort()); if (environment.isStreamTLSEnabled()) { logger.logInfo("Stream Client - {0}:{1} - Secure", environment.getStreamHost(), environment.getStreamPort()); final String keyStorePath = "security/stream_client_keystore"; final char[] keyStorePassword = "password".toCharArray(); try { socketFactory = com.thinkparity.codebase.net.SocketFactory.getSecureInstance(keyStorePath, keyStorePassword, keyStorePath, keyStorePassword); } catch (final Exception x) { throw new StreamException(x); } } else { logger.logInfo("Stream Client - {0}:{1}", environment.getStreamHost(), environment.getStreamPort()); socketFactory = com.thinkparity.codebase.net.SocketFactory.getInstance(); } }
| 1,114,576
|
protected final void connect(final Type type) { try { doConnect(); write(new StreamHeader(StreamHeader.Type.SESSION_BEGIN, session.getId())); write(new StreamHeader(StreamHeader.Type.SESSION_TYPE, type.name())); } catch (final IOException iox) { if (isConnected()) try { doDisconnect(); } catch (final IOException iox2) { /* NOTE We do not want to mask the connection error. */ logger.logError(iox2, "Could not disconnect from bad connection."); } throw new StreamException(iox); } }
|
protected final void connect(final Type type) { try { doConnect(); write(new StreamHeader(StreamHeader.Type.SESSION_BEGIN, session.getId())); write(new StreamHeader(StreamHeader.Type.SESSION_TYPE, type.name())); } catch (final IOException iox) { if (isConnected()) try { doDisconnect(); } catch (final IOException iox2) { /* NOTE We do not want to mask the connection error. */ logger.logError(iox2, "Could not disconnect from bad connection."); } throw new StreamException(iox); } }
| 1,114,577
|
protected final void disconnect() { try { doDisconnect(); } catch (final IOException iox) { throw new StreamException(iox); } }
|
protected final void disconnect() { try { doDisconnect(); } catch (final IOException iox) { throw new StreamException(iox); } }
| 1,114,578
|
protected final void write(final InputStream stream) { logger.logApiId(); try { StreamUtil.copy(stream, output, session.getBufferSize()); output.flush(); } catch (final IOException iox) { throw new StreamException(iox); } }
|
protected final void write(final InputStream stream, final Long streamSize) { logger.logApiId(); try { StreamUtil.copy(stream, output, session.getBufferSize()); output.flush(); } catch (final IOException iox) { throw new StreamException(iox); } }
| 1,114,579
|
protected final void write(final InputStream stream) { logger.logApiId(); try { StreamUtil.copy(stream, output, session.getBufferSize()); output.flush(); } catch (final IOException iox) { throw new StreamException(iox); } }
|
protected final void write(final InputStream stream) { logger.logApiId(); try { StreamUtil.copy(stream, output, session.getBufferSize()); output.flush(); } catch (final IOException iox) { throw new StreamException(iox); } }
| 1,114,580
|
public List<DocumentVersion> readDocumentVersions(final UUID uniqueId, final Long versionId, final UUID documentUniqueId);
|
public List<DocumentVersion> readDocumentVersions(final UUID uniqueId, final Long versionId);
| 1,114,581
|
void addBookmark(final Long containerId) { logger.logApiId(); logger.logVariable("containerId", containerId); try { getInternalArtifactModel().applyFlagBookmark(containerId); notifyContainerUpdated(read(containerId), localEventGenerator); } catch (final Throwable t) { throw translateError(t); } }
|
void addBookmark(final Long containerId) { logger.logApiId(); logger.logVariable("containerId", containerId); try { getArtifactModel().applyFlagBookmark(containerId); notifyContainerUpdated(read(containerId), localEventGenerator); } catch (final Throwable t) { throw translateError(t); } }
| 1,114,582
|
Container create(final String name) { logger.logApiId(); logger.logVariable("name", name); try { final Container container = new Container(); container.setCreatedBy(localUserId()); container.setCreatedOn(currentDateTime()); container.setName(name); container.setState(ArtifactState.ACTIVE); container.setType(ArtifactType.CONTAINER); container.setUniqueId(UUIDGenerator.nextUUID()); container.setUpdatedBy(container.getCreatedBy()); container.setUpdatedOn(container.getCreatedOn()); // local create containerIO.create(container); // local key final InternalArtifactModel artifactModel = getInternalArtifactModel(); artifactModel.applyFlagKey(container.getId()); // create remote info artifactModel.createRemoteInfo(container.getId(), container.getCreatedBy(), container.getCreatedOn()); // index getIndexModel().indexContainer(container.getId()); // create team final TeamMember teamMember = createTeam(container.getId()); // create first draft createFirstDraft(container.getId(), teamMember); // audit\fire event final Container postCreation = read(container.getId()); auditContainerCreated(postCreation); notifyContainerCreated(postCreation, localEventGenerator); return postCreation; } catch (final Throwable t) { throw translateError(t); } }
|
Container create(final String name) { logger.logApiId(); logger.logVariable("name", name); try { final Container container = new Container(); container.setCreatedBy(localUserId()); container.setCreatedOn(currentDateTime()); container.setName(name); container.setState(ArtifactState.ACTIVE); container.setType(ArtifactType.CONTAINER); container.setUniqueId(UUIDGenerator.nextUUID()); container.setUpdatedBy(container.getCreatedBy()); container.setUpdatedOn(container.getCreatedOn()); // local create containerIO.create(container); // local key final InternalArtifactModel artifactModel = getArtifactModel(); artifactModel.applyFlagKey(container.getId()); // create remote info artifactModel.createRemoteInfo(container.getId(), container.getCreatedBy(), container.getCreatedOn()); // index getIndexModel().indexContainer(container.getId()); // create team final TeamMember teamMember = createTeam(container.getId()); // create first draft createFirstDraft(container.getId(), teamMember); // audit\fire event final Container postCreation = read(container.getId()); auditContainerCreated(postCreation); notifyContainerCreated(postCreation, localEventGenerator); return postCreation; } catch (final Throwable t) { throw translateError(t); } }
| 1,114,583
|
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); final InternalDocumentModel documentModel = getInternalDocumentModel(); for (final Document document : documents) { draft.addDocument(document); draft.putState(document, ContainerDraft.ArtifactState.NONE); documentModel.createDraft(document.getId()); } 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); } }
|
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 = getArtifactModel(); 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); final InternalDocumentModel documentModel = getInternalDocumentModel(); for (final Document document : documents) { draft.addDocument(document); draft.putState(document, ContainerDraft.ArtifactState.NONE); documentModel.createDraft(document.getId()); } 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); } }
| 1,114,584
|
private TeamMember createTeam(final Long containerId) { final List<TeamMember> team = getInternalArtifactModel().createTeam(containerId); return team.get(0); }
|
private TeamMember createTeam(final Long containerId) { final List<TeamMember> team = getArtifactModel().createTeam(containerId); return team.get(0); }
| 1,114,585
|
void delete(final Long containerId) { logger.logApiId(); logger.logVariable("containerId", containerId); try { final Container container = read(containerId); if (isDistributed(container.getId())) { final TeamMember localTeamMember = localTeamMember(container.getId()); deleteLocal(container.getId()); getSessionModel().removeTeamMember( container.getUniqueId(), localTeamMember.getId()); } else { deleteLocal(container.getId()); } // fire event notifyContainerDeleted(container, localEventGenerator); } catch (final Throwable t) { throw translateError(t); } }
|
void delete(final Long containerId) { logger.logApiId(); logger.logVariable("containerId", containerId); try { final Container container = read(containerId); if (isDistributed(container.getId())) { final TeamMember localTeamMember = localTeamMember(container.getId()); deleteLocal(container.getId()); getSessionModel().removeTeamMember( container.getUniqueId(), localTeamMember.getId()); } else { deleteLocal(container.getId()); } // fire event notifyContainerDeleted(container, localEventGenerator); } catch (final Throwable t) { throw translateError(t); } }
| 1,114,586
|
private void deleteLocal(final Long containerId) { // delete the draft final ContainerDraft draft = readDraft(containerId); if (null != draft) { for(final Artifact artifact : draft.getArtifacts()) { containerIO.deleteDraftArtifactRel(containerId, artifact.getId()); } containerIO.deleteDraft(containerId); } // delete the team final InternalArtifactModel artifactModel = getInternalArtifactModel(); artifactModel.deleteTeam(containerId); // delete the remote info artifactModel.deleteRemoteInfo(containerId); // delete the audit events getInternalAuditModel().delete(containerId); // delete versions final InternalDocumentModel documentModel = getInternalDocumentModel(); final List<ContainerVersion> versions = readVersions(containerId); List<Document> documents; for (final ContainerVersion version : versions) { documents = containerIO.readDocuments(version.getArtifactId(), version.getVersionId()); // remove the version's artifact versions containerIO.removeVersions(containerId, version.getVersionId()); for(final Document document : documents) { documentModel.delete(document.getId()); } // delete the version's deltas containerIO.deleteDeltas(containerId, version.getVersionId()); // delete the version containerIO.deleteVersion(containerId, version.getVersionId()); } // delete the index getIndexModel().deleteContainer(containerId); // delete the container containerIO.delete(containerId); }
|
private void deleteLocal(final Long containerId) { // delete the draft final ContainerDraft draft = readDraft(containerId); if (null != draft) { for(final Artifact artifact : draft.getArtifacts()) { containerIO.deleteDraftArtifactRel(containerId, artifact.getId()); } containerIO.deleteDraft(containerId); } // delete the team final InternalArtifactModel artifactModel = getArtifactModel(); artifactModel.deleteTeam(containerId); // delete the remote info artifactModel.deleteRemoteInfo(containerId); // delete the audit events getInternalAuditModel().delete(containerId); // delete versions final InternalDocumentModel documentModel = getInternalDocumentModel(); final List<ContainerVersion> versions = readVersions(containerId); List<Document> documents; for (final ContainerVersion version : versions) { documents = containerIO.readDocuments(version.getArtifactId(), version.getVersionId()); // remove the version's artifact versions containerIO.removeVersions(containerId, version.getVersionId()); for(final Document document : documents) { documentModel.delete(document.getId()); } // delete the version's deltas containerIO.deleteDeltas(containerId, version.getVersionId()); // delete the version containerIO.deleteVersion(containerId, version.getVersionId()); } // delete the index getIndexModel().deleteContainer(containerId); // delete the container containerIO.delete(containerId); }
| 1,114,587
|
private void doPublishVersion(final PublishMonitor monitor, final Long containerId, final Long versionId, final List<Contact> contacts, final List<TeamMember> teamMembers) throws IOException { final Container container = read(containerId); final ContainerVersion version = readVersion(containerId, versionId); // update local team final InternalArtifactModel artifactModel = getInternalArtifactModel(); for (final Contact contact : contacts) artifactModel.addTeamMember(container.getId(), contact.getId()); // build the publish to list then publish final List<JabberId> publishTo = new ArrayList<JabberId>(); final List<User> publishToUsers = new ArrayList<User>(); for (final Contact contact : contacts) { publishTo.add(contact.getId()); publishToUsers.add(contact); } for (final TeamMember teamMember : teamMembers) { publishTo.add(teamMember.getId()); publishToUsers.add(teamMember); } final Calendar currentDateTime = currentDateTime(); publish(monitor, version, publishTo, localUserId(), currentDateTime); // update remote team final InternalSessionModel sessionModel = getSessionModel(); for (final Contact contact : contacts) sessionModel.addTeamMember(container.getUniqueId(), contact.getId()); // create published to list containerIO.createPublishedTo(containerId, version.getVersionId(), publishToUsers); }
|
private void doPublishVersion(final PublishMonitor monitor, final Long containerId, final Long versionId, final List<Contact> contacts, final List<TeamMember> teamMembers) throws IOException { final Container container = read(containerId); final ContainerVersion version = readVersion(containerId, versionId); // update local team final InternalArtifactModel artifactModel = getArtifactModel(); for (final Contact contact : contacts) artifactModel.addTeamMember(container.getId(), contact.getId()); // build the publish to list then publish final List<JabberId> publishTo = new ArrayList<JabberId>(); final List<User> publishToUsers = new ArrayList<User>(); for (final Contact contact : contacts) { publishTo.add(contact.getId()); publishToUsers.add(contact); } for (final TeamMember teamMember : teamMembers) { publishTo.add(teamMember.getId()); publishToUsers.add(teamMember); } final Calendar currentDateTime = currentDateTime(); publish(monitor, version, publishTo, localUserId(), currentDateTime); // update remote team final InternalSessionModel sessionModel = getSessionModel(); for (final Contact contact : contacts) sessionModel.addTeamMember(container.getUniqueId(), contact.getId()); // create published to list containerIO.createPublishedTo(containerId, version.getVersionId(), publishToUsers); }
| 1,114,588
|
private void doPublishVersion(final PublishMonitor monitor, final Long containerId, final Long versionId, final List<Contact> contacts, final List<TeamMember> teamMembers) throws IOException { final Container container = read(containerId); final ContainerVersion version = readVersion(containerId, versionId); // update local team final InternalArtifactModel artifactModel = getInternalArtifactModel(); for (final Contact contact : contacts) artifactModel.addTeamMember(container.getId(), contact.getId()); // build the publish to list then publish final List<JabberId> publishTo = new ArrayList<JabberId>(); final List<User> publishToUsers = new ArrayList<User>(); for (final Contact contact : contacts) { publishTo.add(contact.getId()); publishToUsers.add(contact); } for (final TeamMember teamMember : teamMembers) { publishTo.add(teamMember.getId()); publishToUsers.add(teamMember); } final Calendar currentDateTime = currentDateTime(); publish(monitor, version, publishTo, localUserId(), currentDateTime); // update remote team final InternalSessionModel sessionModel = getSessionModel(); for (final Contact contact : contacts) sessionModel.addTeamMember(container.getUniqueId(), contact.getId()); // create published to list containerIO.createPublishedTo(containerId, version.getVersionId(), publishToUsers); }
|
private void doPublishVersion(final PublishMonitor monitor, final Long containerId, final Long versionId, final List<Contact> contacts, final List<TeamMember> teamMembers) throws IOException { final Container container = read(containerId); final ContainerVersion version = readVersion(containerId, versionId); // update local team final InternalArtifactModel artifactModel = getInternalArtifactModel(); for (final Contact contact : contacts) artifactModel.addTeamMember(container.getId(), contact.getId()); // build the publish to list then publish final List<JabberId> publishTo = new ArrayList<JabberId>(); final List<User> publishToUsers = new ArrayList<User>(); for (final Contact contact : contacts) { publishTo.add(contact.getId()); publishToUsers.add(contact); } for (final TeamMember teamMember : teamMembers) { publishTo.add(teamMember.getId()); publishToUsers.add(teamMember); } final Calendar currentDateTime = currentDateTime(); publish(monitor, version, publishTo, localUserId(), currentDateTime); // update remote team final InternalSessionModel sessionModel = getSessionModel(); for (final Contact contact : contacts) sessionModel.addTeamMember(container.getUniqueId(), artifactModel .readTeamIds(container.getId()), contact.getId()); // create published to list containerIO.createPublishedTo(containerId, version.getVersionId(), publishToUsers); }
| 1,114,589
|
void handleArtifactPublished(final ContainerArtifactPublishedEvent event) { logger.logApiId(); logger.logVariable("event", event); try { // determine the existance of the container and the version. final InternalArtifactModel artifactModel = getInternalArtifactModel(); final Boolean doesExist = artifactModel.doesExist(event.getUniqueId()); final Long containerId; final Container container; final ContainerVersion version; if (doesExist) { containerId = artifactModel.readId(event.getUniqueId()); container = read(containerId); final Boolean doesVersionExist = artifactModel.doesVersionExist(containerId, event.getVersionId()); if (doesVersionExist) { version = readVersion(container.getId(), event.getVersionId()); } else { version = createVersion(container.getId(), event.getVersionId(), event.getPublishedBy(), event.getPublishedOn()); } } else { // ensure the published by user exists locally getInternalUserModel().readLazyCreate(event.getPublishedBy()); container = new Container(); container.setCreatedBy(event.getPublishedBy()); container.setCreatedOn(event.getPublishedOn()); container.setName(event.getName()); container.setState(ArtifactState.ACTIVE); container.setType(ArtifactType.CONTAINER); container.setUniqueId(event.getUniqueId()); container.setUpdatedBy(container.getCreatedBy()); container.setUpdatedOn(container.getCreatedOn()); // create containerIO.create(container); // create version version = createVersion(container.getId(), event.getVersionId(), event.getPublishedBy(), event.getPublishedOn()); // create remote info artifactModel.createRemoteInfo(container.getId(), event.getPublishedBy(), container.getCreatedOn()); // index getIndexModel().indexContainer(container.getId()); } // handle the artifact by specific type final ArtifactVersion artifactVersion; switch (event.getArtifactType()) { case DOCUMENT: artifactVersion = handleDocumentPublished(event); break; case CONTAINER: default: throw Assert.createUnreachable("UNKNOWN ARTIFACT TYPE"); } containerIO.addVersion(version.getArtifactId(), version.getVersionId(), artifactVersion.getArtifactId(), artifactVersion.getVersionId(), artifactVersion.getArtifactType()); } catch(final Throwable t) { throw translateError(t); } }
|
void handleArtifactPublished(final ContainerArtifactPublishedEvent event) { logger.logApiId(); logger.logVariable("event", event); try { // determine the existance of the container and the version. final InternalArtifactModel artifactModel = getArtifactModel(); final Boolean doesExist = artifactModel.doesExist(event.getUniqueId()); final Long containerId; final Container container; final ContainerVersion version; if (doesExist) { containerId = artifactModel.readId(event.getUniqueId()); container = read(containerId); final Boolean doesVersionExist = artifactModel.doesVersionExist(containerId, event.getVersionId()); if (doesVersionExist) { version = readVersion(container.getId(), event.getVersionId()); } else { version = createVersion(container.getId(), event.getVersionId(), event.getPublishedBy(), event.getPublishedOn()); } } else { // ensure the published by user exists locally getInternalUserModel().readLazyCreate(event.getPublishedBy()); container = new Container(); container.setCreatedBy(event.getPublishedBy()); container.setCreatedOn(event.getPublishedOn()); container.setName(event.getName()); container.setState(ArtifactState.ACTIVE); container.setType(ArtifactType.CONTAINER); container.setUniqueId(event.getUniqueId()); container.setUpdatedBy(container.getCreatedBy()); container.setUpdatedOn(container.getCreatedOn()); // create containerIO.create(container); // create version version = createVersion(container.getId(), event.getVersionId(), event.getPublishedBy(), event.getPublishedOn()); // create remote info artifactModel.createRemoteInfo(container.getId(), event.getPublishedBy(), container.getCreatedOn()); // index getIndexModel().indexContainer(container.getId()); } // handle the artifact by specific type final ArtifactVersion artifactVersion; switch (event.getArtifactType()) { case DOCUMENT: artifactVersion = handleDocumentPublished(event); break; case CONTAINER: default: throw Assert.createUnreachable("UNKNOWN ARTIFACT TYPE"); } containerIO.addVersion(version.getArtifactId(), version.getVersionId(), artifactVersion.getArtifactId(), artifactVersion.getVersionId(), artifactVersion.getArtifactType()); } catch(final Throwable t) { throw translateError(t); } }
| 1,114,590
|
void handlePublished(final ContainerPublishedEvent event) { logger.logApiId(); logger.logVariable("event", event); try { final InternalArtifactModel artifactModel = getInternalArtifactModel(); final Long containerId = artifactModel.readId(event.getUniqueId()); // add to local team final InternalUserModel userModel = getInternalUserModel(); final List<TeamMember> localTeam = artifactModel.readTeam2(containerId); final List<User> publishedToUsers = new ArrayList<User>(); for (final JabberId publishedToId : event.getPublishedTo()) { if (!contains(localTeam, publishedToId)) { artifactModel.addTeamMember(containerId, publishedToId); } publishedToUsers.add(userModel.read(publishedToId)); } // add the sender as well final TeamMember publishedBy; if (!contains(localTeam, event.getPublishedBy())) { publishedBy = artifactModel.addTeamMember(containerId, event.getPublishedBy()); } else { publishedBy = localTeam.get(indexOf(localTeam, event.getPublishedBy())); } // delete draft final ContainerDraft draft = readDraft(containerId); if (null == draft) { logger.logWarning("Draft did not previously exist for {0}.", event.getName()); } else { deleteDraft(containerId); } // create published to list containerIO.createPublishedTo(containerId, event.getVersionId(), publishedToUsers); // calculate differences final ContainerVersion version = readVersion(containerId, event.getVersionId()); final ContainerVersion previous = readPreviousVersion(containerId, event.getVersionId()); final ContainerVersion next = readNextVersion(containerId, event.getVersionId()); if (null == previous) { logger.logInfo("First version of {0}.", event.getName()); } else { containerIO.deleteDelta(containerId, previous.getVersionId(), version.getVersionId()); containerIO.createDelta(calculateDelta(read(containerId), version, previous)); } if (null == next) { logger.logInfo("Latest version of {0}.", event.getName()); } else { containerIO.deleteDelta(containerId, version.getVersionId(), next.getVersionId()); containerIO.createDelta(calculateDelta(read(containerId), next, version)); } // apply comment if (null != event.getComment() && 0 < event.getComment().trim().length()) containerIO.updateComment(containerId, version.getVersionId(), event.getComment()); // send confirmation getSessionModel().confirmArtifactReceipt(localUserId(), event.getUniqueId(), event.getVersionId(), localUserId(), currentDateTime()); // audit\fire event final Container postPublish = read(containerId); final ContainerVersion postPublishVersion = readVersion(containerId, event.getVersionId()); auditContainerPublished(postPublish, draft, postPublishVersion, event.getPublishedBy(), event.getPublishedTo(), event.getPublishedOn()); notifyContainerPublished(postPublish, publishedBy, postPublishVersion, remoteEventGenerator); } catch (final Throwable t) { throw translateError(t); } }
|
void handlePublished(final ContainerPublishedEvent event) { logger.logApiId(); logger.logVariable("event", event); try { final InternalArtifactModel artifactModel = getArtifactModel(); final Long containerId = artifactModel.readId(event.getUniqueId()); // add to local team final InternalUserModel userModel = getInternalUserModel(); final List<TeamMember> localTeam = artifactModel.readTeam2(containerId); final List<User> publishedToUsers = new ArrayList<User>(); for (final JabberId publishedToId : event.getPublishedTo()) { if (!contains(localTeam, publishedToId)) { artifactModel.addTeamMember(containerId, publishedToId); } publishedToUsers.add(userModel.read(publishedToId)); } // add the sender as well final TeamMember publishedBy; if (!contains(localTeam, event.getPublishedBy())) { publishedBy = artifactModel.addTeamMember(containerId, event.getPublishedBy()); } else { publishedBy = localTeam.get(indexOf(localTeam, event.getPublishedBy())); } // delete draft final ContainerDraft draft = readDraft(containerId); if (null == draft) { logger.logWarning("Draft did not previously exist for {0}.", event.getName()); } else { deleteDraft(containerId); } // create published to list containerIO.createPublishedTo(containerId, event.getVersionId(), publishedToUsers); // calculate differences final ContainerVersion version = readVersion(containerId, event.getVersionId()); final ContainerVersion previous = readPreviousVersion(containerId, event.getVersionId()); final ContainerVersion next = readNextVersion(containerId, event.getVersionId()); if (null == previous) { logger.logInfo("First version of {0}.", event.getName()); } else { containerIO.deleteDelta(containerId, previous.getVersionId(), version.getVersionId()); containerIO.createDelta(calculateDelta(read(containerId), version, previous)); } if (null == next) { logger.logInfo("Latest version of {0}.", event.getName()); } else { containerIO.deleteDelta(containerId, version.getVersionId(), next.getVersionId()); containerIO.createDelta(calculateDelta(read(containerId), next, version)); } // apply comment if (null != event.getComment() && 0 < event.getComment().trim().length()) containerIO.updateComment(containerId, version.getVersionId(), event.getComment()); // send confirmation getSessionModel().confirmArtifactReceipt(localUserId(), event.getUniqueId(), event.getVersionId(), localUserId(), currentDateTime()); // audit\fire event final Container postPublish = read(containerId); final ContainerVersion postPublishVersion = readVersion(containerId, event.getVersionId()); auditContainerPublished(postPublish, draft, postPublishVersion, event.getPublishedBy(), event.getPublishedTo(), event.getPublishedOn()); notifyContainerPublished(postPublish, publishedBy, postPublishVersion, remoteEventGenerator); } catch (final Throwable t) { throw translateError(t); } }
| 1,114,591
|
Boolean isDistributed(final Long containerId) { logger.logApiId(); logger.logVariable("containerId", containerId); try { return getInternalArtifactModel().doesVersionExist(containerId, Versioning.START); } catch (final Throwable t) { throw translateError(t); } }
|
Boolean isDistributed(final Long containerId) { logger.logApiId(); logger.logVariable("containerId", containerId); try { return getArtifactModel().doesVersionExist(containerId, Versioning.START); } catch (final Throwable t) { throw translateError(t); } }
| 1,114,593
|
void publishVersion(final Long containerId, final Long versionId, final List<Contact> contacts) { logger.logApiId(); logger.logVariable("containerId", containerId); logger.logVariable("versionId", versionId); logger.logVariable("contacts", contacts); try { // remove local key getInternalArtifactModel().removeFlagKey(containerId); final List<TeamMember> teamMembers = Collections.emptyList(); doPublishVersion(PUBLISH_MONITOR, containerId, versionId, contacts, teamMembers); // fire event final Container postPublish = read(containerId); final ContainerVersion postPublishVersion = readVersion(containerId, versionId); notifyContainerPublished(postPublish, postPublishVersion, localEventGenerator); } catch (final Throwable t) { throw translateError(t); } }
|
void publishVersion(final Long containerId, final Long versionId, final List<Contact> contacts) { logger.logApiId(); logger.logVariable("containerId", containerId); logger.logVariable("versionId", versionId); logger.logVariable("contacts", contacts); try { // remove local key getArtifactModel().removeFlagKey(containerId); final List<TeamMember> teamMembers = Collections.emptyList(); doPublishVersion(PUBLISH_MONITOR, containerId, versionId, contacts, teamMembers); // fire event final Container postPublish = read(containerId); final ContainerVersion postPublishVersion = readVersion(containerId, versionId); notifyContainerPublished(postPublish, postPublishVersion, localEventGenerator); } catch (final Throwable t) { throw translateError(t); } }
| 1,114,594
|
List<TeamMember> readTeam(final Long containerId) { logger.logApiId(); logger.logVariable("containerId", containerId); return getInternalArtifactModel().readTeam(containerId, UserComparatorFactory.createName(Boolean.TRUE), FilterManager.createDefault()); }
|
List<TeamMember> readTeam(final Long containerId) { logger.logApiId(); logger.logVariable("containerId", containerId); return getArtifactModel().readTeam(containerId, UserComparatorFactory.createName(Boolean.TRUE), FilterManager.createDefault()); }
| 1,114,595
|
void removeBookmark(final Long containerId) { logger.logApiId(); logger.logVariable("containerId", containerId); try { getInternalArtifactModel().removeFlagBookmark(containerId); notifyContainerUpdated(read(containerId), localEventGenerator); } catch (final Throwable t) { throw translateError(t); } }
|
void removeBookmark(final Long containerId) { logger.logApiId(); logger.logVariable("containerId", containerId); try { getArtifactModel().removeFlagBookmark(containerId); notifyContainerUpdated(read(containerId), localEventGenerator); } catch (final Throwable t) { throw translateError(t); } }
| 1,114,596
|
void restore(final UUID uniqueId) { logger.logApiId(); logger.logVariable("uniqueId", uniqueId); try { final InternalArchiveModel archiveModel = getArchiveModel(); // restore container info final Container container = archiveModel.readContainer(uniqueId); restore(container, new RestoreModel() { public InputStream openDocumentVersion(final UUID uniqueId, final Long versionId) { return archiveModel.openDocumentVersion(uniqueId, versionId); } public List<ContainerVersion> readContainerVersions( final UUID uniqueId) { return archiveModel.readContainerVersions(uniqueId); } public List<Document> readDocuments(final UUID uniqueId, final Long versionId) { return archiveModel.readDocuments(uniqueId, versionId); } public List<DocumentVersion> readDocumentVersions( final UUID uniqueId, final Long versionId, final UUID documentUniqueId) { return archiveModel.readDocumentVersions(uniqueId, versionId, documentUniqueId); } public List<JabberId> readTeamIds(final UUID uniqueId) { return archiveModel.readTeamIds(uniqueId); } }); archiveModel.restore(uniqueId); notifyContainerRestored(read(container.getId()), localEventGenerator); } catch (final Throwable t) { throw translateError(t); } }
|
void restore(final UUID uniqueId) { logger.logApiId(); logger.logVariable("uniqueId", uniqueId); try { final InternalArchiveModel archiveModel = getArchiveModel(); // restore container info final Container container = archiveModel.readContainer(uniqueId); restore(container, new RestoreModel() { public InputStream openDocumentVersion(final UUID uniqueId, final Long versionId) { return archiveModel.openDocumentVersion(uniqueId, versionId); } public List<ContainerVersion> readContainerVersions( final UUID uniqueId) { return archiveModel.readContainerVersions(uniqueId); } public List<Document> readDocuments(final UUID uniqueId, final Long versionId) { return archiveModel.readDocuments(uniqueId, versionId); } public List<DocumentVersion> readDocumentVersions( final UUID uniqueId, final Long versionId, final UUID documentUniqueId) { return archiveModel.readDocumentVersions(uniqueId, versionId, documentUniqueId); } public List<JabberId> readTeamIds(final UUID uniqueId) { return archiveModel.readTeamIds(uniqueId); } }); archiveModel.restore(uniqueId); notifyContainerRestored(read(container.getId()), localEventGenerator); } catch (final Throwable t) { throw translateError(t); } }
| 1,114,597
|
void restore(final UUID uniqueId) { logger.logApiId(); logger.logVariable("uniqueId", uniqueId); try { final InternalArchiveModel archiveModel = getArchiveModel(); // restore container info final Container container = archiveModel.readContainer(uniqueId); restore(container, new RestoreModel() { public InputStream openDocumentVersion(final UUID uniqueId, final Long versionId) { return archiveModel.openDocumentVersion(uniqueId, versionId); } public List<ContainerVersion> readContainerVersions( final UUID uniqueId) { return archiveModel.readContainerVersions(uniqueId); } public List<Document> readDocuments(final UUID uniqueId, final Long versionId) { return archiveModel.readDocuments(uniqueId, versionId); } public List<DocumentVersion> readDocumentVersions( final UUID uniqueId, final Long versionId, final UUID documentUniqueId) { return archiveModel.readDocumentVersions(uniqueId, versionId, documentUniqueId); } public List<JabberId> readTeamIds(final UUID uniqueId) { return archiveModel.readTeamIds(uniqueId); } }); archiveModel.restore(uniqueId); notifyContainerRestored(read(container.getId()), localEventGenerator); } catch (final Throwable t) { throw translateError(t); } }
|
void restore(final UUID uniqueId) { logger.logApiId(); logger.logVariable("uniqueId", uniqueId); try { final InternalArchiveModel archiveModel = getArchiveModel(); // restore container info final Container container = archiveModel.readContainer(uniqueId); restore(container, new RestoreModel() { public InputStream openDocumentVersion(final UUID uniqueId, final Long versionId) { return archiveModel.openDocumentVersion(uniqueId, versionId); } public List<ContainerVersion> readContainerVersions( final UUID uniqueId) { return archiveModel.readContainerVersions(uniqueId); } public List<Document> readDocuments(final UUID uniqueId, final Long versionId) { return archiveModel.readDocuments(uniqueId, versionId); } public List<DocumentVersion> readDocumentVersions( final UUID uniqueId, final Long versionId, final UUID documentUniqueId) { return archiveModel.readDocumentVersions(uniqueId, versionId); } public List<JabberId> readTeamIds(final UUID uniqueId) { return archiveModel.readTeamIds(uniqueId); } }); archiveModel.restore(uniqueId); notifyContainerRestored(read(container.getId()), localEventGenerator); } catch (final Throwable t) { throw translateError(t); } }
| 1,114,598
|
public List<DocumentVersion> readDocumentVersions( final UUID uniqueId, final Long versionId, final UUID documentUniqueId) { return archiveModel.readDocumentVersions(uniqueId, versionId, documentUniqueId); }
|
public List<DocumentVersion> readDocumentVersions( final UUID uniqueId, final Long versionId, final UUID documentUniqueId) { return archiveModel.readDocumentVersions(uniqueId, versionId, documentUniqueId); }
| 1,114,599
|
public List<DocumentVersion> readDocumentVersions( final UUID uniqueId, final Long versionId, final UUID documentUniqueId) { return archiveModel.readDocumentVersions(uniqueId, versionId, documentUniqueId); }
|
public List<DocumentVersion> readDocumentVersions( final UUID uniqueId, final Long versionId, final UUID documentUniqueId) { return archiveModel.readDocumentVersions(uniqueId, versionId); }
| 1,114,600
|
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); } }
|
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); } }
| 1,114,601
|
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); } }
|
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); } public List<JabberId> readTeamIds(final UUID uniqueId) { return backupModel.readTeamIds(uniqueId); } }); } } catch (final Throwable t) { throw translateError(t); } }
| 1,114,602
|
public List<DocumentVersion> readDocumentVersions( final UUID uniqueId, final Long versionId, final UUID documentUniqueId) { return backupModel.readDocumentVersions(uniqueId, versionId, documentUniqueId); }
|
public List<DocumentVersion> readDocumentVersions( final UUID uniqueId, final Long versionId, final UUID documentUniqueId) { return backupModel.readDocumentVersions(uniqueId, versionId, documentUniqueId); }
| 1,114,603
|
public List<DocumentVersion> readDocumentVersions( final UUID uniqueId, final Long versionId, final UUID documentUniqueId) { return backupModel.readDocumentVersions(uniqueId, versionId, documentUniqueId); }
|
public List<DocumentVersion> readDocumentVersions( final UUID uniqueId, final Long versionId, final UUID documentUniqueId) { return backupModel.readDocumentVersions(uniqueId, versionId); }
| 1,114,604
|
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); }
|
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); }
| 1,114,605
|
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; }
|
private Fixture(final ArtifactModel aModel, final JabberId closedBy, final DocumentModelImpl dMImpl, final DocumentModel dModel, final Long documentId, final Integer eTeamSize) { this.aModel = aModel; this.closedBy = closedBy; this.dMImpl = dMImpl; this.dModel = dModel; this.documentId = documentId; }
| 1,114,606
|
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())); }
|
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(), aModel.readTeam(d0.getId()).size())); }
| 1,114,608
|
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); } }
|
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]", datum.eTeamSize.intValue(), team.size()); } }
| 1,114,609
|
public Boolean confirmSynchronize() { final ConfirmSynchronize confirmSynchronize = new ConfirmSynchronize(); openWindow(confirmSynchronize); return confirmSynchronize.didConfirm(); }
|
public Boolean confirmSynchronize() { final ConfirmSynchronize confirmSynchronize = new ConfirmSynchronize(); openWindow(confirmSynchronize); return confirmSynchronize.didConfirm(); }
| 1,114,610
|
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); } } }
|
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); } } }
| 1,114,611
|
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); } } }
|
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 (OpheliaJFrame.this) { try { wait(); } catch (final Throwable t) { throw new BrowserException( "Error opening the thinkParity Ophelia JFrame.", t); } } }
| 1,114,612
|
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); } } }
|
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 { OpheliaJFrame.this.wait(); } catch (final Throwable t) { throw new BrowserException( "Error opening the thinkParity Ophelia JFrame.", t); } } }
| 1,114,613
|
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))); }
|
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, -1L)); }
| 1,114,614
|
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); }
| 1,114,615
|
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(); }
|
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).restoreBackup(); }
| 1,114,616
|
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(); } } }
|
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(); } } }
| 1,114,617
|
protected AbstractXMPP(final XMPPCore xmppCore) { super(); this.listeners = new ArrayList<T>(); this.xmppCore = xmppCore; this.xmppEventManager = XMPPEventManager.getInstance(xmppCore); this.xstream = new XStream(); }
|
protected AbstractXMPP(final XMPPCore xmppCore) { super(); this.xmppCore = xmppCore; this.xmppEventManager = XMPPEventManager.getInstance(xmppCore); this.xstream = new XStream(); }
| 1,114,618
|
protected AbstractXMPP(final XMPPCore xmppCore) { super(); this.listeners = new ArrayList<T>(); this.xmppCore = xmppCore; this.xmppEventManager = XMPPEventManager.getInstance(xmppCore); this.xstream = new XStream(); }
|
protected AbstractXMPP(final XMPPCore xmppCore) { super(); this.listeners = new ArrayList<T>(); this.xmppCore = xmppCore; this.xstream = new XStream(); }
| 1,114,619
|
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(); }
|
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(); }
| 1,114,621
|
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(); }
|
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."); } } } }
| 1,114,622
|
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 ); } }
|
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 ); } }
| 1,114,624
|
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(); } }
|
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(); } }
| 1,114,626
|
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(); } }
|
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(); } }
| 1,114,627
|
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
|
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
| 1,114,629
|
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
|
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
| 1,114,630
|
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
|
private void tabJListMouseReleased(java.awt.event.MouseEvent e) {//GEN-FIRST:event_tabJListMouseReleased if (!MenuFactory.isPopupMenu() && 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
| 1,114,631
|
private void addContainerPanel(final Container container) { addContainerPanel(containerPanels.size() == 0 ? 0 : containerPanels .size() - 1, container); }
|
private void addContainerPanel(final Container container) { addContainerPanel(containerPanels.size() == 0 ? 0 : containerPanels .size() - 1, container); }
| 1,114,632
|
public void applySearch(final String searchExpression) { debug(); if (searchExpression.equals(this.searchExpression)) { return; } else { this.searchExpression = searchExpression; this.searchResults = readSearchResults(); synchronize(); } }
|
public void applySearch(final String searchExpression) { debug(); if (searchExpression.equals(this.searchExpression)) { return; } else { this.searchExpression = searchExpression; applySearchResults(); synchronize(); } }
| 1,114,633
|
private void clearPanels() { containerPanels.clear(); }
|
private void clearPanels() { panels.clear(); }
| 1,114,634
|
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()); } }
|
public void debug() { logger.logDebug("{0} container panels.", panels.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()); } }
| 1,114,635
|
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; }
|
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; }
| 1,114,636
|
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); } }
|
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 = panels.remove(panelIndex); expandedState.remove(containerPanel); } else { containerPanels.remove(panelIndex); } }
| 1,114,637
|
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); } }
|
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 = panels.remove(panelIndex); expandedState.remove(containerPanel); } else { panels.remove(panelIndex); } }
| 1,114,638
|
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(); } }
|
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.clear(); synchronize(); } }
| 1,114,639
|
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(); }
|
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(); }
| 1,114,641
|
private Fixture(final InputStream stream, final String streamId, final StreamSession streamSession) { super(); this.stream = stream; this.streamId = streamId; this.streamSession = streamSession; }
|
private Fixture(final InputStream stream, final String streamId, final StreamSession streamSession, final Long streamSize) { super(); this.stream = stream; this.streamId = streamId; this.streamSession = streamSession; }
| 1,114,644
|
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); }
|
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, streamFile.length()); }
| 1,114,646
|
public void testWriter() { final StreamWriter writer = new StreamWriter(datum.streamSession); try { writer.open(); writer.write(datum.streamId, datum.stream); } finally { writer.close(); } }
|
public void testWriter() { final StreamWriter writer = new StreamWriter(datum.streamSession); try { writer.open(); writer.write(datum.streamId, datum.stream, datum.streamSize); } catch (final IOException iox) { fail(createFailMessage(iox)); } finally { writer.close(); } }
| 1,114,647
|
public void testWriter() { final StreamWriter writer = new StreamWriter(datum.streamSession); try { writer.open(); writer.write(datum.streamId, datum.stream); } finally { writer.close(); } }
|
public void testWriter() { final StreamWriter writer = new StreamWriter(datum.streamSession); try { writer.open(); writer.write(datum.streamId, datum.stream); } finally { try { datum.stream.close(); writer.close(); } catch (final IOException iox2) { fail(createFailMessage(iox2)); } } }
| 1,114,648
|
protected AbstractModelImpl(final Workspace workspace) { this(workspace, null); }
|
protected AbstractModelImpl(final Workspace workspace) { 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()); }
| 1,114,649
|
public BooleanTypeConverterImpl(ValueFactory factory) { super(factory); }
|
public BooleanTypeConverterImpl(ValueFactory factory) { super(factory); }
| 1,114,650
|
public void run() { Message message; while (Thread.currentThread() == thread) { if ((message = plug.waitForNewMessage(100)) != null) { callback.airBrushReceiveMessage(message); } } }
|
public void run() { Message message; while (Thread.currentThread() == thread) { if ((message = plug.waitForNewMessage(100)) != null) { if (!callback.airBrushReceiveMessage(message)) { System.out.println("Note: Unhandled callback for: " + message.type + " to: " + message.to); } } } }
| 1,114,652
|
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!"); } }
|
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!"); } }
| 1,114,653
|
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!"); } }
|
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!"); } }
| 1,114,654
|
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!"); } }
|
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("ERROR: Addresses not equal! Assumption false.", 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!"); } }
| 1,114,655
|
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!"); } }
|
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("NOTE: plistSize field does not match plistEnd marker. Assumption false.", "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!"); } }
| 1,114,656
|
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!"); } }
|
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!"); } }
| 1,114,657
|
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!"); } }
|
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!"); } }
| 1,114,658
|
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!"); } }
|
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!"); } }
| 1,114,659
|
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!"); } }
|
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!"); } }
| 1,114,660
|
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!"); } }
|
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("!------>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!"); } }
| 1,114,661
|
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!"); } }
|
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!"); } }
| 1,114,662
|
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!"); } }
|
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("!------>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!"); } }
| 1,114,663
|
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!"); } }
|
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("!------>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!"); } }
| 1,114,664
|
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!"); } }
|
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!"); } }
| 1,114,665
|
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!"); } }
|
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!"); } }
| 1,114,666
|
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!"); } }
|
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("!------>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!"); } }
| 1,114,667
|
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!"); } }
|
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!"); } }
| 1,114,668
|
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!"); } }
|
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("!------>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!"); } }
| 1,114,669
|
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!"); } }
|
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!"); } }
| 1,114,670
|
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!"); } }
|
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("!------>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!"); } }
| 1,114,671
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.