/*
 *  Licensed to the Apache Software Foundation (ASF) under one
 *  or more contributor license agreements.  See the NOTICE file
 *  distributed with this work for additional information
 *  regarding copyright ownership.  The ASF licenses this file
 *  to you under the Apache License, Version 2.0 (the
 *  "License"); you may not use this file except in compliance
 *  with the License.  You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing,
 *  software distributed under the License is distributed on an
 *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 *  KIND, either express or implied.  See the License for the
 *  specific language governing permissions and limitations
 *  under the License.
 *
 */
package org.apache.sshd.agent;

import org.apache.sshd.common.util.OsUtils;
import org.apache.tomcat.jni.Library;
import org.apache.tomcat.jni.Pool;

import java.io.File;
import java.io.IOException;


/**
 * Internal singleton used for initializing correctly the APR native library
 * and the associated root memory pool.
 *
 * It'll finalize nicely the native resources (libraries and memory pools).
 *
 * Each memory pool used in the APR transport module needs to be children of the
 * root pool {@link AprLibrary#getRootPool()}.
 *
 * @author <a href="http://mina.apache.org">Apache MINA Project</a>
 */
class AprLibrary {

    // is APR library was initialized (load of native libraries)
    private static AprLibrary library = null;

    /**
     * get the shared instance of APR library, if none, initialize one
     * @return the current APR library singleton
     */
    static synchronized AprLibrary getInstance() {
        if (!isInitialized())
            initialize();
        return library;
    }

    /**
     * initialize the APR Library by loading the associated native libraries
     * and creating the associated singleton
     */
    private static synchronized void initialize() {
        if (library == null)
            library = new AprLibrary();
    }

    /**
     * is the APR library was initialized.
     * @return true if the Library is initialized, false otherwise
     */
    static synchronized boolean isInitialized() {
        return library != null;
    }

    // APR memory pool (package wide mother pool)
    private final long pool;

    /**
     * APR library singleton constructor. Called only when accessing the
     * singleton the first time.
     * It's initializing an APR memory pool for the whole package (a.k.a mother or root pool).
     */
    private AprLibrary() {
        try {
            Library.initialize(null);
        } catch (Exception e) {
            throw new RuntimeException(
                    "Error loading Apache Portable Runtime (APR).", e);
        }
        pool = Pool.create(0);
    }

    @Override
    protected void finalize() throws Throwable {
        library = null;
        Pool.destroy(pool);
        Library.terminate();
        super.finalize();
    }

    /**
     * get the package wide root pool, the mother of all the pool created
     * in APR transport module.
     * @return number identifying the root pool
     */
    long getRootPool() {
        return pool;
    }

    static String createLocalSocketAddress() throws IOException {
        String name;
        if (OsUtils.isUNIX()) {
            File socket = File.createTempFile("mina", "apr");
            socket.delete();
            name = socket.getAbsolutePath();
        } else {
            File socket = File.createTempFile("mina", "apr");
            socket.delete();
            name = "\\\\.\\pipe\\" + socket.getName();
        }
        return name;
    }

    static void secureLocalSocket(String authSocket, long handle) throws IOException {
        if (OsUtils.isUNIX()) {
            int perms = org.apache.tomcat.jni.File.APR_FPROT_UREAD
                      | org.apache.tomcat.jni.File.APR_FPROT_UWRITE;
            if (org.apache.tomcat.jni.File.permsSet(authSocket, perms) != org.apache.tomcat.jni.Status.APR_SUCCESS) {
                throw new IOException("Unable to secure local socket");
            }

        } else {
            // should be ok on windows
        }
    }
}

@@ -3338,32 +3338,55 @@
 s IOException %7B%0A
+        initialize();%0A%0A
         String n
@@ -3438,55 +3438,569 @@
     
-File socket = File.createTempFile(%22mina%22, %22apr%22
+// Since there is a race condition between bind and when%0A            // we can mark the socket readable only by its owner, make%0A            // the socket in a temporary directory that is visible only%0A            // to the owner.%0A            //%0A            File dir = File.createTempFile(%22mina%22, %22apr%22);%0A            if (!dir.delete() %7C%7C !dir.mkdir()) %7B%0A                throw new IOException(%22Cannot create secure temp directory%22);%0A            %7D%0A            chmodOwner(dir.getAbsolutePath(), true);%0A%0A            File socket = File.createTempFile(%22mina%22,%22apr%22, dir
 );%0A 
@@ -4408,86 +4408,376 @@
     
-int perms = org.apache.tomcat.jni.File.APR_FPROT_UREAD%0A                      %7C
+chmodOwner(authSocket, false);%0A%0A        %7D else %7B%0A            // should be ok on windows%0A        %7D%0A    %7D%0A%0A    private static void chmodOwner(String authSocket, boolean execute) throws IOException %7B%0A        int perms = org.apache.tomcat.jni.File.APR_FPROT_UREAD%0A                  %7C org.apache.tomcat.jni.File.APR_FPROT_UWRITE;%0A        if (execute) %7B%0A            perms %7C=
  org
@@ -4807,35 +4807,37 @@
 .APR_FPROT_U
-WRI
+EXECU
 TE;%0A    
         if (
@@ -4820,24 +4820,30 @@
 XECUTE;%0A    
+    %7D%0A
         if (
@@ -4948,36 +4948,32 @@
 ) %7B%0A            
-    
 throw new IOExce
@@ -5016,79 +5016,8 @@
 %22);%0A
-            %7D%0A%0A        %7D else %7B%0A            // should be ok on windows%0A
     

Secure the agent socket against race conditions