001    /**
002     * Copyright (c) 2000-present Liferay, Inc. All rights reserved.
003     *
004     * This library is free software; you can redistribute it and/or modify it under
005     * the terms of the GNU Lesser General Public License as published by the Free
006     * Software Foundation; either version 2.1 of the License, or (at your option)
007     * any later version.
008     *
009     * This library is distributed in the hope that it will be useful, but WITHOUT
010     * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
011     * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
012     * details.
013     */
014    
015    package com.liferay.portlet.documentlibrary.antivirus;
016    
017    import com.liferay.document.library.kernel.antivirus.AntivirusScannerException;
018    import com.liferay.document.library.kernel.antivirus.BaseFileAntivirusScanner;
019    
020    import java.io.File;
021    import java.io.IOException;
022    
023    /**
024     * @author Michael C. Han
025     */
026    public class ClamAntivirusScannerImpl extends BaseFileAntivirusScanner {
027    
028            @Override
029            public void scan(File file) throws AntivirusScannerException {
030                    Process process = null;
031    
032                    try {
033                            ProcessBuilder processBuilder = new ProcessBuilder(
034                                    "clamscan", "--stdout", "--no-summary", file.getAbsolutePath());
035    
036                            processBuilder.redirectErrorStream(true);
037    
038                            process = processBuilder.start();
039    
040                            process.waitFor();
041    
042                            int exitValue = process.exitValue();
043    
044                            if (exitValue == 1) {
045                                    throw new AntivirusScannerException(
046                                            "Virus detected in " + file.getAbsolutePath(),
047                                            AntivirusScannerException.VIRUS_DETECTED);
048                            }
049                            else if (exitValue >= 2) {
050                                    throw new AntivirusScannerException(
051                                            AntivirusScannerException.PROCESS_FAILURE);
052                            }
053                    }
054                    catch (InterruptedException | IOException e) {
055                            throw new AntivirusScannerException(
056                                    AntivirusScannerException.PROCESS_FAILURE);
057                    }
058                    finally {
059                            if (process != null) {
060                                    process.destroy();
061                            }
062                    }
063            }
064    
065    }