| /* A part of the Native C Library for Windows NT |
| Copyright 2007-2015 PC GO Ld. |
| |
| This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. |
| |
| This program 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 for more details. |
| */ |
| |
| #include <sys/stat.h> |
| #include <windows.h> |
| #include <nt.h> |
| #include <errno.h> |
| #include <string.h> |
| #include <pathname.h> |
| #include <ntstatus.h> |
| |
| //#include <stdio.h> |
| |
| int fchmod(int fd, mode_t mode) { |
| IO_STATUS_BLOCK io_status; |
| FILE_BASIC_INFORMATION fbi; |
| long int status = NtQueryInformationFile((void *)fd, &io_status, &fbi, sizeof fbi, FileBasicInformation); |
| //printf("nativelibc debug: fchmod: status1 = 0x%lx\n", status); |
| if(status < 0) { |
| __set_errno_from_ntstatus(status); |
| return -1; |
| } |
| |
| if(mode & S_IWRITE) fbi.FileAttributes &= ~FILE_ATTRIBUTE_READONLY; |
| else fbi.FileAttributes |= FILE_ATTRIBUTE_READONLY; |
| |
| status = NtSetInformationFile((void *)fd, &io_status, &fbi, sizeof fbi, FileBasicInformation); |
| //printf("nativelibc debug: fchmod: status1 = 0x%lx\n", status); |
| return __set_errno_from_ntstatus(status) ? -1 : 0; |
| } |
| |
| int chmod(const char *path, mode_t mode) { |
| if(!path) { |
| errno = EFAULT; |
| return -1; |
| } |
| |
| // We can't use open bacause we need to allow chmod a directory |
| UNICODE_STRING ntpathname; |
| if(!RtlCreateUnicodeStringFromAsciiz(&ntpathname, path)) { |
| errno = ENOMEM; |
| return -1; |
| } |
| PATHNAME_UNIX2NT_UTF16_STRUCT(ntpathname); |
| OBJECT_ATTRIBUTES object_attrib = { sizeof(OBJECT_ATTRIBUTES), NULL, &ntpathname, 0, NULL, NULL }; |
| void *fh; |
| IO_STATUS_BLOCK io_status; |
| unsigned long int access_mask = FILE_READ_EA | FILE_READ_ATTRIBUTES | FILE_WRITE_EA | FILE_WRITE_ATTRIBUTES | SYNCHRONIZE; |
| unsigned long int file_share = FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE; |
| unsigned long int options = FILE_SYNCHRONOUS_IO_NONALERT | FILE_OPEN_FOR_BACKUP_INTENT; |
| long int status = NtOpenFile(&fh, access_mask, &object_attrib, &io_status, file_share, options); |
| //printf("nativelibc debug: chmod: status = 0x%lx\n", status); |
| RtlFreeUnicodeString(&ntpathname); |
| if(status == STATUS_OBJECT_TYPE_MISMATCH) { |
| errno = EPERM; |
| return -1; |
| } |
| if(status < 0) { |
| __set_errno_from_ntstatus(status); |
| return -1; |
| } |
| int r = fchmod((int)fh, mode); |
| status = NtClose(fh); |
| if(r < 0) return r; |
| if(status < 0) { |
| __set_errno_from_ntstatus(status); |
| return -1; |
| } |
| return r; |
| } |