/otherlibs/threads/unix.ml

http://github.com/multani/ocaml-mirror · OCaml · 1115 lines · 922 code · 157 blank · 36 comment · 50 complexity · b2abf75ae8f0818abc64fe3408dd8ca4 MD5 · raw file

  1. (***********************************************************************)
  2. (* *)
  3. (* OCaml *)
  4. (* *)
  5. (* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
  6. (* *)
  7. (* Copyright 1996 Institut National de Recherche en Informatique et *)
  8. (* en Automatique. All rights reserved. This file is distributed *)
  9. (* under the terms of the GNU Library General Public License, with *)
  10. (* the special exception on linking described in file ../../LICENSE. *)
  11. (* *)
  12. (***********************************************************************)
  13. (* $Id$ *)
  14. (* An alternate implementation of the Unix module from ../unix
  15. which is safe in conjunction with bytecode threads. *)
  16. (* Type definitions that matter for thread operations *)
  17. type file_descr = int
  18. type process_status =
  19. WEXITED of int
  20. | WSIGNALED of int
  21. | WSTOPPED of int
  22. (* We can't call functions from Thread because of type circularities,
  23. so we redefine here the functions that we need *)
  24. type resumption_status =
  25. Resumed_wakeup
  26. | Resumed_delay
  27. | Resumed_join
  28. | Resumed_io
  29. | Resumed_select of file_descr list * file_descr list * file_descr list
  30. | Resumed_wait of int * process_status
  31. external thread_initialize : unit -> unit = "thread_initialize"
  32. external thread_wait_read : file_descr -> unit = "thread_wait_read"
  33. external thread_wait_write : file_descr -> unit = "thread_wait_write"
  34. external thread_select :
  35. file_descr list * file_descr list * file_descr list * float
  36. -> resumption_status
  37. = "thread_select"
  38. external thread_wait_pid : int -> resumption_status = "thread_wait_pid"
  39. external thread_delay : float -> unit = "thread_delay"
  40. let wait_read fd = thread_wait_read fd
  41. let wait_write fd = thread_wait_write fd
  42. let select_aux arg = thread_select arg
  43. let wait_pid_aux pid = thread_wait_pid pid
  44. let delay duration = thread_delay duration
  45. (* Make sure that threads are initialized (PR#1516). *)
  46. let _ = thread_initialize()
  47. (* Back to the Unix module *)
  48. type error =
  49. E2BIG
  50. | EACCES
  51. | EAGAIN
  52. | EBADF
  53. | EBUSY
  54. | ECHILD
  55. | EDEADLK
  56. | EDOM
  57. | EEXIST
  58. | EFAULT
  59. | EFBIG
  60. | EINTR
  61. | EINVAL
  62. | EIO
  63. | EISDIR
  64. | EMFILE
  65. | EMLINK
  66. | ENAMETOOLONG
  67. | ENFILE
  68. | ENODEV
  69. | ENOENT
  70. | ENOEXEC
  71. | ENOLCK
  72. | ENOMEM
  73. | ENOSPC
  74. | ENOSYS
  75. | ENOTDIR
  76. | ENOTEMPTY
  77. | ENOTTY
  78. | ENXIO
  79. | EPERM
  80. | EPIPE
  81. | ERANGE
  82. | EROFS
  83. | ESPIPE
  84. | ESRCH
  85. | EXDEV
  86. | EWOULDBLOCK
  87. | EINPROGRESS
  88. | EALREADY
  89. | ENOTSOCK
  90. | EDESTADDRREQ
  91. | EMSGSIZE
  92. | EPROTOTYPE
  93. | ENOPROTOOPT
  94. | EPROTONOSUPPORT
  95. | ESOCKTNOSUPPORT
  96. | EOPNOTSUPP
  97. | EPFNOSUPPORT
  98. | EAFNOSUPPORT
  99. | EADDRINUSE
  100. | EADDRNOTAVAIL
  101. | ENETDOWN
  102. | ENETUNREACH
  103. | ENETRESET
  104. | ECONNABORTED
  105. | ECONNRESET
  106. | ENOBUFS
  107. | EISCONN
  108. | ENOTCONN
  109. | ESHUTDOWN
  110. | ETOOMANYREFS
  111. | ETIMEDOUT
  112. | ECONNREFUSED
  113. | EHOSTDOWN
  114. | EHOSTUNREACH
  115. | ELOOP
  116. | EOVERFLOW
  117. | EUNKNOWNERR of int
  118. exception Unix_error of error * string * string
  119. let _ = Callback.register_exception "Unix.Unix_error"
  120. (Unix_error(E2BIG, "", ""))
  121. external error_message : error -> string = "unix_error_message"
  122. let handle_unix_error f arg =
  123. try
  124. f arg
  125. with Unix_error(err, fun_name, arg) ->
  126. prerr_string Sys.argv.(0);
  127. prerr_string ": \"";
  128. prerr_string fun_name;
  129. prerr_string "\" failed";
  130. if String.length arg > 0 then begin
  131. prerr_string " on \"";
  132. prerr_string arg;
  133. prerr_string "\""
  134. end;
  135. prerr_string ": ";
  136. prerr_endline (error_message err);
  137. exit 2
  138. external environment : unit -> string array = "unix_environment"
  139. external getenv: string -> string = "caml_sys_getenv"
  140. external putenv: string -> string -> unit = "unix_putenv"
  141. type interval_timer =
  142. ITIMER_REAL
  143. | ITIMER_VIRTUAL
  144. | ITIMER_PROF
  145. type interval_timer_status =
  146. { it_interval: float; (* Period *)
  147. it_value: float } (* Current value of the timer *)
  148. external getitimer: interval_timer -> interval_timer_status = "unix_getitimer"
  149. external setitimer:
  150. interval_timer -> interval_timer_status -> interval_timer_status
  151. = "unix_setitimer"
  152. type wait_flag =
  153. WNOHANG
  154. | WUNTRACED
  155. let stdin = 0
  156. let stdout = 1
  157. let stderr = 2
  158. type open_flag =
  159. O_RDONLY
  160. | O_WRONLY
  161. | O_RDWR
  162. | O_NONBLOCK
  163. | O_APPEND
  164. | O_CREAT
  165. | O_TRUNC
  166. | O_EXCL
  167. | O_NOCTTY
  168. | O_DSYNC
  169. | O_SYNC
  170. | O_RSYNC
  171. | O_SHARE_DELETE
  172. type file_perm = int
  173. external openfile : string -> open_flag list -> file_perm -> file_descr
  174. = "unix_open"
  175. external close : file_descr -> unit = "unix_close"
  176. external unsafe_read : file_descr -> string -> int -> int -> int = "unix_read"
  177. external unsafe_write : file_descr -> string -> int -> int -> int
  178. = "unix_write"
  179. external unsafe_single_write : file_descr -> string -> int -> int -> int
  180. = "unix_single_write"
  181. let rec read fd buf ofs len =
  182. try
  183. if ofs < 0 || len < 0 || ofs > String.length buf - len
  184. then invalid_arg "Unix.read"
  185. else unsafe_read fd buf ofs len
  186. with Unix_error((EAGAIN | EWOULDBLOCK), _, _) ->
  187. wait_read fd; read fd buf ofs len
  188. let rec write fd buf ofs len =
  189. try
  190. if ofs < 0 || len < 0 || ofs > String.length buf - len
  191. then invalid_arg "Unix.write"
  192. else unsafe_write fd buf ofs len
  193. with Unix_error((EAGAIN | EWOULDBLOCK), _, _) ->
  194. wait_write fd; write fd buf ofs len
  195. let rec single_write fd buf ofs len =
  196. try
  197. if ofs < 0 || len < 0 || ofs > String.length buf - len
  198. then invalid_arg "Unix.partial_write"
  199. else unsafe_single_write fd buf ofs len
  200. with Unix_error((EAGAIN | EWOULDBLOCK), _, _) ->
  201. wait_write fd; single_write fd buf ofs len
  202. external in_channel_of_descr : file_descr -> in_channel
  203. = "caml_ml_open_descriptor_in"
  204. external out_channel_of_descr : file_descr -> out_channel
  205. = "caml_ml_open_descriptor_out"
  206. external descr_of_in_channel : in_channel -> file_descr
  207. = "caml_channel_descriptor"
  208. external descr_of_out_channel : out_channel -> file_descr
  209. = "caml_channel_descriptor"
  210. type seek_command =
  211. SEEK_SET
  212. | SEEK_CUR
  213. | SEEK_END
  214. external lseek : file_descr -> int -> seek_command -> int = "unix_lseek"
  215. external truncate : string -> int -> unit = "unix_truncate"
  216. external ftruncate : file_descr -> int -> unit = "unix_ftruncate"
  217. type file_kind =
  218. S_REG
  219. | S_DIR
  220. | S_CHR
  221. | S_BLK
  222. | S_LNK
  223. | S_FIFO
  224. | S_SOCK
  225. type stats =
  226. { st_dev : int;
  227. st_ino : int;
  228. st_kind : file_kind;
  229. st_perm : file_perm;
  230. st_nlink : int;
  231. st_uid : int;
  232. st_gid : int;
  233. st_rdev : int;
  234. st_size : int;
  235. st_atime : float;
  236. st_mtime : float;
  237. st_ctime : float }
  238. external stat : string -> stats = "unix_stat"
  239. external lstat : string -> stats = "unix_lstat"
  240. external fstat : file_descr -> stats = "unix_fstat"
  241. external isatty : file_descr -> bool = "unix_isatty"
  242. external unlink : string -> unit = "unix_unlink"
  243. external rename : string -> string -> unit = "unix_rename"
  244. external link : string -> string -> unit = "unix_link"
  245. module LargeFile =
  246. struct
  247. external lseek : file_descr -> int64 -> seek_command -> int64
  248. = "unix_lseek_64"
  249. external truncate : string -> int64 -> unit = "unix_truncate_64"
  250. external ftruncate : file_descr -> int64 -> unit = "unix_ftruncate_64"
  251. type stats =
  252. { st_dev : int;
  253. st_ino : int;
  254. st_kind : file_kind;
  255. st_perm : file_perm;
  256. st_nlink : int;
  257. st_uid : int;
  258. st_gid : int;
  259. st_rdev : int;
  260. st_size : int64;
  261. st_atime : float;
  262. st_mtime : float;
  263. st_ctime : float;
  264. }
  265. external stat : string -> stats = "unix_stat_64"
  266. external lstat : string -> stats = "unix_lstat_64"
  267. external fstat : file_descr -> stats = "unix_fstat_64"
  268. end
  269. type access_permission =
  270. R_OK
  271. | W_OK
  272. | X_OK
  273. | F_OK
  274. external chmod : string -> file_perm -> unit = "unix_chmod"
  275. external fchmod : file_descr -> file_perm -> unit = "unix_fchmod"
  276. external chown : string -> int -> int -> unit = "unix_chown"
  277. external fchown : file_descr -> int -> int -> unit = "unix_fchown"
  278. external umask : int -> int = "unix_umask"
  279. external access : string -> access_permission list -> unit = "unix_access"
  280. external dup : file_descr -> file_descr = "unix_dup"
  281. external dup2 : file_descr -> file_descr -> unit = "unix_dup2"
  282. external set_nonblock : file_descr -> unit = "unix_set_nonblock"
  283. external clear_nonblock : file_descr -> unit = "unix_clear_nonblock"
  284. external set_close_on_exec : file_descr -> unit = "unix_set_close_on_exec"
  285. external clear_close_on_exec : file_descr -> unit = "unix_clear_close_on_exec"
  286. external mkdir : string -> file_perm -> unit = "unix_mkdir"
  287. external rmdir : string -> unit = "unix_rmdir"
  288. external chdir : string -> unit = "unix_chdir"
  289. external getcwd : unit -> string = "unix_getcwd"
  290. external chroot : string -> unit = "unix_chroot"
  291. type dir_handle
  292. external opendir : string -> dir_handle = "unix_opendir"
  293. external readdir : dir_handle -> string = "unix_readdir"
  294. external rewinddir : dir_handle -> unit = "unix_rewinddir"
  295. external closedir : dir_handle -> unit = "unix_closedir"
  296. external _pipe : unit -> file_descr * file_descr = "unix_pipe"
  297. let pipe() =
  298. let (out_fd, in_fd as fd_pair) = _pipe() in
  299. set_nonblock in_fd;
  300. set_nonblock out_fd;
  301. fd_pair
  302. external symlink : string -> string -> unit = "unix_symlink"
  303. external readlink : string -> string = "unix_readlink"
  304. external mkfifo : string -> file_perm -> unit = "unix_mkfifo"
  305. let select readfds writefds exceptfds delay =
  306. match select_aux (readfds, writefds, exceptfds, delay) with
  307. Resumed_select(r, w, e) -> (r, w, e)
  308. | _ -> ([], [], [])
  309. type lock_command =
  310. F_ULOCK
  311. | F_LOCK
  312. | F_TLOCK
  313. | F_TEST
  314. | F_RLOCK
  315. | F_TRLOCK
  316. external lockf : file_descr -> lock_command -> int -> unit = "unix_lockf"
  317. external _execv : string -> string array -> 'a = "unix_execv"
  318. external _execve : string -> string array -> string array -> 'a = "unix_execve"
  319. external _execvp : string -> string array -> 'a = "unix_execvp"
  320. external _execvpe : string -> string array -> string array -> 'a
  321. = "unix_execvpe"
  322. (* Disable the timer interrupt before doing exec, because some OS
  323. keep sending timer interrupts to the exec'ed code.
  324. Also restore blocking mode on stdin, stdout and stderr,
  325. since this is what most programs expect! *)
  326. let safe_clear_nonblock fd =
  327. try clear_nonblock fd with Unix_error(_,_,_) -> ()
  328. let safe_set_nonblock fd =
  329. try set_nonblock fd with Unix_error(_,_,_) -> ()
  330. let do_exec fn =
  331. let oldtimer =
  332. setitimer ITIMER_VIRTUAL {it_interval = 0.0; it_value = 0.0} in
  333. safe_clear_nonblock stdin;
  334. safe_clear_nonblock stdout;
  335. safe_clear_nonblock stderr;
  336. try
  337. fn ()
  338. with Unix_error(_,_,_) as exn ->
  339. ignore(setitimer ITIMER_VIRTUAL oldtimer);
  340. safe_set_nonblock stdin;
  341. safe_set_nonblock stdout;
  342. safe_set_nonblock stderr;
  343. raise exn
  344. let execv proc args =
  345. do_exec (fun () -> _execv proc args)
  346. let execve proc args env =
  347. do_exec (fun () -> _execve proc args env)
  348. let execvp proc args =
  349. do_exec (fun () -> _execvp proc args)
  350. let execvpe proc args =
  351. do_exec (fun () -> _execvpe proc args)
  352. external fork : unit -> int = "unix_fork"
  353. external _waitpid : wait_flag list -> int -> int * process_status
  354. = "unix_waitpid"
  355. let wait_pid pid =
  356. match wait_pid_aux pid with
  357. Resumed_wait(pid, status) -> (pid, status)
  358. | _ -> invalid_arg "Thread.wait_pid"
  359. let wait () = wait_pid (-1)
  360. let waitpid flags pid =
  361. if List.mem WNOHANG flags
  362. then _waitpid flags pid
  363. else wait_pid pid
  364. external getpid : unit -> int = "unix_getpid"
  365. external getppid : unit -> int = "unix_getppid"
  366. external nice : int -> int = "unix_nice"
  367. external kill : int -> int -> unit = "unix_kill"
  368. type sigprocmask_command = SIG_SETMASK | SIG_BLOCK | SIG_UNBLOCK
  369. external sigprocmask: sigprocmask_command -> int list -> int list
  370. = "unix_sigprocmask"
  371. external sigpending: unit -> int list = "unix_sigpending"
  372. external sigsuspend: int list -> unit = "unix_sigsuspend"
  373. let pause() =
  374. let sigs = sigprocmask SIG_BLOCK [] in sigsuspend sigs
  375. type process_times =
  376. { tms_utime : float;
  377. tms_stime : float;
  378. tms_cutime : float;
  379. tms_cstime : float }
  380. type tm =
  381. { tm_sec : int;
  382. tm_min : int;
  383. tm_hour : int;
  384. tm_mday : int;
  385. tm_mon : int;
  386. tm_year : int;
  387. tm_wday : int;
  388. tm_yday : int;
  389. tm_isdst : bool }
  390. external time : unit -> float = "unix_time"
  391. external gettimeofday : unit -> float = "unix_gettimeofday"
  392. external gmtime : float -> tm = "unix_gmtime"
  393. external localtime : float -> tm = "unix_localtime"
  394. external mktime : tm -> float * tm = "unix_mktime"
  395. external alarm : int -> int = "unix_alarm"
  396. let sleep secs = delay (float secs)
  397. external times : unit -> process_times = "unix_times"
  398. external utimes : string -> float -> float -> unit = "unix_utimes"
  399. external getuid : unit -> int = "unix_getuid"
  400. external geteuid : unit -> int = "unix_geteuid"
  401. external setuid : int -> unit = "unix_setuid"
  402. external getgid : unit -> int = "unix_getgid"
  403. external getegid : unit -> int = "unix_getegid"
  404. external setgid : int -> unit = "unix_setgid"
  405. external getgroups : unit -> int array = "unix_getgroups"
  406. external setgroups : int array -> unit = "unix_setgroups"
  407. external initgroups : string -> int -> unit = "unix_initgroups"
  408. type passwd_entry =
  409. { pw_name : string;
  410. pw_passwd : string;
  411. pw_uid : int;
  412. pw_gid : int;
  413. pw_gecos : string;
  414. pw_dir : string;
  415. pw_shell : string }
  416. type group_entry =
  417. { gr_name : string;
  418. gr_passwd : string;
  419. gr_gid : int;
  420. gr_mem : string array }
  421. external getlogin : unit -> string = "unix_getlogin"
  422. external getpwnam : string -> passwd_entry = "unix_getpwnam"
  423. external getgrnam : string -> group_entry = "unix_getgrnam"
  424. external getpwuid : int -> passwd_entry = "unix_getpwuid"
  425. external getgrgid : int -> group_entry = "unix_getgrgid"
  426. type inet_addr = string
  427. external inet_addr_of_string : string -> inet_addr
  428. = "unix_inet_addr_of_string"
  429. external string_of_inet_addr : inet_addr -> string
  430. = "unix_string_of_inet_addr"
  431. let inet_addr_any = inet_addr_of_string "0.0.0.0"
  432. let inet_addr_loopback = inet_addr_of_string "127.0.0.1"
  433. let inet6_addr_any =
  434. try inet_addr_of_string "::" with Failure _ -> inet_addr_any
  435. let inet6_addr_loopback =
  436. try inet_addr_of_string "::1" with Failure _ -> inet_addr_loopback
  437. let is_inet6_addr s = String.length s = 16
  438. type socket_domain =
  439. PF_UNIX
  440. | PF_INET
  441. | PF_INET6
  442. type socket_type =
  443. SOCK_STREAM
  444. | SOCK_DGRAM
  445. | SOCK_RAW
  446. | SOCK_SEQPACKET
  447. type sockaddr =
  448. ADDR_UNIX of string
  449. | ADDR_INET of inet_addr * int
  450. let domain_of_sockaddr = function
  451. ADDR_UNIX _ -> PF_UNIX
  452. | ADDR_INET(a, _) -> if is_inet6_addr a then PF_INET6 else PF_INET
  453. type shutdown_command =
  454. SHUTDOWN_RECEIVE
  455. | SHUTDOWN_SEND
  456. | SHUTDOWN_ALL
  457. type msg_flag =
  458. MSG_OOB
  459. | MSG_DONTROUTE
  460. | MSG_PEEK
  461. external _socket : socket_domain -> socket_type -> int -> file_descr
  462. = "unix_socket"
  463. external _socketpair :
  464. socket_domain -> socket_type -> int -> file_descr * file_descr
  465. = "unix_socketpair"
  466. let socket dom typ proto =
  467. let s = _socket dom typ proto in
  468. set_nonblock s;
  469. s
  470. let socketpair dom typ proto =
  471. let (s1, s2 as spair) = _socketpair dom typ proto in
  472. set_nonblock s1; set_nonblock s2;
  473. spair
  474. external _accept : file_descr -> file_descr * sockaddr = "unix_accept"
  475. let rec accept req =
  476. wait_read req;
  477. try
  478. let (s, caller as result) = _accept req in
  479. set_nonblock s;
  480. result
  481. with Unix_error((EAGAIN | EWOULDBLOCK), _, _) -> accept req
  482. external bind : file_descr -> sockaddr -> unit = "unix_bind"
  483. external listen : file_descr -> int -> unit = "unix_listen"
  484. external shutdown : file_descr -> shutdown_command -> unit = "unix_shutdown"
  485. external getsockname : file_descr -> sockaddr = "unix_getsockname"
  486. external getpeername : file_descr -> sockaddr = "unix_getpeername"
  487. external _connect : file_descr -> sockaddr -> unit = "unix_connect"
  488. let connect s addr =
  489. try
  490. _connect s addr
  491. with Unix_error((EINPROGRESS | EWOULDBLOCK | EAGAIN), _, _) ->
  492. wait_write s;
  493. (* Check if it really worked *)
  494. ignore(getpeername s)
  495. external unsafe_recv :
  496. file_descr -> string -> int -> int -> msg_flag list -> int
  497. = "unix_recv"
  498. external unsafe_recvfrom :
  499. file_descr -> string -> int -> int -> msg_flag list -> int * sockaddr
  500. = "unix_recvfrom"
  501. external unsafe_send :
  502. file_descr -> string -> int -> int -> msg_flag list -> int
  503. = "unix_send"
  504. external unsafe_sendto :
  505. file_descr -> string -> int -> int -> msg_flag list -> sockaddr -> int
  506. = "unix_sendto" "unix_sendto_native"
  507. let rec recv fd buf ofs len flags =
  508. try
  509. if ofs < 0 || len < 0 || ofs > String.length buf - len
  510. then invalid_arg "Unix.recv"
  511. else unsafe_recv fd buf ofs len flags
  512. with Unix_error((EAGAIN | EWOULDBLOCK), _, _) ->
  513. wait_read fd; recv fd buf ofs len flags
  514. let rec recvfrom fd buf ofs len flags =
  515. try
  516. if ofs < 0 || len < 0 || ofs > String.length buf - len
  517. then invalid_arg "Unix.recvfrom"
  518. else unsafe_recvfrom fd buf ofs len flags
  519. with Unix_error((EAGAIN | EWOULDBLOCK), _, _) ->
  520. wait_read fd;
  521. recvfrom fd buf ofs len flags
  522. let rec send fd buf ofs len flags =
  523. try
  524. if ofs < 0 || len < 0 || ofs > String.length buf - len
  525. then invalid_arg "Unix.send"
  526. else unsafe_send fd buf ofs len flags
  527. with Unix_error((EAGAIN | EWOULDBLOCK), _, _) ->
  528. wait_write fd;
  529. send fd buf ofs len flags
  530. let rec sendto fd buf ofs len flags addr =
  531. try
  532. if ofs < 0 || len < 0 || ofs > String.length buf - len
  533. then invalid_arg "Unix.sendto"
  534. else unsafe_sendto fd buf ofs len flags addr
  535. with Unix_error((EAGAIN | EWOULDBLOCK), _, _) ->
  536. wait_write fd;
  537. sendto fd buf ofs len flags addr
  538. type socket_bool_option =
  539. SO_DEBUG
  540. | SO_BROADCAST
  541. | SO_REUSEADDR
  542. | SO_KEEPALIVE
  543. | SO_DONTROUTE
  544. | SO_OOBINLINE
  545. | SO_ACCEPTCONN
  546. | TCP_NODELAY
  547. | IPV6_ONLY
  548. type socket_int_option =
  549. SO_SNDBUF
  550. | SO_RCVBUF
  551. | SO_ERROR
  552. | SO_TYPE
  553. | SO_RCVLOWAT
  554. | SO_SNDLOWAT
  555. type socket_optint_option = SO_LINGER
  556. type socket_float_option =
  557. SO_RCVTIMEO
  558. | SO_SNDTIMEO
  559. type socket_error_option = SO_ERROR
  560. module SO: sig
  561. type ('opt, 'v) t
  562. val bool: (socket_bool_option, bool) t
  563. val int: (socket_int_option, int) t
  564. val optint: (socket_optint_option, int option) t
  565. val float: (socket_float_option, float) t
  566. val error: (socket_error_option, error option) t
  567. val get: ('opt, 'v) t -> file_descr -> 'opt -> 'v
  568. val set: ('opt, 'v) t -> file_descr -> 'opt -> 'v -> unit
  569. end = struct
  570. type ('opt, 'v) t = int
  571. let bool = 0
  572. let int = 1
  573. let optint = 2
  574. let float = 3
  575. let error = 4
  576. external get: ('opt, 'v) t -> file_descr -> 'opt -> 'v
  577. = "unix_getsockopt"
  578. external set: ('opt, 'v) t -> file_descr -> 'opt -> 'v -> unit
  579. = "unix_setsockopt"
  580. end
  581. let getsockopt fd opt = SO.get SO.bool fd opt
  582. let setsockopt fd opt v = SO.set SO.bool fd opt v
  583. let getsockopt_int fd opt = SO.get SO.int fd opt
  584. let setsockopt_int fd opt v = SO.set SO.int fd opt v
  585. let getsockopt_optint fd opt = SO.get SO.optint fd opt
  586. let setsockopt_optint fd opt v = SO.set SO.optint fd opt v
  587. let getsockopt_float fd opt = SO.get SO.float fd opt
  588. let setsockopt_float fd opt v = SO.set SO.float fd opt v
  589. let getsockopt_error fd = SO.get SO.error fd SO_ERROR
  590. type host_entry =
  591. { h_name : string;
  592. h_aliases : string array;
  593. h_addrtype : socket_domain;
  594. h_addr_list : inet_addr array }
  595. type protocol_entry =
  596. { p_name : string;
  597. p_aliases : string array;
  598. p_proto : int }
  599. type service_entry =
  600. { s_name : string;
  601. s_aliases : string array;
  602. s_port : int;
  603. s_proto : string }
  604. external gethostname : unit -> string = "unix_gethostname"
  605. external gethostbyname : string -> host_entry = "unix_gethostbyname"
  606. external gethostbyaddr : inet_addr -> host_entry = "unix_gethostbyaddr"
  607. external getprotobyname : string -> protocol_entry
  608. = "unix_getprotobyname"
  609. external getprotobynumber : int -> protocol_entry
  610. = "unix_getprotobynumber"
  611. external getservbyname : string -> string -> service_entry
  612. = "unix_getservbyname"
  613. external getservbyport : int -> string -> service_entry
  614. = "unix_getservbyport"
  615. type addr_info =
  616. { ai_family : socket_domain;
  617. ai_socktype : socket_type;
  618. ai_protocol : int;
  619. ai_addr : sockaddr;
  620. ai_canonname : string }
  621. type getaddrinfo_option =
  622. AI_FAMILY of socket_domain
  623. | AI_SOCKTYPE of socket_type
  624. | AI_PROTOCOL of int
  625. | AI_NUMERICHOST
  626. | AI_CANONNAME
  627. | AI_PASSIVE
  628. external getaddrinfo_system
  629. : string -> string -> getaddrinfo_option list -> addr_info list
  630. = "unix_getaddrinfo"
  631. let getaddrinfo_emulation node service opts =
  632. (* Parse options *)
  633. let opt_socktype = ref None
  634. and opt_protocol = ref 0
  635. and opt_passive = ref false in
  636. List.iter
  637. (function AI_SOCKTYPE s -> opt_socktype := Some s
  638. | AI_PROTOCOL p -> opt_protocol := p
  639. | AI_PASSIVE -> opt_passive := true
  640. | _ -> ())
  641. opts;
  642. (* Determine socket types and port numbers *)
  643. let get_port ty kind =
  644. if service = "" then [ty, 0] else
  645. try
  646. [ty, int_of_string service]
  647. with Failure _ ->
  648. try
  649. [ty, (getservbyname service kind).s_port]
  650. with Not_found -> []
  651. in
  652. let ports =
  653. match !opt_socktype with
  654. | None ->
  655. get_port SOCK_STREAM "tcp" @ get_port SOCK_DGRAM "udp"
  656. | Some SOCK_STREAM ->
  657. get_port SOCK_STREAM "tcp"
  658. | Some SOCK_DGRAM ->
  659. get_port SOCK_DGRAM "udp"
  660. | Some ty ->
  661. if service = "" then [ty, 0] else [] in
  662. (* Determine IP addresses *)
  663. let addresses =
  664. if node = "" then
  665. if List.mem AI_PASSIVE opts
  666. then [inet_addr_any, "0.0.0.0"]
  667. else [inet_addr_loopback, "127.0.0.1"]
  668. else
  669. try
  670. [inet_addr_of_string node, node]
  671. with Failure _ ->
  672. try
  673. let he = gethostbyname node in
  674. List.map
  675. (fun a -> (a, he.h_name))
  676. (Array.to_list he.h_addr_list)
  677. with Not_found ->
  678. [] in
  679. (* Cross-product of addresses and ports *)
  680. List.flatten
  681. (List.map
  682. (fun (ty, port) ->
  683. List.map
  684. (fun (addr, name) ->
  685. { ai_family = PF_INET;
  686. ai_socktype = ty;
  687. ai_protocol = !opt_protocol;
  688. ai_addr = ADDR_INET(addr, port);
  689. ai_canonname = name })
  690. addresses)
  691. ports)
  692. let getaddrinfo node service opts =
  693. try
  694. List.rev(getaddrinfo_system node service opts)
  695. with Invalid_argument _ ->
  696. getaddrinfo_emulation node service opts
  697. type name_info =
  698. { ni_hostname : string;
  699. ni_service : string }
  700. type getnameinfo_option =
  701. NI_NOFQDN
  702. | NI_NUMERICHOST
  703. | NI_NAMEREQD
  704. | NI_NUMERICSERV
  705. | NI_DGRAM
  706. external getnameinfo_system
  707. : sockaddr -> getnameinfo_option list -> name_info
  708. = "unix_getnameinfo"
  709. let getnameinfo_emulation addr opts =
  710. match addr with
  711. | ADDR_UNIX f ->
  712. { ni_hostname = ""; ni_service = f } (* why not? *)
  713. | ADDR_INET(a, p) ->
  714. let hostname =
  715. try
  716. if List.mem NI_NUMERICHOST opts then raise Not_found;
  717. (gethostbyaddr a).h_name
  718. with Not_found ->
  719. if List.mem NI_NAMEREQD opts then raise Not_found;
  720. string_of_inet_addr a in
  721. let service =
  722. try
  723. if List.mem NI_NUMERICSERV opts then raise Not_found;
  724. let kind = if List.mem NI_DGRAM opts then "udp" else "tcp" in
  725. (getservbyport p kind).s_name
  726. with Not_found ->
  727. string_of_int p in
  728. { ni_hostname = hostname; ni_service = service }
  729. let getnameinfo addr opts =
  730. try
  731. getnameinfo_system addr opts
  732. with Invalid_argument _ ->
  733. getnameinfo_emulation addr opts
  734. type terminal_io = {
  735. mutable c_ignbrk: bool;
  736. mutable c_brkint: bool;
  737. mutable c_ignpar: bool;
  738. mutable c_parmrk: bool;
  739. mutable c_inpck: bool;
  740. mutable c_istrip: bool;
  741. mutable c_inlcr: bool;
  742. mutable c_igncr: bool;
  743. mutable c_icrnl: bool;
  744. mutable c_ixon: bool;
  745. mutable c_ixoff: bool;
  746. mutable c_opost: bool;
  747. mutable c_obaud: int;
  748. mutable c_ibaud: int;
  749. mutable c_csize: int;
  750. mutable c_cstopb: int;
  751. mutable c_cread: bool;
  752. mutable c_parenb: bool;
  753. mutable c_parodd: bool;
  754. mutable c_hupcl: bool;
  755. mutable c_clocal: bool;
  756. mutable c_isig: bool;
  757. mutable c_icanon: bool;
  758. mutable c_noflsh: bool;
  759. mutable c_echo: bool;
  760. mutable c_echoe: bool;
  761. mutable c_echok: bool;
  762. mutable c_echonl: bool;
  763. mutable c_vintr: char;
  764. mutable c_vquit: char;
  765. mutable c_verase: char;
  766. mutable c_vkill: char;
  767. mutable c_veof: char;
  768. mutable c_veol: char;
  769. mutable c_vmin: int;
  770. mutable c_vtime: int;
  771. mutable c_vstart: char;
  772. mutable c_vstop: char
  773. }
  774. external tcgetattr: file_descr -> terminal_io = "unix_tcgetattr"
  775. type setattr_when = TCSANOW | TCSADRAIN | TCSAFLUSH
  776. external tcsetattr: file_descr -> setattr_when -> terminal_io -> unit
  777. = "unix_tcsetattr"
  778. external tcsendbreak: file_descr -> int -> unit = "unix_tcsendbreak"
  779. external tcdrain: file_descr -> unit = "unix_tcdrain"
  780. type flush_queue = TCIFLUSH | TCOFLUSH | TCIOFLUSH
  781. external tcflush: file_descr -> flush_queue -> unit = "unix_tcflush"
  782. type flow_action = TCOOFF | TCOON | TCIOFF | TCION
  783. external tcflow: file_descr -> flow_action -> unit = "unix_tcflow"
  784. external setsid : unit -> int = "unix_setsid"
  785. (* High-level process management (system, popen) *)
  786. let system cmd =
  787. match fork() with
  788. 0 -> begin try
  789. execv "/bin/sh" [| "/bin/sh"; "-c"; cmd |]
  790. with _ ->
  791. exit 127
  792. end
  793. | id -> snd(waitpid [] id)
  794. let rec safe_dup fd =
  795. let new_fd = dup fd in
  796. if new_fd >= 3 then
  797. new_fd
  798. else begin
  799. let res = safe_dup fd in
  800. close new_fd;
  801. res
  802. end
  803. let safe_close fd =
  804. try close fd with Unix_error(_,_,_) -> ()
  805. let perform_redirections new_stdin new_stdout new_stderr =
  806. let newnewstdin = safe_dup new_stdin in
  807. let newnewstdout = safe_dup new_stdout in
  808. let newnewstderr = safe_dup new_stderr in
  809. safe_close new_stdin;
  810. safe_close new_stdout;
  811. safe_close new_stderr;
  812. dup2 newnewstdin stdin; close newnewstdin;
  813. dup2 newnewstdout stdout; close newnewstdout;
  814. dup2 newnewstderr stderr; close newnewstderr
  815. let create_process cmd args new_stdin new_stdout new_stderr =
  816. match fork() with
  817. 0 ->
  818. begin try
  819. perform_redirections new_stdin new_stdout new_stderr;
  820. execvp cmd args
  821. with _ ->
  822. exit 127
  823. end
  824. | id -> id
  825. let create_process_env cmd args env new_stdin new_stdout new_stderr =
  826. match fork() with
  827. 0 ->
  828. begin try
  829. perform_redirections new_stdin new_stdout new_stderr;
  830. execvpe cmd args env
  831. with _ ->
  832. exit 127
  833. end
  834. | id -> id
  835. type popen_process =
  836. Process of in_channel * out_channel
  837. | Process_in of in_channel
  838. | Process_out of out_channel
  839. | Process_full of in_channel * out_channel * in_channel
  840. let popen_processes = (Hashtbl.create 7 : (popen_process, int) Hashtbl.t)
  841. let open_proc cmd proc input output toclose =
  842. match fork() with
  843. 0 -> if input <> stdin then begin dup2 input stdin; close input end;
  844. if output <> stdout then begin dup2 output stdout; close output end;
  845. List.iter close toclose;
  846. begin try execv "/bin/sh" [| "/bin/sh"; "-c"; cmd |]
  847. with _ -> exit 127
  848. end
  849. | id -> Hashtbl.add popen_processes proc id
  850. let open_process_in cmd =
  851. let (in_read, in_write) = pipe() in
  852. let inchan = in_channel_of_descr in_read in
  853. open_proc cmd (Process_in inchan) stdin in_write [in_read];
  854. close in_write;
  855. inchan
  856. let open_process_out cmd =
  857. let (out_read, out_write) = pipe() in
  858. let outchan = out_channel_of_descr out_write in
  859. open_proc cmd (Process_out outchan) out_read stdout [out_write];
  860. close out_read;
  861. outchan
  862. let open_process cmd =
  863. let (in_read, in_write) = pipe() in
  864. let (out_read, out_write) = pipe() in
  865. let inchan = in_channel_of_descr in_read in
  866. let outchan = out_channel_of_descr out_write in
  867. open_proc cmd (Process(inchan, outchan)) out_read in_write
  868. [in_read; out_write];
  869. close out_read;
  870. close in_write;
  871. (inchan, outchan)
  872. let open_proc_full cmd env proc input output error toclose =
  873. match fork() with
  874. 0 -> dup2 input stdin; close input;
  875. dup2 output stdout; close output;
  876. dup2 error stderr; close error;
  877. List.iter close toclose;
  878. begin try execve "/bin/sh" [| "/bin/sh"; "-c"; cmd |] env
  879. with _ -> exit 127
  880. end
  881. | id -> Hashtbl.add popen_processes proc id
  882. let open_process_full cmd env =
  883. let (in_read, in_write) = pipe() in
  884. let (out_read, out_write) = pipe() in
  885. let (err_read, err_write) = pipe() in
  886. let inchan = in_channel_of_descr in_read in
  887. let outchan = out_channel_of_descr out_write in
  888. let errchan = in_channel_of_descr err_read in
  889. open_proc_full cmd env (Process_full(inchan, outchan, errchan))
  890. out_read in_write err_write [in_read; out_write; err_read];
  891. close out_read;
  892. close in_write;
  893. close err_write;
  894. (inchan, outchan, errchan)
  895. let find_proc_id fun_name proc =
  896. try
  897. let pid = Hashtbl.find popen_processes proc in
  898. Hashtbl.remove popen_processes proc;
  899. pid
  900. with Not_found ->
  901. raise(Unix_error(EBADF, fun_name, ""))
  902. let rec waitpid_non_intr pid =
  903. try waitpid [] pid
  904. with Unix_error (EINTR, _, _) -> waitpid_non_intr pid
  905. let close_process_in inchan =
  906. let pid = find_proc_id "close_process_in" (Process_in inchan) in
  907. close_in inchan;
  908. snd(waitpid_non_intr pid)
  909. let close_process_out outchan =
  910. let pid = find_proc_id "close_process_out" (Process_out outchan) in
  911. close_out outchan;
  912. snd(waitpid_non_intr pid)
  913. let close_process (inchan, outchan) =
  914. let pid = find_proc_id "close_process" (Process(inchan, outchan)) in
  915. close_in inchan;
  916. begin try close_out outchan with Sys_error _ -> () end;
  917. snd(waitpid_non_intr pid)
  918. let close_process_full (inchan, outchan, errchan) =
  919. let pid =
  920. find_proc_id "close_process_full"
  921. (Process_full(inchan, outchan, errchan)) in
  922. close_in inchan;
  923. begin try close_out outchan with Sys_error _ -> () end;
  924. close_in errchan;
  925. snd(waitpid_non_intr pid)
  926. (* High-level network functions *)
  927. let open_connection sockaddr =
  928. let sock =
  929. socket (domain_of_sockaddr sockaddr) SOCK_STREAM 0 in
  930. try
  931. connect sock sockaddr;
  932. (in_channel_of_descr sock, out_channel_of_descr sock)
  933. with exn ->
  934. close sock; raise exn
  935. let shutdown_connection inchan =
  936. shutdown (descr_of_in_channel inchan) SHUTDOWN_SEND
  937. let establish_server server_fun sockaddr =
  938. let sock =
  939. socket (domain_of_sockaddr sockaddr) SOCK_STREAM 0 in
  940. setsockopt sock SO_REUSEADDR true;
  941. bind sock sockaddr;
  942. listen sock 5;
  943. while true do
  944. let (s, caller) = accept sock in
  945. (* The "double fork" trick, the process which calls server_fun will not
  946. leave a zombie process *)
  947. match fork() with
  948. 0 -> if fork() <> 0 then exit 0; (* The son exits, the grandson works *)
  949. let inchan = in_channel_of_descr s in
  950. let outchan = out_channel_of_descr s in
  951. server_fun inchan outchan;
  952. close_out outchan;
  953. (* The file descriptor was already closed by close_out.
  954. close_in inchan;
  955. *)
  956. exit 0
  957. | id -> close s; ignore(waitpid [] id) (* Reclaim the son *)
  958. done