File: unix.lisp

package info (click to toggle)
acl2 8.6%2Bdfsg-2
  • links: PTS
  • area: main
  • in suites: trixie
  • size: 1,111,420 kB
  • sloc: lisp: 17,818,294; java: 125,359; python: 28,122; javascript: 23,458; cpp: 18,851; ansic: 11,569; perl: 7,678; xml: 5,591; sh: 3,976; makefile: 3,833; ruby: 2,633; yacc: 1,126; ml: 763; awk: 295; csh: 233; lex: 197; php: 178; tcl: 49; asm: 23; haskell: 17
file content (907 lines) | stat: -rw-r--r-- 27,153 bytes parent folder | download | duplicates (4)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
;;;; -*- Mode: lisp; indent-tabs-mode: nil -*-
;;;
;;; unix.lisp --- CL-POSIX bindings.
;;;
;;; Copyright (C) 2005-2006, Matthew Backes  <lucca@accela.net>
;;; Copyright (C) 2005-2006, Dan Knapp  <dankna@accela.net> and
;;; Copyright (C) 2007, Stelian Ionescu  <stelian.ionescu-zeus@poste.it>
;;;
;;; Permission is hereby granted, free of charge, to any person
;;; obtaining a copy of this software and associated documentation
;;; files (the "Software"), to deal in the Software without
;;; restriction, including without limitation the rights to use, copy,
;;; modify, merge, publish, distribute, sublicense, and/or sell copies
;;; of the Software, and to permit persons to whom the Software is
;;; furnished to do so, subject to the following conditions:
;;;
;;; The above copyright notice and this permission notice shall be
;;; included in all copies or substantial portions of the Software.
;;;
;;; THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
;;; EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
;;; MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
;;; NONINFRINGEMENT.  IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
;;; HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
;;; WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
;;; OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
;;; DEALINGS IN THE SOFTWARE.

