librazor/atomic.c
author J. Ali Harlow <ali@juiblex.co.uk>
Fri Jan 27 08:12:19 2012 +0000 (2012-01-27)
changeset 406 5ab137def3d1
child 416 d0aa9e0a6d04
permissions -rw-r--r--
Fix bugs causing arguments to not be passed to lua scripts
     1 /*
     2  * Copyright (C) 2011  J. Ali Harlow <ali@juiblex.co.uk>
     3  *
     4  * This program is free software; you can redistribute it and/or modify
     5  * it under the terms of the GNU General Public License as published by
     6  * the Free Software Foundation; either version 2 of the License, or
     7  * (at your option) any later version.
     8  *
     9  * This program is distributed in the hope that it will be useful,
    10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
    11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    12  * GNU General Public License for more details.
    13  *
    14  * You should have received a copy of the GNU General Public License along
    15  * with this program; if not, write to the Free Software Foundation, Inc.,
    16  * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
    17  */
    18 
    19 #include "config.h"
    20 
    21 #include <stdlib.h>
    22 #ifdef MSWIN_API
    23 #include <windows.h>
    24 #endif
    25 #include <stdio.h>
    26 #include <limits.h>
    27 #include <errno.h>
    28 #include <unistd.h>
    29 #include <fcntl.h>
    30 #include <sys/stat.h>
    31 #include <string.h>
    32 #include <assert.h>
    33 #if HAVE_WINDOWS_KTM
    34 #include <wchar.h>
    35 #include <ktmw32.h>
    36 #endif
    37 
    38 #include "razor.h"
    39 #include "razor-internal.h"
    40 
    41 /*
    42  * Atomic transactions
    43  */
    44 
    45 #ifndef O_BINARY
    46 #define O_BINARY	0
    47 #endif
    48 
    49 #define RAZOR_ASCII_ISALPHA(c)	\
    50 			((c) >= 'A' && (c) <= 'Z' || (c) >= 'a' && (c) <= 'z')
    51 
    52 static int allow_all_root_names = 0;
    53 
    54 /*
    55  * Primarily intended for testing named roots under UNIX platforms.
    56  */
    57 RAZOR_EXPORT void
    58 razor_disable_root_name_checks(int disable)
    59 {
    60 	allow_all_root_names = disable;
    61 }
    62 
    63 #ifdef MSWIN_API
    64 
    65 static char *
    66 razor_utf16_to_utf8(const wchar_t *utf16, int len)
    67 {
    68 	int n;
    69 	char *utf8;
    70 
    71 	n = WideCharToMultiByte(CP_UTF8, 0, utf16, len, NULL, 0, NULL, NULL);
    72 	if (len >= 0 && utf16[len])
    73 		n++;
    74 	utf8 = malloc(n);
    75 	(void)WideCharToMultiByte(CP_UTF8, 0, utf16, len, utf8, n, NULL, NULL);
    76 	if (len >= 0 && utf16[len])
    77 		utf8[n - 1] = 0;
    78 
    79 	return utf8;
    80 }
    81 
    82 static wchar_t *
    83 razor_utf8_to_utf16(const char *utf8, int len)
    84 {
    85 	int n;
    86 	wchar_t *utf16;
    87 
    88 	n = MultiByteToWideChar(CP_UTF8, 0, utf8, len, NULL, 0);
    89 	if (len >= 0 && utf8[len])
    90 		n++;
    91 	utf16 = malloc(n * sizeof(wchar_t));
    92 	(void)MultiByteToWideChar(CP_UTF8, 0, utf8, len, utf16, n);
    93 	if (len >= 0 && utf8[len])
    94 		utf16[n - 1] = 0;
    95 
    96 	return utf16;
    97 }
    98 
    99 #endif	/* MSWIN_API */
   100 
   101 #if HAVE_WINDOWS_KTM
   102 
   103 static int
   104 razor_valid_root_name(const wchar_t *name)
   105 {
   106 	if (allow_all_root_names)
   107 		return !wcschr(name, '/');
   108 
   109 	return RAZOR_ASCII_ISALPHA(name[0]) && name[1] == ':' &&
   110 	       name[2] == '\0';
   111 }
   112 
   113 struct razor_atomic {
   114 	HANDLE transaction;
   115 	int n_files;
   116 	struct razor_atomic_file {
   117 		wchar_t *path;
   118 		HANDLE h;
   119 	} *files;
   120 	char *error_path;
   121 	char *error_str;
   122 	char *error_msg;
   123 };
   124 
   125 struct razor_wstr {
   126 	wchar_t *str;
   127 	int len, allocated;
   128 };
   129 
   130 static struct razor_wstr *
   131 razor_wstr_create(const char *init, int len)
   132 {
   133 	int n;
   134 	struct razor_wstr *wstr;
   135 
   136 	wstr = malloc(sizeof(struct razor_wstr));
   137 
   138 	n = MultiByteToWideChar(CP_UTF8, 0, init, len, NULL, 0);
   139 	if (len >= 0 && init[len])
   140 		wstr->len = n++;
   141 	else
   142 		wstr->len = n - 1;
   143 
   144 	wstr->allocated = n * 2;
   145 	wstr->str = malloc(wstr->allocated * sizeof(wchar_t));
   146 	if (!wstr->str) {
   147 		free(wstr);
   148 		return NULL;
   149 	}
   150 
   151 	(void)MultiByteToWideChar(CP_UTF8, 0, init, len, wstr->str, n);
   152 	if (len >= 0 && init[len])
   153 		wstr->str[wstr->len] = 0;
   154 
   155 	return wstr;
   156 }
   157 
   158 static int
   159 razor_wstr_append(struct razor_wstr *wstr, const char *s, int len)
   160 {
   161 	int n, allocated;
   162 	wchar_t *str;
   163 
   164 	n = MultiByteToWideChar(CP_UTF8, 0, s, len, NULL, 0);
   165 	if (len < 0 || !s[len])
   166 		n--;
   167 
   168 	if (wstr->allocated <= wstr->len + n) {
   169 		allocated = (wstr->len + n + 1) * 2;
   170 		str = realloc(wstr->str, allocated * sizeof(wchar_t));
   171 		if (!str)
   172 			return -1;
   173 		wstr->allocated = allocated;
   174 		wstr->str = str;
   175 	}
   176 
   177 	(void)MultiByteToWideChar(CP_UTF8, 0, s, len, wstr->str + wstr->len, n);
   178 	wstr->len += n;
   179 	wstr->str[wstr->len] = 0;
   180 
   181 	return 0;
   182 }
   183 
   184 static void
   185 razor_wstr_destroy(struct razor_wstr *wstr)
   186 {
   187 	free(wstr->str);
   188 	free(wstr);
   189 }
   190 
   191 RAZOR_EXPORT struct razor_atomic *
   192 razor_atomic_open(const char *description)
   193 {
   194 	wchar_t *buf;
   195 	struct razor_atomic *atomic;
   196 
   197 	atomic = zalloc(sizeof *atomic);
   198 	buf = razor_utf8_to_utf16(description, -1);
   199 	atomic->transaction = CreateTransaction(NULL, 0,
   200 						TRANSACTION_DO_NOT_PROMOTE,
   201 						0, 0, 0, buf);
   202 	free(buf);
   203 
   204 	return atomic;
   205 }
   206 
   207 static void
   208 razor_atomic_set_error_str(struct razor_atomic *atomic, const wchar_t *path,
   209 			   const char *str)
   210 {
   211 	assert(!atomic->error_str);
   212 
   213 	free(atomic->error_path);
   214 
   215 	if (path)
   216 		atomic->error_path = razor_utf16_to_utf8(path, -1);
   217 	else
   218 		atomic->error_path = NULL;
   219 
   220 	atomic->error_str = strdup(str);
   221 }
   222 
   223 static void
   224 razor_atomic_set_error(struct razor_atomic *atomic, const wchar_t *path,
   225 		       DWORD error)
   226 {
   227 	wchar_t *buf;
   228 
   229 	assert(!atomic->error_str);
   230 
   231 	free(atomic->error_path);
   232 
   233 	if (path)
   234 		atomic->error_path = razor_utf16_to_utf8(path, -1);
   235 	else
   236 		atomic->error_path = NULL;
   237 
   238 	FormatMessageW(FORMAT_MESSAGE_ALLOCATE_BUFFER|
   239 		       FORMAT_MESSAGE_FROM_SYSTEM|FORMAT_MESSAGE_IGNORE_INSERTS,
   240 		       NULL, error, MAKELANGID(LANG_NEUTRAL,SUBLANG_DEFAULT),
   241 		       (LPWSTR)&buf, 0, NULL);
   242 	atomic->error_str = razor_utf16_to_utf8(buf, -1);
   243 	LocalFree(buf);
   244 }
   245 
   246 RAZOR_EXPORT int
   247 razor_atomic_commit(struct razor_atomic *atomic)
   248 {
   249 	int retval;
   250 
   251 	if (atomic->error_str)
   252 		return -1;
   253 
   254 	retval = !CommitTransaction(atomic->transaction);
   255 
   256 	if (retval) {
   257 		razor_atomic_set_error(atomic, NULL, GetLastError());
   258 		RollbackTransaction(atomic->transaction);
   259 	}
   260 
   261 	CloseHandle(atomic->transaction);
   262 	atomic->transaction = INVALID_HANDLE_VALUE;
   263 
   264 	return retval;
   265 }
   266 
   267 RAZOR_EXPORT void
   268 razor_atomic_destroy(struct razor_atomic *atomic)
   269 {
   270 	int i;
   271 
   272 	for(i = 0; i < atomic->n_files; i++) {
   273 		if (atomic->files[i].h != INVALID_HANDLE_VALUE) {
   274 			CloseHandle(atomic->files[i].h);
   275 			free(atomic->files[i].path);
   276 		}
   277 	}
   278 	free(atomic->files);
   279 	if (atomic->transaction != INVALID_HANDLE_VALUE) {
   280 		RollbackTransaction(atomic->transaction);
   281 		CloseHandle(atomic->transaction);
   282 	}
   283 	free(atomic->error_path);
   284 	free(atomic->error_str);
   285 	free(atomic->error_msg);
   286 	free(atomic);
   287 }
   288 
   289 RAZOR_EXPORT int
   290 razor_atomic_make_dirs(struct razor_atomic *atomic, const char *root,
   291 		       const char *path)
   292 {
   293 	struct razor_wstr *buffer;
   294 	const char *slash, *s, *next;
   295 	WIN32_FILE_ATTRIBUTE_DATA fa;
   296 	DWORD err;
   297 	int r, creating = 0;
   298 
   299 	if (atomic->error_str)
   300 		return -1;
   301 
   302 	buffer = razor_wstr_create(root, -1);
   303 	slash = path;
   304 
   305 	for (; *slash != '\0'; slash = next) {
   306 		next = strpbrk(slash + 1, "/\\");
   307 		if (next == NULL)
   308 			break;
   309 
   310 		razor_wstr_append(buffer, slash, next - slash);
   311 
   312 		if (!creating) {
   313 			if (razor_valid_root_name(buffer->str))
   314 				continue;
   315 
   316 			r = GetFileAttributesTransactedW(buffer->str,
   317 							 GetFileExInfoStandard,
   318 							 &fa,
   319 							 atomic->transaction);
   320 
   321 			if (!r) {
   322 				err = GetLastError();
   323 				if (err == ERROR_FILE_NOT_FOUND) {
   324 					creating = 1;
   325 				} else {
   326 					razor_atomic_set_error(atomic,
   327 							       buffer->str,
   328 							       err);
   329 					razor_wstr_destroy(buffer);
   330 					return -1;
   331 				}
   332 			} else if (!(fa.dwFileAttributes&
   333 				     FILE_ATTRIBUTE_DIRECTORY)) {
   334 				razor_atomic_set_error_str(atomic, buffer->str,
   335 							   "Not a directory");
   336 				razor_wstr_destroy(buffer);
   337 				return -1;
   338 			}
   339 		}
   340 		if (creating) {
   341 			if (!CreateDirectoryTransactedW(NULL, buffer->str, NULL,
   342 							atomic->transaction)) {
   343 				razor_atomic_set_error(atomic, buffer->str,
   344 						       GetLastError());
   345 				razor_wstr_destroy(buffer);
   346 				return -1;
   347 			}
   348 
   349 			/* FIXME: What to do about permissions for dirs we
   350 			 * have to create but are not in the cpio archive? */
   351 		}
   352 	}
   353 
   354 	razor_wstr_destroy(buffer);
   355 
   356 	return 0;
   357 }
   358 
   359 RAZOR_EXPORT int
   360 razor_atomic_remove(struct razor_atomic *atomic, const char *path)
   361 {
   362 	wchar_t *buf;
   363 	DWORD err;
   364 
   365 	if (atomic->error_str)
   366 		return -1;
   367 
   368 	buf = razor_utf8_to_utf16(path, -1);
   369 
   370 	if (DeleteFileTransactedW(buf, atomic->transaction)) {
   371 		free(buf);
   372 		return 0;
   373 	}
   374 
   375 	err = GetLastError();
   376 	if (err == ERROR_FILE_NOT_FOUND || err == ERROR_PATH_NOT_FOUND) {
   377 		free(buf);
   378 		return 0;
   379 	}
   380 
   381 	if (SetFileAttributesTransactedW(buf, FILE_ATTRIBUTE_NORMAL,
   382 					 atomic->transaction)) {
   383 		if (DeleteFileTransactedW(buf, atomic->transaction)) {
   384 			free(buf);
   385 			return 0;
   386 		}
   387 		err = GetLastError();
   388 	}
   389 
   390 	if (RemoveDirectoryTransactedW(buf, atomic->transaction) ||
   391 	    GetLastError() == ERROR_DIR_NOT_EMPTY) {
   392 		free(buf);
   393 		return 0;
   394 	}
   395 
   396 	/*
   397 	 * It would be tempting to use:
   398 	 * 	MoveFileEx(path, NULL, MOVEFILE_DELAY_UNTIL_REBOOT)
   399 	 * but unless we can guarantee that the system will be rebooted
   400 	 * before we (or some other application) write another file with the
   401 	 * same path, this is likely to cause more problems than it solves.
   402 	 */
   403 
   404 	razor_atomic_set_error(atomic, buf, err);
   405 	free(buf);
   406 	return -1;
   407 }
   408 
   409 RAZOR_EXPORT int
   410 razor_atomic_rename_file(struct razor_atomic *atomic, const char *oldpath,
   411 			 const char *newpath)
   412 {
   413 	wchar_t *oldbuf, *newbuf;
   414 	const DWORD flags = MOVEFILE_COPY_ALLOWED | MOVEFILE_REPLACE_EXISTING;
   415 
   416 	if (atomic->error_str)
   417 		return -1;
   418 
   419 	newbuf = razor_utf8_to_utf16(newpath, -1);
   420 	oldbuf = razor_utf8_to_utf16(oldpath, -1);
   421 
   422 	/*
   423 	 * Passing MOVEFILE_REPLACE_EXISTING to MoveFileTransaction() will
   424 	 * cover every case we care about _except_ replacing an empty
   425 	 * directory with a file. Calling RemoveDirectoryTransacted() will deal
   426 	 * with this case while having no effect in all other cases.
   427 	 */
   428 	(void)RemoveDirectoryTransactedW(newbuf, atomic->transaction);
   429 
   430 	if (!MoveFileTransactedW(oldbuf, newbuf, NULL, NULL, flags,
   431 			         atomic->transaction))
   432 		razor_atomic_set_error(atomic, newbuf, GetLastError());
   433 
   434 	free(newbuf);
   435 	free(oldbuf);
   436 
   437 	return !!atomic->error_str;
   438 }
   439 
   440 RAZOR_EXPORT int
   441 razor_atomic_create_dir(struct razor_atomic *atomic, const char *dirname,
   442 			mode_t mode)
   443 {
   444 	wchar_t *buf;
   445 	DWORD err;
   446 	WIN32_FILE_ATTRIBUTE_DATA fa;
   447 
   448 	if (atomic->error_str)
   449 		return -1;
   450 
   451 	buf = razor_utf8_to_utf16(dirname, -1);
   452 
   453 	if (!CreateDirectoryTransactedW(NULL, buf, NULL, atomic->transaction)) {
   454 		err = GetLastError();
   455 		if (err != ERROR_FILE_EXISTS && err != ERROR_ALREADY_EXISTS) {
   456 abort:
   457 			razor_atomic_set_error(atomic, buf, err);
   458 			free(buf);
   459 			return -1;
   460 		}
   461 
   462 		if (!GetFileAttributesTransactedW(buf, GetFileExInfoStandard,
   463 						  &fa, atomic->transaction))
   464 			goto abort;
   465 
   466 		if (!(fa.dwFileAttributes&FILE_ATTRIBUTE_DIRECTORY)) {
   467 			if (razor_atomic_remove(atomic, dirname)) {
   468 				free(buf);
   469 				return -1;
   470 			}
   471 			if (!CreateDirectoryTransactedW(NULL, buf, NULL,
   472 							atomic->transaction)) {
   473 				err = GetLastError();
   474 				goto abort;
   475 			}
   476 		}
   477 	}
   478 
   479 	free(buf);
   480 
   481 	return 0;
   482 }
   483 
   484 RAZOR_EXPORT int
   485 razor_atomic_create_symlink(struct razor_atomic *atomic, const char *target,
   486 			    const char *path)
   487 {
   488 	if (atomic->error_str)
   489 		return -1;
   490 
   491 	/*
   492 	 * This isn't true, but symbolic links under Windows 7
   493 	 * need to know whether the target is a directory or not
   494 	 * and we don't always know that at the time when the
   495 	 * link is created, so it's a convienent lie for now.
   496 	 */
   497 	razor_atomic_set_error_str(atomic, NULL, "Symbolic links not supported "
   498 						 "on this platform");
   499 
   500 	return -1;
   501 }
   502 
   503 RAZOR_EXPORT int
   504 razor_atomic_create_file(struct razor_atomic *atomic, const char *filename,
   505 			 mode_t mode)
   506 {
   507 	DWORD attribs;
   508 	struct razor_atomic_file *files;
   509 	int i = atomic->n_files;
   510 
   511 	if (atomic->error_str)
   512 		return -1;
   513 
   514 	files = realloc(atomic->files,
   515 			(atomic->n_files+1) * sizeof(struct razor_atomic_file));
   516 	if (!files) {
   517 		razor_atomic_set_error_str(atomic, NULL, "Not enough memory");
   518 		return -1;
   519 	}
   520 	atomic->n_files++;
   521 	atomic->files = files;
   522 
   523 	files[i].path = razor_utf8_to_utf16(filename, -1);
   524 
   525 	/*
   526 	 * Passing CREATE_ALWAYS to CreateFileTransacted() will cover
   527 	 * every case we care about _except_ replacing an empty directory
   528 	 * with a file. Calling RemoveDirectoryTransacted() will deal
   529 	 * with this case while having no effect in all other cases.
   530 	 */
   531 	(void)RemoveDirectoryTransactedW(files[i].path, atomic->transaction);
   532 
   533 	if (mode & S_IWUSR)
   534 		attribs = FILE_ATTRIBUTE_NORMAL;
   535 	else
   536 		attribs = FILE_ATTRIBUTE_READONLY;
   537 
   538 	files[i].h = CreateFileTransactedW(files[i].path, GENERIC_WRITE,
   539 					   0, NULL, CREATE_ALWAYS, attribs,
   540 					   NULL, atomic->transaction, NULL,
   541 					   NULL);
   542 
   543 	if (files[i].h == INVALID_HANDLE_VALUE) {
   544 		razor_atomic_set_error(atomic, files[i].path, GetLastError());
   545 		free(files[i].path);
   546 		atomic->n_files--;
   547 		return -1;
   548 	}
   549 
   550 	return i;
   551 }
   552 
   553 RAZOR_EXPORT int
   554 razor_atomic_write(struct razor_atomic *atomic, int handle, const void *data,
   555 		   size_t size)
   556 {
   557 	DWORD written;
   558 
   559 	if (atomic->error_str)
   560 		return -1;
   561 
   562 	assert(handle < atomic->n_files);
   563 	assert(atomic->files[handle].h != INVALID_HANDLE_VALUE);
   564 
   565 	while(size) {
   566 		if (!WriteFile(atomic->files[handle].h, data, size, &written,
   567 			       NULL)) {
   568 			razor_atomic_set_error(atomic,
   569 					       atomic->files[handle].path,
   570 					       GetLastError());
   571 
   572 			(void)CloseHandle(atomic->files[handle].h);
   573 			free(atomic->files[handle].path);
   574 			atomic->files[handle].path = NULL;
   575 			atomic->files[handle].h = INVALID_HANDLE_VALUE;
   576 
   577 			return -1;
   578 		}
   579 
   580 		data += written;
   581 		size -= written;
   582 	}
   583 
   584 	return 0;
   585 }
   586 
   587 RAZOR_EXPORT int
   588 razor_atomic_sync(struct razor_atomic *atomic, int handle)
   589 {
   590 	HANDLE h;
   591 
   592 	if (atomic->error_str)
   593 		return -1;
   594 
   595 	assert(handle < atomic->n_files);
   596 	assert(atomic->files[handle].h != INVALID_HANDLE_VALUE);
   597 
   598 	if (!CloseHandle(atomic->files[handle].h)) {
   599 		razor_atomic_set_error(atomic, atomic->files[handle].path,
   600 				       GetLastError());
   601 		free(atomic->files[handle].path);
   602 		atomic->files[handle].path = NULL;
   603 		atomic->files[handle].h = INVALID_HANDLE_VALUE;
   604 		return -1;
   605 	}
   606 
   607 	h = CreateFileTransactedW(atomic->files[handle].path, GENERIC_WRITE, 0,
   608 				  NULL, OPEN_EXISTING, 0, NULL,
   609 				  atomic->transaction, NULL, NULL);
   610 	atomic->files[handle].h = h;
   611 
   612 	if (atomic->files[handle].h == INVALID_HANDLE_VALUE) {
   613 		razor_atomic_set_error(atomic, atomic->files[handle].path,
   614 				       GetLastError());
   615 		free(atomic->files[handle].path);
   616 		atomic->files[handle].path = NULL;
   617 		return -1;
   618 	}
   619 
   620 	return !!atomic->error_str;
   621 }
   622 
   623 RAZOR_EXPORT int
   624 razor_atomic_close(struct razor_atomic *atomic, int handle)
   625 {
   626 	if (atomic->error_str)
   627 		return -1;
   628 
   629 	assert(handle < atomic->n_files);
   630 	assert(atomic->files[handle].h != INVALID_HANDLE_VALUE);
   631 
   632 	if (!CloseHandle(atomic->files[handle].h))
   633 		razor_atomic_set_error(atomic, atomic->files[handle].path,
   634 				       GetLastError());
   635 
   636 	free(atomic->files[handle].path);
   637 	atomic->files[handle].path = NULL;
   638 	atomic->files[handle].h = INVALID_HANDLE_VALUE;
   639 
   640 	while(atomic->n_files > 0 &&
   641 	      atomic->files[atomic->n_files-1].h == INVALID_HANDLE_VALUE)
   642 		atomic->n_files--;
   643 
   644 	return !!atomic->error_str;
   645 }
   646 
   647 #else		/* HAVE_WINDOWS_KVM */
   648 
   649 static int
   650 razor_valid_root_name(const char *name)
   651 {
   652 	if (allow_all_root_names) {
   653 #ifdef MSWIN_API
   654 		return !strpbrk(name, "/\\");
   655 #else
   656 		return !strchr(name, '/');
   657 #endif
   658 	}
   659 
   660 #ifdef MSWIN_API
   661 	return RAZOR_ASCII_ISALPHA(name[0]) && name[1] == ':' &&
   662 	       name[2] == '\0';
   663 #else
   664 	return name[0] == '\0';
   665 #endif
   666 }
   667 
   668 struct razor_atomic {
   669 	char *error_path;
   670 	char *error_str;
   671 	char *error_msg;
   672 };
   673 
   674 RAZOR_EXPORT struct razor_atomic *
   675 razor_atomic_open(const char *description)
   676 {
   677 	struct razor_atomic *atomic;
   678 
   679 	atomic = zalloc(sizeof *atomic);
   680 
   681 	return atomic;
   682 }
   683 
   684 static void
   685 razor_atomic_set_error_str(struct razor_atomic *atomic, const char *path,
   686 			   const char *str)
   687 {
   688 	assert(!atomic->error_str);
   689 
   690 	atomic->error_path = path ? strdup(path) : NULL;
   691 	atomic->error_str = strdup(str);
   692 }
   693 
   694 #ifdef MSWIN_API
   695 static void
   696 razor_atomic_set_error_mswin(struct razor_atomic *atomic, const wchar_t *path,
   697 		       DWORD error)
   698 {
   699 	wchar_t *buf;
   700 
   701 	assert(!atomic->error_str);
   702 
   703 	free(atomic->error_path);
   704 
   705 	if (path)
   706 		atomic->error_path = razor_utf16_to_utf8(path, -1);
   707 	else
   708 		atomic->error_path = NULL;
   709 
   710 	FormatMessageW(FORMAT_MESSAGE_ALLOCATE_BUFFER|
   711 		       FORMAT_MESSAGE_FROM_SYSTEM|FORMAT_MESSAGE_IGNORE_INSERTS,
   712 		       NULL, error, MAKELANGID(LANG_NEUTRAL,SUBLANG_DEFAULT),
   713 		       (LPWSTR)&buf, 0, NULL);
   714 	atomic->error_str = razor_utf16_to_utf8(buf, -1);
   715 	LocalFree(buf);
   716 }
   717 #endif
   718 
   719 RAZOR_EXPORT int
   720 razor_atomic_commit(struct razor_atomic *atomic)
   721 {
   722 	return !!atomic->error_str;
   723 }
   724 
   725 RAZOR_EXPORT void
   726 razor_atomic_destroy(struct razor_atomic *atomic)
   727 {
   728 	free(atomic->error_path);
   729 	free(atomic->error_str);
   730 	free(atomic->error_msg);
   731 	free(atomic);
   732 }
   733 
   734 RAZOR_EXPORT int
   735 razor_atomic_make_dirs(struct razor_atomic *atomic, const char *root,
   736 		       const char *path)
   737 {
   738 	char buffer[PATH_MAX], *p;
   739 	const char *slash, *next;
   740 	struct stat buf;
   741 
   742 	if (atomic->error_str)
   743 		return -1;
   744 
   745 	strcpy(buffer, root);
   746 	p = buffer + strlen(buffer);
   747 	slash = path;
   748 	for (slash = path; *slash != '\0'; slash = next) {
   749 #ifdef MSWIN_API
   750 		next = strpbrk(slash + 1, "/\\");
   751 #else
   752 		next = strchr(slash + 1, '/');
   753 #endif
   754 		if (next == NULL)
   755 			break;
   756 
   757 		memcpy(p, slash, next - slash);
   758 		p += next - slash;
   759 		*p = '\0';
   760 
   761 		if (razor_valid_root_name(buffer))
   762 			continue;
   763 
   764 		if (stat(buffer, &buf) == 0) {
   765 			if (!S_ISDIR(buf.st_mode)) {
   766 				razor_atomic_set_error_str(atomic, buffer,
   767 							   "Not a directory");
   768 				return -1;
   769 			}
   770 		} else if (mkdir(buffer, 0777) < 0) {
   771 			razor_atomic_set_error_str(atomic, buffer,
   772 						   strerror(errno));
   773 			return -1;
   774 		}
   775 	}
   776 
   777 	return 0;
   778 }
   779 
   780 RAZOR_EXPORT int
   781 razor_atomic_remove(struct razor_atomic *atomic, const char *path)
   782 {
   783 #ifdef MSWIN_API
   784 	wchar_t *buf;
   785 	DWORD err;
   786 #endif
   787 
   788 	if (atomic->error_str)
   789 		return -1;
   790 
   791 #ifdef MSWIN_API
   792 	buf = razor_utf8_to_utf16(path, -1);
   793 
   794 	if (!DeleteFileW(buf)) {
   795 		err = GetLastError();
   796 		if (err != ERROR_FILE_NOT_FOUND &&
   797 		    err != ERROR_PATH_NOT_FOUND &&
   798 		    !(SetFileAttributesW(buf, FILE_ATTRIBUTE_NORMAL) &&
   799 		      DeleteFileW(buf)) &&
   800 		    !RemoveDirectoryW(buf) &&
   801 		    GetLastError() != ERROR_DIR_NOT_EMPTY)
   802 			razor_atomic_set_error_mswin(atomic, buf, err);
   803 	}
   804 
   805 	free(buf);
   806 #else
   807 	if (remove(path))
   808 		razor_atomic_set_error_str(atomic, path, strerror(errno));
   809 #endif
   810 
   811 	return !!atomic->error_str;
   812 }
   813 
   814 RAZOR_EXPORT int
   815 razor_atomic_rename_file(struct razor_atomic *atomic, const char *oldpath,
   816 			 const char *newpath)
   817 {
   818 #ifdef MSWIN_API
   819 	wchar_t *oldbuf, *newbuf;
   820 	const DWORD flags = MOVEFILE_COPY_ALLOWED | MOVEFILE_REPLACE_EXISTING;
   821 #endif
   822 
   823 	if (atomic->error_str)
   824 		return -1;
   825 
   826 #ifdef MSWIN_API
   827 	newbuf = razor_utf8_to_utf16(newpath, -1);
   828 	oldbuf = razor_utf8_to_utf16(oldpath, -1);
   829 
   830 	/*
   831 	 * Passing MOVEFILE_REPLACE_EXISTING to MoveFileEx() will
   832 	 * cover every case we care about _except_ replacing an empty
   833 	 * directory with a file. Calling RemoveDirectory() will deal
   834 	 * with this case while having no effect in all other cases.
   835 	 */
   836 	(void)RemoveDirectoryW(newbuf);
   837 
   838 	if (!MoveFileExW(oldbuf, newbuf, flags))
   839 		razor_atomic_set_error_mswin(atomic, newbuf, GetLastError());
   840 
   841 	free(newbuf);
   842 	free(oldbuf);
   843 #else
   844 	if (rename(oldpath, newpath))
   845 		razor_atomic_set_error_str(atomic, newpath, strerror(errno));
   846 #endif
   847 
   848 	return !!atomic->error_str;
   849 }
   850 
   851 RAZOR_EXPORT int
   852 razor_atomic_create_dir(struct razor_atomic *atomic, const char *dirname,
   853 			mode_t mode)
   854 {
   855 	if (atomic->error_str)
   856 		return -1;
   857 
   858 	if (!mkdir(dirname, mode & (S_IRWXU | S_IRWXG | S_IRWXO)))
   859 		return 0;
   860 
   861 	if (errno != EEXIST) {
   862 		razor_atomic_set_error_str(atomic, dirname, strerror(errno));
   863 		return -1;
   864 	}
   865 
   866 	if (chmod(dirname, mode & (S_IRWXU | S_IRWXG | S_IRWXO)) < 0) {
   867 		razor_atomic_set_error_str(atomic, dirname, strerror(errno));
   868 		return -1;
   869 	}
   870 
   871 	return 0;
   872 }
   873 
   874 RAZOR_EXPORT int
   875 razor_atomic_create_symlink(struct razor_atomic *atomic, const char *target,
   876 			    const char *path)
   877 {
   878 	if (atomic->error_str)
   879 		return -1;
   880 
   881 #if HAVE_SYMLINK
   882 	if (symlink(target, path) < 0) {
   883 		razor_atomic_set_error_str(atomic, NULL, strerror(errno));
   884 		return -1;
   885 	}
   886 #else
   887 	razor_atomic_set_error_str(atomic, NULL, "Symbolic links not supported "
   888 						 "on this platform");
   889 #endif
   890 
   891 	return 0;
   892 }
   893 
   894 RAZOR_EXPORT int
   895 razor_atomic_create_file(struct razor_atomic *atomic, const char *filename,
   896 			 mode_t mode)
   897 {
   898 	int fd;
   899 
   900 	if (atomic->error_str)
   901 		return -1;
   902 
   903 	atomic->error_path = strdup(filename);
   904 	fd = open(atomic->error_path, O_WRONLY | O_CREAT | O_TRUNC | O_BINARY,
   905 		  mode & (S_IRWXU | S_IRWXG | S_IRWXO));
   906 
   907 	if (fd == -1)
   908 		razor_atomic_set_error_str(atomic, NULL, strerror(errno));
   909 
   910 	return fd;
   911 }
   912 
   913 RAZOR_EXPORT int
   914 razor_atomic_write(struct razor_atomic *atomic, int fd, const void *data,
   915 		   size_t size)
   916 {
   917 	int written;
   918 
   919 	if (atomic->error_str)
   920 		return -1;
   921 
   922 	while(size) {
   923 		written = write(fd, data, size);
   924 		if (written < 0) {
   925 			razor_atomic_set_error_str(atomic, NULL, strerror(errno));
   926 
   927 			(void)close(fd);
   928 
   929 			return -1;
   930 		}
   931 
   932 		data += written;
   933 		size -= written;
   934 	}
   935 
   936 	return 0;
   937 }
   938 
   939 RAZOR_EXPORT int
   940 razor_atomic_sync(struct razor_atomic *atomic, int handle)
   941 {
   942 	if (atomic->error_str)
   943 		return -1;
   944 
   945 	if (fsync(handle) < 0) {
   946 		razor_atomic_set_error_str(atomic, NULL, strerror(errno));
   947 		return -1;
   948 	}
   949 
   950 	free(atomic->error_path);
   951 	atomic->error_path = NULL;
   952 
   953 	return 0;
   954 }
   955 
   956 RAZOR_EXPORT int
   957 razor_atomic_close(struct razor_atomic *atomic, int fd)
   958 {
   959 	if (atomic->error_str)
   960 		return -1;
   961 
   962 	if (close(fd) < 0) {
   963 		razor_atomic_set_error_str(atomic, NULL, strerror(errno));
   964 		return -1;
   965 	}
   966 
   967 	free(atomic->error_path);
   968 	atomic->error_path = NULL;
   969 
   970 	return 0;
   971 }
   972 
   973 #endif		/* HAVE_WINDOWS_KVM */
   974 
   975 RAZOR_EXPORT const char *
   976 razor_atomic_get_error_msg(struct razor_atomic *atomic)
   977 {
   978 	if (!atomic->error_msg) {
   979 		if (atomic->error_path)
   980 			atomic->error_msg = razor_concat(atomic->error_path,
   981 							 ": ",
   982 							 atomic->error_str,
   983 							 NULL);
   984 		else
   985 			atomic->error_msg = strdup(atomic->error_str);
   986 	}
   987 
   988 	return atomic->error_msg;
   989 }
   990 
   991 RAZOR_EXPORT void
   992 razor_atomic_abort(struct razor_atomic *atomic, const char *error_msg)
   993 {
   994 	if (!atomic->error_str)
   995 		razor_atomic_set_error_str(atomic, NULL, error_msg);
   996 }
   997 
   998 RAZOR_EXPORT int
   999 razor_atomic_in_error_state(struct razor_atomic *atomic)
  1000 {
  1001 	return !!atomic->error_str;
  1002 }