LinuxUserDefinedFileAttributeView.java 12.5 KB
Newer Older
1
/*
2
 * Copyright (c) 2008, 2012, Oracle and/or its affiliates. All rights reserved.
3 4 5 6
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * This code is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License version 2 only, as
7
 * published by the Free Software Foundation.  Oracle designates this
8
 * particular file as subject to the "Classpath" exception as provided
9
 * by Oracle in the LICENSE file that accompanied this code.
10 11 12 13 14 15 16 17 18 19 20
 *
 * This code is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
 * version 2 for more details (a copy is included in the LICENSE file that
 * accompanied this code).
 *
 * You should have received a copy of the GNU General Public License version
 * 2 along with this work; if not, write to the Free Software Foundation,
 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
 *
21 22 23
 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
 * or visit www.oracle.com if you need additional information or have any
 * questions.
24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55
 */

package sun.nio.fs;

import java.nio.file.*;
import java.nio.ByteBuffer;
import java.io.IOException;
import java.util.*;
import sun.misc.Unsafe;

import static sun.nio.fs.UnixConstants.*;
import static sun.nio.fs.LinuxNativeDispatcher.*;

/**
 * Linux implementation of UserDefinedFileAttributeView using extended attributes.
 */

class LinuxUserDefinedFileAttributeView
    extends AbstractUserDefinedFileAttributeView
{
    private static final Unsafe unsafe = Unsafe.getUnsafe();

    // namespace for extended user attributes
    private static final String USER_NAMESPACE = "user.";

    // maximum bytes in extended attribute name (includes namespace)
    private static final int XATTR_NAME_MAX = 255;

    private byte[] nameAsBytes(UnixPath file, String name) throws IOException {
        if (name == null)
            throw new NullPointerException("'name' is null");
        name = USER_NAMESPACE + name;
56
        byte[] bytes = Util.toBytes(name);
57
        if (bytes.length > XATTR_NAME_MAX) {
58
            throw new FileSystemException(file.getPathForExceptionMessage(),
59 60 61 62 63 64 65
                null, "'" + name + "' is too big");
        }
        return bytes;
    }

    // Parses buffer as array of NULL-terminated C strings.
    private List<String> asList(long address, int size) {
66
        List<String> list = new ArrayList<>();
67 68 69 70 71 72 73 74
        int start = 0;
        int pos = 0;
        while (pos < size) {
            if (unsafe.getByte(address + pos) == 0) {
                int len = pos - start;
                byte[] value = new byte[len];
                unsafe.copyMemory(null, address+start, value,
                    Unsafe.ARRAY_BYTE_BASE_OFFSET, len);
75
                String s = Util.toString(value);
76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118
                if (s.startsWith(USER_NAMESPACE)) {
                    s = s.substring(USER_NAMESPACE.length());
                    list.add(s);
                }
                start = pos + 1;
            }
            pos++;
        }
        return list;
    }

    private final UnixPath file;
    private final boolean followLinks;

    LinuxUserDefinedFileAttributeView(UnixPath file, boolean followLinks) {
        this.file = file;
        this.followLinks = followLinks;
    }

    @Override
    public List<String> list() throws IOException  {
        if (System.getSecurityManager() != null)
            checkAccess(file.getPathForPermissionCheck(), true, false);

        int fd = file.openForAttributeAccess(followLinks);
        NativeBuffer buffer = null;
        try {
            int size = 1024;
            buffer = NativeBuffers.getNativeBuffer(size);
            for (;;) {
                try {
                    int n = flistxattr(fd, buffer.address(), size);
                    List<String> list = asList(buffer.address(), n);
                    return Collections.unmodifiableList(list);
                } catch (UnixException x) {
                    // allocate larger buffer if required
                    if (x.errno() == ERANGE && size < 32*1024) {
                        buffer.release();
                        size *= 2;
                        buffer = null;
                        buffer = NativeBuffers.getNativeBuffer(size);
                        continue;
                    }
119
                    throw new FileSystemException(file.getPathForExceptionMessage(),
120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140
                        null, "Unable to get list of extended attributes: " +
                        x.getMessage());
                }
            }
        } finally {
            if (buffer != null)
                buffer.release();
            close(fd);
        }
    }

    @Override
    public int size(String name) throws IOException  {
        if (System.getSecurityManager() != null)
            checkAccess(file.getPathForPermissionCheck(), true, false);

        int fd = file.openForAttributeAccess(followLinks);
        try {
            // fgetxattr returns size if called with size==0
            return fgetxattr(fd, nameAsBytes(file,name), 0L, 0);
        } catch (UnixException x) {
141
            throw new FileSystemException(file.getPathForExceptionMessage(),
142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193
                null, "Unable to get size of extended attribute '" + name +
                "': " + x.getMessage());
        } finally {
            close(fd);
        }
    }

    @Override
    public int read(String name, ByteBuffer dst) throws IOException {
        if (System.getSecurityManager() != null)
            checkAccess(file.getPathForPermissionCheck(), true, false);

        if (dst.isReadOnly())
            throw new IllegalArgumentException("Read-only buffer");
        int pos = dst.position();
        int lim = dst.limit();
        assert (pos <= lim);
        int rem = (pos <= lim ? lim - pos : 0);

        NativeBuffer nb;
        long address;
        if (dst instanceof sun.nio.ch.DirectBuffer) {
            nb = null;
            address = ((sun.nio.ch.DirectBuffer)dst).address() + pos;
        } else {
            // substitute with native buffer
            nb = NativeBuffers.getNativeBuffer(rem);
            address = nb.address();
        }

        int fd = file.openForAttributeAccess(followLinks);
        try {
            try {
                int n = fgetxattr(fd, nameAsBytes(file,name), address, rem);

                // if remaining is zero then fgetxattr returns the size
                if (rem == 0) {
                    if (n > 0)
                        throw new UnixException(ERANGE);
                    return 0;
                }

                // copy from buffer into backing array if necessary
                if (nb != null) {
                    int off = dst.arrayOffset() + pos + Unsafe.ARRAY_BYTE_BASE_OFFSET;
                    unsafe.copyMemory(null, address, dst.array(), off, n);
                }
                dst.position(pos + n);
                return n;
            } catch (UnixException x) {
                String msg = (x.errno() == ERANGE) ?
                    "Insufficient space in buffer" : x.getMessage();
194
                throw new FileSystemException(file.getPathForExceptionMessage(),
195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245
                    null, "Error reading extended attribute '" + name + "': " + msg);
            } finally {
                close(fd);
            }
        } finally {
            if (nb != null)
                nb.release();
        }
    }

    @Override
    public int write(String name, ByteBuffer src) throws IOException {
        if (System.getSecurityManager() != null)
            checkAccess(file.getPathForPermissionCheck(), false, true);

        int pos = src.position();
        int lim = src.limit();
        assert (pos <= lim);
        int rem = (pos <= lim ? lim - pos : 0);

        NativeBuffer nb;
        long address;
        if (src instanceof sun.nio.ch.DirectBuffer) {
            nb = null;
            address = ((sun.nio.ch.DirectBuffer)src).address() + pos;
        } else {
            // substitute with native buffer
            nb = NativeBuffers.getNativeBuffer(rem);
            address = nb.address();

            if (src.hasArray()) {
                // copy from backing array into buffer
                int off = src.arrayOffset() + pos + Unsafe.ARRAY_BYTE_BASE_OFFSET;
                unsafe.copyMemory(src.array(), off, null, address, rem);
            } else {
                // backing array not accessible so transfer via temporary array
                byte[] tmp = new byte[rem];
                src.get(tmp);
                src.position(pos);  // reset position as write may fail
                unsafe.copyMemory(tmp, Unsafe.ARRAY_BYTE_BASE_OFFSET, null,
                    address, rem);
            }
        }

        int fd = file.openForAttributeAccess(followLinks);
        try {
            try {
                fsetxattr(fd, nameAsBytes(file,name), address, rem);
                src.position(pos + rem);
                return rem;
            } catch (UnixException x) {
246
                throw new FileSystemException(file.getPathForExceptionMessage(),
247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266
                    null, "Error writing extended attribute '" + name + "': " +
                    x.getMessage());
            } finally {
                close(fd);
            }
        } finally {
            if (nb != null)
                nb.release();
        }
    }

    @Override
    public void delete(String name) throws IOException {
        if (System.getSecurityManager() != null)
            checkAccess(file.getPathForPermissionCheck(), false, true);

        int fd = file.openForAttributeAccess(followLinks);
        try {
            fremovexattr(fd, nameAsBytes(file,name));
        } catch (UnixException x) {
267
            throw new FileSystemException(file.getPathForExceptionMessage(),
268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350
                null, "Unable to delete extended attribute '" + name + "': " + x.getMessage());
        } finally {
            close(fd);
        }
    }

    /**
     * Used by copyTo/moveTo to copy extended attributes from source to target.
     *
     * @param   ofd
     *          file descriptor for source file
     * @param   nfd
     *          file descriptor for target file
     */
    static void copyExtendedAttributes(int ofd, int nfd) {
        NativeBuffer buffer = null;
        try {

            // call flistxattr to get list of extended attributes.
            int size = 1024;
            buffer = NativeBuffers.getNativeBuffer(size);
            for (;;) {
                try {
                    size = flistxattr(ofd, buffer.address(), size);
                    break;
                } catch (UnixException x) {
                    // allocate larger buffer if required
                    if (x.errno() == ERANGE && size < 32*1024) {
                        buffer.release();
                        size *= 2;
                        buffer = null;
                        buffer = NativeBuffers.getNativeBuffer(size);
                        continue;
                    }

                    // unable to get list of attributes
                    return;
                }
            }

            // parse buffer as array of NULL-terminated C strings.
            long address = buffer.address();
            int start = 0;
            int pos = 0;
            while (pos < size) {
                if (unsafe.getByte(address + pos) == 0) {
                    // extract attribute name and copy attribute to target.
                    // FIXME: We can avoid needless copying by using address+pos
                    // as the address of the name.
                    int len = pos - start;
                    byte[] name = new byte[len];
                    unsafe.copyMemory(null, address+start, name,
                        Unsafe.ARRAY_BYTE_BASE_OFFSET, len);
                    try {
                        copyExtendedAttribute(ofd, name, nfd);
                    } catch (UnixException ignore) {
                        // ignore
                    }
                    start = pos + 1;
                }
                pos++;
            }

        } finally {
            if (buffer != null)
                buffer.release();
        }
    }

    private static void copyExtendedAttribute(int ofd, byte[] name, int nfd)
        throws UnixException
    {
        int size = fgetxattr(ofd, name, 0L, 0);
        NativeBuffer buffer = NativeBuffers.getNativeBuffer(size);
        try {
            long address = buffer.address();
            size = fgetxattr(ofd, name, address, size);
            fsetxattr(nfd, name, address, size);
        } finally {
            buffer.release();
        }
    }
}