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.
26 #include <sys/socket.h>
33 /* pushes nil, error number and errstring on the stack */
34 int nixio__perror(lua_State
*L
) {
36 lua_pushinteger(L
, errno
);
37 lua_pushstring(L
, strerror(errno
));
41 /* pushes true, if operation succeeded, otherwise call nixio__perror */
42 int nixio__pstatus(lua_State
*L
, int condition
) {
44 lua_pushboolean(L
, 1);
47 return nixio__perror(L
);
51 /* checks whether the first argument is a socket and returns it */
52 nixio_sock
* nixio__checksock(lua_State
*L
) {
53 nixio_sock
*sock
= (nixio_sock
*)luaL_checkudata(L
, 1, NIXIO_META
);
54 luaL_argcheck(L
, sock
->fd
!= -1, 1, "invalid socket object");
58 /* read fd from nixio_sock object */
59 int nixio__checksockfd(lua_State
*L
) {
60 return nixio__checksock(L
)->fd
;
63 /* return any possible fd, otherwise error out */
64 int nixio__checkfd(lua_State
*L
, int ud
) {
65 int fd
= nixio__tofd(L
, ud
);
66 return (fd
!= -1) ? fd
: luaL_argerror(L
, ud
, "invalid file descriptor");
69 /* return any possible fd */
70 int nixio__tofd(lua_State
*L
, int ud
) {
71 void *udata
= lua_touserdata(L
, ud
);
73 if (udata
&& lua_getmetatable(L
, ud
)) {
74 luaL_getmetatable(L
, NIXIO_META
);
75 luaL_getmetatable(L
, LUA_FILEHANDLE
);
76 if (lua_rawequal(L
, -2, -3)) {
77 fd
= ((nixio_sock
*)udata
)->fd
;
78 } else if (lua_rawequal(L
, -1, -3)) {
79 fd
= fileno(*((FILE **)udata
));
87 static const luaL_reg R
[] = {
92 LUALIB_API
int luaopen_nixio(lua_State
*L
) {
93 /* create metatable */
94 luaL_newmetatable(L
, NIXIO_META
);
100 /* metatable.__index = M */
101 lua_setfield(L
, -3, "__index");
104 /* register module */
105 luaL_register(L
, "nixio", R
);
107 /* register methods */
108 nixio_open_socket(L
);
109 nixio_open_sockopt(L
);
111 nixio_open_address(L
);
112 nixio_open_select(L
);
115 lua_pushnumber(L
, VERSION
);
116 lua_setfield(L
, -2, "version");
118 /* remove meta table */