/Modules/posixmodule.c

http://unladen-swallow.googlecode.com/ · C · 9117 lines · 7549 code · 929 blank · 639 comment · 1330 complexity · 45aba128b4b8ee359a4c42560351554e MD5 · raw file

Large files are truncated click here to view the full file

  1. /* POSIX module implementation */
  2. /* This file is also used for Windows NT/MS-Win and OS/2. In that case the
  3. module actually calls itself 'nt' or 'os2', not 'posix', and a few
  4. functions are either unimplemented or implemented differently. The source
  5. assumes that for Windows NT, the macro 'MS_WINDOWS' is defined independent
  6. of the compiler used. Different compilers define their own feature
  7. test macro, e.g. '__BORLANDC__' or '_MSC_VER'. For OS/2, the compiler
  8. independent macro PYOS_OS2 should be defined. On OS/2 the default
  9. compiler is assumed to be IBM's VisualAge C++ (VACPP). PYCC_GCC is used
  10. as the compiler specific macro for the EMX port of gcc to OS/2. */
  11. /* See also ../Dos/dosmodule.c */
  12. #ifdef __APPLE__
  13. /*
  14. * Step 1 of support for weak-linking a number of symbols existing on
  15. * OSX 10.4 and later, see the comment in the #ifdef __APPLE__ block
  16. * at the end of this file for more information.
  17. */
  18. # pragma weak lchown
  19. # pragma weak statvfs
  20. # pragma weak fstatvfs
  21. #endif /* __APPLE__ */
  22. #define PY_SSIZE_T_CLEAN
  23. #include "Python.h"
  24. #include "structseq.h"
  25. #if defined(__VMS)
  26. # include <unixio.h>
  27. #endif /* defined(__VMS) */
  28. #ifdef __cplusplus
  29. extern "C" {
  30. #endif
  31. PyDoc_STRVAR(posix__doc__,
  32. "This module provides access to operating system functionality that is\n\
  33. standardized by the C Standard and the POSIX standard (a thinly\n\
  34. disguised Unix interface). Refer to the library manual and\n\
  35. corresponding Unix manual entries for more information on calls.");
  36. #ifndef Py_USING_UNICODE
  37. /* This is used in signatures of functions. */
  38. #define Py_UNICODE void
  39. #endif
  40. #if defined(PYOS_OS2)
  41. #define INCL_DOS
  42. #define INCL_DOSERRORS
  43. #define INCL_DOSPROCESS
  44. #define INCL_NOPMAPI
  45. #include <os2.h>
  46. #if defined(PYCC_GCC)
  47. #include <ctype.h>
  48. #include <io.h>
  49. #include <stdio.h>
  50. #include <process.h>
  51. #endif
  52. #include "osdefs.h"
  53. #endif
  54. #ifdef HAVE_SYS_TYPES_H
  55. #include <sys/types.h>
  56. #endif /* HAVE_SYS_TYPES_H */
  57. #ifdef HAVE_SYS_STAT_H
  58. #include <sys/stat.h>
  59. #endif /* HAVE_SYS_STAT_H */
  60. #ifdef HAVE_SYS_WAIT_H
  61. #include <sys/wait.h> /* For WNOHANG */
  62. #endif
  63. #ifdef HAVE_SIGNAL_H
  64. #include <signal.h>
  65. #endif
  66. #ifdef HAVE_FCNTL_H
  67. #include <fcntl.h>
  68. #endif /* HAVE_FCNTL_H */
  69. #ifdef HAVE_GRP_H
  70. #include <grp.h>
  71. #endif
  72. #ifdef HAVE_SYSEXITS_H
  73. #include <sysexits.h>
  74. #endif /* HAVE_SYSEXITS_H */
  75. #ifdef HAVE_SYS_LOADAVG_H
  76. #include <sys/loadavg.h>
  77. #endif
  78. /* Various compilers have only certain posix functions */
  79. /* XXX Gosh I wish these were all moved into pyconfig.h */
  80. #if defined(PYCC_VACPP) && defined(PYOS_OS2)
  81. #include <process.h>
  82. #else
  83. #if defined(__WATCOMC__) && !defined(__QNX__) /* Watcom compiler */
  84. #define HAVE_GETCWD 1
  85. #define HAVE_OPENDIR 1
  86. #define HAVE_SYSTEM 1
  87. #if defined(__OS2__)
  88. #define HAVE_EXECV 1
  89. #define HAVE_WAIT 1
  90. #endif
  91. #include <process.h>
  92. #else
  93. #ifdef __BORLANDC__ /* Borland compiler */
  94. #define HAVE_EXECV 1
  95. #define HAVE_GETCWD 1
  96. #define HAVE_OPENDIR 1
  97. #define HAVE_PIPE 1
  98. #define HAVE_POPEN 1
  99. #define HAVE_SYSTEM 1
  100. #define HAVE_WAIT 1
  101. #else
  102. #ifdef _MSC_VER /* Microsoft compiler */
  103. #define HAVE_GETCWD 1
  104. #define HAVE_SPAWNV 1
  105. #define HAVE_EXECV 1
  106. #define HAVE_PIPE 1
  107. #define HAVE_POPEN 1
  108. #define HAVE_SYSTEM 1
  109. #define HAVE_CWAIT 1
  110. #define HAVE_FSYNC 1
  111. #define fsync _commit
  112. #else
  113. #if defined(PYOS_OS2) && defined(PYCC_GCC) || defined(__VMS)
  114. /* Everything needed is defined in PC/os2emx/pyconfig.h or vms/pyconfig.h */
  115. #else /* all other compilers */
  116. /* Unix functions that the configure script doesn't check for */
  117. #define HAVE_EXECV 1
  118. #define HAVE_FORK 1
  119. #if defined(__USLC__) && defined(__SCO_VERSION__) /* SCO UDK Compiler */
  120. #define HAVE_FORK1 1
  121. #endif
  122. #define HAVE_GETCWD 1
  123. #define HAVE_GETEGID 1
  124. #define HAVE_GETEUID 1
  125. #define HAVE_GETGID 1
  126. #define HAVE_GETPPID 1
  127. #define HAVE_GETUID 1
  128. #define HAVE_KILL 1
  129. #define HAVE_OPENDIR 1
  130. #define HAVE_PIPE 1
  131. #ifndef __rtems__
  132. #define HAVE_POPEN 1
  133. #endif
  134. #define HAVE_SYSTEM 1
  135. #define HAVE_WAIT 1
  136. #define HAVE_TTYNAME 1
  137. #endif /* PYOS_OS2 && PYCC_GCC && __VMS */
  138. #endif /* _MSC_VER */
  139. #endif /* __BORLANDC__ */
  140. #endif /* ! __WATCOMC__ || __QNX__ */
  141. #endif /* ! __IBMC__ */
  142. #ifndef _MSC_VER
  143. #if defined(__sgi)&&_COMPILER_VERSION>=700
  144. /* declare ctermid_r if compiling with MIPSPro 7.x in ANSI C mode
  145. (default) */
  146. extern char *ctermid_r(char *);
  147. #endif
  148. #ifndef HAVE_UNISTD_H
  149. #if defined(PYCC_VACPP)
  150. extern int mkdir(char *);
  151. #else
  152. #if ( defined(__WATCOMC__) || defined(_MSC_VER) ) && !defined(__QNX__)
  153. extern int mkdir(const char *);
  154. #else
  155. extern int mkdir(const char *, mode_t);
  156. #endif
  157. #endif
  158. #if defined(__IBMC__) || defined(__IBMCPP__)
  159. extern int chdir(char *);
  160. extern int rmdir(char *);
  161. #else
  162. extern int chdir(const char *);
  163. extern int rmdir(const char *);
  164. #endif
  165. #ifdef __BORLANDC__
  166. extern int chmod(const char *, int);
  167. #else
  168. extern int chmod(const char *, mode_t);
  169. #endif
  170. /*#ifdef HAVE_FCHMOD
  171. extern int fchmod(int, mode_t);
  172. #endif*/
  173. /*#ifdef HAVE_LCHMOD
  174. extern int lchmod(const char *, mode_t);
  175. #endif*/
  176. extern int chown(const char *, uid_t, gid_t);
  177. extern char *getcwd(char *, int);
  178. extern char *strerror(int);
  179. extern int link(const char *, const char *);
  180. extern int rename(const char *, const char *);
  181. extern int stat(const char *, struct stat *);
  182. extern int unlink(const char *);
  183. extern int pclose(FILE *);
  184. #ifdef HAVE_SYMLINK
  185. extern int symlink(const char *, const char *);
  186. #endif /* HAVE_SYMLINK */
  187. #ifdef HAVE_LSTAT
  188. extern int lstat(const char *, struct stat *);
  189. #endif /* HAVE_LSTAT */
  190. #endif /* !HAVE_UNISTD_H */
  191. #endif /* !_MSC_VER */
  192. #ifdef HAVE_UTIME_H
  193. #include <utime.h>
  194. #endif /* HAVE_UTIME_H */
  195. #ifdef HAVE_SYS_UTIME_H
  196. #include <sys/utime.h>
  197. #define HAVE_UTIME_H /* pretend we do for the rest of this file */
  198. #endif /* HAVE_SYS_UTIME_H */
  199. #ifdef HAVE_SYS_TIMES_H
  200. #include <sys/times.h>
  201. #endif /* HAVE_SYS_TIMES_H */
  202. #ifdef HAVE_SYS_PARAM_H
  203. #include <sys/param.h>
  204. #endif /* HAVE_SYS_PARAM_H */
  205. #ifdef HAVE_SYS_UTSNAME_H
  206. #include <sys/utsname.h>
  207. #endif /* HAVE_SYS_UTSNAME_H */
  208. #ifdef HAVE_DIRENT_H
  209. #include <dirent.h>
  210. #define NAMLEN(dirent) strlen((dirent)->d_name)
  211. #else
  212. #if defined(__WATCOMC__) && !defined(__QNX__)
  213. #include <direct.h>
  214. #define NAMLEN(dirent) strlen((dirent)->d_name)
  215. #else
  216. #define dirent direct
  217. #define NAMLEN(dirent) (dirent)->d_namlen
  218. #endif
  219. #ifdef HAVE_SYS_NDIR_H
  220. #include <sys/ndir.h>
  221. #endif
  222. #ifdef HAVE_SYS_DIR_H
  223. #include <sys/dir.h>
  224. #endif
  225. #ifdef HAVE_NDIR_H
  226. #include <ndir.h>
  227. #endif
  228. #endif
  229. #ifdef _MSC_VER
  230. #ifdef HAVE_DIRECT_H
  231. #include <direct.h>
  232. #endif
  233. #ifdef HAVE_IO_H
  234. #include <io.h>
  235. #endif
  236. #ifdef HAVE_PROCESS_H
  237. #include <process.h>
  238. #endif
  239. #include "osdefs.h"
  240. #include <windows.h>
  241. #include <shellapi.h> /* for ShellExecute() */
  242. #define popen _popen
  243. #define pclose _pclose
  244. #endif /* _MSC_VER */
  245. #if defined(PYCC_VACPP) && defined(PYOS_OS2)
  246. #include <io.h>
  247. #endif /* OS2 */
  248. #ifndef MAXPATHLEN
  249. #if defined(PATH_MAX) && PATH_MAX > 1024
  250. #define MAXPATHLEN PATH_MAX
  251. #else
  252. #define MAXPATHLEN 1024
  253. #endif
  254. #endif /* MAXPATHLEN */
  255. #ifdef UNION_WAIT
  256. /* Emulate some macros on systems that have a union instead of macros */
  257. #ifndef WIFEXITED
  258. #define WIFEXITED(u_wait) (!(u_wait).w_termsig && !(u_wait).w_coredump)
  259. #endif
  260. #ifndef WEXITSTATUS
  261. #define WEXITSTATUS(u_wait) (WIFEXITED(u_wait)?((u_wait).w_retcode):-1)
  262. #endif
  263. #ifndef WTERMSIG
  264. #define WTERMSIG(u_wait) ((u_wait).w_termsig)
  265. #endif
  266. #define WAIT_TYPE union wait
  267. #define WAIT_STATUS_INT(s) (s.w_status)
  268. #else /* !UNION_WAIT */
  269. #define WAIT_TYPE int
  270. #define WAIT_STATUS_INT(s) (s)
  271. #endif /* UNION_WAIT */
  272. /* Issue #1983: pid_t can be longer than a C long on some systems */
  273. #if !defined(SIZEOF_PID_T) || SIZEOF_PID_T == SIZEOF_INT
  274. #define PARSE_PID "i"
  275. #define PyLong_FromPid PyInt_FromLong
  276. #define PyLong_AsPid PyInt_AsLong
  277. #elif SIZEOF_PID_T == SIZEOF_LONG
  278. #define PARSE_PID "l"
  279. #define PyLong_FromPid PyInt_FromLong
  280. #define PyLong_AsPid PyInt_AsLong
  281. #elif defined(SIZEOF_LONG_LONG) && SIZEOF_PID_T == SIZEOF_LONG_LONG
  282. #define PARSE_PID "L"
  283. #define PyLong_FromPid PyLong_FromLongLong
  284. #define PyLong_AsPid PyInt_AsLongLong
  285. #else
  286. #error "sizeof(pid_t) is neither sizeof(int), sizeof(long) or sizeof(long long)"
  287. #endif /* SIZEOF_PID_T */
  288. /* Don't use the "_r" form if we don't need it (also, won't have a
  289. prototype for it, at least on Solaris -- maybe others as well?). */
  290. #if defined(HAVE_CTERMID_R) && defined(WITH_THREAD)
  291. #define USE_CTERMID_R
  292. #endif
  293. #if defined(HAVE_TMPNAM_R) && defined(WITH_THREAD)
  294. #define USE_TMPNAM_R
  295. #endif
  296. /* choose the appropriate stat and fstat functions and return structs */
  297. #undef STAT
  298. #if defined(MS_WIN64) || defined(MS_WINDOWS)
  299. # define STAT win32_stat
  300. # define FSTAT win32_fstat
  301. # define STRUCT_STAT struct win32_stat
  302. #else
  303. # define STAT stat
  304. # define FSTAT fstat
  305. # define STRUCT_STAT struct stat
  306. #endif
  307. #if defined(MAJOR_IN_MKDEV)
  308. #include <sys/mkdev.h>
  309. #else
  310. #if defined(MAJOR_IN_SYSMACROS)
  311. #include <sys/sysmacros.h>
  312. #endif
  313. #if defined(HAVE_MKNOD) && defined(HAVE_SYS_MKDEV_H)
  314. #include <sys/mkdev.h>
  315. #endif
  316. #endif
  317. /* Return a dictionary corresponding to the POSIX environment table */
  318. #ifdef WITH_NEXT_FRAMEWORK
  319. /* On Darwin/MacOSX a shared library or framework has no access to
  320. ** environ directly, we must obtain it with _NSGetEnviron().
  321. */
  322. #include <crt_externs.h>
  323. static char **environ;
  324. #elif !defined(_MSC_VER) && ( !defined(__WATCOMC__) || defined(__QNX__) )
  325. extern char **environ;
  326. #endif /* !_MSC_VER */
  327. static PyObject *
  328. convertenviron(void)
  329. {
  330. PyObject *d;
  331. char **e;
  332. d = PyDict_New();
  333. if (d == NULL)
  334. return NULL;
  335. #ifdef WITH_NEXT_FRAMEWORK
  336. if (environ == NULL)
  337. environ = *_NSGetEnviron();
  338. #endif
  339. if (environ == NULL)
  340. return d;
  341. /* This part ignores errors */
  342. for (e = environ; *e != NULL; e++) {
  343. PyObject *k;
  344. PyObject *v;
  345. char *p = strchr(*e, '=');
  346. if (p == NULL)
  347. continue;
  348. k = PyString_FromStringAndSize(*e, (int)(p-*e));
  349. if (k == NULL) {
  350. PyErr_Clear();
  351. continue;
  352. }
  353. v = PyString_FromString(p+1);
  354. if (v == NULL) {
  355. PyErr_Clear();
  356. Py_DECREF(k);
  357. continue;
  358. }
  359. if (PyDict_GetItem(d, k) == NULL) {
  360. if (PyDict_SetItem(d, k, v) != 0)
  361. PyErr_Clear();
  362. }
  363. Py_DECREF(k);
  364. Py_DECREF(v);
  365. }
  366. #if defined(PYOS_OS2)
  367. {
  368. APIRET rc;
  369. char buffer[1024]; /* OS/2 Provides a Documented Max of 1024 Chars */
  370. rc = DosQueryExtLIBPATH(buffer, BEGIN_LIBPATH);
  371. if (rc == NO_ERROR) { /* (not a type, envname is NOT 'BEGIN_LIBPATH') */
  372. PyObject *v = PyString_FromString(buffer);
  373. PyDict_SetItemString(d, "BEGINLIBPATH", v);
  374. Py_DECREF(v);
  375. }
  376. rc = DosQueryExtLIBPATH(buffer, END_LIBPATH);
  377. if (rc == NO_ERROR) { /* (not a typo, envname is NOT 'END_LIBPATH') */
  378. PyObject *v = PyString_FromString(buffer);
  379. PyDict_SetItemString(d, "ENDLIBPATH", v);
  380. Py_DECREF(v);
  381. }
  382. }
  383. #endif
  384. return d;
  385. }
  386. /* Set a POSIX-specific error from errno, and return NULL */
  387. static PyObject *
  388. posix_error(void)
  389. {
  390. return PyErr_SetFromErrno(PyExc_OSError);
  391. }
  392. static PyObject *
  393. posix_error_with_filename(char* name)
  394. {
  395. return PyErr_SetFromErrnoWithFilename(PyExc_OSError, name);
  396. }
  397. #ifdef Py_WIN_WIDE_FILENAMES
  398. static PyObject *
  399. posix_error_with_unicode_filename(Py_UNICODE* name)
  400. {
  401. return PyErr_SetFromErrnoWithUnicodeFilename(PyExc_OSError, name);
  402. }
  403. #endif /* Py_WIN_WIDE_FILENAMES */
  404. static PyObject *
  405. posix_error_with_allocated_filename(char* name)
  406. {
  407. PyObject *rc = PyErr_SetFromErrnoWithFilename(PyExc_OSError, name);
  408. PyMem_Free(name);
  409. return rc;
  410. }
  411. #ifdef MS_WINDOWS
  412. static PyObject *
  413. win32_error(char* function, char* filename)
  414. {
  415. /* XXX We should pass the function name along in the future.
  416. (_winreg.c also wants to pass the function name.)
  417. This would however require an additional param to the
  418. Windows error object, which is non-trivial.
  419. */
  420. errno = GetLastError();
  421. if (filename)
  422. return PyErr_SetFromWindowsErrWithFilename(errno, filename);
  423. else
  424. return PyErr_SetFromWindowsErr(errno);
  425. }
  426. #ifdef Py_WIN_WIDE_FILENAMES
  427. static PyObject *
  428. win32_error_unicode(char* function, Py_UNICODE* filename)
  429. {
  430. /* XXX - see win32_error for comments on 'function' */
  431. errno = GetLastError();
  432. if (filename)
  433. return PyErr_SetFromWindowsErrWithUnicodeFilename(errno, filename);
  434. else
  435. return PyErr_SetFromWindowsErr(errno);
  436. }
  437. static PyObject *_PyUnicode_FromFileSystemEncodedObject(register PyObject *obj)
  438. {
  439. }
  440. static int
  441. convert_to_unicode(PyObject **param)
  442. {
  443. if (PyUnicode_CheckExact(*param))
  444. Py_INCREF(*param);
  445. else if (PyUnicode_Check(*param))
  446. /* For a Unicode subtype that's not a Unicode object,
  447. return a true Unicode object with the same data. */
  448. *param = PyUnicode_FromUnicode(PyUnicode_AS_UNICODE(*param),
  449. PyUnicode_GET_SIZE(*param));
  450. else
  451. *param = PyUnicode_FromEncodedObject(*param,
  452. Py_FileSystemDefaultEncoding,
  453. "strict");
  454. return (*param) != NULL;
  455. }
  456. #endif /* Py_WIN_WIDE_FILENAMES */
  457. #endif
  458. #if defined(PYOS_OS2)
  459. /**********************************************************************
  460. * Helper Function to Trim and Format OS/2 Messages
  461. **********************************************************************/
  462. static void
  463. os2_formatmsg(char *msgbuf, int msglen, char *reason)
  464. {
  465. msgbuf[msglen] = '\0'; /* OS/2 Doesn't Guarantee a Terminator */
  466. if (strlen(msgbuf) > 0) { /* If Non-Empty Msg, Trim CRLF */
  467. char *lastc = &msgbuf[ strlen(msgbuf)-1 ];
  468. while (lastc > msgbuf && isspace(Py_CHARMASK(*lastc)))
  469. *lastc-- = '\0'; /* Trim Trailing Whitespace (CRLF) */
  470. }
  471. /* Add Optional Reason Text */
  472. if (reason) {
  473. strcat(msgbuf, " : ");
  474. strcat(msgbuf, reason);
  475. }
  476. }
  477. /**********************************************************************
  478. * Decode an OS/2 Operating System Error Code
  479. *
  480. * A convenience function to lookup an OS/2 error code and return a
  481. * text message we can use to raise a Python exception.
  482. *
  483. * Notes:
  484. * The messages for errors returned from the OS/2 kernel reside in
  485. * the file OSO001.MSG in the \OS2 directory hierarchy.
  486. *
  487. **********************************************************************/
  488. static char *
  489. os2_strerror(char *msgbuf, int msgbuflen, int errorcode, char *reason)
  490. {
  491. APIRET rc;
  492. ULONG msglen;
  493. /* Retrieve Kernel-Related Error Message from OSO001.MSG File */
  494. Py_BEGIN_ALLOW_THREADS
  495. rc = DosGetMessage(NULL, 0, msgbuf, msgbuflen,
  496. errorcode, "oso001.msg", &msglen);
  497. Py_END_ALLOW_THREADS
  498. if (rc == NO_ERROR)
  499. os2_formatmsg(msgbuf, msglen, reason);
  500. else
  501. PyOS_snprintf(msgbuf, msgbuflen,
  502. "unknown OS error #%d", errorcode);
  503. return msgbuf;
  504. }
  505. /* Set an OS/2-specific error and return NULL. OS/2 kernel
  506. errors are not in a global variable e.g. 'errno' nor are
  507. they congruent with posix error numbers. */
  508. static PyObject * os2_error(int code)
  509. {
  510. char text[1024];
  511. PyObject *v;
  512. os2_strerror(text, sizeof(text), code, "");
  513. v = Py_BuildValue("(is)", code, text);
  514. if (v != NULL) {
  515. PyErr_SetObject(PyExc_OSError, v);
  516. Py_DECREF(v);
  517. }
  518. return NULL; /* Signal to Python that an Exception is Pending */
  519. }
  520. #endif /* OS2 */
  521. /* POSIX generic methods */
  522. static PyObject *
  523. posix_fildes(PyObject *fdobj, int (*func)(int))
  524. {
  525. int fd;
  526. int res;
  527. fd = PyObject_AsFileDescriptor(fdobj);
  528. if (fd < 0)
  529. return NULL;
  530. Py_BEGIN_ALLOW_THREADS
  531. res = (*func)(fd);
  532. Py_END_ALLOW_THREADS
  533. if (res < 0)
  534. return posix_error();
  535. Py_INCREF(Py_None);
  536. return Py_None;
  537. }
  538. #ifdef Py_WIN_WIDE_FILENAMES
  539. static int
  540. unicode_file_names(void)
  541. {
  542. static int canusewide = -1;
  543. if (canusewide == -1) {
  544. /* As per doc for ::GetVersion(), this is the correct test for
  545. the Windows NT family. */
  546. canusewide = (GetVersion() < 0x80000000) ? 1 : 0;
  547. }
  548. return canusewide;
  549. }
  550. #endif
  551. static PyObject *
  552. posix_1str(PyObject *args, char *format, int (*func)(const char*))
  553. {
  554. char *path1 = NULL;
  555. int res;
  556. if (!PyArg_ParseTuple(args, format,
  557. Py_FileSystemDefaultEncoding, &path1))
  558. return NULL;
  559. Py_BEGIN_ALLOW_THREADS
  560. res = (*func)(path1);
  561. Py_END_ALLOW_THREADS
  562. if (res < 0)
  563. return posix_error_with_allocated_filename(path1);
  564. PyMem_Free(path1);
  565. Py_INCREF(Py_None);
  566. return Py_None;
  567. }
  568. static PyObject *
  569. posix_2str(PyObject *args,
  570. char *format,
  571. int (*func)(const char *, const char *))
  572. {
  573. char *path1 = NULL, *path2 = NULL;
  574. int res;
  575. if (!PyArg_ParseTuple(args, format,
  576. Py_FileSystemDefaultEncoding, &path1,
  577. Py_FileSystemDefaultEncoding, &path2))
  578. return NULL;
  579. Py_BEGIN_ALLOW_THREADS
  580. res = (*func)(path1, path2);
  581. Py_END_ALLOW_THREADS
  582. PyMem_Free(path1);
  583. PyMem_Free(path2);
  584. if (res != 0)
  585. /* XXX how to report both path1 and path2??? */
  586. return posix_error();
  587. Py_INCREF(Py_None);
  588. return Py_None;
  589. }
  590. #ifdef Py_WIN_WIDE_FILENAMES
  591. static PyObject*
  592. win32_1str(PyObject* args, char* func,
  593. char* format, BOOL (__stdcall *funcA)(LPCSTR),
  594. char* wformat, BOOL (__stdcall *funcW)(LPWSTR))
  595. {
  596. PyObject *uni;
  597. char *ansi;
  598. BOOL result;
  599. if (unicode_file_names()) {
  600. if (!PyArg_ParseTuple(args, wformat, &uni))
  601. PyErr_Clear();
  602. else {
  603. Py_BEGIN_ALLOW_THREADS
  604. result = funcW(PyUnicode_AsUnicode(uni));
  605. Py_END_ALLOW_THREADS
  606. if (!result)
  607. return win32_error_unicode(func, PyUnicode_AsUnicode(uni));
  608. Py_INCREF(Py_None);
  609. return Py_None;
  610. }
  611. }
  612. if (!PyArg_ParseTuple(args, format, &ansi))
  613. return NULL;
  614. Py_BEGIN_ALLOW_THREADS
  615. result = funcA(ansi);
  616. Py_END_ALLOW_THREADS
  617. if (!result)
  618. return win32_error(func, ansi);
  619. Py_INCREF(Py_None);
  620. return Py_None;
  621. }
  622. /* This is a reimplementation of the C library's chdir function,
  623. but one that produces Win32 errors instead of DOS error codes.
  624. chdir is essentially a wrapper around SetCurrentDirectory; however,
  625. it also needs to set "magic" environment variables indicating
  626. the per-drive current directory, which are of the form =<drive>: */
  627. BOOL __stdcall
  628. win32_chdir(LPCSTR path)
  629. {
  630. char new_path[MAX_PATH+1];
  631. int result;
  632. char env[4] = "=x:";
  633. if(!SetCurrentDirectoryA(path))
  634. return FALSE;
  635. result = GetCurrentDirectoryA(MAX_PATH+1, new_path);
  636. if (!result)
  637. return FALSE;
  638. /* In the ANSI API, there should not be any paths longer
  639. than MAX_PATH. */
  640. assert(result <= MAX_PATH+1);
  641. if (strncmp(new_path, "\\\\", 2) == 0 ||
  642. strncmp(new_path, "//", 2) == 0)
  643. /* UNC path, nothing to do. */
  644. return TRUE;
  645. env[1] = new_path[0];
  646. return SetEnvironmentVariableA(env, new_path);
  647. }
  648. /* The Unicode version differs from the ANSI version
  649. since the current directory might exceed MAX_PATH characters */
  650. BOOL __stdcall
  651. win32_wchdir(LPCWSTR path)
  652. {
  653. wchar_t _new_path[MAX_PATH+1], *new_path = _new_path;
  654. int result;
  655. wchar_t env[4] = L"=x:";
  656. if(!SetCurrentDirectoryW(path))
  657. return FALSE;
  658. result = GetCurrentDirectoryW(MAX_PATH+1, new_path);
  659. if (!result)
  660. return FALSE;
  661. if (result > MAX_PATH+1) {
  662. new_path = malloc(result * sizeof(wchar_t));
  663. if (!new_path) {
  664. SetLastError(ERROR_OUTOFMEMORY);
  665. return FALSE;
  666. }
  667. result = GetCurrentDirectoryW(result, new_path);
  668. if (!result) {
  669. free(new_path);
  670. return FALSE;
  671. }
  672. }
  673. if (wcsncmp(new_path, L"\\\\", 2) == 0 ||
  674. wcsncmp(new_path, L"//", 2) == 0)
  675. /* UNC path, nothing to do. */
  676. return TRUE;
  677. env[1] = new_path[0];
  678. result = SetEnvironmentVariableW(env, new_path);
  679. if (new_path != _new_path)
  680. free(new_path);
  681. return result;
  682. }
  683. #endif
  684. #ifdef MS_WINDOWS
  685. /* The CRT of Windows has a number of flaws wrt. its stat() implementation:
  686. - time stamps are restricted to second resolution
  687. - file modification times suffer from forth-and-back conversions between
  688. UTC and local time
  689. Therefore, we implement our own stat, based on the Win32 API directly.
  690. */
  691. #define HAVE_STAT_NSEC 1
  692. struct win32_stat{
  693. int st_dev;
  694. __int64 st_ino;
  695. unsigned short st_mode;
  696. int st_nlink;
  697. int st_uid;
  698. int st_gid;
  699. int st_rdev;
  700. __int64 st_size;
  701. int st_atime;
  702. int st_atime_nsec;
  703. int st_mtime;
  704. int st_mtime_nsec;
  705. int st_ctime;
  706. int st_ctime_nsec;
  707. };
  708. static __int64 secs_between_epochs = 11644473600; /* Seconds between 1.1.1601 and 1.1.1970 */
  709. static void
  710. FILE_TIME_to_time_t_nsec(FILETIME *in_ptr, int *time_out, int* nsec_out)
  711. {
  712. /* XXX endianness. Shouldn't matter, as all Windows implementations are little-endian */
  713. /* Cannot simply cast and dereference in_ptr,
  714. since it might not be aligned properly */
  715. __int64 in;
  716. memcpy(&in, in_ptr, sizeof(in));
  717. *nsec_out = (int)(in % 10000000) * 100; /* FILETIME is in units of 100 nsec. */
  718. /* XXX Win32 supports time stamps past 2038; we currently don't */
  719. *time_out = Py_SAFE_DOWNCAST((in / 10000000) - secs_between_epochs, __int64, int);
  720. }
  721. static void
  722. time_t_to_FILE_TIME(int time_in, int nsec_in, FILETIME *out_ptr)
  723. {
  724. /* XXX endianness */
  725. __int64 out;
  726. out = time_in + secs_between_epochs;
  727. out = out * 10000000 + nsec_in / 100;
  728. memcpy(out_ptr, &out, sizeof(out));
  729. }
  730. /* Below, we *know* that ugo+r is 0444 */
  731. #if _S_IREAD != 0400
  732. #error Unsupported C library
  733. #endif
  734. static int
  735. attributes_to_mode(DWORD attr)
  736. {
  737. int m = 0;
  738. if (attr & FILE_ATTRIBUTE_DIRECTORY)
  739. m |= _S_IFDIR | 0111; /* IFEXEC for user,group,other */
  740. else
  741. m |= _S_IFREG;
  742. if (attr & FILE_ATTRIBUTE_READONLY)
  743. m |= 0444;
  744. else
  745. m |= 0666;
  746. return m;
  747. }
  748. static int
  749. attribute_data_to_stat(WIN32_FILE_ATTRIBUTE_DATA *info, struct win32_stat *result)
  750. {
  751. memset(result, 0, sizeof(*result));
  752. result->st_mode = attributes_to_mode(info->dwFileAttributes);
  753. result->st_size = (((__int64)info->nFileSizeHigh)<<32) + info->nFileSizeLow;
  754. FILE_TIME_to_time_t_nsec(&info->ftCreationTime, &result->st_ctime, &result->st_ctime_nsec);
  755. FILE_TIME_to_time_t_nsec(&info->ftLastWriteTime, &result->st_mtime, &result->st_mtime_nsec);
  756. FILE_TIME_to_time_t_nsec(&info->ftLastAccessTime, &result->st_atime, &result->st_atime_nsec);
  757. return 0;
  758. }
  759. /* Emulate GetFileAttributesEx[AW] on Windows 95 */
  760. static int checked = 0;
  761. static BOOL (CALLBACK *gfaxa)(LPCSTR, GET_FILEEX_INFO_LEVELS, LPVOID);
  762. static BOOL (CALLBACK *gfaxw)(LPCWSTR, GET_FILEEX_INFO_LEVELS, LPVOID);
  763. static void
  764. check_gfax()
  765. {
  766. HINSTANCE hKernel32;
  767. if (checked)
  768. return;
  769. checked = 1;
  770. hKernel32 = GetModuleHandle("KERNEL32");
  771. *(FARPROC*)&gfaxa = GetProcAddress(hKernel32, "GetFileAttributesExA");
  772. *(FARPROC*)&gfaxw = GetProcAddress(hKernel32, "GetFileAttributesExW");
  773. }
  774. static BOOL
  775. attributes_from_dir(LPCSTR pszFile, LPWIN32_FILE_ATTRIBUTE_DATA pfad)
  776. {
  777. HANDLE hFindFile;
  778. WIN32_FIND_DATAA FileData;
  779. hFindFile = FindFirstFileA(pszFile, &FileData);
  780. if (hFindFile == INVALID_HANDLE_VALUE)
  781. return FALSE;
  782. FindClose(hFindFile);
  783. pfad->dwFileAttributes = FileData.dwFileAttributes;
  784. pfad->ftCreationTime = FileData.ftCreationTime;
  785. pfad->ftLastAccessTime = FileData.ftLastAccessTime;
  786. pfad->ftLastWriteTime = FileData.ftLastWriteTime;
  787. pfad->nFileSizeHigh = FileData.nFileSizeHigh;
  788. pfad->nFileSizeLow = FileData.nFileSizeLow;
  789. return TRUE;
  790. }
  791. static BOOL
  792. attributes_from_dir_w(LPCWSTR pszFile, LPWIN32_FILE_ATTRIBUTE_DATA pfad)
  793. {
  794. HANDLE hFindFile;
  795. WIN32_FIND_DATAW FileData;
  796. hFindFile = FindFirstFileW(pszFile, &FileData);
  797. if (hFindFile == INVALID_HANDLE_VALUE)
  798. return FALSE;
  799. FindClose(hFindFile);
  800. pfad->dwFileAttributes = FileData.dwFileAttributes;
  801. pfad->ftCreationTime = FileData.ftCreationTime;
  802. pfad->ftLastAccessTime = FileData.ftLastAccessTime;
  803. pfad->ftLastWriteTime = FileData.ftLastWriteTime;
  804. pfad->nFileSizeHigh = FileData.nFileSizeHigh;
  805. pfad->nFileSizeLow = FileData.nFileSizeLow;
  806. return TRUE;
  807. }
  808. static BOOL WINAPI
  809. Py_GetFileAttributesExA(LPCSTR pszFile,
  810. GET_FILEEX_INFO_LEVELS level,
  811. LPVOID pv)
  812. {
  813. BOOL result;
  814. LPWIN32_FILE_ATTRIBUTE_DATA pfad = pv;
  815. /* First try to use the system's implementation, if that is
  816. available and either succeeds to gives an error other than
  817. that it isn't implemented. */
  818. check_gfax();
  819. if (gfaxa) {
  820. result = gfaxa(pszFile, level, pv);
  821. if (result || GetLastError() != ERROR_CALL_NOT_IMPLEMENTED)
  822. return result;
  823. }
  824. /* It's either not present, or not implemented.
  825. Emulate using FindFirstFile. */
  826. if (level != GetFileExInfoStandard) {
  827. SetLastError(ERROR_INVALID_PARAMETER);
  828. return FALSE;
  829. }
  830. /* Use GetFileAttributes to validate that the file name
  831. does not contain wildcards (which FindFirstFile would
  832. accept). */
  833. if (GetFileAttributesA(pszFile) == 0xFFFFFFFF)
  834. return FALSE;
  835. return attributes_from_dir(pszFile, pfad);
  836. }
  837. static BOOL WINAPI
  838. Py_GetFileAttributesExW(LPCWSTR pszFile,
  839. GET_FILEEX_INFO_LEVELS level,
  840. LPVOID pv)
  841. {
  842. BOOL result;
  843. LPWIN32_FILE_ATTRIBUTE_DATA pfad = pv;
  844. /* First try to use the system's implementation, if that is
  845. available and either succeeds to gives an error other than
  846. that it isn't implemented. */
  847. check_gfax();
  848. if (gfaxa) {
  849. result = gfaxw(pszFile, level, pv);
  850. if (result || GetLastError() != ERROR_CALL_NOT_IMPLEMENTED)
  851. return result;
  852. }
  853. /* It's either not present, or not implemented.
  854. Emulate using FindFirstFile. */
  855. if (level != GetFileExInfoStandard) {
  856. SetLastError(ERROR_INVALID_PARAMETER);
  857. return FALSE;
  858. }
  859. /* Use GetFileAttributes to validate that the file name
  860. does not contain wildcards (which FindFirstFile would
  861. accept). */
  862. if (GetFileAttributesW(pszFile) == 0xFFFFFFFF)
  863. return FALSE;
  864. return attributes_from_dir_w(pszFile, pfad);
  865. }
  866. static int
  867. win32_stat(const char* path, struct win32_stat *result)
  868. {
  869. WIN32_FILE_ATTRIBUTE_DATA info;
  870. int code;
  871. char *dot;
  872. /* XXX not supported on Win95 and NT 3.x */
  873. if (!Py_GetFileAttributesExA(path, GetFileExInfoStandard, &info)) {
  874. if (GetLastError() != ERROR_SHARING_VIOLATION) {
  875. /* Protocol violation: we explicitly clear errno, instead of
  876. setting it to a POSIX error. Callers should use GetLastError. */
  877. errno = 0;
  878. return -1;
  879. } else {
  880. /* Could not get attributes on open file. Fall back to
  881. reading the directory. */
  882. if (!attributes_from_dir(path, &info)) {
  883. /* Very strange. This should not fail now */
  884. errno = 0;
  885. return -1;
  886. }
  887. }
  888. }
  889. code = attribute_data_to_stat(&info, result);
  890. if (code != 0)
  891. return code;
  892. /* Set S_IFEXEC if it is an .exe, .bat, ... */
  893. dot = strrchr(path, '.');
  894. if (dot) {
  895. if (stricmp(dot, ".bat") == 0 ||
  896. stricmp(dot, ".cmd") == 0 ||
  897. stricmp(dot, ".exe") == 0 ||
  898. stricmp(dot, ".com") == 0)
  899. result->st_mode |= 0111;
  900. }
  901. return code;
  902. }
  903. static int
  904. win32_wstat(const wchar_t* path, struct win32_stat *result)
  905. {
  906. int code;
  907. const wchar_t *dot;
  908. WIN32_FILE_ATTRIBUTE_DATA info;
  909. /* XXX not supported on Win95 and NT 3.x */
  910. if (!Py_GetFileAttributesExW(path, GetFileExInfoStandard, &info)) {
  911. if (GetLastError() != ERROR_SHARING_VIOLATION) {
  912. /* Protocol violation: we explicitly clear errno, instead of
  913. setting it to a POSIX error. Callers should use GetLastError. */
  914. errno = 0;
  915. return -1;
  916. } else {
  917. /* Could not get attributes on open file. Fall back to
  918. reading the directory. */
  919. if (!attributes_from_dir_w(path, &info)) {
  920. /* Very strange. This should not fail now */
  921. errno = 0;
  922. return -1;
  923. }
  924. }
  925. }
  926. code = attribute_data_to_stat(&info, result);
  927. if (code < 0)
  928. return code;
  929. /* Set IFEXEC if it is an .exe, .bat, ... */
  930. dot = wcsrchr(path, '.');
  931. if (dot) {
  932. if (_wcsicmp(dot, L".bat") == 0 ||
  933. _wcsicmp(dot, L".cmd") == 0 ||
  934. _wcsicmp(dot, L".exe") == 0 ||
  935. _wcsicmp(dot, L".com") == 0)
  936. result->st_mode |= 0111;
  937. }
  938. return code;
  939. }
  940. static int
  941. win32_fstat(int file_number, struct win32_stat *result)
  942. {
  943. BY_HANDLE_FILE_INFORMATION info;
  944. HANDLE h;
  945. int type;
  946. h = (HANDLE)_get_osfhandle(file_number);
  947. /* Protocol violation: we explicitly clear errno, instead of
  948. setting it to a POSIX error. Callers should use GetLastError. */
  949. errno = 0;
  950. if (h == INVALID_HANDLE_VALUE) {
  951. /* This is really a C library error (invalid file handle).
  952. We set the Win32 error to the closes one matching. */
  953. SetLastError(ERROR_INVALID_HANDLE);
  954. return -1;
  955. }
  956. memset(result, 0, sizeof(*result));
  957. type = GetFileType(h);
  958. if (type == FILE_TYPE_UNKNOWN) {
  959. DWORD error = GetLastError();
  960. if (error != 0) {
  961. return -1;
  962. }
  963. /* else: valid but unknown file */
  964. }
  965. if (type != FILE_TYPE_DISK) {
  966. if (type == FILE_TYPE_CHAR)
  967. result->st_mode = _S_IFCHR;
  968. else if (type == FILE_TYPE_PIPE)
  969. result->st_mode = _S_IFIFO;
  970. return 0;
  971. }
  972. if (!GetFileInformationByHandle(h, &info)) {
  973. return -1;
  974. }
  975. /* similar to stat() */
  976. result->st_mode = attributes_to_mode(info.dwFileAttributes);
  977. result->st_size = (((__int64)info.nFileSizeHigh)<<32) + info.nFileSizeLow;
  978. FILE_TIME_to_time_t_nsec(&info.ftCreationTime, &result->st_ctime, &result->st_ctime_nsec);
  979. FILE_TIME_to_time_t_nsec(&info.ftLastWriteTime, &result->st_mtime, &result->st_mtime_nsec);
  980. FILE_TIME_to_time_t_nsec(&info.ftLastAccessTime, &result->st_atime, &result->st_atime_nsec);
  981. /* specific to fstat() */
  982. result->st_nlink = info.nNumberOfLinks;
  983. result->st_ino = (((__int64)info.nFileIndexHigh)<<32) + info.nFileIndexLow;
  984. return 0;
  985. }
  986. #endif /* MS_WINDOWS */
  987. PyDoc_STRVAR(stat_result__doc__,
  988. "stat_result: Result from stat or lstat.\n\n\
  989. This object may be accessed either as a tuple of\n\
  990. (mode, ino, dev, nlink, uid, gid, size, atime, mtime, ctime)\n\
  991. or via the attributes st_mode, st_ino, st_dev, st_nlink, st_uid, and so on.\n\
  992. \n\
  993. Posix/windows: If your platform supports st_blksize, st_blocks, st_rdev,\n\
  994. or st_flags, they are available as attributes only.\n\
  995. \n\
  996. See os.stat for more information.");
  997. static PyStructSequence_Field stat_result_fields[] = {
  998. {"st_mode", "protection bits"},
  999. {"st_ino", "inode"},
  1000. {"st_dev", "device"},
  1001. {"st_nlink", "number of hard links"},
  1002. {"st_uid", "user ID of owner"},
  1003. {"st_gid", "group ID of owner"},
  1004. {"st_size", "total size, in bytes"},
  1005. /* The NULL is replaced with PyStructSequence_UnnamedField later. */
  1006. {NULL, "integer time of last access"},
  1007. {NULL, "integer time of last modification"},
  1008. {NULL, "integer time of last change"},
  1009. {"st_atime", "time of last access"},
  1010. {"st_mtime", "time of last modification"},
  1011. {"st_ctime", "time of last change"},
  1012. #ifdef HAVE_STRUCT_STAT_ST_BLKSIZE
  1013. {"st_blksize", "blocksize for filesystem I/O"},
  1014. #endif
  1015. #ifdef HAVE_STRUCT_STAT_ST_BLOCKS
  1016. {"st_blocks", "number of blocks allocated"},
  1017. #endif
  1018. #ifdef HAVE_STRUCT_STAT_ST_RDEV
  1019. {"st_rdev", "device type (if inode device)"},
  1020. #endif
  1021. #ifdef HAVE_STRUCT_STAT_ST_FLAGS
  1022. {"st_flags", "user defined flags for file"},
  1023. #endif
  1024. #ifdef HAVE_STRUCT_STAT_ST_GEN
  1025. {"st_gen", "generation number"},
  1026. #endif
  1027. #ifdef HAVE_STRUCT_STAT_ST_BIRTHTIME
  1028. {"st_birthtime", "time of creation"},
  1029. #endif
  1030. {0}
  1031. };
  1032. #ifdef HAVE_STRUCT_STAT_ST_BLKSIZE
  1033. #define ST_BLKSIZE_IDX 13
  1034. #else
  1035. #define ST_BLKSIZE_IDX 12
  1036. #endif
  1037. #ifdef HAVE_STRUCT_STAT_ST_BLOCKS
  1038. #define ST_BLOCKS_IDX (ST_BLKSIZE_IDX+1)
  1039. #else
  1040. #define ST_BLOCKS_IDX ST_BLKSIZE_IDX
  1041. #endif
  1042. #ifdef HAVE_STRUCT_STAT_ST_RDEV
  1043. #define ST_RDEV_IDX (ST_BLOCKS_IDX+1)
  1044. #else
  1045. #define ST_RDEV_IDX ST_BLOCKS_IDX
  1046. #endif
  1047. #ifdef HAVE_STRUCT_STAT_ST_FLAGS
  1048. #define ST_FLAGS_IDX (ST_RDEV_IDX+1)
  1049. #else
  1050. #define ST_FLAGS_IDX ST_RDEV_IDX
  1051. #endif
  1052. #ifdef HAVE_STRUCT_STAT_ST_GEN
  1053. #define ST_GEN_IDX (ST_FLAGS_IDX+1)
  1054. #else
  1055. #define ST_GEN_IDX ST_FLAGS_IDX
  1056. #endif
  1057. #ifdef HAVE_STRUCT_STAT_ST_BIRTHTIME
  1058. #define ST_BIRTHTIME_IDX (ST_GEN_IDX+1)
  1059. #else
  1060. #define ST_BIRTHTIME_IDX ST_GEN_IDX
  1061. #endif
  1062. static PyStructSequence_Desc stat_result_desc = {
  1063. "stat_result", /* name */
  1064. stat_result__doc__, /* doc */
  1065. stat_result_fields,
  1066. 10
  1067. };
  1068. PyDoc_STRVAR(statvfs_result__doc__,
  1069. "statvfs_result: Result from statvfs or fstatvfs.\n\n\
  1070. This object may be accessed either as a tuple of\n\
  1071. (bsize, frsize, blocks, bfree, bavail, files, ffree, favail, flag, namemax),\n\
  1072. or via the attributes f_bsize, f_frsize, f_blocks, f_bfree, and so on.\n\
  1073. \n\
  1074. See os.statvfs for more information.");
  1075. static PyStructSequence_Field statvfs_result_fields[] = {
  1076. {"f_bsize", },
  1077. {"f_frsize", },
  1078. {"f_blocks", },
  1079. {"f_bfree", },
  1080. {"f_bavail", },
  1081. {"f_files", },
  1082. {"f_ffree", },
  1083. {"f_favail", },
  1084. {"f_flag", },
  1085. {"f_namemax",},
  1086. {0}
  1087. };
  1088. static PyStructSequence_Desc statvfs_result_desc = {
  1089. "statvfs_result", /* name */
  1090. statvfs_result__doc__, /* doc */
  1091. statvfs_result_fields,
  1092. 10
  1093. };
  1094. static int initialized;
  1095. static PyTypeObject StatResultType;
  1096. static PyTypeObject StatVFSResultType;
  1097. static newfunc structseq_new;
  1098. static PyObject *
  1099. statresult_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
  1100. {
  1101. PyStructSequence *result;
  1102. int i;
  1103. result = (PyStructSequence*)structseq_new(type, args, kwds);
  1104. if (!result)
  1105. return NULL;
  1106. /* If we have been initialized from a tuple,
  1107. st_?time might be set to None. Initialize it
  1108. from the int slots. */
  1109. for (i = 7; i <= 9; i++) {
  1110. if (result->ob_item[i+3] == Py_None) {
  1111. Py_DECREF(Py_None);
  1112. Py_INCREF(result->ob_item[i]);
  1113. result->ob_item[i+3] = result->ob_item[i];
  1114. }
  1115. }
  1116. return (PyObject*)result;
  1117. }
  1118. /* If true, st_?time is float. */
  1119. static int _stat_float_times = 1;
  1120. PyDoc_STRVAR(stat_float_times__doc__,
  1121. "stat_float_times([newval]) -> oldval\n\n\
  1122. Determine whether os.[lf]stat represents time stamps as float objects.\n\
  1123. If newval is True, future calls to stat() return floats, if it is False,\n\
  1124. future calls return ints. \n\
  1125. If newval is omitted, return the current setting.\n");
  1126. static PyObject*
  1127. stat_float_times(PyObject* self, PyObject *args)
  1128. {
  1129. int newval = -1;
  1130. if (!PyArg_ParseTuple(args, "|i:stat_float_times", &newval))
  1131. return NULL;
  1132. if (newval == -1)
  1133. /* Return old value */
  1134. return PyBool_FromLong(_stat_float_times);
  1135. _stat_float_times = newval;
  1136. Py_INCREF(Py_None);
  1137. return Py_None;
  1138. }
  1139. static void
  1140. fill_time(PyObject *v, int index, time_t sec, unsigned long nsec)
  1141. {
  1142. PyObject *fval,*ival;
  1143. #if SIZEOF_TIME_T > SIZEOF_LONG
  1144. ival = PyLong_FromLongLong((PY_LONG_LONG)sec);
  1145. #else
  1146. ival = PyInt_FromLong((long)sec);
  1147. #endif
  1148. if (!ival)
  1149. return;
  1150. if (_stat_float_times) {
  1151. fval = PyFloat_FromDouble(sec + 1e-9*nsec);
  1152. } else {
  1153. fval = ival;
  1154. Py_INCREF(fval);
  1155. }
  1156. PyStructSequence_SET_ITEM(v, index, ival);
  1157. PyStructSequence_SET_ITEM(v, index+3, fval);
  1158. }
  1159. /* pack a system stat C structure into the Python stat tuple
  1160. (used by posix_stat() and posix_fstat()) */
  1161. static PyObject*
  1162. _pystat_fromstructstat(STRUCT_STAT *st)
  1163. {
  1164. unsigned long ansec, mnsec, cnsec;
  1165. PyObject *v = PyStructSequence_New(&StatResultType);
  1166. if (v == NULL)
  1167. return NULL;
  1168. PyStructSequence_SET_ITEM(v, 0, PyInt_FromLong((long)st->st_mode));
  1169. #ifdef HAVE_LARGEFILE_SUPPORT
  1170. PyStructSequence_SET_ITEM(v, 1,
  1171. PyLong_FromLongLong((PY_LONG_LONG)st->st_ino));
  1172. #else
  1173. PyStructSequence_SET_ITEM(v, 1, PyInt_FromLong((long)st->st_ino));
  1174. #endif
  1175. #if defined(HAVE_LONG_LONG) && !defined(MS_WINDOWS)
  1176. PyStructSequence_SET_ITEM(v, 2,
  1177. PyLong_FromLongLong((PY_LONG_LONG)st->st_dev));
  1178. #else
  1179. PyStructSequence_SET_ITEM(v, 2, PyInt_FromLong((long)st->st_dev));
  1180. #endif
  1181. PyStructSequence_SET_ITEM(v, 3, PyInt_FromLong((long)st->st_nlink));
  1182. PyStructSequence_SET_ITEM(v, 4, PyInt_FromLong((long)st->st_uid));
  1183. PyStructSequence_SET_ITEM(v, 5, PyInt_FromLong((long)st->st_gid));
  1184. #ifdef HAVE_LARGEFILE_SUPPORT
  1185. PyStructSequence_SET_ITEM(v, 6,
  1186. PyLong_FromLongLong((PY_LONG_LONG)st->st_size));
  1187. #else
  1188. PyStructSequence_SET_ITEM(v, 6, PyInt_FromLong(st->st_size));
  1189. #endif
  1190. #if defined(HAVE_STAT_TV_NSEC)
  1191. ansec = st->st_atim.tv_nsec;
  1192. mnsec = st->st_mtim.tv_nsec;
  1193. cnsec = st->st_ctim.tv_nsec;
  1194. #elif defined(HAVE_STAT_TV_NSEC2)
  1195. ansec = st->st_atimespec.tv_nsec;
  1196. mnsec = st->st_mtimespec.tv_nsec;
  1197. cnsec = st->st_ctimespec.tv_nsec;
  1198. #elif defined(HAVE_STAT_NSEC)
  1199. ansec = st->st_atime_nsec;
  1200. mnsec = st->st_mtime_nsec;
  1201. cnsec = st->st_ctime_nsec;
  1202. #else
  1203. ansec = mnsec = cnsec = 0;
  1204. #endif
  1205. fill_time(v, 7, st->st_atime, ansec);
  1206. fill_time(v, 8, st->st_mtime, mnsec);
  1207. fill_time(v, 9, st->st_ctime, cnsec);
  1208. #ifdef HAVE_STRUCT_STAT_ST_BLKSIZE
  1209. PyStructSequence_SET_ITEM(v, ST_BLKSIZE_IDX,
  1210. PyInt_FromLong((long)st->st_blksize));
  1211. #endif
  1212. #ifdef HAVE_STRUCT_STAT_ST_BLOCKS
  1213. PyStructSequence_SET_ITEM(v, ST_BLOCKS_IDX,
  1214. PyInt_FromLong((long)st->st_blocks));
  1215. #endif
  1216. #ifdef HAVE_STRUCT_STAT_ST_RDEV
  1217. PyStructSequence_SET_ITEM(v, ST_RDEV_IDX,
  1218. PyInt_FromLong((long)st->st_rdev));
  1219. #endif
  1220. #ifdef HAVE_STRUCT_STAT_ST_GEN
  1221. PyStructSequence_SET_ITEM(v, ST_GEN_IDX,
  1222. PyInt_FromLong((long)st->st_gen));
  1223. #endif
  1224. #ifdef HAVE_STRUCT_STAT_ST_BIRTHTIME
  1225. {
  1226. PyObject *val;
  1227. unsigned long bsec,bnsec;
  1228. bsec = (long)st->st_birthtime;
  1229. #ifdef HAVE_STAT_TV_NSEC2
  1230. bnsec = st->st_birthtimespec.tv_nsec;
  1231. #else
  1232. bnsec = 0;
  1233. #endif
  1234. if (_stat_float_times) {
  1235. val = PyFloat_FromDouble(bsec + 1e-9*bnsec);
  1236. } else {
  1237. val = PyInt_FromLong((long)bsec);
  1238. }
  1239. PyStructSequence_SET_ITEM(v, ST_BIRTHTIME_IDX,
  1240. val);
  1241. }
  1242. #endif
  1243. #ifdef HAVE_STRUCT_STAT_ST_FLAGS
  1244. PyStructSequence_SET_ITEM(v, ST_FLAGS_IDX,
  1245. PyInt_FromLong((long)st->st_flags));
  1246. #endif
  1247. if (PyErr_Occurred()) {
  1248. Py_DECREF(v);
  1249. return NULL;
  1250. }
  1251. return v;
  1252. }
  1253. #ifdef MS_WINDOWS
  1254. /* IsUNCRoot -- test whether the supplied path is of the form \\SERVER\SHARE\,
  1255. where / can be used in place of \ and the trailing slash is optional.
  1256. Both SERVER and SHARE must have at least one character.
  1257. */
  1258. #define ISSLASHA(c) ((c) == '\\' || (c) == '/')
  1259. #define ISSLASHW(c) ((c) == L'\\' || (c) == L'/')
  1260. #ifndef ARRAYSIZE
  1261. #define ARRAYSIZE(a) (sizeof(a) / sizeof(a[0]))
  1262. #endif
  1263. static BOOL
  1264. IsUNCRootA(char *path, int pathlen)
  1265. {
  1266. #define ISSLASH ISSLASHA
  1267. int i, share;
  1268. if (pathlen < 5 || !ISSLASH(path[0]) || !ISSLASH(path[1]))
  1269. /* minimum UNCRoot is \\x\y */
  1270. return FALSE;
  1271. for (i = 2; i < pathlen ; i++)
  1272. if (ISSLASH(path[i])) break;
  1273. if (i == 2 || i == pathlen)
  1274. /* do not allow \\\SHARE or \\SERVER */
  1275. return FALSE;
  1276. share = i+1;
  1277. for (i = share; i < pathlen; i++)
  1278. if (ISSLASH(path[i])) break;
  1279. return (i != share && (i == pathlen || i == pathlen-1));
  1280. #undef ISSLASH
  1281. }
  1282. #ifdef Py_WIN_WIDE_FILENAMES
  1283. static BOOL
  1284. IsUNCRootW(Py_UNICODE *path, int pathlen)
  1285. {
  1286. #define ISSLASH ISSLASHW
  1287. int i, share;
  1288. if (pathlen < 5 || !ISSLASH(path[0]) || !ISSLASH(path[1]))
  1289. /* minimum UNCRoot is \\x\y */
  1290. return FALSE;
  1291. for (i = 2; i < pathlen ; i++)
  1292. if (ISSLASH(path[i])) break;
  1293. if (i == 2 || i == pathlen)
  1294. /* do not allow \\\SHARE or \\SERVER */
  1295. return FALSE;
  1296. share = i+1;
  1297. for (i = share; i < pathlen; i++)
  1298. if (ISSLASH(path[i])) break;
  1299. return (i != share && (i == pathlen || i == pathlen-1));
  1300. #undef ISSLASH
  1301. }
  1302. #endif /* Py_WIN_WIDE_FILENAMES */
  1303. #endif /* MS_WINDOWS */
  1304. static PyObject *
  1305. posix_do_stat(PyObject *self, PyObject *args,
  1306. char *format,
  1307. #ifdef __VMS
  1308. int (*statfunc)(const char *, STRUCT_STAT *, ...),
  1309. #else
  1310. int (*statfunc)(const char *, STRUCT_STAT *),
  1311. #endif
  1312. char *wformat,
  1313. int (*wstatfunc)(const Py_UNICODE *, STRUCT_STAT *))
  1314. {
  1315. STRUCT_STAT st;
  1316. char *path = NULL; /* pass this to stat; do not free() it */
  1317. char *pathfree = NULL; /* this memory must be free'd */
  1318. int res;
  1319. PyObject *result;
  1320. #ifdef Py_WIN_WIDE_FILENAMES
  1321. /* If on wide-character-capable OS see if argument
  1322. is Unicode and if so use wide API. */
  1323. if (unicode_file_names()) {
  1324. PyUnicodeObject *po;
  1325. if (PyArg_ParseTuple(args, wformat, &po)) {
  1326. Py_UNICODE *wpath = PyUnicode_AS_UNICODE(po);
  1327. Py_BEGIN_ALLOW_THREADS
  1328. /* PyUnicode_AS_UNICODE result OK without
  1329. thread lock as it is a simple dereference. */
  1330. res = wstatfunc(wpath, &st);
  1331. Py_END_ALLOW_THREADS
  1332. if (res != 0)
  1333. return win32_error_unicode("stat", wpath);
  1334. return _pystat_fromstructstat(&st);
  1335. }
  1336. /* Drop the argument parsing error as narrow strings
  1337. are also valid. */
  1338. PyErr_Clear();
  1339. }
  1340. #endif
  1341. if (!PyArg_ParseTuple(args, format,
  1342. Py_FileSystemDefaultEncoding, &path))
  1343. return NULL;
  1344. pathfree = path;
  1345. Py_BEGIN_ALLOW_THREADS
  1346. res = (*statfunc)(path, &st);
  1347. Py_END_ALLOW_THREADS
  1348. if (res != 0) {
  1349. #ifdef MS_WINDOWS
  1350. result = win32_error("stat", pathfree);
  1351. #else
  1352. result = posix_error_with_filename(pathfree);
  1353. #endif
  1354. }
  1355. else
  1356. result = _pystat_fromstructstat(&st);
  1357. PyMem_Free(pathfree);
  1358. return result;
  1359. }
  1360. /* POSIX methods */
  1361. PyDoc_STRVAR(posix_access__doc__,
  1362. "access(path, mode) -> True if granted, False otherwise\n\n\
  1363. Use the real uid/gid to test for access to a path. Note that most\n\
  1364. operations will use the effective uid/gid, therefore this routine can\n\
  1365. be used in a suid/sgid environment to test if the invoking user has the\n\
  1366. specified access to the path. The mode argument can be F_OK to test\n\
  1367. existence, or the inclusive-OR of R_OK, W_OK, and X_OK.");
  1368. static PyObject *
  1369. posix_access(PyObject *self, PyObject *args)
  1370. {
  1371. char *path;
  1372. int mode;
  1373. #ifdef Py_WIN_WIDE_FILENAMES
  1374. DWORD attr;
  1375. if (unicode_file_names()) {
  1376. PyUnicodeObject *po;
  1377. if (PyArg_ParseTuple(args, "Ui:access", &po, &mode)) {
  1378. Py_BEGIN_ALLOW_THREADS
  1379. /* PyUnicode_AS_UNICODE OK without thread lock as
  1380. it is a simple dereference. */
  1381. attr = GetFileAttributesW(PyUnicode_AS_UNICODE(po));
  1382. Py_END_ALLOW_THREADS
  1383. goto finish;
  1384. }
  1385. /* Drop the argument parsing error as narrow strings
  1386. are also valid. */
  1387. PyErr_Clear();
  1388. }
  1389. if (!PyArg_ParseTuple(args, "eti:access",
  1390. Py_FileSystemDefaultEncoding, &path, &mode))
  1391. return 0;
  1392. Py_BEGIN_ALLOW_THREADS
  1393. attr = GetFileAttributesA(path);
  1394. Py_END_ALLOW_THREADS
  1395. PyMem_Free(path);
  1396. finish:
  1397. if (attr == 0xFFFFFFFF)
  1398. /* File does not exist, or cannot read attributes */
  1399. return PyBool_FromLong(0);
  1400. /* Access is possible if either write access wasn't requested, or
  1401. the file isn't read-only, or if it's a directory, as there are
  1402. no read-only directories on Windows. */
  1403. return PyBool_FromLong(!(mode & 2)
  1404. || !(attr & FILE_ATTRIBUTE_READONLY)
  1405. || (attr & FILE_ATTRIBUTE_DIRECTORY));
  1406. #else
  1407. int res;
  1408. if (!PyArg_ParseTuple(args, "eti:access",
  1409. Py_FileSystemDefaultEncoding, &path, &mode))
  1410. return NULL;
  1411. Py_BEGIN_ALLOW_THREADS
  1412. res = access(path, mode);
  1413. Py_END_ALLOW_THREADS
  1414. PyMem_Free(path);
  1415. return PyBool_FromLong(res == 0);
  1416. #endif
  1417. }
  1418. #ifndef F_OK
  1419. #define F_OK 0
  1420. #endif
  1421. #ifndef R_OK
  1422. #define R_OK 4
  1423. #endif
  1424. #ifndef W_OK
  1425. #define W_OK 2
  1426. #endif
  1427. #ifndef X_OK
  1428. #define X_OK 1
  1429. #endif
  1430. #ifdef HAVE_TTYNAME
  1431. PyDoc_STRVAR(posix_ttyname__doc__,
  1432. "ttyname(fd) -> string\n\n\
  1433. Return the name of the terminal device connected to 'fd'.");
  1434. static PyObject *
  1435. posix_ttyname(PyObject *self, PyObject *args)
  1436. {
  1437. int id;
  1438. char *ret;
  1439. if (!PyArg_ParseTuple(args, "i:ttyname", &id))
  1440. return NULL;
  1441. #if defined(__VMS)
  1442. /* file descriptor 0 only, the default input device (stdin) */
  1443. if (id == 0) {
  1444. ret = ttyname();
  1445. }
  1446. else {
  1447. ret = NULL;
  1448. }
  1449. #else
  1450. ret = ttyname(id);
  1451. #endif
  1452. if (ret == NULL)
  1453. return posix_error();
  1454. return PyString_FromString(ret);
  1455. }
  1456. #endif
  1457. #ifdef HAVE_CTERMID
  1458. PyDoc_STRVAR(posix_ctermid__doc__,
  1459. "ctermid() -> string\n\n\
  1460. Return the name of the controlling terminal for this process.");
  1461. static PyObject *
  1462. posix_ctermid(PyObject *self, PyObject *noargs)
  1463. {
  1464. char *ret;
  1465. char buffer[L_ctermid];
  1466. #ifdef USE_CTERMID_R
  1467. ret = ctermid_r(buffer);
  1468. #else
  1469. ret = ctermid(buffer);
  1470. #endif
  1471. if (ret == NULL)
  1472. return posix_error();
  1473. return PyString_FromString(buffer);
  1474. }
  1475. #endif
  1476. PyDoc_STRVAR(posix_chdir__doc__,
  1477. "chdir(path)\n\n\
  1478. Change the current working directory to the specified path.");
  1479. static PyObject *
  1480. posix_chdir(PyObject *self, PyObject *args)
  1481. {
  1482. #ifdef MS_WINDOWS
  1483. return win32_1str(args, "chdir", "s:chdir", win32_chdir, "U:chdir", win32_wchdir);
  1484. #elif defined(PYOS_OS2) && defined(PYCC_GCC)
  1485. return posix_1str(args, "et:chdir", _chdir2);
  1486. #elif defined(__VMS)
  1487. return posix_1str(args, "et:chdir", (int (*)(const char *))chdir);
  1488. #else
  1489. return posix_1str(args, "et:chdir", chdir);
  1490. #endif
  1491. }
  1492. #ifdef HAVE_FCHDIR
  1493. PyDoc_STRVAR(posix_fchdir__doc__,
  1494. "fchdir(fildes)\n\n\
  1495. Change to the directory of the given file descriptor. fildes must be\n\
  1496. opened on a directory, not a file.");
  1497. static PyObject *
  1498. posix_fchdir(PyObject *self, PyObject *fdobj)
  1499. {
  1500. return posix_fildes(fdobj, fchdir);
  1501. }
  1502. #endif /* HAVE_FCHDIR */
  1503. PyDoc_STRVAR(posix_chmod__doc__,
  1504. "chmod(path, mode)\n\n\
  1505. Change the access permissions of a file.");
  1506. static PyObject *
  1507. posix_chmod(PyObject *self, PyObject *args)
  1508. {
  1509. char *path = NULL;
  1510. int i;
  1511. int res;
  1512. #ifdef Py_WIN_WIDE_FILENAMES
  1513. DWORD attr;
  1514. if (unicode_file_names()) {
  1515. PyUnicodeObject *po;
  1516. if (PyArg_ParseTuple(args, "Ui|:chmod", &po, &i)) {
  1517. Py_BEGIN_ALLOW_THREADS
  1518. attr = GetFileAttributesW(PyUnicode_AS_UNICODE(po));
  1519. if (attr != 0xFFFFFFFF) {
  1520. if (i & _S_IWRITE)
  1521. attr &= ~FILE_ATTRIBUTE_READONLY;
  1522. else
  1523. attr |= FILE_ATTRIBUTE_READONLY;
  1524. res = SetFileAttributesW(PyUnicode_AS_UNICODE(po), attr);
  1525. }
  1526. else
  1527. res = 0;
  1528. Py_END_ALLOW_THREADS
  1529. if (!res)
  1530. return win32_error_unicode("chmod",
  1531. PyUnicode_AS_UNICODE(po));
  1532. Py_INCREF(Py_None);
  1533. return Py_None;
  1534. }
  1535. /* Drop the argument parsing error as narrow strings
  1536. are also valid. */
  1537. PyErr_Clear();
  1538. }
  1539. if (!PyArg_ParseTuple(args, "eti:chmod", Py_FileSystemDefaultEncoding,
  1540. &path, &i))
  1541. return NULL;
  1542. Py_BEGIN_ALLOW_THREADS
  1543. attr = GetFileAttributesA(path);
  1544. if (attr != 0xFFFFFFFF) {
  1545. if (i & _S_IWRITE)
  1546. attr &= ~FILE_ATTRIBUTE_READONLY;
  1547. else
  1548. attr |= FILE_ATTRIBUTE_READONLY;
  1549. res = SetFileAttributesA(path, attr);
  1550. }
  1551. else
  1552. res = 0;
  1553. Py_END_ALLOW_THREADS
  1554. if (!res) {
  1555. win32_error("chmod", path);
  1556. PyMem_Free(path);
  1557. return NULL;
  1558. }
  1559. PyMem_Free(path);
  1560. Py_INCREF(Py_None);
  1561. return Py_None;
  1562. #else /* Py_WIN_WIDE_FILENAMES */
  1563. if (!PyArg_ParseTuple(args, "eti:chmod", Py_FileSystemDefaultEncoding,
  1564. &path, &i))
  1565. return NULL;
  1566. Py_BEGIN_ALLOW_THREADS
  1567. res = chmod(path, i);
  1568. Py_END_ALLOW_THREADS
  1569. if (res < 0)
  1570. return posix_error_with_allocated_filename(path);
  1571. PyMem_Free(path);
  1572. Py_INCREF(Py_None);
  1573. return Py_None;
  1574. #endif
  1575. }
  1576. #ifdef HAVE_FCHMOD
  1577. PyDoc_STRVAR(posix_fchmod__doc__,
  1578. "fchmod(fd, mode)\n\n\
  1579. Change the access permissions of the file given by file\n\
  1580. descriptor fd.");
  1581. static PyObject *
  1582. posix_fchmod(PyObject *self, PyObject *args)
  1583. {
  1584. int fd, mode, res;
  1585. if (!PyArg_ParseTuple(args, "ii:fchmod", &fd, &mode))
  1586. return NULL;
  1587. Py_BEGIN_ALLOW_THREADS
  1588. res = fchmod(fd, mode);
  1589. Py_END_ALLOW_THREADS
  1590. if (res < 0)
  1591. return posix_error();
  1592. Py_RETURN_NONE;
  1593. }
  1594. #endif /* HAVE_FCHMOD */
  1595. #ifdef HAVE_LCHMOD
  1596. PyDoc_STRVAR(posix_lchmod__doc__,
  1597. "lchmod(path, mode)\n\n\
  1598. Change the access permissions of a file. If path is a symlink, this\n\
  1599. affects the link itself rather than the target.");
  1600. static PyObject *
  1601. posix_lchmod(PyObject *self, PyObject *args)
  1602. {
  1603. char *path = NULL;
  1604. int i;
  1605. int res;
  1606. if (!PyArg_ParseTuple(args, "eti:lchmod", Py_FileSystemDefaultEncoding,
  1607. &path, &i))
  1608. return NULL;
  1609. Py_BEGIN_ALLOW_THREADS
  1610. res = lchmod(path, i);
  1611. Py_END_ALLOW_THREADS
  1612. if (res < 0)
  1613. return posix_error_with_allocated_filename(path);
  1614. PyMem_Free(path);
  1615. Py_RETURN_NONE;
  1616. }
  1617. #endif /* HAVE_LCHMOD */
  1618. #ifdef HAVE_CHFLAGS
  1619. PyDoc_STRVAR(posix_chflags__doc__,
  1620. "chflags(path, flags)\n\n\
  1621. Set file flags.");
  1622. static PyObject *
  1623. posix_chflags(PyObject *self, PyObject *args)
  1624. {
  1625. char *path;
  1626. unsigned long flags;
  1627. int res;
  1628. if (!PyArg_ParseTuple(args, "etk:chflags",
  1629. Py_FileSystemDefaultEncoding, &path, &flags))
  1630. return NULL;
  1631. Py_BEGIN_ALLOW_THREADS
  1632. res = chflags(path, flags);
  1633. Py_END_ALLOW_THREADS
  1634. if (res < 0)
  1635. return posix_error_with_allocated_filename(path);
  1636. PyMem_Free(path);
  1637. Py_INCREF(Py_None);
  1638. return Py_None;
  1639. }
  1640. #endif /* HAVE_CHFLAGS */
  1641. #ifdef HAVE_LCHFLAGS
  1642. PyDoc_STRVAR(posix_lchflags__doc__,
  1643. "lchflags(path, flags)\n\n\
  1644. Set file flags.\n\
  1645. This function will not follow symbolic links.");
  1646. static PyObject *
  1647. posix_lchflags(PyObject *self, PyObject *args)
  1648. {
  1649. char *path;
  1650. unsigned long flags;
  1651. int res;
  1652. if (!PyArg_ParseTuple(args, "etk:lchflags",
  1653. Py_FileSystemDefaultEncoding, &path, &flags))
  1654. return NULL;
  1655. Py_BEGIN_ALLOW_THREADS
  1656. res = lchflags(path, flags);
  1657. Py_END_ALLOW_THREADS
  1658. if (res < 0)
  1659. return posix_error_with_allocated_filename(path);
  1660. PyMem_Free(path);
  1661. Py_INCREF(Py_None);
  1662. return Py_None;
  1663. }
  1664. #endif /* HAVE_LCHFLAGS */
  1665. #ifdef HAVE_CHROOT
  1666. PyDoc_STRVAR(posix_chroot__doc__,
  1667. "chroot(path)\n\n\
  1668. Change root directory to path.");
  1669. static PyObject *
  1670. posix_chroot(PyObject *self, PyObject *args)
  1671. {
  1672. return posix_1str(args, "et:chroot", chroot);
  1673. }
  1674. #endif
  1675. #ifdef HAVE_FSYNC
  1676. PyDoc_STRVAR(posix_fsync__doc__,
  1677. "fsync(fildes)\n\n\
  1678. force write of file with filedescriptor to disk.");
  1679. static PyObject *
  1680. posix_fsync(PyObject *self, PyObject *fdobj)
  1681. {
  1682. return posix_fildes(fdobj, fsync);
  1683. }
  1684. #endif /* HAVE_FSYNC */
  1685. #ifdef HAVE_FDATASYNC
  1686. #ifdef __hpux
  1687. extern int fdatasync(int); /* On HP-UX, in libc but not in unistd.h */
  1688. #endif
  1689. PyDoc_STRVAR(posix_fdatasync__doc__,
  1690. "fdatasync(fildes)\n\n\
  1691. force write of file with filedescriptor to disk.\n\
  1692. does not force update of metadata.");
  1693. static PyObject *
  1694. posix_fdatasync(PyObject *self, PyObject *fdobj)
  1695. {
  1696. return posix_fildes(fdobj, fdatasync);
  1697. }
  1698. #endif /* HAVE_FDATASYNC */
  1699. #ifdef HAVE_CHOWN
  1700. PyDoc_STRVAR(posix_chown__doc__,
  1701. "chown(path, uid, gid)\n\n\
  1702. Change the owner and group id of path to the numeric uid and gid.");
  1703. static PyObject *
  1704. posix_chown(PyObject *self, PyObject *args)
  1705. {
  1706. char *path = NULL;
  1707. long uid, gid;
  1708. int res;
  1709. if (!PyArg_ParseTuple(args, "etll:chown",
  1710. Py_FileSystemDefaultEncoding, &path,
  1711. &uid, &gid))
  1712. return NULL;
  1713. Py_BEGIN_ALLOW_THREADS
  1714. res = chown(path, (uid_t) uid, (gid_t) gid);
  1715. Py_END_ALLOW_THREADS
  1716. if (res < 0)
  1717. return posix_error_with_allocated_filename(path);
  1718. PyMem_Free(path);
  1719. Py_INCREF(Py_None);
  1720. return Py_None;
  1721. }
  1722. #endif /* HAVE_CHOWN */
  1723. #ifdef HAVE_FCHOWN
  1724. PyDoc_STRVAR(posix_fchown__doc__,
  1725. "fchown(fd, uid, gid)\n\n\
  1726. Change the owner and group id of the file given by file descri