2 * nixio - Linux I/O library for lua
4 * Copyright (C) 2009 Steven Barth <steven@midlink.org>
6 * Licensed under the Apache License, Version 2.0 (the "License");
7 * you may not use this file except in compliance with the License.
8 * You may obtain a copy of the License at
10 * http://www.apache.org/licenses/LICENSE-2.0
12 * Unless required by applicable law or agreed to in writing, software
13 * distributed under the License is distributed on an "AS IS" BASIS,
14 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 * See the License for the specific language governing permissions and
16 * limitations under the License.
28 #include <sys/param.h>
34 #include <sys/sendfile.h>
36 #include <sys/types.h>
37 #include <sys/socket.h>
43 /* guess what sucks... */
46 #include <sys/syscall.h>
47 ssize_t splice(int __fdin, __off64_t *__offin, int __fdout,
48 __off64_t *__offout, size_t __len, unsigned int __flags) {
50 return syscall(__NR_splice, __fdin, __offin, __fdout, __offout, __len, __flags);
64 #undef SPLICE_F_NONBLOCK
67 #define SPLICE_F_MOVE 1
68 #define SPLICE_F_NONBLOCK 2
69 #define SPLICE_F_MORE 4
71 #endif /* __UCLIBC__ */
74 * splice(fd_in, fd_out, length, flags)
76 static int nixio_splice(lua_State *L) {
77 int fd_in = nixio__checkfd(L, 1);
78 int fd_out = nixio__checkfd(L, 2);
79 size_t len = luaL_checkinteger(L, 3);
80 int flags = luaL_optinteger(L, 4, 0);
84 spliced = splice(fd_in, NULL, fd_out, NULL, len, flags);
85 } while (spliced == -1 && errno == EINTR);
88 return nixio__perror(L);
91 lua_pushnumber(L, spliced);
96 * Translate splice flags to integer
98 static int nixio_splice_flags(lua_State *L) {
99 const int j = lua_gettop(L);
101 for (int i=1; i<=j; i++) {
102 const char *flag = luaL_checkstring(L, i);
103 if (!strcmp(flag, "move")) {
104 flags |= SPLICE_F_MOVE;
105 } else if (!strcmp(flag, "nonblock")) {
106 flags |= SPLICE_F_NONBLOCK;
107 } else if (!strcmp(flag, "more")) {
108 flags |= SPLICE_F_MORE;
110 return luaL_argerror(L, i, "supported values: "
111 "move, nonblock, more");
114 lua_pushinteger(L, flags);
119 #endif /* _GNU_SOURCE */
122 * sendfile(outfd, infd, length)
124 static int nixio_sendfile(lua_State *L) {
125 int sock = nixio__checksockfd(L);
126 int infd = nixio__checkfd(L, 2);
127 size_t len = luaL_checkinteger(L, 3);
132 spliced = sendfile(sock, infd, NULL, len);
133 } while (spliced == -1 && errno == EINTR);
136 return nixio__perror(L);
140 const off_t offset = lseek(infd, 0, SEEK_CUR);
143 r = sendfile(infd, sock, offset, len, NULL, &spliced, 0);
144 } while (r == -1 && errno == EINTR);
147 return nixio__perror(L);
151 lua_pushnumber(L, spliced);
156 static const luaL_reg R[] = {
158 {"splice", nixio_splice},
159 {"splice_flags", nixio_splice_flags},
161 {"sendfile", nixio_sendfile},
166 void nixio_open_splice(lua_State *L) {
167 luaL_register(L, NULL, R);
170 #else /* __WINNT__ */
172 void nixio_open_splice(lua_State *L) {
175 #endif /* !__WINNT__ */