File: luasocket.c

package info (click to toggle)
thrift 0.22.0-3
  • links: PTS
  • area: main
  • in suites: forky, sid
  • size: 29,588 kB
  • sloc: cpp: 103,295; java: 26,996; ansic: 21,793; pascal: 15,437; php: 12,823; cs: 10,610; python: 9,733; javascript: 9,274; ruby: 8,316; erlang: 7,360; sh: 5,569; makefile: 4,203; perl: 3,351; yacc: 1,145; xml: 1,079; ml: 962; lisp: 664; lex: 322
file content (380 lines) | stat: -rw-r--r-- 11,371 bytes parent folder | download
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
//
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
//   http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
//

#include <lua.h>
#include <lauxlib.h>

#include <unistd.h>
#include "string.h"
#include "socket.h"

////////////////////////////////////////////////////////////////////////////////

static const char *SOCKET_ANY     = "__thrift_socket_any";
static const char *SOCKET_CONN    = "__thrift_socket_connected";

static const char *SOCKET_GENERIC = "__thrift_socket_generic";
static const char *SOCKET_CLIENT  = "__thrift_socket_client";
static const char *SOCKET_SERVER  = "__thrift_socket_server";

static const char *DEFAULT_HOST   = "localhost";

typedef struct __t_tcp {
  t_socket sock;
  int timeout; // Milliseconds
} t_tcp;
typedef t_tcp *p_tcp;

////////////////////////////////////////////////////////////////////////////////
// Util

static void throw_argerror(lua_State *L, int index, const char *expected) {
  char msg[256];
  sprintf(msg, "%s expected, got %s", expected, luaL_typename(L, index));
  luaL_argerror(L, index, msg);
}

static void *checkgroup(lua_State *L, int index, const char *groupname) {
  if (!lua_getmetatable(L, index)) {
    throw_argerror(L, index, groupname);
  }

  lua_pushstring(L, groupname);
  lua_rawget(L, -2);
  if (lua_isnil(L, -1)) {
    lua_pop(L, 2);
    throw_argerror(L, index, groupname);
  } else {
    lua_pop(L, 2);
    return lua_touserdata(L, index);
  }
  return NULL; // Not reachable
}

static void *checktype(lua_State *L, int index, const char *typename) {
  if (strcmp(typename, SOCKET_ANY) == 0 ||
      strcmp(typename, SOCKET_CONN) == 0) {
    return checkgroup(L, index, typename);
  } else {
    return luaL_checkudata(L, index, typename);
  }
}

static void settype(lua_State *L, int index, const char *typename) {
  luaL_getmetatable(L, typename);
  lua_setmetatable(L, index);
}

#define LUA_SUCCESS_RETURN(L) \
  lua_pushnumber(L, 1); \
  return 1

#define LUA_CHECK_RETURN(L, err) \
  if (err) { \
    lua_pushnil(L); \
    lua_pushstring(L, err); \
    return 2; \
  } \
  LUA_SUCCESS_RETURN(L)

////////////////////////////////////////////////////////////////////////////////

static int l_socket_create(lua_State *L);
static int l_socket_destroy(lua_State *L);
static int l_socket_settimeout(lua_State *L);
static int l_socket_getsockinfo(lua_State *L);

static int l_socket_accept(lua_State *L);
static int l_socket_listen(lua_State *L);

static int l_socket_create_and_connect(lua_State *L);
static int l_socket_connect(lua_State *L);
static int l_socket_send(lua_State *L);
static int l_socket_receive(lua_State *L);

////////////////////////////////////////////////////////////////////////////////

static const struct luaL_Reg methods_generic[] = {
  {"destroy",     l_socket_destroy},
  {"settimeout",  l_socket_settimeout},
  {"getsockinfo", l_socket_getsockinfo},
  {"listen",      l_socket_listen},
  {"connect",     l_socket_connect},
  {NULL, NULL}
};

static const struct luaL_Reg methods_server[] = {
  {"destroy",     l_socket_destroy},
  {"getsockinfo", l_socket_getsockinfo},
  {"accept",      l_socket_accept},
  {"send",        l_socket_send},
  {"receive",     l_socket_receive},
  {NULL, NULL}
};

static const struct luaL_Reg methods_client[] = {
  {"destroy",     l_socket_destroy},
  {"settimeout",  l_socket_settimeout},
  {"getsockinfo", l_socket_getsockinfo},
  {"send",        l_socket_send},
  {"receive",     l_socket_receive},
  {NULL, NULL}
};

