bsdtar_windows.c 26 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214
  1. /*-
  2. * Copyright (c) 2009 Michihiro NAKAJIMA
  3. * All rights reserved.
  4. *
  5. * Redistribution and use in source and binary forms, with or without
  6. * modification, are permitted provided that the following conditions
  7. * are met:
  8. * 1. Redistributions of source code must retain the above copyright
  9. * notice, this list of conditions and the following disclaimer.
  10. * 2. Redistributions in binary form must reproduce the above copyright
  11. * notice, this list of conditions and the following disclaimer in the
  12. * documentation and/or other materials provided with the distribution.
  13. *
  14. * THIS SOFTWARE IS PROVIDED BY THE AUTHOR(S) ``AS IS'' AND ANY EXPRESS OR
  15. * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
  16. * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
  17. * IN NO EVENT SHALL THE AUTHOR(S) BE LIABLE FOR ANY DIRECT, INDIRECT,
  18. * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
  19. * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  20. * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  21. * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  22. * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
  23. * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  24. *
  25. * $FreeBSD$
  26. */
  27. #if defined(_WIN32) && !defined(__CYGWIN__)
  28. #define _WIN32_WINNT 0x0500
  29. #define WINVER 0x0500
  30. #include "bsdtar_platform.h"
  31. #include <errno.h>
  32. #include <stddef.h>
  33. #include <sys/utime.h>
  34. #include <sys/stat.h>
  35. #include <process.h>
  36. #include <stdlib.h>
  37. #include <wchar.h>
  38. #include <windows.h>
  39. #include <sddl.h>
  40. #include "bsdtar.h"
  41. #define EPOC_TIME (116444736000000000ULL)
  42. struct ustat {
  43. int64_t st_atime;
  44. uint32_t st_atime_nsec;
  45. int64_t st_ctime;
  46. uint32_t st_ctime_nsec;
  47. int64_t st_mtime;
  48. uint32_t st_mtime_nsec;
  49. gid_t st_gid;
  50. /* 64bits ino */
  51. int64_t st_ino;
  52. mode_t st_mode;
  53. uint32_t st_nlink;
  54. uint64_t st_size;
  55. uid_t st_uid;
  56. dev_t st_dev;
  57. dev_t st_rdev;
  58. };
  59. struct __DIR {
  60. HANDLE handle;
  61. WIN32_FIND_DATAW fileData;
  62. struct dirent de;
  63. int first;
  64. BOOL finished;
  65. };
  66. /* Transform 64-bits ino into 32-bits by hashing.
  67. * You do not forget that really unique number size is 64-bits.
  68. */
  69. #define INOSIZE (8*sizeof(ino_t)) /* 32 */
  70. static __inline ino_t
  71. getino(struct ustat *ub)
  72. {
  73. ULARGE_INTEGER ino64;
  74. ino64.QuadPart = ub->st_ino;
  75. /* I don't know this hashing is correct way */
  76. return (ino64.LowPart ^ (ino64.LowPart >> INOSIZE));
  77. }
  78. /*
  79. * Prepend "\\?\" to the path name and convert it to unicode to permit
  80. * an extended-length path for a maximum total path length of 32767
  81. * characters.
  82. * see also http://msdn.microsoft.com/en-us/library/aa365247.aspx
  83. */
  84. static wchar_t *
  85. permissive_name(const char *name)
  86. {
  87. wchar_t *wn, *wnp;
  88. wchar_t *ws, *wsp;
  89. size_t l, len, slen;
  90. int unc;
  91. len = strlen(name);
  92. wn = malloc((len + 1) * sizeof(wchar_t));
  93. if (wn == NULL)
  94. return (NULL);
  95. l = MultiByteToWideChar(CP_ACP, 0, name, len, wn, len);
  96. if (l == 0) {
  97. free(wn);
  98. return (NULL);
  99. }
  100. wn[l] = L'\0';
  101. /* Get a full path names */
  102. l = GetFullPathNameW(wn, 0, NULL, NULL);
  103. if (l == 0) {
  104. free(wn);
  105. return (NULL);
  106. }
  107. wnp = malloc(l * sizeof(wchar_t));
  108. if (wnp == NULL) {
  109. free(wn);
  110. return (NULL);
  111. }
  112. len = GetFullPathNameW(wn, l, wnp, NULL);
  113. free(wn);
  114. wn = wnp;
  115. if (wnp[0] == L'\\' && wnp[1] == L'\\' &&
  116. wnp[2] == L'?' && wnp[3] == L'\\')
  117. /* We have already permissive names. */
  118. return (wn);
  119. if (wnp[0] == L'\\' && wnp[1] == L'\\' &&
  120. wnp[2] == L'.' && wnp[3] == L'\\') {
  121. /* Device names */
  122. if (((wnp[4] >= L'a' && wnp[4] <= L'z') ||
  123. (wnp[4] >= L'A' && wnp[4] <= L'Z')) &&
  124. wnp[5] == L':' && wnp[6] == L'\\')
  125. wnp[2] = L'?';/* Not device names. */
  126. return (wn);
  127. }
  128. unc = 0;
  129. if (wnp[0] == L'\\' && wnp[1] == L'\\' && wnp[2] != L'\\') {
  130. wchar_t *p = &wnp[2];
  131. /* Skip server-name letters. */
  132. while (*p != L'\\' && *p != L'\0')
  133. ++p;
  134. if (*p == L'\\') {
  135. wchar_t *rp = ++p;
  136. /* Skip share-name letters. */
  137. while (*p != L'\\' && *p != L'\0')
  138. ++p;
  139. if (*p == L'\\' && p != rp) {
  140. /* Now, match patterns such as
  141. * "\\server-name\share-name\" */
  142. wnp += 2;
  143. len -= 2;
  144. unc = 1;
  145. }
  146. }
  147. }
  148. slen = 4 + (unc * 4) + len + 1;
  149. ws = wsp = malloc(slen * sizeof(wchar_t));
  150. if (ws == NULL) {
  151. free(wn);
  152. return (NULL);
  153. }
  154. /* prepend "\\?\" */
  155. wcsncpy(wsp, L"\\\\?\\", 4);
  156. wsp += 4;
  157. slen -= 4;
  158. if (unc) {
  159. /* append "UNC\" ---> "\\?\UNC\" */
  160. wcsncpy(wsp, L"UNC\\", 4);
  161. wsp += 4;
  162. slen -= 4;
  163. }
  164. wcsncpy_s(wsp, slen, wnp, _TRUNCATE);
  165. free(wn);
  166. return (ws);
  167. }
  168. static HANDLE
  169. la_CreateFile(const char *path, DWORD dwDesiredAccess, DWORD dwShareMode,
  170. LPSECURITY_ATTRIBUTES lpSecurityAttributes, DWORD dwCreationDisposition,
  171. DWORD dwFlagsAndAttributes, HANDLE hTemplateFile)
  172. {
  173. wchar_t *wpath;
  174. HANDLE handle;
  175. handle = CreateFileA(path, dwDesiredAccess, dwShareMode,
  176. lpSecurityAttributes, dwCreationDisposition, dwFlagsAndAttributes,
  177. hTemplateFile);
  178. if (handle != INVALID_HANDLE_VALUE)
  179. return (handle);
  180. if (GetLastError() != ERROR_PATH_NOT_FOUND)
  181. return (handle);
  182. wpath = permissive_name(path);
  183. if (wpath == NULL)
  184. return (handle);
  185. handle = CreateFileW(wpath, dwDesiredAccess, dwShareMode,
  186. lpSecurityAttributes, dwCreationDisposition, dwFlagsAndAttributes,
  187. hTemplateFile);
  188. free(wpath);
  189. return (handle);
  190. }
  191. static size_t
  192. wequallen(const wchar_t *s1, const wchar_t *s2)
  193. {
  194. size_t i = 0;
  195. while (*s1 != L'\0' && *s2 != L'\0' && *s1 == *s2) {
  196. ++s1; ++s2; ++i;
  197. }
  198. return (i);
  199. }
  200. /* Check that path1 and path2 can be hard-linked by each other.
  201. * Both arguments must be made by permissive_name function.
  202. */
  203. static int
  204. canHardLinkW(const wchar_t *path1, const wchar_t *path2)
  205. {
  206. wchar_t root[MAX_PATH];
  207. wchar_t fs[32];
  208. const wchar_t *s;
  209. int r;
  210. r = wequallen(path1, path2);
  211. /* Is volume-name the same? */
  212. if (r < 7)
  213. return (0);
  214. if (wcsncmp(path1, L"\\\\?\\UNC\\", 8) == 0) {
  215. int len;
  216. s = path1 + 8;
  217. if (*s == L'\\')
  218. return (0);
  219. /* 012345678
  220. * Name : "\\?\UNC\Server\Share\"
  221. * ^ search
  222. */
  223. s = wcschr(++s, L'\\');
  224. if (s == NULL)
  225. return (0);
  226. if (*++s == L'\\')
  227. return (0);
  228. /* 012345678
  229. * Name : "\\?\UNC\Server\Share\"
  230. * ^ search
  231. */
  232. s = wcschr(++s, L'\\');
  233. if (s == NULL)
  234. return (0);
  235. s++;
  236. /* 012345678
  237. * Name : "\\?\UNC\Server\Share\xxxx"
  238. * ^--- len ----^
  239. */
  240. len = (int)(s - path1 - 8);
  241. /* Is volume-name the same? */
  242. if (r < len + 8)
  243. return (0);
  244. /* Is volume-name too long? */
  245. if (sizeof(root) -3 < len)
  246. return (0);
  247. root[0] = root[1] = L'\\';
  248. wcsncpy(root + 2, path1 + 8, len);
  249. /* root : "\\Server\Share\" */
  250. root[2 + len] = L'\0';
  251. } else if (wcsncmp(path1, L"\\\\?\\", 4) == 0) {
  252. s = path1 + 4;
  253. if ((!iswalpha(*s)) || s[1] != L':' || s[2] != L'\\')
  254. return (0);
  255. wcsncpy(root, path1 + 4, 3);
  256. root[3] = L'\0';
  257. } else
  258. return (0);
  259. if (!GetVolumeInformationW(root, NULL, 0, NULL, NULL, NULL, fs, sizeof(fs)))
  260. return (0);
  261. if (wcscmp(fs, L"NTFS") == 0)
  262. return (1);
  263. else
  264. return (0);
  265. }
  266. /* Make a link to src called dst. */
  267. static int
  268. __link(const char *src, const char *dst, int sym)
  269. {
  270. wchar_t *wsrc, *wdst;
  271. int res, retval;
  272. DWORD attr;
  273. if (src == NULL || dst == NULL) {
  274. set_errno (EINVAL);
  275. return -1;
  276. }
  277. wsrc = permissive_name(src);
  278. wdst = permissive_name(dst);
  279. if (wsrc == NULL || wdst == NULL) {
  280. if (wsrc != NULL)
  281. free(wsrc);
  282. if (wdst != NULL)
  283. free(wdst);
  284. set_errno (EINVAL);
  285. return -1;
  286. }
  287. if ((attr = GetFileAttributesW(wsrc)) != -1) {
  288. if ((attr & FILE_ATTRIBUTE_DIRECTORY) != 0) {
  289. errno = EPERM;
  290. retval = -1;
  291. goto exit;
  292. }
  293. if (!sym && canHardLinkW(wsrc, wdst))
  294. res = CreateHardLinkW(wdst, wsrc, NULL);
  295. else
  296. res = CopyFileW(wsrc, wdst, FALSE);
  297. } else {
  298. /* wsrc does not exist; try src prepend it with the dirname of wdst */
  299. wchar_t *wnewsrc, *slash;
  300. int i, n, slen, wlen;
  301. if (strlen(src) >= 3 && isalpha((unsigned char)src[0]) &&
  302. src[1] == ':' && src[2] == '\\') {
  303. /* Original src name is already full-path */
  304. retval = -1;
  305. goto exit;
  306. }
  307. if (src[0] == '\\') {
  308. /* Original src name is almost full-path
  309. * (maybe src name is without drive) */
  310. retval = -1;
  311. goto exit;
  312. }
  313. wnewsrc = malloc ((wcslen(wsrc) + wcslen(wdst) + 1) * sizeof(wchar_t));
  314. if (wnewsrc == NULL) {
  315. errno = ENOMEM;
  316. retval = -1;
  317. goto exit;
  318. }
  319. /* Copying a dirname of wdst */
  320. wcscpy(wnewsrc, wdst);
  321. slash = wcsrchr(wnewsrc, L'\\');
  322. if (slash != NULL)
  323. *++slash = L'\0';
  324. else
  325. wcscat(wnewsrc, L"\\");
  326. /* Converting multi-byte src to wide-char src */
  327. wlen = wcslen(wsrc);
  328. slen = strlen(src);
  329. n = MultiByteToWideChar(CP_ACP, 0, src, slen, wsrc, slen);
  330. if (n == 0) {
  331. free (wnewsrc);
  332. retval = -1;
  333. goto exit;
  334. }
  335. for (i = 0; i < n; i++)
  336. if (wsrc[i] == L'/')
  337. wsrc[i] = L'\\';
  338. wcsncat(wnewsrc, wsrc, n);
  339. /* Check again */
  340. attr = GetFileAttributesW(wnewsrc);
  341. if (attr == -1 || (attr & FILE_ATTRIBUTE_DIRECTORY) != 0) {
  342. if (attr == -1)
  343. _dosmaperr(GetLastError());
  344. else
  345. errno = EPERM;
  346. free (wnewsrc);
  347. retval = -1;
  348. goto exit;
  349. }
  350. if (!sym && canHardLinkW(wnewsrc, wdst))
  351. res = CreateHardLinkW(wdst, wnewsrc, NULL);
  352. else
  353. res = CopyFileW(wnewsrc, wdst, FALSE);
  354. free (wnewsrc);
  355. }
  356. if (res == 0) {
  357. _dosmaperr(GetLastError());
  358. retval = -1;
  359. } else
  360. retval = 0;
  361. exit:
  362. free(wsrc);
  363. free(wdst);
  364. return (retval);
  365. }
  366. /* Make a hard link to src called dst. */
  367. int
  368. link(const char *src, const char *dst)
  369. {
  370. return __link (src, dst, 0);
  371. }
  372. /* Make a symbolic link to FROM called TO. */
  373. int symlink (from, to)
  374. const char *from;
  375. const char *to;
  376. {
  377. return __link (from, to, 1);
  378. }
  379. int
  380. ftruncate(int fd, off_t length)
  381. {
  382. LARGE_INTEGER distance;
  383. HANDLE handle;
  384. if (fd < 0) {
  385. errno = EBADF;
  386. return (-1);
  387. }
  388. handle = (HANDLE)_get_osfhandle(fd);
  389. if (GetFileType(handle) != FILE_TYPE_DISK) {
  390. errno = EBADF;
  391. return (-1);
  392. }
  393. distance.QuadPart = length;
  394. if (!SetFilePointerEx(handle, distance, NULL, FILE_BEGIN)) {
  395. _dosmaperr(GetLastError());
  396. return (-1);
  397. }
  398. if (!SetEndOfFile(handle)) {
  399. _dosmaperr(GetLastError());
  400. return (-1);
  401. }
  402. return (0);
  403. }
  404. DIR *
  405. __opendir(const char *path, int ff)
  406. {
  407. DIR *dir;
  408. wchar_t *wpath, *wfname;
  409. size_t wlen;
  410. dir = malloc(sizeof(*dir));
  411. if (dir == NULL) {
  412. errno = ENOMEM;
  413. return (NULL);
  414. }
  415. wpath = permissive_name(path);
  416. if (wpath == NULL) {
  417. errno = EINVAL;
  418. free(dir);
  419. return (NULL);
  420. }
  421. if (ff) {
  422. wfname = wpath;
  423. wpath = NULL;
  424. } else {
  425. wlen = wcslen(wpath);
  426. wfname = malloc((wlen + 3) * sizeof(wchar_t));
  427. if (wfname == NULL) {
  428. errno = ENOMEM;
  429. free(dir);
  430. free(wpath);
  431. return (NULL);
  432. }
  433. wcscpy(wfname, wpath);
  434. wcscat(wfname, L"\\*");
  435. free(wpath);
  436. }
  437. dir->handle = FindFirstFileW(wfname, &dir->fileData);
  438. if (dir->handle == INVALID_HANDLE_VALUE) {
  439. _dosmaperr(GetLastError());
  440. free(dir);
  441. free(wfname);
  442. return (NULL);
  443. }
  444. dir->first = 1;
  445. dir->finished = FALSE;
  446. free(wfname);
  447. return (dir);
  448. }
  449. static DIR *
  450. opendir_findfile(const char *path)
  451. {
  452. return (__opendir(path, 1));
  453. }
  454. DIR *
  455. opendir(const char *path)
  456. {
  457. return (__opendir(path, 0));
  458. }
  459. struct dirent *
  460. readdir(DIR *dirp)
  461. {
  462. size_t len;
  463. while (!dirp->finished) {
  464. if (!dirp->first && !FindNextFileW(dirp->handle, &dirp->fileData)) {
  465. if (GetLastError() != ERROR_NO_MORE_FILES)
  466. _dosmaperr(GetLastError());
  467. dirp->finished = TRUE;
  468. break;
  469. }
  470. dirp->first = 0;
  471. len = wcstombs(dirp->de.d_name, dirp->fileData.cFileName,
  472. sizeof(dirp->de.d_name) -1);
  473. if (len == -1) {
  474. errno = EINVAL;
  475. dirp->finished = TRUE;
  476. break;
  477. }
  478. dirp->de.d_name[len] = '\0';
  479. dirp->de.d_nameln = strlen(dirp->de.d_name);
  480. return (&dirp->de);
  481. }
  482. return (NULL);
  483. }
  484. int
  485. closedir(DIR *dirp)
  486. {
  487. BOOL ret;
  488. ret = FindClose(dirp->handle);
  489. free(dirp);
  490. if (ret == 0) {
  491. _dosmaperr(GetLastError());
  492. return (-1);
  493. }
  494. return (0);
  495. }
  496. int
  497. la_chdir(const char *path)
  498. {
  499. wchar_t *ws;
  500. int r;
  501. r = SetCurrentDirectoryA(path);
  502. if (r == 0) {
  503. if (GetLastError() != ERROR_FILE_NOT_FOUND) {
  504. _dosmaperr(GetLastError());
  505. return (-1);
  506. }
  507. } else
  508. return (0);
  509. ws = permissive_name(path);
  510. if (ws == NULL) {
  511. errno = EINVAL;
  512. return (-1);
  513. }
  514. r = SetCurrentDirectoryW(ws);
  515. free(ws);
  516. if (r == 0) {
  517. _dosmaperr(GetLastError());
  518. return (-1);
  519. }
  520. return (0);
  521. }
  522. __int64
  523. la_lseek(int fd, __int64 offset, int whence)
  524. {
  525. LARGE_INTEGER distance;
  526. LARGE_INTEGER newpointer;
  527. HANDLE handle;
  528. if (fd < 0) {
  529. errno = EBADF;
  530. return (-1);
  531. }
  532. handle = (HANDLE)_get_osfhandle(fd);
  533. if (GetFileType(handle) != FILE_TYPE_DISK) {
  534. errno = EBADF;
  535. return (-1);
  536. }
  537. distance.QuadPart = offset;
  538. if (!SetFilePointerEx(handle, distance, &newpointer, whence)) {
  539. DWORD lasterr;
  540. lasterr = GetLastError();
  541. if (lasterr == ERROR_BROKEN_PIPE)
  542. return (0);
  543. if (lasterr == ERROR_ACCESS_DENIED)
  544. errno = EBADF;
  545. else
  546. _dosmaperr(lasterr);
  547. return (-1);
  548. }
  549. return (newpointer.QuadPart);
  550. }
  551. int
  552. la_mkdir(const char *path, mode_t mode)
  553. {
  554. wchar_t *ws;
  555. int r;
  556. (void)mode;/* UNUSED */
  557. r = CreateDirectoryA(path, NULL);
  558. if (r == 0) {
  559. DWORD lasterr = GetLastError();
  560. if (lasterr != ERROR_FILENAME_EXCED_RANGE &&
  561. lasterr != ERROR_PATH_NOT_FOUND) {
  562. _dosmaperr(GetLastError());
  563. return (-1);
  564. }
  565. } else
  566. return (0);
  567. ws = permissive_name(path);
  568. if (ws == NULL) {
  569. errno = EINVAL;
  570. return (-1);
  571. }
  572. r = CreateDirectoryW(ws, NULL);
  573. free(ws);
  574. if (r == 0) {
  575. _dosmaperr(GetLastError());
  576. return (-1);
  577. }
  578. return (0);
  579. }
  580. /* Windows' mbstowcs is differrent error handling from other unix mbstowcs.
  581. * That one is using MultiByteToWideChar function with MB_PRECOMPOSED and
  582. * MB_ERR_INVALID_CHARS flags.
  583. * This implements for only to pass libarchive_test.
  584. */
  585. size_t
  586. la_mbstowcs(wchar_t *wcstr, const char *mbstr, size_t nwchars)
  587. {
  588. return (MultiByteToWideChar(CP_ACP, MB_ERR_INVALID_CHARS,
  589. mbstr, (int)strlen(mbstr), wcstr,
  590. (int)nwchars));
  591. }
  592. int
  593. la_open(const char *path, int flags, ...)
  594. {
  595. va_list ap;
  596. wchar_t *ws;
  597. int r, pmode;
  598. DWORD attr;
  599. va_start(ap, flags);
  600. pmode = va_arg(ap, int);
  601. va_end(ap);
  602. ws = NULL;
  603. if ((flags & ~O_BINARY) == O_RDONLY) {
  604. /*
  605. * When we open a directory, _open function returns
  606. * "Permission denied" error.
  607. */
  608. attr = GetFileAttributesA(path);
  609. if (attr == -1 && GetLastError() == ERROR_PATH_NOT_FOUND) {
  610. ws = permissive_name(path);
  611. if (ws == NULL) {
  612. errno = EINVAL;
  613. return (-1);
  614. }
  615. attr = GetFileAttributesW(ws);
  616. }
  617. if (attr == -1) {
  618. _dosmaperr(GetLastError());
  619. free(ws);
  620. return (-1);
  621. }
  622. if (attr & FILE_ATTRIBUTE_DIRECTORY) {
  623. HANDLE handle;
  624. if (ws != NULL)
  625. handle = CreateFileW(ws, 0, 0, NULL,
  626. OPEN_EXISTING,
  627. FILE_FLAG_BACKUP_SEMANTICS |
  628. FILE_ATTRIBUTE_READONLY,
  629. NULL);
  630. else
  631. handle = CreateFileA(path, 0, 0, NULL,
  632. OPEN_EXISTING,
  633. FILE_FLAG_BACKUP_SEMANTICS |
  634. FILE_ATTRIBUTE_READONLY,
  635. NULL);
  636. free(ws);
  637. if (handle == INVALID_HANDLE_VALUE) {
  638. _dosmaperr(GetLastError());
  639. return (-1);
  640. }
  641. r = _open_osfhandle((intptr_t)handle, _O_RDONLY);
  642. return (r);
  643. }
  644. }
  645. if (ws == NULL) {
  646. r = _open(path, flags, pmode);
  647. if (r < 0 && errno == EACCES && (flags & O_CREAT) != 0) {
  648. /* simular other POSIX system action to pass a test */
  649. attr = GetFileAttributesA(path);
  650. if (attr == -1)
  651. _dosmaperr(GetLastError());
  652. else if (attr & FILE_ATTRIBUTE_DIRECTORY)
  653. errno = EISDIR;
  654. else
  655. errno = EACCES;
  656. return (-1);
  657. }
  658. if (r >= 0 || errno != ENOENT)
  659. return (r);
  660. ws = permissive_name(path);
  661. if (ws == NULL) {
  662. errno = EINVAL;
  663. return (-1);
  664. }
  665. }
  666. r = _wopen(ws, flags, pmode);
  667. if (r < 0 && errno == EACCES && (flags & O_CREAT) != 0) {
  668. /* simular other POSIX system action to pass a test */
  669. attr = GetFileAttributesW(ws);
  670. if (attr == -1)
  671. _dosmaperr(GetLastError());
  672. else if (attr & FILE_ATTRIBUTE_DIRECTORY)
  673. errno = EISDIR;
  674. else
  675. errno = EACCES;
  676. }
  677. free(ws);
  678. return (r);
  679. }
  680. ssize_t
  681. la_read(int fd, void *buf, size_t nbytes)
  682. {
  683. HANDLE handle;
  684. DWORD bytes_read, lasterr;
  685. int r;
  686. #ifdef _WIN64
  687. if (nbytes > UINT32_MAX)
  688. nbytes = UINT32_MAX;
  689. #endif
  690. if (fd < 0) {
  691. errno = EBADF;
  692. return (-1);
  693. }
  694. handle = (HANDLE)_get_osfhandle(fd);
  695. if (GetFileType(handle) == FILE_TYPE_PIPE) {
  696. DWORD sta;
  697. if (GetNamedPipeHandleState(
  698. handle, &sta, NULL, NULL, NULL, NULL, 0) != 0 &&
  699. (sta & PIPE_NOWAIT) == 0) {
  700. DWORD avail = -1;
  701. int cnt = 3;
  702. while (PeekNamedPipe(
  703. handle, NULL, 0, NULL, &avail, NULL) != 0 &&
  704. avail == 0 && --cnt)
  705. Sleep(100);
  706. if (avail == 0)
  707. return (0);
  708. }
  709. }
  710. r = ReadFile(handle, buf, (uint32_t)nbytes,
  711. &bytes_read, NULL);
  712. if (r == 0) {
  713. lasterr = GetLastError();
  714. if (lasterr == ERROR_NO_DATA) {
  715. errno = EAGAIN;
  716. return (-1);
  717. }
  718. if (lasterr == ERROR_BROKEN_PIPE)
  719. return (0);
  720. if (lasterr == ERROR_ACCESS_DENIED)
  721. errno = EBADF;
  722. else
  723. _dosmaperr(lasterr);
  724. return (-1);
  725. }
  726. return ((ssize_t)bytes_read);
  727. }
  728. /* Remove directory */
  729. int
  730. la_rmdir(const char *path)
  731. {
  732. wchar_t *ws;
  733. int r;
  734. r = _rmdir(path);
  735. if (r >= 0 || errno != ENOENT)
  736. return (r);
  737. ws = permissive_name(path);
  738. if (ws == NULL) {
  739. errno = EINVAL;
  740. return (-1);
  741. }
  742. r = _wrmdir(ws);
  743. free(ws);
  744. return (r);
  745. }
  746. /* Convert Windows FILETIME to UTC */
  747. __inline static void
  748. fileTimeToUTC(const FILETIME *filetime, time_t *time, long *ns)
  749. {
  750. ULARGE_INTEGER utc;
  751. utc.HighPart = filetime->dwHighDateTime;
  752. utc.LowPart = filetime->dwLowDateTime;
  753. if (utc.QuadPart >= EPOC_TIME) {
  754. utc.QuadPart -= EPOC_TIME;
  755. *time = (time_t)(utc.QuadPart / 10000000); /* milli seconds base */
  756. *ns = (long)(utc.QuadPart % 10000000) * 100;/* nano seconds base */
  757. } else {
  758. *time = 0;
  759. *ns = 0;
  760. }
  761. }
  762. /* Stat by handle
  763. * Windows' stat() does not accept path which is added "\\?\" especially "?"
  764. * character.
  765. * It means we cannot access a long name path(which is longer than MAX_PATH).
  766. * So I've implemented simular Windows' stat() to access the long name path.
  767. * And I've added some feature.
  768. * 1. set st_ino by nFileIndexHigh and nFileIndexLow of
  769. * BY_HANDLE_FILE_INFORMATION.
  770. * 2. set st_nlink by nNumberOfLinks of BY_HANDLE_FILE_INFORMATION.
  771. * 3. set st_dev by dwVolumeSerialNumber by BY_HANDLE_FILE_INFORMATION.
  772. */
  773. static int
  774. __hstat(HANDLE handle, struct ustat *st)
  775. {
  776. BY_HANDLE_FILE_INFORMATION info;
  777. ULARGE_INTEGER ino64;
  778. DWORD ftype;
  779. mode_t mode;
  780. time_t time;
  781. long ns;
  782. switch (ftype = GetFileType(handle)) {
  783. case FILE_TYPE_UNKNOWN:
  784. errno = EBADF;
  785. return (-1);
  786. case FILE_TYPE_CHAR:
  787. case FILE_TYPE_PIPE:
  788. if (ftype == FILE_TYPE_CHAR) {
  789. st->st_mode = S_IFCHR;
  790. st->st_size = 0;
  791. } else {
  792. DWORD avail;
  793. st->st_mode = S_IFIFO;
  794. if (PeekNamedPipe(handle, NULL, 0, NULL, &avail, NULL))
  795. st->st_size = avail;
  796. else
  797. st->st_size = 0;
  798. }
  799. st->st_atime = 0;
  800. st->st_atime_nsec = 0;
  801. st->st_mtime = 0;
  802. st->st_mtime_nsec = 0;
  803. st->st_ctime = 0;
  804. st->st_ctime_nsec = 0;
  805. st->st_ino = 0;
  806. st->st_nlink = 1;
  807. st->st_uid = 0;
  808. st->st_gid = 0;
  809. st->st_rdev = 0;
  810. st->st_dev = 0;
  811. return (0);
  812. case FILE_TYPE_DISK:
  813. break;
  814. default:
  815. /* This ftype is undocumented type. */
  816. _dosmaperr(GetLastError());
  817. return (-1);
  818. }
  819. ZeroMemory(&info, sizeof(info));
  820. if (!GetFileInformationByHandle (handle, &info)) {
  821. _dosmaperr(GetLastError());
  822. return (-1);
  823. }
  824. mode = S_IRUSR | S_IRGRP | S_IROTH;
  825. if ((info.dwFileAttributes & FILE_ATTRIBUTE_READONLY) == 0)
  826. mode |= S_IWUSR | S_IWGRP | S_IWOTH;
  827. if (info.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
  828. mode |= S_IFDIR | S_IXUSR | S_IXGRP | S_IXOTH;
  829. else
  830. mode |= S_IFREG;
  831. st->st_mode = mode;
  832. fileTimeToUTC(&info.ftLastAccessTime, &time, &ns);
  833. st->st_atime = time;
  834. st->st_atime_nsec = ns;
  835. fileTimeToUTC(&info.ftLastWriteTime, &time, &ns);
  836. st->st_mtime = time;
  837. st->st_mtime_nsec = ns;
  838. fileTimeToUTC(&info.ftCreationTime, &time, &ns);
  839. st->st_ctime = time;
  840. st->st_ctime_nsec = ns;
  841. st->st_size =
  842. ((int64_t)(info.nFileSizeHigh) * ((int64_t)MAXDWORD + 1))
  843. + (int64_t)(info.nFileSizeLow);
  844. #ifdef SIMULATE_WIN_STAT
  845. st->st_ino = 0;
  846. st->st_nlink = 1;
  847. st->st_dev = 0;
  848. #else
  849. /* Getting FileIndex as i-node. We have to remove a sequence which
  850. * is high-16-bits of nFileIndexHigh. */
  851. ino64.HighPart = info.nFileIndexHigh & 0x0000FFFFUL;
  852. ino64.LowPart = info.nFileIndexLow;
  853. st->st_ino = ino64.QuadPart;
  854. st->st_nlink = info.nNumberOfLinks;
  855. if (info.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
  856. ++st->st_nlink;/* Add parent directory. */
  857. st->st_dev = info.dwVolumeSerialNumber;
  858. #endif
  859. st->st_uid = 0;
  860. st->st_gid = 0;
  861. st->st_rdev = 0;
  862. return (0);
  863. }
  864. static void
  865. copy_stat(struct stat *st, struct ustat *us)
  866. {
  867. st->st_atime = us->st_atime;
  868. st->st_ctime = us->st_ctime;
  869. st->st_mtime = us->st_mtime;
  870. st->st_gid = us->st_gid;
  871. st->st_ino = getino(us);
  872. st->st_mode = us->st_mode;
  873. st->st_nlink = us->st_nlink;
  874. st->st_size = us->st_size;
  875. st->st_uid = us->st_uid;
  876. st->st_dev = us->st_dev;
  877. st->st_rdev = us->st_rdev;
  878. }
  879. int
  880. la_fstat(int fd, struct stat *st)
  881. {
  882. struct ustat u;
  883. int ret;
  884. if (fd < 0) {
  885. errno = EBADF;
  886. return (-1);
  887. }
  888. ret = __hstat((HANDLE)_get_osfhandle(fd), &u);
  889. if (ret >= 0) {
  890. copy_stat(st, &u);
  891. if (u.st_mode & (S_IFCHR | S_IFIFO)) {
  892. st->st_dev = fd;
  893. st->st_rdev = fd;
  894. }
  895. }
  896. return (ret);
  897. }
  898. int
  899. la_stat(const char *path, struct stat *st)
  900. {
  901. HANDLE handle;
  902. struct ustat u;
  903. int ret;
  904. handle = la_CreateFile(path, 0, 0, NULL, OPEN_EXISTING,
  905. FILE_FLAG_BACKUP_SEMANTICS | FILE_ATTRIBUTE_READONLY,
  906. NULL);
  907. if (handle == INVALID_HANDLE_VALUE) {
  908. _dosmaperr(GetLastError());
  909. return (-1);
  910. }
  911. ret = __hstat(handle, &u);
  912. CloseHandle(handle);
  913. if (ret >= 0) {
  914. char *p;
  915. copy_stat(st, &u);
  916. p = strrchr(path, '.');
  917. if (p != NULL && strlen(p) == 4) {
  918. char exttype[4];
  919. ++ p;
  920. exttype[0] = toupper(*p++);
  921. exttype[1] = toupper(*p++);
  922. exttype[2] = toupper(*p++);
  923. exttype[3] = '\0';
  924. if (!strcmp(exttype, "EXE") || !strcmp(exttype, "CMD") ||
  925. !strcmp(exttype, "BAT") || !strcmp(exttype, "COM"))
  926. st->st_mode |= S_IXUSR | S_IXGRP | S_IXOTH;
  927. }
  928. }
  929. return (ret);
  930. }
  931. ssize_t
  932. la_write(int fd, const void *buf, size_t nbytes)
  933. {
  934. uint32_t bytes_written;
  935. #ifdef _WIN64
  936. if (nbytes > UINT32_MAX)
  937. nbytes = UINT32_MAX;
  938. #endif
  939. if (fd < 0) {
  940. errno = EBADF;
  941. return (-1);
  942. }
  943. if (!WriteFile((HANDLE)_get_osfhandle(fd), buf, (uint32_t)nbytes,
  944. &bytes_written, NULL)) {
  945. DWORD lasterr;
  946. lasterr = GetLastError();
  947. if (lasterr == ERROR_ACCESS_DENIED)
  948. errno = EBADF;
  949. else
  950. _dosmaperr(lasterr);
  951. return (-1);
  952. }
  953. return (bytes_written);
  954. }
  955. #ifndef LIST_H
  956. static int
  957. _is_privileged(HANDLE thandle, const char *sidlist[])
  958. {
  959. TOKEN_USER *tuser;
  960. TOKEN_GROUPS *tgrp;
  961. DWORD bytes;
  962. PSID psid;
  963. DWORD i, g;
  964. int member;
  965. psid = NULL;
  966. tuser = NULL;
  967. tgrp = NULL;
  968. member = 0;
  969. for (i = 0; sidlist[i] != NULL && member == 0; i++) {
  970. if (psid != NULL)
  971. LocalFree(psid);
  972. if (ConvertStringSidToSidA(sidlist[i], &psid) == 0) {
  973. errno = EPERM;
  974. return (-1);
  975. }
  976. if (tuser == NULL) {
  977. GetTokenInformation(thandle, TokenUser, NULL, 0, &bytes);
  978. tuser = malloc(bytes);
  979. if (tuser == NULL) {
  980. errno = ENOMEM;
  981. member = -1;
  982. break;
  983. }
  984. if (GetTokenInformation(thandle, TokenUser, tuser, bytes, &bytes) == 0) {
  985. errno = EPERM;
  986. member = -1;
  987. break;
  988. }
  989. }
  990. member = EqualSid(tuser->User.Sid, psid);
  991. if (member)
  992. break;
  993. if (tgrp == NULL) {
  994. GetTokenInformation(thandle, TokenGroups, NULL, 0, &bytes);
  995. tgrp = malloc(bytes);
  996. if (tgrp == NULL) {
  997. errno = ENOMEM;
  998. member = -1;
  999. break;
  1000. }
  1001. if (GetTokenInformation(thandle, TokenGroups, tgrp, bytes, &bytes) == 0) {
  1002. errno = EPERM;
  1003. member = -1;
  1004. break;
  1005. }
  1006. }
  1007. for (g = 0; g < tgrp->GroupCount; g++) {
  1008. member = EqualSid(tgrp->Groups[g].Sid, psid);
  1009. if (member)
  1010. break;
  1011. }
  1012. }
  1013. LocalFree(psid);
  1014. free(tuser);
  1015. free(tgrp);
  1016. return (member);
  1017. }
  1018. int
  1019. bsdtar_is_privileged(struct bsdtar *bsdtar)
  1020. {
  1021. HANDLE thandle;
  1022. int ret;
  1023. const char *sidlist[] = {
  1024. "S-1-5-32-544", /* Administrators */
  1025. "S-1-5-32-551", /* Backup Operators */
  1026. NULL
  1027. };
  1028. (void)bsdtar;/* UNUSED */
  1029. if (OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &thandle) == 0) {
  1030. bsdtar_warnc(bsdtar, EPERM, "Failed to check privilege");
  1031. return (0);
  1032. }
  1033. ret = _is_privileged(thandle, sidlist);
  1034. if (ret < 0) {
  1035. bsdtar_warnc(bsdtar, errno, "Failed to check privilege");
  1036. return (0);
  1037. }
  1038. return (ret);
  1039. }
  1040. /*
  1041. * Note: We should use wide-character for findng '\' character,
  1042. * a directory separator on Windows, because some character-set have
  1043. * been using the '\' character for a part of its multibyte character
  1044. * code.
  1045. */
  1046. static size_t
  1047. dir_len_w(const char *path)
  1048. {
  1049. wchar_t wc;
  1050. const char *p, *rp;
  1051. size_t al, l, size;
  1052. al = l = -1;
  1053. for (p = path; *p != '\0'; ++p) {
  1054. if (*p == '\\')
  1055. al = l = p - path;
  1056. else if (*p == '/')
  1057. al = p - path;
  1058. }
  1059. if (l == -1)
  1060. goto alen;
  1061. size = p - path;
  1062. rp = p = path;
  1063. while (*p != '\0') {
  1064. l = mbtowc(&wc, p, size);
  1065. if (l == -1)
  1066. goto alen;
  1067. if (l == 1 && (wc == L'/' || wc == L'\\'))
  1068. rp = p;
  1069. p += l;
  1070. size -= l;
  1071. }
  1072. return (rp - path + 1);
  1073. alen:
  1074. if (al == -1)
  1075. return (0);
  1076. return (al + 1);
  1077. }
  1078. /*
  1079. * Find file names and call write_hierarchy function.
  1080. */
  1081. void
  1082. write_hierarchy_win(struct bsdtar *bsdtar, struct archive *a,
  1083. const char *path, void (*write_hierarchy)(struct bsdtar *bsdtar,
  1084. struct archive *a, const char *path))
  1085. {
  1086. DIR *dir;
  1087. struct dirent *ent;
  1088. const char *r;
  1089. char *xpath;
  1090. size_t dl;
  1091. r = path;
  1092. while (*r != '\0' && *r != '*' && *r != '?')
  1093. ++r;
  1094. if (*r == '\0')
  1095. /* There aren't meta-characters '*' and '?' in path */
  1096. goto try_plain;
  1097. dir = opendir_findfile(path);
  1098. if (dir == NULL)
  1099. goto try_plain;
  1100. dl = dir_len_w(path);
  1101. xpath = malloc(dl + MAX_PATH);
  1102. if (xpath == NULL)
  1103. goto try_plain;
  1104. strncpy(xpath, path, dl);
  1105. while ((ent = readdir(dir)) != NULL) {
  1106. if (ent->d_name[0] == '.' && ent->d_name[1] == '\0')
  1107. continue;
  1108. if (ent->d_name[0] == '.' && ent->d_name[1] == '.' &&
  1109. ent->d_name[2] == '\0')
  1110. continue;
  1111. strcpy(&xpath[dl], ent->d_name);
  1112. write_hierarchy(bsdtar, a, xpath);
  1113. }
  1114. free(xpath);
  1115. closedir(dir);
  1116. return;
  1117. try_plain:
  1118. write_hierarchy(bsdtar, a, path);
  1119. }
  1120. #endif /* LIST_H */
  1121. #endif