summaryrefslogblamecommitdiffstats
path: root/src/main/java/org/openslx/taskmanager/tasks/MakeTarball.java
blob: bec2cdf209799824fbc3cefe2019c7a80bc68d6b (plain) (tree)















































































                                                                                                                       




                                          


         
package org.openslx.taskmanager.tasks;

import java.io.IOException;
import java.util.Map;
import java.util.Map.Entry;

import org.apache.commons.compress.archivers.tar.TarArchiveOutputStream;
import org.apache.commons.io.FilenameUtils;
import org.openslx.satserver.util.Archive;
import org.openslx.satserver.util.Util;
import org.openslx.taskmanager.api.AbstractTask;

import com.google.gson.annotations.Expose;

public class MakeTarball extends AbstractTask
{

	@Expose
	private Map<String, byte[]> files;

	@Expose
	private String destination;

	private Status status = new Status();

	protected static final String[] ALLOWED_DIRS = { "/tmp/", "/opt/openslx/configs/" };

	@Override
	protected boolean initTask()
	{
		this.setStatusObject( this.status );
		destination = FilenameUtils.normalize( destination );
		if ( !Util.startsWith( destination, ALLOWED_DIRS ) ) {
			status.error = "Illegal target directory " + destination;
			return false;
		}
		if ( files.isEmpty() ) {
			status.error = "Empty list of files";
			return false;
		}
		for ( Entry<String, byte[]> f : files.entrySet() ) {
			String fn = f.getKey();
			if ( fn == null || fn.isEmpty() ) {
				status.error = "File list contains empty file name";
				return false;
			}
			if ( f.getValue() == null ) {
				status.error = "File list contains NULL file payload for " + fn;
				return false;
			}
		}
		return true;
	}

	@Override
	protected boolean execute()
	{
		TarArchiveOutputStream outArchive = null;
		try {
			try {
				outArchive = Archive.createTarArchive( this.destination );
			} catch ( IOException e ) {
				status.error = "Could not create archive at " + this.destination;
				return false;
			}
			for ( Entry<String, byte[]> f : files.entrySet() ) {
				if ( !Archive.tarCreateFileFromString( outArchive, f.getKey(), f.getValue(), 0644 ) ) {
					status.error = "Cannot add " + f.getKey() + " to " + this.destination;
					return false;
				}
			}
		} finally {
			Util.multiClose( outArchive );
		}
		return true;
	}

	static class Status
	{
		private String error;
		
		public String getError()
		{
			return this.error;
		}
	}

}