static const struct luaL_Reg funcs_luasocket[] = {
  {"create",             l_socket_create},
  {"create_and_connect", l_socket_create_and_connect},
  {NULL, NULL}
};

////////////////////////////////////////////////////////////////////////////////

// Check/enforce inheritance
static void add_to_group(lua_State *L,
                  const char *metatablename,
                  const char *groupname) {
  luaL_getmetatable(L, metatablename); // mt
  lua_pushstring(L, groupname);        // mt, "name"
  lua_pushboolean(L, 1);               // mt, "name", true
  lua_rawset(L, -3);                   // mt
  lua_pop(L, 1);
}

static void set_methods(lua_State *L,
  const char *metatablename,
  const struct luaL_Reg *methods) {
  luaL_getmetatable(L, metatablename);   // mt
  // Create the __index table
  lua_pushstring(L, "__index");          // mt, "__index"
  lua_newtable(L);                       // mt, "__index", t
  for (; methods->name; methods++) {
    lua_pushstring(L, methods->name);    // mt, "__index", t, "name"
    lua_pushcfunction(L, methods->func); // mt, "__index", t, "name", func
    lua_rawset(L, -3);                   // mt, "__index", t
  }
  lua_rawset(L, -3);                     // mt
  lua_pop(L, 1);
}

int luaopen_libluasocket(lua_State *L) {
  luaL_newmetatable(L, SOCKET_GENERIC);
  luaL_newmetatable(L, SOCKET_CLIENT);
  luaL_newmetatable(L, SOCKET_SERVER);
  lua_pop(L, 3);
  add_to_group(L, SOCKET_GENERIC, SOCKET_ANY);
  add_to_group(L, SOCKET_CLIENT, SOCKET_ANY);
  add_to_group(L, SOCKET_SERVER, SOCKET_ANY);
  add_to_group(L, SOCKET_CLIENT, SOCKET_CONN);
  add_to_group(L, SOCKET_SERVER, SOCKET_CONN);
  set_methods(L, SOCKET_GENERIC, methods_generic);
  set_methods(L, SOCKET_CLIENT, methods_client);
  set_methods(L, SOCKET_SERVER, methods_server);
#if LUA_VERSION_NUM >= 502
    lua_newtable(L);
    luaL_setfuncs(L, funcs_luasocket, 0);
#else
  luaL_register(L, "luasocket", funcs_luasocket);
#endif
  return 1;
}

////////////////////////////////////////////////////////////////////////////////
// General

// sock,err create(bind_host, bind_port)
// sock,err create(bind_host) -> any port
// sock,err create() -> any port on localhost
static int l_socket_create(lua_State *L) {
  const char *err;
  t_socket sock;
  const char *addr = lua_tostring(L, 1);
  if (!addr) {
    addr = DEFAULT_HOST;
  }
  unsigned short port = lua_tonumber(L, 2);
  err = tcp_create(&sock);
  if (!err) {
    err = tcp_bind(&sock, addr, port); // bind on create
    if (err) {
      tcp_destroy(&sock);
    } else {
      p_tcp tcp = (p_tcp) lua_newuserdata(L, sizeof(t_tcp));
      settype(L, -2, SOCKET_GENERIC);
      socket_setnonblocking(&sock);
      tcp->sock = sock;
      tcp->timeout = 0;
      return 1; // Return userdata
    }
  }
  LUA_CHECK_RETURN(L, err);
}

// destroy()
static int l_socket_destroy(lua_State *L) {
  p_tcp tcp = (p_tcp) checktype(L, 1, SOCKET_ANY);
  const char *err = tcp_destroy(&tcp->sock);
  LUA_CHECK_RETURN(L, err);
}

// send(socket, data)
static int l_socket_send(lua_State *L) {
  p_tcp self = (p_tcp) checktype(L, 1, SOCKET_CONN);
  p_tcp tcp = (p_tcp) checktype(L, 2, SOCKET_CONN);
  size_t len;
  const char *data = luaL_checklstring(L, 3, &len);
  const char *err =
    tcp_send(&tcp->sock, data, len, tcp->timeout);
  LUA_CHECK_RETURN(L, err);
}