(in-package #:osicat-posix)

;;; Needed for clock_gettime() and friends.
(define-foreign-library librt
  (:linux (:or "librt.so.1" "librt.so")))
(use-foreign-library librt)

;;;; stdlib.h

(defsyscall ("mkstemp" %mkstemp) :int
  (template :pointer))

(defun mkstemp (&optional (template ""))
  (let ((template (concatenate 'string template "XXXXXX")))
    (with-foreign-string (ptr (filename template))
      (values (%mkstemp ptr) (foreign-string-to-lisp ptr)))))

(defsyscall ("mkdtemp" %mkdtemp) :string
  (template filename-designator))

(defun mkdtemp (&optional (template ""))
  (%mkdtemp (concatenate 'string template "XXXXXX")))

(defsyscall ("mkstemps" %mkstemps) :int
  (template :pointer)
  (suffix-length :int))

(defun mkstemps (template suffix)
  (let ((actual-template (concatenate 'string
                                      template
                                      "XXXXXX"
                                      suffix)))
    (with-foreign-string (ptr-template actual-template)
      (values (%mkstemps ptr-template (length suffix))
              (foreign-string-to-lisp ptr-template)))))

;;;; unistd.h

;;; directories

(defsyscall "fchdir" :int
  (fildes :int))

(defsyscall "link" :int
  (path1 filename-designator)
  (path2 filename-designator))

(defsyscall "linkat" :int
  (olddirfd :int)
  (oldpath  filename-designator)
  (newdirfd :int)
  (newpath  filename-designator)
  (flags    :int))

(defsyscall "isatty" :int
  (fd file-descriptor-designator))

(defsyscall "mkdirat" :int
  (dirfd    file-descriptor-designator)
  (pathname filename-designator)
  (mode     mode))

;;; files

(defsyscall ("openat" %openat) :int
  (dirfd    :int)
  (pathname filename-designator)
  (flags    :int)
  (mode     mode))

(defun openat (dirfd pathname flags &optional (mode *default-open-mode*))
  ;; Let's just use O_BINARY always unless there's a good reason not to.
  #+windows (setq flags (logior flags o-binary))
  (cond
    ((integerp mode) (%openat dirfd pathname flags mode))
    (t (error "Wrong mode: ~S" mode))))

(defsyscall ("readlink" %readlink) ssize
  (path    filename-designator)
  (buf     :pointer)
  (bufsize size))

(defun readlink (path)
  "Read value of a symbolic link."
  (with-foreign-pointer (buf 4096 bufsize)
    (let ((count (%readlink path buf bufsize)))
      (values (foreign-string-to-lisp buf :count count)))))

(defsyscall ("readlinkat" %readlinkat) ssize
  (dirfd   file-descriptor-designator)
  (path    filename-designator)
  (buf     :pointer)
  (bufsize size))

(defun readlinkat (dirfd path)
  "Read value of a symbolic link, relative to a directory."
  (with-foreign-pointer (buf 4096 bufsize)
    (let ((count (%readlinkat dirfd path buf bufsize)))
      (values (foreign-string-to-lisp buf :count count)))))

(defsyscall "symlink" :int
  "Creates a symbolic link"
  (name1 filename-designator)
  (name2 filename-designator))

(defsyscall "symlinkat" :int
  (target   filename-designator)
  (newdirfd :int)
  (linkpath filename-designator))

(defsyscall "chown" :int
  "Change ownership of a file."
  (path  filename-designator)
  (owner uid)
  (group uid))

(defsyscall "fchown" :int
  "Change ownership of an open file."
  (fd    file-descriptor-designator)
  (owner uid)
  (group uid))

(defsyscall "lchown" :int
  "Change ownership of a file or symlink."
  (path  filename-designator)
  (owner uid)
  (group uid))

(defsyscall "fchownat" :int
  "Change ownership of an open file."
  (dirfd :int)
  (path  filename-designator)
  (owner uid)
  (group uid)
  (flags :int))

(defsyscall "fchmod" :int
  (fd   file-descriptor-designator)
  (mode mode))

(defsyscall "sync" :void
  "Schedule all file system buffers to be written to disk.")

(defsyscall "fsync" :int
  (fildes file-descriptor-designator))

(defsyscall "lockf" :int
  "Apply, test or remove a POSIX lock on an open file."
  (fd  file-descriptor-designator)
  (cmd :int)
  (len off))

(defsyscall "unlinkat" :int
  (dirfd    :int)
  (pathname filename-designator)
  (flags    :int))

(defsyscall "renameat" :int
  (olddirfd :int)
  (oldpath  filename-designator)
  (newdirfd :int)
  (newpath  filename-designator))

(defsyscall ("utimes" %utimes) :int
  (filename filename-designator)
  (times (:pointer (:array (:struct timeval) 2))))

(defun utimes (filename atime-sec atime-usec mtime-sec mtime-usec)
  "Set file access and modification time with microsecond precision."
  (with-foreign-object (times '(:struct timeval) 2)
    (let ((mtime (inc-pointer times size-of-timeval)))
      (setf (foreign-slot-value times '(:struct timeval) 'sec) atime-sec
            (foreign-slot-value times '(:struct timeval) 'usec) atime-usec
            (foreign-slot-value mtime '(:struct timeval) 'sec) mtime-sec
            (foreign-slot-value mtime '(:struct timeval) 'usec) mtime-usec))
    (%utimes filename times)))

(defsyscall ("futimens" %futimens) :int
  (fd    file-descriptor-designator)
  (times (:pointer (:array (:struct timespec) 2))))

(defun futimens (fd atime-sec atime-nsec mtime-sec mtime-nsec)
  "Set file access and modification time with nanosecond precision."
  (with-foreign-object (times '(:struct timespec) 2)
    (let ((mtime (inc-pointer times size-of-timespec)))
      (setf (foreign-slot-value times '(:struct timespec) 'sec) atime-sec
            (foreign-slot-value times '(:struct timespec) 'nsec) atime-nsec
            (foreign-slot-value mtime '(:struct timespec) 'sec) mtime-sec
            (foreign-slot-value mtime '(:struct timespec) 'nsec) mtime-nsec))
    (%futimens fd times)))

(defsyscall ("utimensat" %utimensat) :int
  (dirfd    :int)
  (pathname filename-designator)
  (times    (:pointer (:array (:struct timespec) 2)))
  (flags    :int))

(defun utimensat (dirfd filename atime-sec atime-nsec mtime-sec mtime-nsec flags)
  "Set file access and modification time with nanosecond precision."
  (with-foreign-object (times '(:struct timespec) 2)
    (let ((mtime (inc-pointer times size-of-timespec)))
      (setf (foreign-slot-value times '(:struct timespec) 'sec) atime-sec
            (foreign-slot-value times '(:struct timespec) 'nsec) atime-nsec
            (foreign-slot-value mtime '(:struct timespec) 'sec) mtime-sec
            (foreign-slot-value mtime '(:struct timespec) 'nsec) mtime-nsec))
    (%utimensat dirfd filename times flags)))

;;; processes

(defcfun ("nice" %nice) :int
  (increment :int))

(defun nice (increment)
  "Change process priority."
  (set-errno 0)
  (let ((r (%nice increment)))
    (if (and (= r -1) (/= (get-errno) 0))
        (posix-error)
        r)))

(defsyscall "fork" pid
  "Create a child process.")

(defsyscall "exit" :int
  "Exit a process immediately."
  (code :int))

(defcfun ("wait" %wait) pid
  (stat-loc :pointer))

(defun wait ()
  "Wait for any child process to terminate."
  (with-foreign-object (stat-loc :int)
    (let ((result (%wait stat-loc)))
      (values result (mem-ref stat-loc :int)))))

(defcfun ("waitpid" %waitpid) pid
  (pid pid)
  (stat-loc :pointer)
  (options :int))

(defun waitpid (pid &key (no-hang nil) (untraced nil))
  "Wait for a specific child process to terminate"
  (with-foreign-object (stat-loc :int)
    (let ((result (%waitpid pid stat-loc (logior (if no-hang wnohang 0)
                                                 (if untraced wuntraced 0)))))
      (values result (mem-ref stat-loc :int)))))

(defsyscall "getegid" gid
  "Get effective group id of the current process.")

(defsyscall "geteuid" uid
  "Get effective user id of the current process.")

(defsyscall "getgid" gid
  "Get real group id of the current process.")

(defsyscall "getpgid" pid
  "Get process group id of a process."
  (pid pid))

(defsyscall "getpgrp" pid
  "Get process group id of the current process.")

(defsyscall "getpid" pid
  "Returns the process id of the current process")

(defsyscall "getppid" pid
  "Returns the process id of the current process's parent")

(defsyscall "getuid" uid
  "Get real user id of the current process.")

(defsyscall "setegid" :int
  "Set effective group id of the current process."
  (gid gid))

(defsyscall "seteuid" :int
  "Set effective user id of the current process."
  (uid uid))

(defsyscall "setgid" :int
  "Get real group id of the current process."
  (gid gid))

(defsyscall "setpgid" :int
  "Set process group id of a process."
  (pid  pid)
  (pgid pid))

(defsyscall "setpgrp" pid
  "Set process group id of the current process.")

(defsyscall "setregid" :int
  "Set real and effective group id of the current process."
  (rgid gid)
  (egid gid))

(defsyscall "setreuid" :int
  "Set real and effective user id of the current process."
  (ruid uid)
  (euid uid))

(defsyscall "setsid" pid
  "Create session and set process group id of the current process.")

(defsyscall "setuid" :int
  "Set real user id of the current process."
  (uid uid))

;;; environment

(defsyscall "setenv" :int
  "Changes the value of an environment variable"
  (name  :string)
  (value :string))

(defsyscall "unsetenv" :int
  "Removes the binding of an environment variable"
  (name :string))

;;; time

(defsyscall "usleep" :int
  (useconds useconds))

;;; misc

(defsyscall ("gethostname" %gethostname) :int
  (name    :pointer)
  (namelen size))

(defun gethostname ()
  (with-foreign-pointer-as-string ((cstr size) 256)
    (%gethostname cstr size)))

(defsyscall ("getdomainname" %getdomainname) :int
  (name    :pointer)
  (namelen size))

(defun getdomainname ()
  (with-foreign-pointer-as-string ((cstr size) 256)
    (%getdomainname cstr size)))

(defsyscall ("sysconf" %sysconf) :long
  (name :int))

(defun sysconf (name)
  "Get value of configurable system variables."
  (set-errno 0)
  (let ((r (%sysconf name)))
    (if (and (= r -1) (/= (get-errno) 0))
        (posix-error)
        r)))

(defun getpagesize ()
  "Get memory page size."
  (sysconf sc-pagesize))

;;;; fcntl.h

(defun fcntl (fd cmd &optional (arg nil argp))
  (cond
    ((not argp) (fcntl-without-arg fd cmd))
    ((integerp arg) (fcntl-with-int-arg fd cmd arg))
    ((pointerp arg) (fcntl-with-pointer-arg fd cmd arg))
    (t (error "Wrong argument to fcntl: ~S" arg))))

;;;; ioctl.h

(defsyscall ("ioctl" %ioctl-without-arg) :int
  (fd      file-descriptor-designator)
  (request :int))

(defsyscall ("ioctl" %ioctl-with-arg) :int
 (fd      file-descriptor-designator)
 (request :int)
 (arg     :pointer))

(defun ioctl (fd request &optional (arg nil argp))
  "Control device."
  (cond
    ((not argp) (%ioctl-without-arg fd request))
    ((pointerp arg) (%ioctl-with-arg fd request arg))
    (t (error "Wrong argument to ioctl: ~S" arg))))

;;;; signal.h

(defsyscall "kill" :int
  "Send signal to a process."
  (pid pid)
  (sig :int))

;;;; sys/mman.h

(defsyscall "mlock" :int
  "Lock a range of process address space."
  (addr :pointer)
  (len  size))

(defsyscall "munlock" :int
  "Unlock a range of process address space."
  (addr :pointer)
  (len  size))

(defsyscall "mlockall" :int
  "Lock the address space of a process."
  (flags :int))

(defsyscall "munlockall" :int)

(defsyscall "munmap" :int
  "Unmap pages of memory."
  (addr :pointer)
  (len  size))

(defsyscall "msync" :int
  "Synchronize memory with physical storage."
  (addr  :pointer)
  (len   size)
  (flags :int))

(defsyscall "mprotect" :int
  "Set protection of memory mapping."
  (addr  :pointer)
  (len   size)
  (flags :int))

;;;; sys/time.h

(defsyscall ("gettimeofday" %gettimeofday) :int
  (tp  :pointer)
  (tzp :pointer))

(defun gettimeofday ()
  "Return the time in seconds and microseconds."
  (with-foreign-object (tv '(:struct timeval))
    (with-foreign-slots ((sec usec) tv (:struct timeval))
      (%gettimeofday tv (null-pointer))
      (values sec usec))))

;;; FIXME: or we can implement this through the MACH functions.
#+darwin
(progn
  (unsupported-function clock-getres)
  (unsupported-function clock-gettime)
  (unsupported-function clock-settime))

#-darwin
(progn
  (defsyscall ("clock_getres" %clock-getres) :int
    "Returns the resolution of the clock CLOCKID."
    (clockid clockid)
    (res     :pointer))

  (defun clock-getres (clock-id)
    (with-foreign-object (ts '(:struct timespec))
      (with-foreign-slots ((sec nsec) ts (:struct timespec))
        (%clock-getres clock-id ts)
        (values sec nsec))))

  (defsyscall ("clock_gettime" %clock-gettime) :int
    (clockid clockid)
    (tp      :pointer))

  (defun clock-gettime (clock-id)
    "Returns the time of the clock CLOCKID."
    (with-foreign-object (ts '(:struct timespec))
      (with-foreign-slots ((sec nsec) ts (:struct timespec))
        (%clock-gettime clock-id ts)
        (values sec nsec))))

  (defsyscall ("clock_settime" %clock-settime) :int
    (clockid clockid)
    (tp      :pointer))

  (defun clock-settime (clock-id)
    "Sets the time of the clock CLOCKID."
    (with-foreign-object (ts '(:struct timespec))
      (with-foreign-slots ((sec nsec) ts (:struct timespec))
        (%clock-settime clock-id ts)
        (values sec nsec)))))

#-(or darwin openbsd)
(progn
  (defsyscall ("timer_create" %timer-create) :int
    (clockid clockid)
    (sigevent :pointer)
    (timer :pointer))

  (defun timer-create (clock-id notify-method
                       &key signal notify-value function attributes
                            #+linux thread-id)
    "Creates a new per-process interval timer."
    (with-foreign-object (se '(:struct sigevent))
      (with-foreign-slots ((notify signo value
                            notify-function notify-attributes
                            #+linux notify-thread-id)
                           se (:struct sigevent))
        (with-foreign-slots ((int) value (:union sigval))
          (setf notify notify-method)
          (cond ((= notify-method sigev-none))
                ((= notify-method sigev-signal)
                 (setf signo signal
                       int notify-value))
                #+linux
                ((= notify-method (logior sigev-signal sigev-thread-id))
                 (setf signo signal
                       notify-thread-id thread-id
                       int notify-value))
                ((= notify-method sigev-thread)
                 (setf notify-function function
                       notify-attributes attributes
                       int notify-value))
                (t (error "bad timer notification method")))
          (with-foreign-object (timer 'timer)
            (%timer-create clock-id se timer)
            (mem-ref timer :int))))))

  (defsyscall ("timer_delete" timer-delete) :int
    "Deletes the timer identified by TIMER-ID."
    (timer-id timer))

  (defsyscall ("timer_getoverrun" timer-getoverrun) :int
    "Returns the overrun count for the timer identified by TIMER-ID."
    (timer-id timer))

  (defsyscall ("timer_gettime" %timer-gettime) :int
    (timer timer)
    (itimerspec :pointer))

  (defun deconstruct-itimerspec (its)
    (with-foreign-slots ((interval value) its (:struct itimerspec))
      (with-foreign-slots ((sec nsec) interval (:struct timespec))
        (let ((interval-sec sec)
              (interval-nsec nsec))
          (with-foreign-slots ((sec nsec) value (:struct timespec))
            (values interval-sec interval-nsec sec nsec))))))

  (defun timer-gettime (timer-id)
    "Returns the interval and the time until next expiration for the
timer specified by TIMER-ID.  Both the interval and the time are returned
as seconds and nanoseconds, so four values are returned."
    (with-foreign-object (its '(:struct itimerspec))
      (%timer-gettime timer-id its)
      (values-list (multiple-value-list (deconstruct-itimerspec its)))))

  (defsyscall ("timer_settime" %timer-settime) :int
    (timer timer)
    (flags :int)
    (new :pointer)
    (old :pointer))

  (defun timer-settime (timer-id flags interval-sec interval-nsec
                        initial-sec initial-nsec
                        &optional return-previous-p)
    "Arms or disarms the timer identified by TIMER-ID."
    (with-foreign-object (new '(:struct itimerspec))
      (with-foreign-slots ((interval value) new (:struct itimerspec))
        (with-foreign-slots ((sec nsec) interval (:struct timespec))
          (setf sec interval-sec
                nsec interval-nsec)
          (with-foreign-slots ((sec nsec) value (:struct timespec))
            (setf sec initial-sec
                  nsec initial-nsec)
            (with-foreign-object (old '(:struct itimerspec))
              (let ((result (%timer-settime timer-id flags new old)))
                (if return-previous-p
                    (values-list (multiple-value-list (deconstruct-itimerspec old)))
                    result)))))))))

;;;; sys/stat.h

(defun lstat (path)
  "Get information about a file or symlink."
  (funcall-stat #'%lstat path))

(defun fstatat (dirfd pathname flags)
  "Get information about a file located in the DIRFD directory"
  (with-foreign-object (buf '(:struct stat))
    (%fstatat dirfd pathname buf flags)
    (make-instance 'stat :pointer buf)))

(defsyscall "mkfifo" :int
  "Create a FIFO (named pipe)."
  (path filename-designator)
  (mode mode))

(defsyscall "mkfifoat" :int
  "Create a FIFO (named pipe)."
  (dirfd :int)
  (path filename-designator)
  (mode mode))

;;;; syslog.h

(defvar *syslog-identity* nil)

(defsyscall ("openlog" %openlog) :void
  (ident    :string)
  (option   :int)
  (facility syslog-facilities))

;;; not my BUG: on Linux openlog() keeps a pointer to the "ident"
;;; string which syslog() then uses when logging, therefore
;;; we need to keep the foreign string around.
;;;
;;; FIXME: this workaround seems broken to me. --luis
(defun openlog (name options &optional (facility :user))
  "Open system log."
  (when *syslog-identity*
    (foreign-string-free *syslog-identity*)
    (setf *syslog-identity* nil))
  (setf *syslog-identity* (foreign-string-alloc name))
  (%openlog *syslog-identity* options facility))

(defsyscall ("syslog" %syslog) :void
  (priority syslog-priorities)
  (format   :string)
  (message  :string))

(defun syslog (priority format &rest args)
  "Send a message to the syslog facility, with severity level
PRIORITY.  The message will be formatted by CL:FORMAT (rather
than C's printf) with format string FORMAT and arguments ARGS."
  (%syslog priority "%s" (format nil "~?" format args)))

(defsyscall ("closelog" %closelog) :void)

(defun closelog ()
  "Close system log."
  (%closelog)
  (when *syslog-identity*
    (foreign-string-free *syslog-identity*)
    (setf *syslog-identity* nil)))

(defsyscall "setlogmask" :int
  (mask :int))

;;;; sys/resource.h

(defun getrlimit (resource)
  (with-foreign-object (rl '(:struct rlimit))
    (with-foreign-slots ((cur max) rl (:struct rlimit))
      (%getrlimit resource rl)
      (values cur max))))

(defun setrlimit (resource soft-limit hard-limit)
  (with-foreign-object (rl '(:struct rlimit))
    (with-foreign-slots ((cur max) rl (:struct rlimit))
      (setf cur soft-limit
            max hard-limit)
      (%setrlimit resource rl))))

(defsyscall ("getrusage" %getrusage) :int
  (who   :int)
  (usage :pointer))

;;; TODO: it might be more convenient to return a wrapper object here
;;; instead like we do in STAT.
(defun getrusage (who)
  (with-foreign-object (ru '(:struct rusage))
    (%getrusage who ru)
    (with-foreign-slots ((maxrss ixrss idrss isrss minflt majflt nswap inblock
                          oublock msgsnd msgrcv nsignals nvcsw nivcsw)
                         ru (:struct rusage))
      (values (foreign-slot-value
               (foreign-slot-pointer ru '(:struct rusage) 'utime)
               '(:struct timeval) 'sec)
              (foreign-slot-value
               (foreign-slot-pointer ru '(:struct rusage) 'utime)
               '(:struct timeval) 'usec)
              (foreign-slot-value
               (foreign-slot-pointer ru '(:struct rusage) 'stime)
               '(:struct timeval) 'sec)
              (foreign-slot-value
               (foreign-slot-pointer ru '(:struct rusage) 'stime)
               '(:struct timeval) 'usec)
              maxrss ixrss idrss isrss minflt majflt
              nswap inblock oublock msgsnd
              msgrcv nsignals nvcsw nivcsw))))

(defsyscall "getpriority" :int
  (which :int)
  (who   :int))

(defsyscall "setpriority" :int
  (which :int)
  (who   :int)
  (value :int))

;;;; sys/utsname.h

(defsyscall ("uname" %uname) :int
  (buf :pointer))

(defun uname ()
  "Get name and information about current kernel."
  (with-foreign-object (buf '(:struct utsname))
    (bzero buf size-of-utsname)
    (%uname buf)
    (macrolet ((utsname-slot (name)
                 `(foreign-string-to-lisp
                   (foreign-slot-pointer buf '(:struct utsname) ',name))))
      (values (utsname-slot sysname)
              (utsname-slot nodename)
              (utsname-slot release)
              (utsname-slot version)
              (utsname-slot machine)))))

;;;; sys/statvfs.h

(defun funcall-statvfs (fn arg)
  (with-foreign-object (buf '(:struct statvfs))
    (funcall fn arg buf)
    (with-foreign-slots ((bsize frsize blocks bfree bavail files
                          ffree favail fsig flag namemax)
                         buf (:struct statvfs))
      (values bsize frsize blocks bfree bavail files
              ffree favail fsig flag namemax))))

(defun statvfs (path)
  "Retrieve file system information."
  (funcall-statvfs #'%statvfs path))

(defun fstatvfs (fd)
  "Retrieve file system information."
  (funcall-statvfs #'%fstatvfs fd))

;;;; pwd.h

;;; Should actually be
;;;   (errno-wrapper :int :error-predicate (lambda (x) (not (zerop x))))
;;; but see explanation below.
(defcfun ("getpwuid_r" %getpwuid-r)
    :int
  (uid     uid)
  (pwd     :pointer)
  (buffer  :pointer)
  (bufsize size)
  (result  :pointer))

(defcfun ("getpwnam_r" %getpwnam-r)
    :int
  (name    :string)
  (pwd     :pointer)
  (buffer  :pointer)
  (bufsize size)
  (result  :pointer))

(defun funcall-getpw (fn arg)
  ;; http://pubs.opengroup.org/onlinepubs/009695399/functions/getpwnam.html
  ;; "Applications wishing to check for error situations should set
  ;; errno to 0 before calling getpwnam(). If getpwnam() returns null
  ;; pointer and errno is non-zero, an error occured.
  (set-errno 0)
  (with-foreign-objects ((pw '(:struct passwd)) (pwp :pointer))
    (with-foreign-pointer (buf 4096 bufsize)
      (with-foreign-slots ((name passwd uid gid gecos dir shell) pw (:struct passwd))
        (let ((ret (funcall fn arg pw buf bufsize pwp)))
          (cond ((and (null-pointer-p (mem-ref pwp :pointer))
                      (not (zerop (get-errno))))
                 (posix-error ret))
                ((and (null-pointer-p (mem-ref pwp :pointer))
                      (zerop (get-errno)))
                 nil)
                (t (values name passwd uid gid gecos dir shell))))))))

(defun getpwuid (uid)
  "Gets the password-entry of a user, by user id."
  (funcall-getpw #'%getpwuid-r uid))

(defun getpwnam (name)
  "Gets the password-entry of a user, by username."
  (funcall-getpw #'%getpwnam-r name))

;;;; grp.h

(defsyscall ("getgrgid_r" %getgrgid-r) :int
  (uid     uid)
  (grp     :pointer)
  (buffer  :pointer)
  (bufsize size)
  (result  :pointer))

(defsyscall ("getgrnam_r" %getgrnam-r) :int
  (name    :string)
  (grp     :pointer)
  (buffer  :pointer)
  (bufsize size)
  (result  :pointer))

(defun funcall-getgr (fn arg)
  (with-foreign-objects ((gr '(:struct group)) (grp :pointer))
    (with-foreign-pointer (buf 4096 bufsize)
      (with-foreign-slots ((name passwd gid) gr (:struct group))
        (if (and (zerop (funcall fn arg gr buf bufsize grp))
                 (null-pointer-p (mem-ref grp :pointer)))
            (values)
            (values name passwd gid))))))

(defun getgrgid (gid)
  "Gets a group-entry, by group id. (reentrant)"
  (funcall-getgr #'%getgrgid-r gid))

(defun getgrnam (name)
  "Gets a group-entry, by group name. (reentrant)"
  (funcall-getgr #'%getgrnam-r name))

(defsyscall ("setgroups" %setgroups) :int
  (count size)
  (gids :pointer))

(defun setgroups (gids)
  (with-foreign-object (list 'gid (length gids))
    (loop for id in gids and i upfrom 0
          do (setf (mem-aref list 'gid i) id))
    (%setgroups (length gids) list)))

(defsyscall "initgroups" :int
  (user :string)
  (gid gid))

;;;; dirent.h

(defsyscall "opendir" :pointer
  "Opens a directory for listing of its contents"
  (filename filename-designator))

(defsyscall "closedir" :int
  "Closes a directory when done listing its contents"
  (dir :pointer))

(defun readdir (dir)
  "Reads an item from the listing of a directory (reentrant)"
  (with-foreign-objects ((entry '(:struct dirent)) (result :pointer))
    (%readdir-r dir entry result)
    (if (null-pointer-p (mem-ref result :pointer))
        nil
        (with-foreign-slots ((name #-sunos type #-sunos fileno) entry (:struct dirent))
          (values (foreign-string-to-lisp name) #-sunos type #-sunos fileno)))))

(defsyscall "rewinddir" :void
  "Rewinds a directory."
  (dir :pointer))

(defsyscall "seekdir" :void
  "Seeks a directory."
  (dir :pointer)
  (pos :long))

;;; FIXME: According to POSIX docs "no errors are defined" for
;;; telldir() but Linux manpages specify a possible EBADF.
(defsyscall "telldir" off
  "Returns the current location in a directory"
  (dir :pointer))

;;;; sys/uio.h

(defsyscall "readv" ssize
  (fd    file-descriptor-designator)
  (iov   :pointer)
  (count size))

(defsyscall "writev" ssize
  (fd    file-descriptor-designator)
  (iov   :pointer)
  (count size))

;; termios.h

(defsyscall "tcgetattr" :int
  (fd      file-descriptor-designator)
  (termios :pointer))

(defsyscall "tcsetattr" :int
  (fd      file-descriptor-designator)
  (mode    :int)
  (termios :pointer))