#define LUA_READ_STEP 8192
static int l_socket_receive(lua_State *L) {
  p_tcp self = (p_tcp) checktype(L, 1, SOCKET_CONN);
  p_tcp handle = (p_tcp) checktype(L, 2, SOCKET_CONN);
  size_t len = luaL_checknumber(L, 3);
  char buf[LUA_READ_STEP];
  const char *err = NULL;
  int received;
  size_t got = 0, step = 0;
  luaL_Buffer b;

  luaL_buffinit(L, &b);
  do {
    step = (LUA_READ_STEP < len - got ? LUA_READ_STEP : len - got);
    err = tcp_raw_receive(&handle->sock, buf, step, self->timeout, &received);
    if (err == NULL) {
      luaL_addlstring(&b, buf, received);
      got += received;
    }
  } while (err == NULL && got < len);

  if (err) {
    lua_pushnil(L);
    lua_pushstring(L, err);
    return 2;
  }
  luaL_pushresult(&b);
  return 1;
}

// settimeout(timeout)
static int l_socket_settimeout(lua_State *L) {
  p_tcp self = (p_tcp) checktype(L, 1, SOCKET_ANY);
  int timeout = luaL_checknumber(L, 2);
  self->timeout = timeout;
  LUA_SUCCESS_RETURN(L);
}

// table getsockinfo()
static int l_socket_getsockinfo(lua_State *L) {
  char buf[256];
  short port = 0;
  p_tcp tcp = (p_tcp) checktype(L, 1, SOCKET_ANY);
  if (socket_get_info(&tcp->sock, &port, buf, 256) == SUCCESS) {
    lua_newtable(L);                    // t
    lua_pushstring(L, "host");          // t, "host"
    lua_pushstring(L, buf);             // t, "host", buf
    lua_rawset(L, -3);                  // t
    lua_pushstring(L, "port");          // t, "port"
    lua_pushnumber(L, port);            // t, "port", port
    lua_rawset(L, -3);                  // t
    return 1;
  }
  return 0;
}

////////////////////////////////////////////////////////////////////////////////
// Server

// accept()
static int l_socket_accept(lua_State *L) {
  const char *err;
  p_tcp self = (p_tcp) checktype(L, 1, SOCKET_SERVER);
  t_socket sock;
  err = tcp_accept(&self->sock, &sock, self->timeout);
  if (!err) { // Success
    // Create a reference to the client
    p_tcp client = (p_tcp) lua_newuserdata(L, sizeof(t_tcp));
    settype(L, 2, SOCKET_CLIENT);
    socket_setnonblocking(&sock);
    client->sock = sock;
    client->timeout = self->timeout;
    return 1;
  }
  LUA_CHECK_RETURN(L, err);
}

static int l_socket_listen(lua_State *L) {
  const char* err;
  p_tcp tcp = (p_tcp) checktype(L, 1, SOCKET_GENERIC);
  int backlog = 10;
  err = tcp_listen(&tcp->sock, backlog);
  if (!err) {
    // Set the current as a server
    settype(L, 1, SOCKET_SERVER); // Now a server
  }
  LUA_CHECK_RETURN(L, err);
}

////////////////////////////////////////////////////////////////////////////////
// Client

// create_and_connect(host, port, timeout)
extern double __gettime();
static int l_socket_create_and_connect(lua_State *L) {
  const char* err = NULL;
  double end;
  t_socket sock;
  const char *host = luaL_checkstring(L, 1);
  unsigned short port = luaL_checknumber(L, 2);
  int timeout = luaL_checknumber(L, 3);

  // Create and connect loop for timeout milliseconds
  end = __gettime() + timeout/1000;
  do {
    // Create and connect the socket
    err = tcp_create_and_connect(&sock, host, port, timeout);
    if (err) {
      tcp_destroy(&sock);
      usleep(100000); // sleep for 100ms
    } else {
      p_tcp tcp = (p_tcp) lua_newuserdata(L, sizeof(t_tcp));
      settype(L, -2, SOCKET_CLIENT);
      socket_setnonblocking(&sock);
      tcp->sock = sock;
      tcp->timeout = timeout;
      return 1; // Return userdata
    }
  } while (err && __gettime() < end);

  LUA_CHECK_RETURN(L, err);
}

// connect(host, port)
static int l_socket_connect(lua_State *L) {
  const char *err;
  p_tcp tcp = (p_tcp) checktype(L, 1, SOCKET_GENERIC);
  const char *host = luaL_checkstring(L, 2);
  unsigned short port = luaL_checknumber(L, 3);
  err = tcp_connect(&tcp->sock, host, port, tcp->timeout);
  if (!err) {
    settype(L, 1, SOCKET_CLIENT); // Now a client
  }
  LUA_CHECK_RETURN(L, err);
}