sq_socket.cpp 70 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987
  1. #include "squirrel.h"
  2. #include "sqstdblobimpl.h"
  3. #include <string.h>
  4. #include <stdio.h>
  5. SQ_OPT_STRING_STRLEN();
  6. #include "lua_socket.h"
  7. #ifdef _WIN32
  8. #include <windows.h>
  9. #else
  10. #include <time.h>
  11. #include <sys/time.h>
  12. #endif
  13. /* option registry */
  14. typedef struct t_opt {
  15. const char *name;
  16. int (*func)(HSQUIRRELVM v, p_socket ps);
  17. } t_opt;
  18. typedef t_opt *p_opt;
  19. /*=========================================================================*\
  20. * Internal functions prototypes
  21. \*=========================================================================*/
  22. static int opt_setmembership(HSQUIRRELVM v, p_socket ps, int level, int name);
  23. static int opt_setboolean(HSQUIRRELVM v, p_socket ps, int level, int name);
  24. static int opt_set(HSQUIRRELVM v, p_socket ps, int level, int name,
  25. void *val, int len);
  26. /*=========================================================================*\
  27. * Exported functions
  28. \*=========================================================================*/
  29. /*-------------------------------------------------------------------------*\
  30. * Calls appropriate option handler
  31. \*-------------------------------------------------------------------------*/
  32. static int opt_meth_setoption(HSQUIRRELVM v, p_opt opt, p_socket ps)
  33. {
  34. SQ_FUNC_VARS_NO_TOP(v);
  35. SQ_GET_STRING(v, 2, name); /* obj, name, ... */
  36. while (opt->name && strcmp(name, opt->name))
  37. opt++;
  38. if (!opt->func) {
  39. return sq_throwerror(v, _SC("unsupported option `%.35s'"), name);
  40. }
  41. return opt->func(v, ps);
  42. }
  43. /* enables reuse of local address */
  44. static int opt_bindtodevice(HSQUIRRELVM v, p_socket ps)
  45. {
  46. SQ_FUNC_VARS_NO_TOP(v);
  47. if(sq_gettype(v, 3) != OT_STRING) return sq_throwerror(v, _SC("string expected as parameter 2"));
  48. SQ_GET_STRING(v, 3, device);
  49. return opt_set(v, ps, SOL_SOCKET, SO_BINDTODEVICE, (void *)device, device_size+1);
  50. }
  51. /* enables reuse of local address */
  52. static int opt_reuseaddr(HSQUIRRELVM v, p_socket ps)
  53. {
  54. return opt_setboolean(v, ps, SOL_SOCKET, SO_REUSEADDR);
  55. }
  56. /* disables the Naggle algorithm */
  57. static int opt_tcp_nodelay(HSQUIRRELVM v, p_socket ps)
  58. {
  59. return opt_setboolean(v, ps, IPPROTO_TCP, TCP_NODELAY);
  60. }
  61. static int opt_keepalive(HSQUIRRELVM v, p_socket ps)
  62. {
  63. return opt_setboolean(v, ps, SOL_SOCKET, SO_KEEPALIVE);
  64. }
  65. static int opt_dontroute(HSQUIRRELVM v, p_socket ps)
  66. {
  67. return opt_setboolean(v, ps, SOL_SOCKET, SO_DONTROUTE);
  68. }
  69. static int opt_broadcast(HSQUIRRELVM v, p_socket ps)
  70. {
  71. return opt_setboolean(v, ps, SOL_SOCKET, SO_BROADCAST);
  72. }
  73. static int opt_ip_multicast_loop(HSQUIRRELVM v, p_socket ps)
  74. {
  75. return opt_setboolean(v, ps, IPPROTO_IP, IP_MULTICAST_LOOP);
  76. }
  77. static int opt_linger(HSQUIRRELVM v, p_socket ps)
  78. {
  79. SQ_FUNC_VARS_NO_TOP(v);
  80. struct linger li; /* obj, name, table */
  81. if(sq_gettype(v, 3) != OT_TABLE) return sq_throwerror(v, _SC("table expected as parameter 2"));
  82. sq_pushliteral(v, _SC("on"));
  83. sq_get(v, 3);
  84. if (!sq_gettype(v, -1) != OT_BOOL)
  85. return sq_throwerror(v, _SC("boolean 'on' field expected"));
  86. SQ_GET_BOOL(v, -1, bval);
  87. li.l_onoff = (u_short) bval == SQTrue;
  88. sq_pushliteral(v, _SC("timeout"));
  89. sq_get(v, 3);
  90. if (!sq_gettype(v, -1) != OT_INTEGER)
  91. return sq_throwerror(v, _SC("integer 'timeout' field expected"));
  92. SQ_GET_INTEGER(v, -1, ival);
  93. li.l_linger = (u_short) ival;
  94. return opt_set(v, ps, SOL_SOCKET, SO_LINGER, (char *) &li, sizeof(li));
  95. }
  96. static int opt_ip_multicast_ttl(HSQUIRRELVM v, p_socket ps)
  97. {
  98. SQ_FUNC_VARS_NO_TOP(v);
  99. SQ_GET_INTEGER(v, 3, val); /* obj, name, int */
  100. return opt_set(v, ps, SOL_SOCKET, SO_LINGER, (char *) &val, sizeof(val));
  101. }
  102. static int opt_ip_add_membership(HSQUIRRELVM v, p_socket ps)
  103. {
  104. return opt_setmembership(v, ps, IPPROTO_IP, IP_ADD_MEMBERSHIP);
  105. }
  106. static int opt_ip_drop_membersip(HSQUIRRELVM v, p_socket ps)
  107. {
  108. return opt_setmembership(v, ps, IPPROTO_IP, IP_DROP_MEMBERSHIP);
  109. }
  110. /*=========================================================================*\
  111. * Auxiliar functions
  112. \*=========================================================================*/
  113. /*-------------------------------------------------------------------------*\
  114. * Some systems do not provide this so that we provide our own. It's not
  115. * marvelously fast, but it works just fine.
  116. \*-------------------------------------------------------------------------*/
  117. #ifdef INET_ATON
  118. static int inet_aton(const char *cp, struct in_addr *inp)
  119. {
  120. unsigned int a = 0, b = 0, c = 0, d = 0;
  121. int n = 0, r;
  122. unsigned long int addr = 0;
  123. r = sscanf(cp, "%u.%u.%u.%u%n", &a, &b, &c, &d, &n);
  124. if (r == 0 || n == 0) return 0;
  125. cp += n;
  126. if (*cp) return 0;
  127. if (a > 255 || b > 255 || c > 255 || d > 255) return 0;
  128. if (inp) {
  129. addr += a; addr <<= 8;
  130. addr += b; addr <<= 8;
  131. addr += c; addr <<= 8;
  132. addr += d;
  133. inp->s_addr = htonl(addr);
  134. }
  135. return 1;
  136. }
  137. #endif
  138. #ifdef _WIN32
  139. //#define inet_aton inet_addr
  140. //#define inet_aton(a,b) inet_pton(a,b, AF_INET)
  141. #endif
  142. static SQRESULT socket_open(HSQUIRRELVM v)
  143. {
  144. lua_socket_open();
  145. return 0;
  146. }
  147. static SQRESULT socket_close(HSQUIRRELVM v)
  148. {
  149. lua_socket_close();
  150. return 0;
  151. }
  152. static int opt_setmembership(HSQUIRRELVM v, p_socket ps, int level, int name)
  153. {
  154. SQ_FUNC_VARS_NO_TOP(v);
  155. struct ip_mreq val; /* obj, name, table */
  156. if(sq_gettype(v, 3) != OT_TABLE) return sq_throwerror(v, _SC("table expected as parameter 2"));
  157. sq_pushliteral(v, _SC("multiaddr"));
  158. sq_get(v, 3);
  159. if (!sq_gettype(v, -1) != OT_STRING)
  160. return sq_throwerror(v, _SC("string 'multiaddr' field expected"));
  161. SQ_GET_STRING(v, -1, multiaddr);
  162. if (!inet_aton(multiaddr, &val.imr_multiaddr))
  163. return sq_throwerror(v, _SC("invalid 'multiaddr' ip address"));
  164. sq_pushliteral(v, _SC("interface"));
  165. sq_get(v, 3);
  166. if (!sq_gettype(v, -1) != OT_STRING)
  167. return sq_throwerror(v, _SC("string 'interface' field expected"));
  168. val.imr_interface.s_addr = htonl(INADDR_ANY);
  169. SQ_GET_STRING(v, -1, saddr);
  170. if (strcmp(saddr, "*") &&
  171. !inet_aton(saddr, &val.imr_interface))
  172. return sq_throwerror(v, _SC("invalid 'interface' ip address"));
  173. return opt_set(v, ps, level, name, (char *) &val, sizeof(val));
  174. }
  175. static
  176. int opt_set(HSQUIRRELVM v, p_socket ps, int level, int name, void *val, int len)
  177. {
  178. if (setsockopt(*ps, level, name, (char *) val, len) < 0) {
  179. return sq_throwerror(v, _SC("setsockopt failed"));
  180. }
  181. return 0;
  182. }
  183. static int opt_setboolean(HSQUIRRELVM v, p_socket ps, int level, int name)
  184. {
  185. SQ_FUNC_VARS_NO_TOP(v);
  186. SQ_GET_BOOL(v, 3, bval);
  187. int val = bval == SQTrue; /* obj, name, bool */
  188. return opt_set(v, ps, level, name, (char *) &val, sizeof(val));
  189. }
  190. /*=========================================================================*\
  191. * Global Lua functions
  192. \*=========================================================================*/
  193. /*-------------------------------------------------------------------------*\
  194. * Sets timeout values for IO operations
  195. * Lua Input: base, time [, mode]
  196. * time: time out value in seconds
  197. * mode: "b" for block timeout, "t" for total timeout. (default: b)
  198. \*-------------------------------------------------------------------------*/
  199. static int timeout_meth_settimeout(HSQUIRRELVM v, p_timeout tm) {
  200. SQ_FUNC_VARS(v);
  201. SQ_OPT_INTEGER(v, 2, t, -1);
  202. SQ_OPT_STRING(v, 3, mode, "b");
  203. switch (*mode) {
  204. case _SC('b'):
  205. tm->block = t;
  206. break;
  207. case _SC('r'): case _SC('t'):
  208. tm->total = t;
  209. break;
  210. default:
  211. return sq_throwerror(v, _SC("invalid timeout mode"));
  212. break;
  213. }
  214. return 0;
  215. }
  216. /*=========================================================================*\
  217. * Test support functions
  218. \*=========================================================================*/
  219. /*-------------------------------------------------------------------------*\
  220. * Returns the time the system has been up, in secconds.
  221. \*-------------------------------------------------------------------------*/
  222. static SQRESULT timeout_lua_gettime(HSQUIRRELVM v)
  223. {
  224. sq_pushinteger(v, lua_timeout_gettime());
  225. return 1;
  226. }
  227. /*-------------------------------------------------------------------------*\
  228. * Sleep for n seconds.
  229. \*-------------------------------------------------------------------------*/
  230. static SQRESULT timeout_lua_sleep(HSQUIRRELVM v)
  231. {
  232. SQ_FUNC_VARS_NO_TOP(v);
  233. SQ_GET_FLOAT(v, 2, n);
  234. #ifdef _WIN32
  235. Sleep((int)(n*1000));
  236. #else
  237. struct timespec t, r;
  238. t.tv_sec = (int) n;
  239. n -= t.tv_sec;
  240. t.tv_nsec = (int) (n * 1000000000);
  241. if (t.tv_nsec >= 1000000000) t.tv_nsec = 999999999;
  242. while (nanosleep(&t, &r) != 0) {
  243. t.tv_sec = r.tv_sec;
  244. t.tv_nsec = r.tv_nsec;
  245. }
  246. #endif
  247. return 0;
  248. }
  249. /*-------------------------------------------------------------------------*\
  250. * Sleep for n Milliseconds.
  251. * Clone of the above for murgaLua.
  252. \*-------------------------------------------------------------------------*/
  253. static SQRESULT timeout_lua_sleepMillisecs(HSQUIRRELVM v)
  254. {
  255. SQ_FUNC_VARS_NO_TOP(v);
  256. SQ_GET_FLOAT(v, 2, n);
  257. #ifdef _WIN32
  258. Sleep((int)(n));
  259. #else
  260. struct timespec t, r;
  261. n = n / 1000;
  262. t.tv_sec = (int) n;
  263. n -= t.tv_sec;
  264. t.tv_nsec = (int) (n * 1000000000);
  265. if (t.tv_nsec >= 1000000000) t.tv_nsec = 999999999;
  266. while (nanosleep(&t, &r) != 0) {
  267. t.tv_sec = r.tv_sec;
  268. t.tv_nsec = r.tv_nsec;
  269. }
  270. #endif
  271. return 0;
  272. }
  273. /*=========================================================================*\
  274. * Internal functions
  275. \*=========================================================================*/
  276. /*-------------------------------------------------------------------------*\
  277. * Passes all resolver information to Lua as a table
  278. \*-------------------------------------------------------------------------*/
  279. static void inet_pushresolved(HSQUIRRELVM v, struct hostent *hp)
  280. {
  281. char **alias;
  282. struct in_addr **addr;
  283. int i, resolved;
  284. sq_newtable(v); resolved = sq_gettop(v);
  285. sq_pushliteral(v, _SC("name"));
  286. sq_pushstring(v, hp->h_name, -1);
  287. sq_rawset(v, resolved);
  288. sq_pushliteral(v, _SC("ip"));
  289. sq_pushliteral(v, _SC("alias"));
  290. i = 1;
  291. alias = hp->h_aliases;
  292. sq_newarray(v, 0);
  293. if (alias) {
  294. while (*alias) {
  295. sq_pushstring(v, *alias, -1);
  296. sq_arrayappend(v, -2);
  297. i++; alias++;
  298. }
  299. }
  300. sq_rawset(v, resolved);
  301. i = 1;
  302. sq_newarray(v, 0);
  303. addr = (struct in_addr **) hp->h_addr_list;
  304. if (addr) {
  305. while (*addr) {
  306. sq_pushstring(v, inet_ntoa(**addr), -1);
  307. sq_arrayappend(v, -2);
  308. i++; addr++;
  309. }
  310. }
  311. sq_rawset(v, resolved);
  312. }
  313. /*-------------------------------------------------------------------------*\
  314. * Returns all information provided by the resolver given a host name
  315. * or ip address
  316. \*-------------------------------------------------------------------------*/
  317. static int inet_gethost(const char *address, struct hostent **hp) {
  318. struct in_addr addr;
  319. if (inet_aton(address, &addr))
  320. return lua_socket_gethostbyaddr((char *) &addr, sizeof(addr), hp);
  321. else
  322. return lua_socket_gethostbyname(address, hp);
  323. }
  324. /*-------------------------------------------------------------------------*\
  325. * Returns all information provided by the resolver given a host name
  326. * or ip address
  327. \*-------------------------------------------------------------------------*/
  328. static SQRESULT inet_global_tohostname(HSQUIRRELVM v) {
  329. SQ_FUNC_VARS_NO_TOP(v);
  330. SQ_GET_STRING(v, 2, address);
  331. struct hostent *hp = NULL;
  332. int err = inet_gethost(address, &hp);
  333. if (err != IO_DONE) return sq_throwerror(v, lua_socket_hoststrerror(err));
  334. sq_newtable(v);
  335. sq_pushliteral(v, _SC("name"));
  336. sq_pushstring(v, hp->h_name, -1);
  337. sq_rawset(v, -3);
  338. sq_pushliteral(v, _SC("resolved"));
  339. inet_pushresolved(v, hp);
  340. sq_rawset(v, -3);
  341. return 1;
  342. }
  343. /*-------------------------------------------------------------------------*\
  344. * Returns all information provided by the resolver given a host name
  345. * or ip address
  346. \*-------------------------------------------------------------------------*/
  347. static SQRESULT inet_global_toip(HSQUIRRELVM v)
  348. {
  349. SQ_FUNC_VARS_NO_TOP(v);
  350. SQ_GET_STRING(v, 2, address);
  351. struct hostent *hp = NULL;
  352. int err = inet_gethost(address, &hp);
  353. if (err != IO_DONE) return sq_throwerror(v, lua_socket_hoststrerror(err));
  354. sq_newtable(v);
  355. sq_pushliteral(v, _SC("address"));
  356. sq_pushstring(v, inet_ntoa(*((struct in_addr *) hp->h_addr)), -1);
  357. sq_rawset(v, -3);
  358. sq_pushliteral(v, _SC("resolved"));
  359. inet_pushresolved(v, hp);
  360. sq_rawset(v, -3);
  361. return 1;
  362. }
  363. /*-------------------------------------------------------------------------*\
  364. * Gets the host name
  365. \*-------------------------------------------------------------------------*/
  366. static SQRESULT inet_global_gethostname(HSQUIRRELVM v)
  367. {
  368. char name[257];
  369. name[256] = '\0';
  370. if (gethostname(name, 256) < 0) return sq_throwerror(v, _SC("gethostname failed"));
  371. sq_pushstring(v, name, -1);
  372. return 1;
  373. }
  374. /*=========================================================================*\
  375. * Lua methods
  376. \*=========================================================================*/
  377. /*-------------------------------------------------------------------------*\
  378. * Retrieves socket peer name
  379. \*-------------------------------------------------------------------------*/
  380. static int inet_meth_getpeername(HSQUIRRELVM v, p_socket ps)
  381. {
  382. struct sockaddr_in peer;
  383. socklen_t peer_len = sizeof(peer);
  384. if (getpeername(*ps, (SA *) &peer, &peer_len) < 0) return sq_throwerror(v, _SC("getpeername failed"));
  385. sq_newtable(v);
  386. sq_pushliteral(v, _SC("address"));
  387. sq_pushstring(v, inet_ntoa(peer.sin_addr), -1);
  388. sq_rawset(v, -3);
  389. sq_pushliteral(v, _SC("port"));
  390. sq_pushinteger(v, ntohs(peer.sin_port));
  391. sq_rawset(v, -3);
  392. return 1;
  393. }
  394. /*-------------------------------------------------------------------------*\
  395. * Retrieves socket local name
  396. \*-------------------------------------------------------------------------*/
  397. static int inet_meth_getsockname(HSQUIRRELVM v, p_socket ps)
  398. {
  399. struct sockaddr_in local;
  400. socklen_t local_len = sizeof(local);
  401. if (getsockname(*ps, (SA *) &local, &local_len) < 0) return sq_throwerror(v, _SC("getsockname failed"));
  402. sq_newtable(v);
  403. sq_pushliteral(v, _SC("address"));
  404. sq_pushstring(v, inet_ntoa(local.sin_addr), -1);
  405. sq_rawset(v, -3);
  406. sq_pushliteral(v, _SC("port"));
  407. sq_pushinteger(v, ntohs(local.sin_port));
  408. sq_rawset(v, -3);
  409. return 1;
  410. }
  411. /*-------------------------------------------------------------------------*\
  412. * Tries to create a new inet socket
  413. \*-------------------------------------------------------------------------*/
  414. static const char *inet_trycreate(p_socket ps, int type) {
  415. return lua_socket_strerror(lua_socket_create(ps, AF_INET, type, 0));
  416. }
  417. /*-------------------------------------------------------------------------*\
  418. * Tries to connect to remote address (address, port)
  419. \*-------------------------------------------------------------------------*/
  420. static const char *inet_tryconnect(p_socket ps, const char *address,
  421. unsigned short port, p_timeout tm)
  422. {
  423. struct sockaddr_in remote;
  424. int err;
  425. memset(&remote, 0, sizeof(remote));
  426. remote.sin_family = AF_INET;
  427. remote.sin_port = htons(port);
  428. if (strcmp(address, "*")) {
  429. if (!inet_aton(address, &remote.sin_addr)) {
  430. struct hostent *hp = NULL;
  431. struct in_addr **addr;
  432. err = lua_socket_gethostbyname(address, &hp);
  433. if (err != IO_DONE) return lua_socket_hoststrerror(err);
  434. addr = (struct in_addr **) hp->h_addr_list;
  435. memcpy(&remote.sin_addr, *addr, sizeof(struct in_addr));
  436. }
  437. } else remote.sin_family = AF_UNSPEC;
  438. err = lua_socket_connect(ps, (SA *) &remote, sizeof(remote), tm);
  439. return lua_socket_strerror(err);
  440. }
  441. /*-------------------------------------------------------------------------*\
  442. * Tries to bind socket to (address, port)
  443. \*-------------------------------------------------------------------------*/
  444. static const char *inet_trybind(p_socket ps, const char *address, unsigned short port)
  445. {
  446. struct sockaddr_in local;
  447. int err;
  448. memset(&local, 0, sizeof(local));
  449. /* address is either wildcard or a valid ip address */
  450. local.sin_addr.s_addr = htonl(INADDR_ANY);
  451. local.sin_port = htons(port);
  452. local.sin_family = AF_INET;
  453. if (strcmp(address, "*") && !inet_aton(address, &local.sin_addr)) {
  454. struct hostent *hp = NULL;
  455. struct in_addr **addr;
  456. err = lua_socket_gethostbyname(address, &hp);
  457. if (err != IO_DONE) return lua_socket_hoststrerror(err);
  458. addr = (struct in_addr **) hp->h_addr_list;
  459. memcpy(&local.sin_addr, *addr, sizeof(struct in_addr));
  460. }
  461. err = lua_socket_bind(ps, (SA *) &local, sizeof(local));
  462. if (err != IO_DONE) lua_socket_destroy(ps);
  463. return lua_socket_strerror(err);
  464. }
  465. /*=========================================================================*\
  466. * Input/Output interface for Lua programs
  467. * LuaSocket toolkit
  468. *
  469. * Line patterns require buffering. Reading one character at a time involves
  470. * too many system calls and is very slow. This module implements the
  471. * LuaSocket interface for input/output on connected objects, as seen by
  472. * Lua programs.
  473. *
  474. * Input is buffered. Output is *not* buffered because there was no simple
  475. * way of making sure the buffered output data would ever be sent.
  476. *
  477. * The module is built on top of the I/O abstraction defined in io.h and the
  478. * timeout management is done with the timeout.h interface.
  479. *
  480. * Adapted to Squirrel by Domingo Alvarez Duarte on 04/01/2013
  481. *
  482. * RCS ID: $Id: buffer.h,v 1.12 2005/10/07 04:40:59 diego Exp $
  483. \*=========================================================================*/
  484. /* buffer size in bytes */
  485. #define BUF_SIZE 8192
  486. /* buffer control structure */
  487. typedef struct t_buffer_ {
  488. SQFloat birthday; /* throttle support info: creation time, */
  489. SQInteger sent, received; /* bytes sent, and bytes received */
  490. p_io io; /* IO driver used for this buffer */
  491. p_timeout tm; /* timeout management for this buffer */
  492. #ifdef LUASOCKET_DEBUG
  493. int elapsed;
  494. #endif
  495. SQInteger first, last; /* index of first and last bytes of stored data */
  496. char data[BUF_SIZE]; /* storage space for buffer data */
  497. } t_buffer;
  498. typedef t_buffer *p_buffer;
  499. /*=========================================================================*\
  500. * Internal function prototypes
  501. \*=========================================================================*/
  502. static int recvraw(p_buffer buf, size_t wanted, SQBlob &b);
  503. static int recvline(p_buffer buf, SQBlob &b);
  504. static int recvall(p_buffer buf, SQBlob &b);
  505. static int buffer_get(p_buffer buf, const char **data, size_t *count);
  506. static void buffer_skip(p_buffer buf, size_t count);
  507. static int sendraw(p_buffer buf, const char *data, size_t count, size_t *sent);
  508. /* min and max macros */
  509. #ifndef MIN
  510. #define MIN(x, y) ((x) < (y) ? x : y)
  511. #endif
  512. #ifndef MAX
  513. #define MAX(x, y) ((x) > (y) ? x : y)
  514. #endif
  515. /*=========================================================================*\
  516. * Exported functions
  517. \*=========================================================================*/
  518. /*-------------------------------------------------------------------------*\
  519. * Initializes module
  520. \*-------------------------------------------------------------------------*/
  521. /*
  522. static SQRESULT buffer_open(HSQUIRRELVM v) {
  523. (void) v;
  524. return 0;
  525. }
  526. */
  527. /*-------------------------------------------------------------------------*\
  528. * Initializes C structure
  529. \*-------------------------------------------------------------------------*/
  530. static void buffer_init(p_buffer buf, p_io io, p_timeout tm) {
  531. buf->first = buf->last = 0;
  532. buf->io = io;
  533. buf->tm = tm;
  534. buf->received = buf->sent = 0;
  535. buf->birthday = lua_timeout_gettime();
  536. }
  537. /*-------------------------------------------------------------------------*\
  538. * object:getstats() interface
  539. \*-------------------------------------------------------------------------*/
  540. static int buffer_meth_getstats(HSQUIRRELVM v, p_buffer buf) {
  541. sq_newtable(v);
  542. sq_pushliteral(v, _SC("received"));
  543. sq_pushinteger(v, buf->received);
  544. sq_rawset(v, -3);
  545. sq_pushliteral(v, _SC("sent"));
  546. sq_pushinteger(v, buf->sent);
  547. sq_rawset(v, -3);
  548. sq_pushliteral(v, _SC("age"));
  549. sq_pushinteger(v, lua_timeout_gettime() - buf->birthday);
  550. sq_rawset(v, -3);
  551. return 1;
  552. }
  553. /*-------------------------------------------------------------------------*\
  554. * object:setstats() interface
  555. \*-------------------------------------------------------------------------*/
  556. static int buffer_meth_setstats(HSQUIRRELVM v, p_buffer buf) {
  557. SQ_FUNC_VARS(v);
  558. if(sq_getinteger(v, 2, &buf->received) < 0
  559. || sq_getinteger(v, 3, &buf->sent) < 0) return SQ_ERROR;
  560. if(_top_ > 3){
  561. SQ_GET_INTEGER(v, 4, age);
  562. buf->birthday = lua_timeout_gettime() - age;
  563. }
  564. return 0;
  565. }
  566. /*-------------------------------------------------------------------------*\
  567. * object:send() interface
  568. \*-------------------------------------------------------------------------*/
  569. static int buffer_meth_send(HSQUIRRELVM v, p_buffer buf) {
  570. SQ_FUNC_VARS(v);
  571. int err = IO_DONE;
  572. size_t sent = 0;
  573. SQ_GET_STRING(v, 2, data);
  574. SQ_OPT_INTEGER(v, 3, start, 0);
  575. SQ_OPT_INTEGER(v, 4, end, -1);
  576. #ifdef LUASOCKET_DEBUG
  577. p_timeout tm =
  578. #endif
  579. lua_timeout_markstart(buf->tm);
  580. if (start < 0) start = (data_size+start);
  581. if (end < 0) end = (data_size+end+1);
  582. if (start < 0) start = 0;
  583. if (end > data_size) end = data_size;
  584. if (start <= end) err = sendraw(buf, data+start, end-start, &sent);
  585. /* check if there was an error */
  586. if (err != IO_DONE) {
  587. return sq_throwerror(v, buf->io->error(buf->io->ctx, err));
  588. } else {
  589. sq_pushinteger(v, sent+start);
  590. }
  591. #ifdef LUASOCKET_DEBUG
  592. /* push time elapsed during operation as the last return value */
  593. buf->elapsed = timeout_gettime() - timeout_getstart(tm);
  594. #endif
  595. return 1;
  596. }
  597. /*-------------------------------------------------------------------------*\
  598. * object:receive() interface
  599. \*-------------------------------------------------------------------------*/
  600. static int buffer_meth_receive(HSQUIRRELVM v, p_buffer buf) {
  601. SQ_FUNC_VARS(v);
  602. int err = IO_DONE;
  603. SQBlob b(0, 8192);
  604. SQ_OPT_STRING(v, 3, prefix, NULL);
  605. #ifdef LUASOCKET_DEBUG
  606. p_timeout tm =
  607. #endif
  608. lua_timeout_markstart(buf->tm);
  609. /* initialize buffer with optional extra prefix
  610. * (useful for concatenating previous partial results) */
  611. if(prefix) {
  612. b.Write(prefix, prefix_size);
  613. }
  614. /* receive new patterns */
  615. SQObjectType ptype = sq_gettype(v, 2);
  616. if (ptype == OT_INTEGER) {
  617. /* get a fixed number of bytes (minus what was already partially
  618. * received) */
  619. SQ_GET_INTEGER(v, 2, recv_size);
  620. err = recvraw(buf, (size_t) recv_size-prefix_size, b);
  621. }
  622. else
  623. {
  624. SQ_OPT_STRING(v, 2, p, "*l");
  625. if (p[0] == _SC('*') && p[1] == _SC('l')) err = recvline(buf, b);
  626. else if (p[0] == _SC('*') && p[1] == _SC('a')) err = recvall(buf, b);
  627. else return sq_throwerror(v, _SC("invalid receive pattern"));
  628. }
  629. sq_newarray(v,2);
  630. sq_pushinteger(v, 0);
  631. sq_pushstring(v, (const SQChar*)b.GetBuf(), b.Len());
  632. sq_rawset(v, -3);
  633. sq_pushinteger(v, 1);
  634. sq_pushinteger(v, err);
  635. sq_rawset(v, -3);
  636. /* check if there was an error */
  637. //if (err != IO_DONE) return sq_throwerror(v, buf->io->error(buf->io->ctx, err));
  638. #ifdef LUASOCKET_DEBUG
  639. /* push time elapsed during operation as the last return value */
  640. buf->elapsed = timeout_gettime() - timeout_getstart(tm);
  641. #endif
  642. return 1;
  643. }
  644. /*-------------------------------------------------------------------------*\
  645. * Determines if there is any data in the read buffer
  646. \*-------------------------------------------------------------------------*/
  647. static int buffer_isempty(p_buffer buf) {
  648. return buf->first >= buf->last;
  649. }
  650. /*=========================================================================*\
  651. * Internal functions
  652. \*=========================================================================*/
  653. /*-------------------------------------------------------------------------*\
  654. * Sends a block of data (unbuffered)
  655. \*-------------------------------------------------------------------------*/
  656. #define STEPSIZE 8192
  657. static int sendraw(p_buffer buf, const char *data, size_t count, size_t *sent) {
  658. p_io io = buf->io;
  659. p_timeout tm = buf->tm;
  660. size_t total = 0;
  661. int err = IO_DONE;
  662. while (total < count && err == IO_DONE) {
  663. size_t done;
  664. size_t step = (count-total <= STEPSIZE)? count-total: STEPSIZE;
  665. err = io->send(io->ctx, data+total, step, &done, tm);
  666. total += done;
  667. }
  668. *sent = total;
  669. buf->sent += total;
  670. return err;
  671. }
  672. /*-------------------------------------------------------------------------*\
  673. * Reads a fixed number of bytes (buffered)
  674. \*-------------------------------------------------------------------------*/
  675. static int recvraw(p_buffer buf, size_t wanted, SQBlob &b) {
  676. int err = IO_DONE;
  677. size_t total = 0;
  678. while (err == IO_DONE) {
  679. size_t count; const char *data;
  680. err = buffer_get(buf, &data, &count);
  681. count = MIN(count, wanted - total);
  682. b.Write(data, count);
  683. buffer_skip(buf, count);
  684. total += count;
  685. if (total >= wanted) break;
  686. }
  687. return err;
  688. }
  689. /*-------------------------------------------------------------------------*\
  690. * Reads everything until the connection is closed (buffered)
  691. \*-------------------------------------------------------------------------*/
  692. static int recvall(p_buffer buf, SQBlob &b) {
  693. int err = IO_DONE;
  694. size_t total = 0;
  695. while (err == IO_DONE) {
  696. const char *data; size_t count;
  697. err = buffer_get(buf, &data, &count);
  698. total += count;
  699. b.Write(data, count);
  700. buffer_skip(buf, count);
  701. }
  702. if (err == IO_CLOSED) {
  703. if (total > 0) return IO_DONE;
  704. else return IO_CLOSED;
  705. } else return err;
  706. }
  707. /*-------------------------------------------------------------------------*\
  708. * Reads a line terminated by a CR LF pair or just by a LF. The CR and LF
  709. * are not returned by the function and are discarded from the buffer
  710. \*-------------------------------------------------------------------------*/
  711. static int recvline(p_buffer buf, SQBlob &b) {
  712. int err = IO_DONE;
  713. while (err == IO_DONE) {
  714. size_t count, pos; const char *data;
  715. err = buffer_get(buf, &data, &count);
  716. pos = 0;
  717. while (pos < count && data[pos] != '\n') {
  718. /* we ignore all \r's */
  719. if (data[pos] != '\r') b.WriteChar(data[pos]);
  720. pos++;
  721. }
  722. if (pos < count) { /* found '\n' */
  723. buffer_skip(buf, pos+1); /* skip '\n' too */
  724. break; /* we are done */
  725. } else /* reached the end of the buffer */
  726. buffer_skip(buf, pos);
  727. }
  728. return err;
  729. }
  730. /*-------------------------------------------------------------------------*\
  731. * Skips a given number of bytes from read buffer. No data is read from the
  732. * transport layer
  733. \*-------------------------------------------------------------------------*/
  734. static void buffer_skip(p_buffer buf, size_t count) {
  735. buf->received += count;
  736. buf->first += count;
  737. if (buffer_isempty(buf))
  738. buf->first = buf->last = 0;
  739. }
  740. /*-------------------------------------------------------------------------*\
  741. * Return any data available in buffer, or get more data from transport layer
  742. * if buffer is empty
  743. \*-------------------------------------------------------------------------*/
  744. static int buffer_get(p_buffer buf, const char **data, size_t *count) {
  745. int err = IO_DONE;
  746. p_io io = buf->io;
  747. p_timeout tm = buf->tm;
  748. if (buffer_isempty(buf)) {
  749. size_t got;
  750. err = io->recv(io->ctx, buf->data, BUF_SIZE, &got, tm);
  751. buf->first = 0;
  752. buf->last = got;
  753. }
  754. *count = buf->last - buf->first;
  755. *data = buf->data + buf->first;
  756. return err;
  757. }
  758. /*=========================================================================*\
  759. * Lua methods
  760. \*=========================================================================*/
  761. #define TCP_TYPE_ANY 0
  762. #define TCP_TYPE_CLIENT 1
  763. #define TCP_TYPE_SERVER 2
  764. #define TCP_TYPE_MASTER 3
  765. typedef struct t_tcp_ {
  766. t_socket sock;
  767. t_io io;
  768. t_buffer buf;
  769. t_timeout tm;
  770. int type;
  771. } t_tcp;
  772. typedef t_tcp *p_tcp;
  773. static const SQChar SQ_tcp_TAG[] = _SC("sq_tcp");
  774. #define GET_tcp_INSTANCE_AT(v, idx) \
  775. p_tcp tcp; \
  776. if((_rc_ = sq_getinstanceup(v,idx,(SQUserPointer*)&tcp,(void*)SQ_tcp_TAG)) < 0) return _rc_;
  777. #define GET_tcp_client_INSTANCE_AT(v, idx) GET_tcp_INSTANCE_AT(v, idx)\
  778. if(tcp->type != TCP_TYPE_CLIENT) return sq_throwerror(v, _SC("tcp client expected"));
  779. #define GET_tcp_server_INSTANCE_AT(v, idx) GET_tcp_INSTANCE_AT(v, idx)\
  780. if(tcp->type != TCP_TYPE_SERVER) return sq_throwerror(v, _SC("tcp server expected"));
  781. #define GET_tcp_master_INSTANCE_AT(v, idx) GET_tcp_INSTANCE_AT(v, idx)\
  782. if(tcp->type != TCP_TYPE_MASTER) return sq_throwerror(v, _SC("tcp master expected"));
  783. /*-------------------------------------------------------------------------*\
  784. * Just call buffered IO methods
  785. \*-------------------------------------------------------------------------*/
  786. /* socket tcp option handlers */
  787. static t_opt tcp_opt[] = {
  788. {"keepalive", opt_keepalive},
  789. {"reuseaddr", opt_reuseaddr},
  790. {"tcp-nodelay", opt_tcp_nodelay},
  791. {"linger", opt_linger},
  792. {"bindtodevice", opt_bindtodevice},
  793. {NULL, NULL}
  794. };
  795. static SQRESULT tcp_meth_send(HSQUIRRELVM v) {
  796. SQ_FUNC_VARS_NO_TOP(v);
  797. GET_tcp_client_INSTANCE_AT(v, 1);
  798. return buffer_meth_send(v, &tcp->buf);
  799. }
  800. static SQRESULT tcp_meth_receive(HSQUIRRELVM v) {
  801. SQ_FUNC_VARS_NO_TOP(v);
  802. GET_tcp_client_INSTANCE_AT(v, 1);
  803. return buffer_meth_receive(v, &tcp->buf);
  804. }
  805. static SQRESULT tcp_meth_getstats(HSQUIRRELVM v) {
  806. SQ_FUNC_VARS_NO_TOP(v);
  807. GET_tcp_client_INSTANCE_AT(v, 1);
  808. return buffer_meth_getstats(v, &tcp->buf);
  809. }
  810. static SQRESULT tcp_meth_setstats(HSQUIRRELVM v) {
  811. SQ_FUNC_VARS_NO_TOP(v);
  812. GET_tcp_client_INSTANCE_AT(v, 1);
  813. return buffer_meth_setstats(v, &tcp->buf);
  814. }
  815. /*-------------------------------------------------------------------------*\
  816. * Just call option handler
  817. \*-------------------------------------------------------------------------*/
  818. static SQRESULT tcp_meth_setoption(HSQUIRRELVM v)
  819. {
  820. SQ_FUNC_VARS_NO_TOP(v);
  821. GET_tcp_INSTANCE_AT(v, 1);
  822. return opt_meth_setoption(v, tcp_opt, &tcp->sock);
  823. }
  824. /*-------------------------------------------------------------------------*\
  825. * Select support methods
  826. \*-------------------------------------------------------------------------*/
  827. static SQRESULT tcp_meth_getfd(HSQUIRRELVM v)
  828. {
  829. SQ_FUNC_VARS_NO_TOP(v);
  830. GET_tcp_INSTANCE_AT(v, 1);
  831. sq_pushinteger(v, (int) tcp->sock);
  832. return 1;
  833. }
  834. /* this is very dangerous, but can be handy for those that are brave enough */
  835. static SQRESULT tcp_meth_setfd(HSQUIRRELVM v)
  836. {
  837. SQ_FUNC_VARS_NO_TOP(v);
  838. GET_tcp_INSTANCE_AT(v, 1);
  839. SQ_GET_INTEGER(v, 2, fd);
  840. tcp->sock = (t_socket) fd;
  841. return 0;
  842. }
  843. static SQRESULT tcp_meth_dirty(HSQUIRRELVM v)
  844. {
  845. SQ_FUNC_VARS_NO_TOP(v);
  846. GET_tcp_INSTANCE_AT(v, 1);
  847. sq_pushbool(v, !buffer_isempty(&tcp->buf));
  848. return 1;
  849. }
  850. /*=========================================================================*\
  851. * Library functions
  852. \*=========================================================================*/
  853. /*-------------------------------------------------------------------------*\
  854. * Creates a master tcp object
  855. \*-------------------------------------------------------------------------*/
  856. static SQRESULT tcp_releasehook(SQUserPointer p, SQInteger size, HSQUIRRELVM v)
  857. {
  858. p_tcp tcp = (p_tcp)p;
  859. if(tcp) {
  860. lua_socket_destroy(&tcp->sock);
  861. sq_free(tcp, sizeof(t_tcp));
  862. }
  863. return 0;
  864. }
  865. static int tcp_constructor_for_socket(HSQUIRRELVM v, int idx, t_socket sock, int type)
  866. {
  867. /* allocate tcp object */
  868. p_tcp tcp = (p_tcp) sq_malloc(sizeof(t_tcp));
  869. /* set its type as master object */
  870. tcp->type = type;
  871. /* initialize remaining structure fields */
  872. lua_socket_setnonblocking(&sock);
  873. tcp->sock = sock;
  874. lua_io_init(&tcp->io, (p_send) lua_socket_send, (p_recv) lua_socket_recv,
  875. (p_error) lua_socket_ioerror, &tcp->sock);
  876. lua_timeout_init(&tcp->tm, -1, -1);
  877. buffer_init(&tcp->buf, &tcp->io, &tcp->tm);
  878. sq_setinstanceup(v, idx, tcp);
  879. sq_setreleasehook(v, idx, tcp_releasehook);
  880. return 1;
  881. }
  882. static SQRESULT tcp_constructor(HSQUIRRELVM v)
  883. {
  884. t_socket sock;
  885. const char *err = inet_trycreate(&sock, SOCK_STREAM);
  886. /* try to allocate a system socket */
  887. if (!err) {
  888. return tcp_constructor_for_socket(v, 1, sock, TCP_TYPE_MASTER);
  889. }
  890. return sq_throwerror(v, err);
  891. }
  892. /*-------------------------------------------------------------------------*\
  893. * Waits for and returns a client object attempting connection to the
  894. * server object
  895. \*-------------------------------------------------------------------------*/
  896. static SQRESULT tcp_meth_accept(HSQUIRRELVM v)
  897. {
  898. SQ_FUNC_VARS_NO_TOP(v);
  899. GET_tcp_server_INSTANCE_AT(v, 1);
  900. p_timeout tm = lua_timeout_markstart(&tcp->tm);
  901. t_socket sock;
  902. int err = lua_socket_accept(&tcp->sock, &sock, NULL, NULL, tm);
  903. /* if successful, push client socket */
  904. if (err == IO_DONE) {
  905. sq_pushstring(v,_SC("socket"),-1);
  906. int rc = sq_getonroottable(v);
  907. if(rc < 0) return rc;
  908. sq_pushstring(v,_SC("tcp"),-1);
  909. rc = sq_rawget(v, -2);
  910. if(rc < 0) return rc;
  911. rc = sq_createinstance(v, -1);
  912. if(rc < 0) return rc;
  913. tcp_constructor_for_socket(v, sq_gettop(v), sock, TCP_TYPE_CLIENT);
  914. } else {
  915. return sq_throwerror(v, lua_socket_strerror(err));
  916. }
  917. return 1;
  918. }
  919. /*-------------------------------------------------------------------------*\
  920. * Binds an object to an address
  921. \*-------------------------------------------------------------------------*/
  922. static SQRESULT tcp_meth_bind(HSQUIRRELVM v)
  923. {
  924. SQ_FUNC_VARS_NO_TOP(v);
  925. GET_tcp_master_INSTANCE_AT(v, 1);
  926. SQ_GET_STRING(v, 2, address);
  927. SQ_GET_INTEGER(v, 3, port);
  928. const char *err = inet_trybind(&tcp->sock, address, port);
  929. if (err) return sq_throwerror(v, err);
  930. return 0;
  931. }
  932. /*-------------------------------------------------------------------------*\
  933. * Turns a master tcp object into a client object.
  934. \*-------------------------------------------------------------------------*/
  935. static SQRESULT tcp_meth_connect(HSQUIRRELVM v)
  936. {
  937. SQ_FUNC_VARS_NO_TOP(v);
  938. GET_tcp_INSTANCE_AT(v, 1);
  939. SQ_GET_STRING(v, 2, address);
  940. SQ_GET_INTEGER(v, 3, port);
  941. p_timeout tm = lua_timeout_markstart(&tcp->tm);
  942. const char *err = inet_tryconnect(&tcp->sock, address, port, tm);
  943. /* have to set the class even if it failed due to non-blocking connects */
  944. if (err) return sq_throwerror(v, err);
  945. tcp->type = TCP_TYPE_CLIENT;
  946. return 0;
  947. }
  948. /*-------------------------------------------------------------------------*\
  949. * Closes socket used by object
  950. \*-------------------------------------------------------------------------*/
  951. static SQRESULT tcp_meth_close(HSQUIRRELVM v)
  952. {
  953. SQ_FUNC_VARS_NO_TOP(v);
  954. GET_tcp_INSTANCE_AT(v, 1);
  955. lua_socket_destroy(&tcp->sock);
  956. return 0;
  957. }
  958. /*-------------------------------------------------------------------------*\
  959. * Puts the sockt in listen mode
  960. \*-------------------------------------------------------------------------*/
  961. static SQRESULT tcp_meth_listen(HSQUIRRELVM v)
  962. {
  963. SQ_FUNC_VARS(v);
  964. GET_tcp_master_INSTANCE_AT(v, 1);
  965. SQ_OPT_INTEGER(v, 2, backlog, 32);
  966. int err = lua_socket_listen(&tcp->sock, backlog);
  967. if (err != IO_DONE) return sq_throwerror(v, lua_socket_strerror(err));
  968. /* turn master object into a server object */
  969. tcp->type = TCP_TYPE_SERVER;
  970. return 0;
  971. }
  972. /*-------------------------------------------------------------------------*\
  973. * Shuts the connection down partially
  974. \*-------------------------------------------------------------------------*/
  975. static SQRESULT tcp_meth_shutdown(HSQUIRRELVM v)
  976. {
  977. SQ_FUNC_VARS(v);
  978. GET_tcp_client_INSTANCE_AT(v, 1);
  979. SQ_OPT_STRING(v, 2, how, _SC("both"));
  980. switch (how[0]) {
  981. case _SC('b'):
  982. if (strcmp(how, "both")) goto error;
  983. lua_socket_shutdown(&tcp->sock, 2);
  984. break;
  985. case _SC('s'):
  986. if (strcmp(how, "send")) goto error;
  987. lua_socket_shutdown(&tcp->sock, 1);
  988. break;
  989. case _SC('r'):
  990. if (strcmp(how, "receive")) goto error;
  991. lua_socket_shutdown(&tcp->sock, 0);
  992. break;
  993. }
  994. return 0;
  995. error:
  996. return sq_throwerror(v, _SC("invalid shutdown method"));
  997. }
  998. /*-------------------------------------------------------------------------*\
  999. * Just call inet methods
  1000. \*-------------------------------------------------------------------------*/
  1001. static SQRESULT tcp_meth_getpeername(HSQUIRRELVM v)
  1002. {
  1003. SQ_FUNC_VARS_NO_TOP(v);
  1004. GET_tcp_INSTANCE_AT(v, 1);
  1005. return inet_meth_getpeername(v, &tcp->sock);
  1006. }
  1007. static SQRESULT tcp_meth_getsockname(HSQUIRRELVM v)
  1008. {
  1009. SQ_FUNC_VARS_NO_TOP(v);
  1010. GET_tcp_INSTANCE_AT(v, 1);
  1011. return inet_meth_getsockname(v, &tcp->sock);
  1012. }
  1013. /*-------------------------------------------------------------------------*\
  1014. * Just call tm methods
  1015. \*-------------------------------------------------------------------------*/
  1016. static SQRESULT tcp_meth_settimeout(HSQUIRRELVM v)
  1017. {
  1018. SQ_FUNC_VARS_NO_TOP(v);
  1019. GET_tcp_INSTANCE_AT(v, 1);
  1020. return timeout_meth_settimeout(v, &tcp->tm);
  1021. }
  1022. /*=========================================================================*\
  1023. * Lua udp methods
  1024. \*=========================================================================*/
  1025. /* can't be larger than wsocket.c MAXCHUNK!!! */
  1026. #define UDP_DATAGRAMSIZE 8192
  1027. #define UDP_TYPE_ANY 0
  1028. #define UDP_TYPE_CONNECTED 1
  1029. #define UDP_TYPE_UNCONNECTED 2
  1030. typedef struct t_udp_ {
  1031. t_socket sock;
  1032. t_timeout tm;
  1033. int type;
  1034. } t_udp;
  1035. typedef t_udp *p_udp;
  1036. /* socket udp options */
  1037. static t_opt udp_opt[] = {
  1038. {"dontroute", opt_dontroute},
  1039. {"broadcast", opt_broadcast},
  1040. {"reuseaddr", opt_reuseaddr},
  1041. {"ip-multicast-ttl", opt_ip_multicast_ttl},
  1042. {"ip-multicast-loop", opt_ip_multicast_loop},
  1043. {"ip-add-membership", opt_ip_add_membership},
  1044. {"ip-drop-membership", opt_ip_drop_membersip},
  1045. {"bindtodevice", opt_bindtodevice},
  1046. {NULL, NULL}
  1047. };
  1048. static const SQChar SQ_udp_TAG[] = _SC("sq_udp");
  1049. #define GET_udp_INSTANCE_AT(v, idx) \
  1050. p_udp udp; \
  1051. if((_rc_ = sq_getinstanceup(v,idx,(SQUserPointer*)&udp,(void*)SQ_udp_TAG)) < 0) return _rc_;
  1052. #define GET_udp_connected_INSTANCE_AT(v, idx) GET_udp_INSTANCE_AT(v, idx)\
  1053. if(udp->type != UDP_TYPE_CONNECTED) return sq_throwerror(v, _SC("udp connected expected"));
  1054. #define GET_udp_unconnected_INSTANCE_AT(v, idx) GET_udp_INSTANCE_AT(v, idx)\
  1055. if(udp->type != UDP_TYPE_UNCONNECTED) return sq_throwerror(v, _SC("udp unconnected expected"));
  1056. static const char *udp_strerror(int err) {
  1057. /* a 'closed' error on an unconnected means the target address was not
  1058. * accepted by the transport layer */
  1059. if (err == IO_CLOSED) return "refused";
  1060. else return lua_socket_strerror(err);
  1061. }
  1062. /*-------------------------------------------------------------------------*\
  1063. * Send data through connected udp socket
  1064. \*-------------------------------------------------------------------------*/
  1065. static SQRESULT udp_meth_send(HSQUIRRELVM v) {
  1066. SQ_FUNC_VARS_NO_TOP(v);
  1067. GET_udp_connected_INSTANCE_AT(v, 1);
  1068. p_timeout tm = &udp->tm;
  1069. size_t sent = 0;
  1070. int err;
  1071. SQ_GET_STRING(v, 2, data);
  1072. lua_timeout_markstart(tm);
  1073. err = lua_socket_send(&udp->sock, data, data_size, &sent, tm);
  1074. if (err != IO_DONE) return sq_throwerror(v, udp_strerror(err));
  1075. sq_pushinteger(v, sent);
  1076. return 1;
  1077. }
  1078. /*-------------------------------------------------------------------------*\
  1079. * Send data through unconnected udp socket
  1080. \*-------------------------------------------------------------------------*/
  1081. static SQRESULT udp_meth_sendto(HSQUIRRELVM v) {
  1082. SQ_FUNC_VARS_NO_TOP(v);
  1083. GET_udp_unconnected_INSTANCE_AT(v, 1);
  1084. size_t sent = 0;
  1085. SQ_GET_STRING(v, 2, data);
  1086. SQ_GET_STRING(v, 3, ip);
  1087. SQ_GET_INTEGER(v, 4, port);
  1088. p_timeout tm = &udp->tm;
  1089. struct sockaddr_in addr;
  1090. int err;
  1091. memset(&addr, 0, sizeof(addr));
  1092. if (!inet_aton(ip, &addr.sin_addr))
  1093. return sq_throwerror(v, _SC("invalid ip address"));
  1094. addr.sin_family = AF_INET;
  1095. addr.sin_port = htons(port);
  1096. lua_timeout_markstart(tm);
  1097. err = lua_socket_sendto(&udp->sock, data, data_size, &sent,
  1098. (SA *) &addr, sizeof(addr), tm);
  1099. if (err != IO_DONE) return sq_throwerror(v, udp_strerror(err));
  1100. sq_pushinteger(v, sent);
  1101. return 1;
  1102. }
  1103. /*-------------------------------------------------------------------------*\
  1104. * Receives data from a UDP socket
  1105. \*-------------------------------------------------------------------------*/
  1106. static SQRESULT udp_meth_receive(HSQUIRRELVM v) {
  1107. SQ_FUNC_VARS(v);
  1108. GET_udp_INSTANCE_AT(v, 1);
  1109. char buffer[UDP_DATAGRAMSIZE];
  1110. SQ_OPT_INTEGER(v, 2, count, sizeof(buffer));
  1111. if(count <= 0) return sq_throwerror(v, _SC("invalid size for receive (%d)"), count);
  1112. size_t got;
  1113. int err;
  1114. p_timeout tm = &udp->tm;
  1115. count = MIN(count, sizeof(buffer));
  1116. lua_timeout_markstart(tm);
  1117. err = lua_socket_recv(&udp->sock, buffer, count, &got, tm);
  1118. if (err != IO_DONE) return sq_throwerror(v, udp_strerror(err));
  1119. sq_pushstring(v, buffer, got);
  1120. return 1;
  1121. }
  1122. /*-------------------------------------------------------------------------*\
  1123. * Receives data and sender from a UDP socket
  1124. \*-------------------------------------------------------------------------*/
  1125. static SQRESULT udp_meth_receivefrom(HSQUIRRELVM v) {
  1126. SQ_FUNC_VARS(v);
  1127. GET_udp_unconnected_INSTANCE_AT(v, 1);
  1128. struct sockaddr_in addr;
  1129. socklen_t addr_len = sizeof(addr);
  1130. char buffer[UDP_DATAGRAMSIZE];
  1131. size_t got;
  1132. SQ_OPT_INTEGER(v, 2, count, sizeof(buffer));
  1133. if(count <= 0) return sq_throwerror(v, _SC("invalid size for receive (%d)"), count);
  1134. int err;
  1135. p_timeout tm = &udp->tm;
  1136. lua_timeout_markstart(tm);
  1137. count = MIN(count, sizeof(buffer));
  1138. err = lua_socket_recvfrom(&udp->sock, buffer, count, &got,
  1139. (SA *) &addr, &addr_len, tm);
  1140. if (err == IO_DONE) {
  1141. sq_newtable(v);
  1142. sq_pushliteral(v, _SC("data"));
  1143. sq_pushstring(v, buffer, got);
  1144. sq_rawset(v, -3);
  1145. sq_pushliteral(v, _SC("address"));
  1146. sq_pushstring(v, inet_ntoa(addr.sin_addr), -1);
  1147. sq_rawset(v, -3);
  1148. sq_pushliteral(v, _SC("port"));
  1149. sq_pushinteger(v, ntohs(addr.sin_port));
  1150. sq_rawset(v, -3);
  1151. return 1;
  1152. }
  1153. else return sq_throwerror(v, udp_strerror(err));
  1154. }
  1155. /*-------------------------------------------------------------------------*\
  1156. * Select support methods
  1157. \*-------------------------------------------------------------------------*/
  1158. static SQRESULT udp_meth_getfd(HSQUIRRELVM v) {
  1159. SQ_FUNC_VARS_NO_TOP(v);
  1160. GET_udp_INSTANCE_AT(v, 1);
  1161. sq_pushinteger(v, (SQInteger) udp->sock);
  1162. return 1;
  1163. }
  1164. /* this is very dangerous, but can be handy for those that are brave enough */
  1165. static SQRESULT udp_meth_setfd(HSQUIRRELVM v) {
  1166. SQ_FUNC_VARS_NO_TOP(v);
  1167. GET_udp_INSTANCE_AT(v, 1);
  1168. SQ_GET_INTEGER(v, 2, fd);
  1169. udp->sock = (t_socket) fd;
  1170. return 0;
  1171. }
  1172. static SQRESULT udp_meth_dirty(HSQUIRRELVM v) {
  1173. SQ_FUNC_VARS_NO_TOP(v);
  1174. GET_udp_INSTANCE_AT(v, 1);
  1175. (void) udp;
  1176. sq_pushbool(v, SQFalse);
  1177. return 1;
  1178. }
  1179. /*-------------------------------------------------------------------------*\
  1180. * Just call inet methods
  1181. \*-------------------------------------------------------------------------*/
  1182. static SQRESULT udp_meth_getpeername(HSQUIRRELVM v) {
  1183. SQ_FUNC_VARS_NO_TOP(v);
  1184. GET_udp_connected_INSTANCE_AT(v, 1);
  1185. return inet_meth_getpeername(v, &udp->sock);
  1186. }
  1187. static SQRESULT udp_meth_getsockname(HSQUIRRELVM v) {
  1188. SQ_FUNC_VARS_NO_TOP(v);
  1189. GET_udp_INSTANCE_AT(v, 1);
  1190. return inet_meth_getsockname(v, &udp->sock);
  1191. }
  1192. /*-------------------------------------------------------------------------*\
  1193. * Just call option handler
  1194. \*-------------------------------------------------------------------------*/
  1195. static SQRESULT udp_meth_setoption(HSQUIRRELVM v) {
  1196. SQ_FUNC_VARS_NO_TOP(v);
  1197. GET_udp_INSTANCE_AT(v, 1);
  1198. return opt_meth_setoption(v, udp_opt, &udp->sock);
  1199. }
  1200. /*-------------------------------------------------------------------------*\
  1201. * Just call tm methods
  1202. \*-------------------------------------------------------------------------*/
  1203. static SQRESULT udp_meth_settimeout(HSQUIRRELVM v) {
  1204. SQ_FUNC_VARS_NO_TOP(v);
  1205. GET_udp_INSTANCE_AT(v, 1);
  1206. return timeout_meth_settimeout(v, &udp->tm);
  1207. }
  1208. /*-------------------------------------------------------------------------*\
  1209. * Turns a master udp object into a client object.
  1210. \*-------------------------------------------------------------------------*/
  1211. static SQRESULT udp_meth_setpeername(HSQUIRRELVM v) {
  1212. SQ_FUNC_VARS_NO_TOP(v);
  1213. GET_udp_INSTANCE_AT(v, 1);
  1214. p_timeout tm = &udp->tm;
  1215. SQ_GET_STRING(v, 2, address);
  1216. int connecting = scstrcmp(address, _SC("*"));
  1217. SQInteger port;
  1218. if(connecting) sq_getinteger(v, 3, &port);
  1219. else sq_optinteger(v, 3, &port, 0);
  1220. const char *err = inet_tryconnect(&udp->sock, address, port, tm);
  1221. if (err) return sq_throwerror(v, err);
  1222. /* change class to connected or unconnected depending on address */
  1223. if (connecting)
  1224. udp->type = connecting ? UDP_TYPE_CONNECTED : UDP_TYPE_UNCONNECTED;
  1225. return 0;
  1226. }
  1227. /*-------------------------------------------------------------------------*\
  1228. * Closes socket used by object
  1229. \*-------------------------------------------------------------------------*/
  1230. static SQRESULT udp_meth_close(HSQUIRRELVM v) {
  1231. SQ_FUNC_VARS_NO_TOP(v);
  1232. GET_udp_INSTANCE_AT(v, 1);
  1233. lua_socket_destroy(&udp->sock);
  1234. return 0;
  1235. }
  1236. /*-------------------------------------------------------------------------*\
  1237. * Turns a master object into a server object
  1238. \*-------------------------------------------------------------------------*/
  1239. static SQRESULT udp_meth_setsockname(HSQUIRRELVM v) {
  1240. SQ_FUNC_VARS_NO_TOP(v);
  1241. GET_udp_unconnected_INSTANCE_AT(v, 1);
  1242. SQ_GET_STRING(v, 2, address);
  1243. SQ_GET_INTEGER(v, 3, port);
  1244. const char *err = inet_trybind(&udp->sock, address, port);
  1245. if (err) return sq_throwerror(v, err);
  1246. return 0;
  1247. }
  1248. /*=========================================================================*\
  1249. * Library functions
  1250. \*=========================================================================*/
  1251. /*-------------------------------------------------------------------------*\
  1252. * Creates a master udp object
  1253. \*-------------------------------------------------------------------------*/
  1254. static SQRESULT udp_releasehook(SQUserPointer p, SQInteger size, HSQUIRRELVM v)
  1255. {
  1256. p_udp udp = (p_udp)p;
  1257. if(udp) {
  1258. lua_socket_destroy(&udp->sock);
  1259. sq_free(udp, sizeof(p_udp));
  1260. }
  1261. return 0;
  1262. }
  1263. static SQRESULT udp_constructor(HSQUIRRELVM v) {
  1264. t_socket sock;
  1265. const char *err = inet_trycreate(&sock, SOCK_DGRAM);
  1266. /* try to allocate a system socket */
  1267. if (!err) {
  1268. /* allocate tcp object */
  1269. p_udp udp = (p_udp) sq_malloc(sizeof(t_udp));
  1270. udp->type = UDP_TYPE_UNCONNECTED;
  1271. /* initialize remaining structure fields */
  1272. lua_socket_setnonblocking(&sock);
  1273. udp->sock = sock;
  1274. lua_timeout_init(&udp->tm, -1, -1);
  1275. sq_setinstanceup(v, 1, udp);
  1276. sq_setreleasehook(v, 1, udp_releasehook);
  1277. return 1;
  1278. }
  1279. return sq_throwerror(v, err);
  1280. }
  1281. #ifdef HAS_UNIX_DOMAIN_SOCKETS
  1282. /*=========================================================================*\
  1283. * Unix domain socket
  1284. * LuaSocket toolkit
  1285. \*=========================================================================*/
  1286. //#include "unix.h"
  1287. #include <sys/un.h>
  1288. /*=========================================================================*\
  1289. * Internal function prototypes
  1290. \*=========================================================================*/
  1291. /* unix socket option handlers */
  1292. static t_opt unix_opt[] = {
  1293. {"keepalive", opt_keepalive},
  1294. {"reuseaddr", opt_reuseaddr},
  1295. {"linger", opt_linger},
  1296. {NULL, NULL}
  1297. };
  1298. /*=========================================================================*\
  1299. * Lua methods
  1300. \*=========================================================================*/
  1301. #define UNIX_TYPE_ANY 0
  1302. #define UNIX_TYPE_CLIENT 1
  1303. #define UNIX_TYPE_SERVER 2
  1304. #define UNIX_TYPE_MASTER 3
  1305. typedef struct t_unix_ {
  1306. t_socket sock;
  1307. t_io io;
  1308. t_buffer buf;
  1309. t_timeout tm;
  1310. int type;
  1311. } t_unix;
  1312. typedef t_unix *p_unix;
  1313. static const SQChar SQ_unix_TAG[] = _SC("sq_unix_socket");
  1314. #define GET_unix_INSTANCE_AT(v, idx) \
  1315. p_unix unix_sock; \
  1316. if((_rc_ = sq_getinstanceup(v,idx,(SQUserPointer*)&unix_sock,(void*)SQ_unix_TAG)) < 0) return _rc_;
  1317. #define GET_unix_client_INSTANCE_AT(v, idx) GET_unix_INSTANCE_AT(v, idx)\
  1318. if(unix_sock->type != UNIX_TYPE_CLIENT) return sq_throwerror(v, _SC("unix client expected"));
  1319. #define GET_unix_server_INSTANCE_AT(v, idx) GET_unix_INSTANCE_AT(v, idx)\
  1320. if(unix_sock->type != UNIX_TYPE_SERVER) return sq_throwerror(v, _SC("unix server expected"));
  1321. #define GET_unix_master_INSTANCE_AT(v, idx) GET_unix_INSTANCE_AT(v, idx)\
  1322. if(unix_sock->type != UNIX_TYPE_MASTER) return sq_throwerror(v, _SC("unix master expected"));
  1323. /*-------------------------------------------------------------------------*\
  1324. * Creates a master unix object
  1325. \*-------------------------------------------------------------------------*/
  1326. static SQRESULT unix_releasehook(SQUserPointer p, SQInteger size, HSQUIRRELVM v)
  1327. {
  1328. p_unix unix_sock = (p_unix)p;
  1329. if(unix_sock) {
  1330. lua_socket_destroy(&unix_sock->sock);
  1331. sq_free(unix_sock, sizeof(t_unix));
  1332. }
  1333. return 0;
  1334. }
  1335. static SQRESULT unix_constructor_for_socket(HSQUIRRELVM v, int idx, t_socket sock, int type)
  1336. {
  1337. /* allocate unix object */
  1338. p_unix unix_sock = (p_unix) sq_malloc(sizeof(t_unix));
  1339. /* set its type as master object */
  1340. unix_sock->type = type;
  1341. /* initialize remaining structure fields */
  1342. lua_socket_setnonblocking(&sock);
  1343. unix_sock->sock = sock;
  1344. lua_io_init(&unix_sock->io, (p_send) lua_socket_send, (p_recv) lua_socket_recv,
  1345. (p_error) lua_socket_ioerror, &unix_sock->sock);
  1346. lua_timeout_init(&unix_sock->tm, -1, -1);
  1347. buffer_init(&unix_sock->buf, &unix_sock->io, &unix_sock->tm);
  1348. sq_setinstanceup(v, idx, unix_sock);
  1349. sq_setreleasehook(v, idx, unix_releasehook);
  1350. return 1;
  1351. }
  1352. static SQRESULT unix__tostring(HSQUIRRELVM v)
  1353. {
  1354. SQ_FUNC_VARS_NO_TOP(v);
  1355. GET_unix_INSTANCE_AT(v, 1);
  1356. char buff[64];
  1357. snprintf(buff, sizeof(buff), "unix sockets %d (%p)", unix_sock->type, unix_sock);
  1358. sq_pushstring(v, buff, -1);
  1359. return 1;
  1360. }
  1361. /*-------------------------------------------------------------------------*\
  1362. * Just call buffered IO methods
  1363. \*-------------------------------------------------------------------------*/
  1364. static SQRESULT unix_meth_send(HSQUIRRELVM v) {
  1365. SQ_FUNC_VARS_NO_TOP(v);
  1366. GET_unix_client_INSTANCE_AT(v, 1);
  1367. return buffer_meth_send(v, &unix_sock->buf);
  1368. }
  1369. static SQRESULT unix_meth_receive(HSQUIRRELVM v) {
  1370. SQ_FUNC_VARS_NO_TOP(v);
  1371. GET_unix_client_INSTANCE_AT(v, 1);
  1372. return buffer_meth_receive(v, &unix_sock->buf);
  1373. }
  1374. static SQRESULT unix_meth_getstats(HSQUIRRELVM v) {
  1375. SQ_FUNC_VARS_NO_TOP(v);
  1376. GET_unix_client_INSTANCE_AT(v, 1);
  1377. return buffer_meth_getstats(v, &unix_sock->buf);
  1378. }
  1379. static SQRESULT unix_meth_setstats(HSQUIRRELVM v) {
  1380. SQ_FUNC_VARS_NO_TOP(v);
  1381. GET_unix_client_INSTANCE_AT(v, 1);
  1382. return buffer_meth_setstats(v, &unix_sock->buf);
  1383. }
  1384. /*-------------------------------------------------------------------------*\
  1385. * Just call option handler
  1386. \*-------------------------------------------------------------------------*/
  1387. static SQRESULT unix_meth_setoption(HSQUIRRELVM v)
  1388. {
  1389. SQ_FUNC_VARS_NO_TOP(v);
  1390. GET_unix_INSTANCE_AT(v, 1);
  1391. return opt_meth_setoption(v, unix_opt, &unix_sock->sock);
  1392. }
  1393. /*-------------------------------------------------------------------------*\
  1394. * Select support methods
  1395. \*-------------------------------------------------------------------------*/
  1396. static SQRESULT unix_meth_getfd(HSQUIRRELVM v)
  1397. {
  1398. SQ_FUNC_VARS_NO_TOP(v);
  1399. GET_unix_INSTANCE_AT(v, 1);
  1400. sq_pushinteger(v, (int) unix_sock->sock);
  1401. return 1;
  1402. }
  1403. /* this is very dangerous, but can be handy for those that are brave enough */
  1404. static SQRESULT unix_meth_setfd(HSQUIRRELVM v)
  1405. {
  1406. SQ_FUNC_VARS_NO_TOP(v);
  1407. GET_unix_INSTANCE_AT(v, 1);
  1408. SQ_GET_INTEGER(v, 2, fd);
  1409. unix_sock->sock = (t_socket) fd;
  1410. return 0;
  1411. }
  1412. static SQRESULT unix_meth_dirty(HSQUIRRELVM v)
  1413. {
  1414. SQ_FUNC_VARS_NO_TOP(v);
  1415. GET_unix_INSTANCE_AT(v, 1);
  1416. sq_pushbool(v, !buffer_isempty(&unix_sock->buf));
  1417. return 1;
  1418. }
  1419. /*-------------------------------------------------------------------------*\
  1420. * Waits for and returns a client object attempting connection to the
  1421. * server object
  1422. \*-------------------------------------------------------------------------*/
  1423. static SQRESULT unix_meth_accept(HSQUIRRELVM v)
  1424. {
  1425. SQ_FUNC_VARS_NO_TOP(v);
  1426. GET_unix_server_INSTANCE_AT(v, 1);
  1427. p_timeout tm = lua_timeout_markstart(&unix_sock->tm);
  1428. t_socket sock;
  1429. int err = lua_socket_accept(&unix_sock->sock, &sock, NULL, NULL, tm);
  1430. /* if successful, push client socket */
  1431. if (err == IO_DONE) {
  1432. sq_pushstring(v,_SC("socket"),-1);
  1433. int rc = sq_getonroottable(v);
  1434. if(rc < 0) return rc;
  1435. sq_pushstring(v,_SC("unix"),-1);
  1436. rc = sq_rawget(v, -2);
  1437. if(rc < 0) return rc;
  1438. rc = sq_createinstance(v, -1);
  1439. if(rc < 0) return rc;
  1440. unix_constructor_for_socket(v, sq_gettop(v), sock, UNIX_TYPE_CLIENT);
  1441. } else {
  1442. return sq_throwerror(v, lua_socket_strerror(err));
  1443. }
  1444. return 1;
  1445. }
  1446. /*-------------------------------------------------------------------------*\
  1447. * Binds an object to an address
  1448. \*-------------------------------------------------------------------------*/
  1449. static const char *unix_trybind(p_unix un, const char *path) {
  1450. struct sockaddr_un local;
  1451. size_t len = strlen(path);
  1452. int err;
  1453. if (len >= sizeof(local.sun_path)) return "path too long";
  1454. memset(&local, 0, sizeof(local));
  1455. strcpy(local.sun_path, path);
  1456. local.sun_family = AF_UNIX;
  1457. #ifdef UNIX_HAS_SUN_LEN
  1458. local.sun_len = sizeof(local.sun_family) + sizeof(local.sun_len)
  1459. + len + 1;
  1460. err = lua_socket_bind(&un->sock, (SA *) &local, local.sun_len);
  1461. #else
  1462. err = lua_socket_bind(&un->sock, (SA *) &local,
  1463. sizeof(local.sun_family) + len);
  1464. #endif
  1465. if (err != IO_DONE) lua_socket_destroy(&un->sock);
  1466. return lua_socket_strerror(err);
  1467. }
  1468. static SQRESULT unix_meth_bind(HSQUIRRELVM v)
  1469. {
  1470. SQ_FUNC_VARS_NO_TOP(v);
  1471. GET_unix_master_INSTANCE_AT(v, 1);
  1472. SQ_GET_STRING(v, 2, path);
  1473. const char *err = unix_trybind(unix_sock, path);
  1474. if (err) return sq_throwerror(v, err);
  1475. return 0;
  1476. }
  1477. /*-------------------------------------------------------------------------*\
  1478. * Turns a master unix object into a client object.
  1479. \*-------------------------------------------------------------------------*/
  1480. static const char *unix_tryconnect(p_unix un, const char *path)
  1481. {
  1482. struct sockaddr_un remote;
  1483. int err;
  1484. size_t len = strlen(path);
  1485. if (len >= sizeof(remote.sun_path)) return "path too long";
  1486. memset(&remote, 0, sizeof(remote));
  1487. strcpy(remote.sun_path, path);
  1488. remote.sun_family = AF_UNIX;
  1489. lua_timeout_markstart(&un->tm);
  1490. #ifdef UNIX_HAS_SUN_LEN
  1491. remote.sun_len = sizeof(remote.sun_family) + sizeof(remote.sun_len)
  1492. + len + 1;
  1493. err = lua_socket_connect(&un->sock, (SA *) &remote, remote.sun_len, &un->tm);
  1494. #else
  1495. err = lua_socket_connect(&un->sock, (SA *) &remote,
  1496. sizeof(remote.sun_family) + len, &un->tm);
  1497. #endif
  1498. if (err != IO_DONE) lua_socket_destroy(&un->sock);
  1499. return lua_socket_strerror(err);
  1500. }
  1501. static SQRESULT unix_meth_connect(HSQUIRRELVM v)
  1502. {
  1503. SQ_FUNC_VARS_NO_TOP(v);
  1504. GET_unix_INSTANCE_AT(v, 1);
  1505. SQ_GET_STRING(v, 2, path);
  1506. const char *err = unix_tryconnect(unix_sock, path);
  1507. if (err) return sq_throwerror(v, err);
  1508. unix_sock->type = UNIX_TYPE_CLIENT;
  1509. return 0;
  1510. }
  1511. /*-------------------------------------------------------------------------*\
  1512. * Closes socket used by object
  1513. \*-------------------------------------------------------------------------*/
  1514. static SQRESULT unix_meth_close(HSQUIRRELVM v)
  1515. {
  1516. SQ_FUNC_VARS_NO_TOP(v);
  1517. GET_unix_INSTANCE_AT(v, 1);
  1518. lua_socket_destroy(&unix_sock->sock);
  1519. return 0;
  1520. }
  1521. /*-------------------------------------------------------------------------*\
  1522. * Puts the sockt in listen mode
  1523. \*-------------------------------------------------------------------------*/
  1524. static SQRESULT unix_meth_listen(HSQUIRRELVM v) {
  1525. SQ_FUNC_VARS(v);
  1526. GET_unix_master_INSTANCE_AT(v, 1);
  1527. SQ_OPT_INTEGER(v, 2, backlog, 32);
  1528. int err = lua_socket_listen(&unix_sock->sock, backlog);
  1529. if (err != IO_DONE) return sq_throwerror(v, lua_socket_strerror(err));
  1530. /* turn master object into a server object */
  1531. unix_sock->type = UNIX_TYPE_SERVER;
  1532. return 0;
  1533. }
  1534. /*-------------------------------------------------------------------------*\
  1535. * Shuts the connection down partially
  1536. \*-------------------------------------------------------------------------*/
  1537. static SQRESULT unix_meth_shutdown(HSQUIRRELVM v) {
  1538. SQ_FUNC_VARS(v);
  1539. GET_unix_INSTANCE_AT(v, 1);
  1540. /* SHUT_RD, SHUT_WR, SHUT_RDWR have the value 0, 1, 2, so we can use method index directly */
  1541. SQ_OPT_STRING(v, 2, how, _SC("both"));
  1542. switch (how[0]) {
  1543. case _SC('b'):
  1544. if (strcmp(how, "both")) goto error;
  1545. lua_socket_shutdown(&unix_sock->sock, 2);
  1546. break;
  1547. case _SC('s'):
  1548. if (strcmp(how, "send")) goto error;
  1549. lua_socket_shutdown(&unix_sock->sock, 1);
  1550. break;
  1551. case _SC('r'):
  1552. if (strcmp(how, "receive")) goto error;
  1553. lua_socket_shutdown(&unix_sock->sock, 0);
  1554. break;
  1555. }
  1556. return 0;
  1557. error:
  1558. return sq_throwerror(v, _SC("invalid shutdown method"));
  1559. }
  1560. /*-------------------------------------------------------------------------*\
  1561. * Just call tm methods
  1562. \*-------------------------------------------------------------------------*/
  1563. static SQRESULT unix_meth_settimeout(HSQUIRRELVM v) {
  1564. SQ_FUNC_VARS_NO_TOP(v);
  1565. GET_unix_INSTANCE_AT(v, 1);
  1566. return timeout_meth_settimeout(v, &unix_sock->tm);
  1567. }
  1568. /*=========================================================================*\
  1569. * Library functions
  1570. \*=========================================================================*/
  1571. /*-------------------------------------------------------------------------*\
  1572. * Creates a master unix object
  1573. \*-------------------------------------------------------------------------*/
  1574. static SQRESULT unix_constructor(HSQUIRRELVM v) {
  1575. t_socket sock;
  1576. const char *err = lua_socket_strerror(lua_socket_create(&sock, AF_UNIX, SOCK_STREAM, 0));
  1577. /* try to allocate a system socket */
  1578. if (!err) {
  1579. return unix_constructor_for_socket(v, 1, sock, UNIX_TYPE_MASTER);
  1580. }
  1581. return sq_throwerror(v, err);
  1582. }
  1583. #endif //HAS_UNIX_DOMAIN_SOCKETS
  1584. /*=========================================================================*\
  1585. * Internal Select function prototypes.
  1586. \*=========================================================================*/
  1587. static t_socket getfd(HSQUIRRELVM v);
  1588. static SQRESULT dirty(HSQUIRRELVM v);
  1589. static t_socket collect_fd(HSQUIRRELVM v, int tab, t_socket max_fd,
  1590. int itab, fd_set *set);
  1591. static int check_dirty(HSQUIRRELVM v, int tab, int dtab, fd_set *set);
  1592. static void return_fd(HSQUIRRELVM v, fd_set *set, t_socket max_fd,
  1593. int itab, int tab, int start);
  1594. //static void make_assoc(HSQUIRRELVM v, int tab);
  1595. /*-------------------------------------------------------------------------*\
  1596. * Waits for a set of sockets until a condition is met or timeout.
  1597. \*-------------------------------------------------------------------------*/
  1598. static SQRESULT global_select(HSQUIRRELVM v) {
  1599. SQ_FUNC_VARS(v);
  1600. int rtab, wtab, itab, ret, ndirty;
  1601. t_socket max_fd;
  1602. fd_set rset, wset;
  1603. t_timeout tm;
  1604. SQ_OPT_FLOAT(v, 4, t, -1);
  1605. FD_ZERO(&rset); FD_ZERO(&wset);
  1606. sq_settop(v, 4);
  1607. sq_newtable(v); itab = sq_gettop(v);
  1608. sq_newarray(v, 0); rtab = sq_gettop(v);
  1609. sq_newarray(v, 0); wtab = sq_gettop(v);
  1610. max_fd = collect_fd(v, 2, SOCKET_INVALID, itab, &rset);
  1611. ndirty = check_dirty(v, 2, rtab, &rset);
  1612. t = ndirty > 0 ? 0.0: t;
  1613. lua_timeout_init(&tm, t, -1);
  1614. lua_timeout_markstart(&tm);
  1615. max_fd = collect_fd(v, 3, max_fd, itab, &wset);
  1616. ret = lua_socket_select(max_fd+1, &rset, &wset, NULL, &tm);
  1617. if (ret > 0 || ndirty > 0) {
  1618. return_fd(v, &rset, max_fd+1, itab, rtab, ndirty);
  1619. return_fd(v, &wset, max_fd+1, itab, wtab, 0);
  1620. sq_newarray(v, 2);
  1621. sq_pushinteger(v, 0);
  1622. sq_push(v, rtab);
  1623. sq_rawset(v, -3);
  1624. sq_pushinteger(v, 1);
  1625. sq_push(v, wtab);
  1626. sq_rawset(v, -3);
  1627. return 1;
  1628. } else if (ret == 0) {
  1629. return sq_throwerror(v, _SC("timeout"));
  1630. }
  1631. return sq_throwerror(v, _SC("select error %d"), ret);
  1632. }
  1633. /*=========================================================================*\
  1634. * Internal functions
  1635. \*=========================================================================*/
  1636. static t_socket getfd(HSQUIRRELVM v) {
  1637. t_socket fd = SOCKET_INVALID;
  1638. SQInteger top = sq_gettop(v);
  1639. sq_pushliteral(v, _SC("getfd"));
  1640. if(sq_get(v, -2) == SQ_OK){
  1641. SQObjectType ptype = sq_gettype(v, -1);
  1642. if (ptype == OT_CLOSURE || ptype == OT_NATIVECLOSURE) {
  1643. sq_push(v, -2);
  1644. if(sq_call(v, 1, SQTrue, SQFalse) == SQ_OK){
  1645. if (sq_gettype(v, -1) == OT_INTEGER){
  1646. SQInteger ifd;
  1647. sq_getinteger(v, -1, &ifd);
  1648. fd = (t_socket) ifd;
  1649. }
  1650. }
  1651. }
  1652. }
  1653. sq_settop(v, top);
  1654. return fd;
  1655. }
  1656. static SQRESULT dirty(HSQUIRRELVM v) {
  1657. int is = 0;
  1658. SQInteger top = sq_gettop(v);
  1659. sq_pushliteral(v, _SC("dirty"));
  1660. if(sq_get(v, -2) == SQ_OK){
  1661. SQObjectType ptype = sq_gettype(v, -1);
  1662. if (ptype == OT_CLOSURE || ptype == OT_NATIVECLOSURE) {
  1663. sq_push(v, -2);
  1664. if(sq_call(v, 1, SQTrue, SQFalse) == SQ_OK){
  1665. if (sq_gettype(v, -1) == OT_INTEGER){
  1666. SQBool bval;
  1667. sq_getbool(v, -1, &bval);
  1668. is = bval == SQTrue;
  1669. }
  1670. }
  1671. }
  1672. sq_pop(v, 1);
  1673. }
  1674. sq_settop(v, top);
  1675. return is;
  1676. }
  1677. static t_socket collect_fd(HSQUIRRELVM v, int tab, t_socket max_fd,
  1678. int itab, fd_set *set) {
  1679. int i = 0;
  1680. if (sq_gettype(v, tab) == OT_NULL) return max_fd;
  1681. while (1) {
  1682. t_socket fd;
  1683. sq_pushinteger(v, i);
  1684. if(sq_rawget(v, tab) == SQ_ERROR) break;
  1685. fd = getfd(v);
  1686. if (fd != SOCKET_INVALID) {
  1687. FD_SET(fd, set);
  1688. if (max_fd == SOCKET_INVALID || max_fd < fd)
  1689. max_fd = fd;
  1690. sq_pushinteger(v, fd);
  1691. sq_push(v, -2);
  1692. sq_rawset(v, itab);
  1693. }
  1694. sq_pop(v, 1);
  1695. ++i;
  1696. }
  1697. return max_fd;
  1698. }
  1699. static int check_dirty(HSQUIRRELVM v, int tab, int dtab, fd_set *set) {
  1700. int ndirty = 0, i = 0;
  1701. if (sq_gettype(v, tab) == OT_NULL)
  1702. return 0;
  1703. while (1) {
  1704. t_socket fd;
  1705. sq_pushinteger(v, i);
  1706. if(sq_rawget(v, tab) == SQ_ERROR) break;
  1707. fd = getfd(v);
  1708. if (fd != SOCKET_INVALID && dirty(v)) {
  1709. sq_pushinteger(v, ++ndirty);
  1710. sq_push(v, -2);
  1711. sq_rawset(v, dtab);
  1712. FD_CLR(fd, set);
  1713. }
  1714. sq_pop(v, 1);
  1715. ++i;
  1716. }
  1717. return ndirty;
  1718. }
  1719. static void return_fd(HSQUIRRELVM v, fd_set *set, t_socket max_fd,
  1720. int itab, int tab, int start) {
  1721. t_socket fd;
  1722. for (fd = 0; fd < max_fd; fd++) {
  1723. if (FD_ISSET(fd, set)) {
  1724. sq_pushinteger(v, fd);
  1725. sq_rawget(v, itab);
  1726. sq_arrayappend(v, tab);
  1727. }
  1728. }
  1729. }
  1730. #define INT_CONST(v,num) sq_pushstring(v,_SC(#num),-1);sq_pushinteger(v,num);sq_newslot(v,-3,SQTrue);
  1731. #ifdef __cplusplus
  1732. extern "C" {
  1733. #endif
  1734. SQRESULT sqext_register_sq_socket(HSQUIRRELVM v)
  1735. {
  1736. sq_pushliteral(v,_SC("socket"));
  1737. sq_newtable(v);
  1738. INT_CONST(v, IO_DONE);
  1739. INT_CONST(v, IO_TIMEOUT);
  1740. INT_CONST(v, IO_CLOSED);
  1741. INT_CONST(v, IO_UNKNOWN);
  1742. INT_CONST(v, IO_SSL);
  1743. sq_insertfunc(v, _SC("open"), socket_open, 1, _SC("."), SQTrue);
  1744. sq_insertfunc(v, _SC("close"), socket_close, 1, _SC("."), SQTrue);
  1745. sq_insertfunc(v, _SC("gethostname"), inet_global_gethostname, 1, _SC("."), SQTrue);
  1746. sq_insertfunc(v, _SC("gettime"), timeout_lua_gettime, 1, _SC("."), SQTrue);
  1747. sq_insertfunc(v, _SC("select"), global_select, -3, _SC(".aan"), SQTrue);
  1748. sq_insertfunc(v, _SC("sleep"), timeout_lua_sleep, 2, _SC(".i"), SQTrue);
  1749. sq_insertfunc(v, _SC("sleepMillisecs"), timeout_lua_sleepMillisecs, 2, _SC(".i"), SQTrue);
  1750. sq_insertfunc(v, _SC("tohostname"), inet_global_tohostname, 2, _SC(".s"), SQTrue);
  1751. sq_insertfunc(v, _SC("toip"), inet_global_toip, 2, _SC(".s"), SQTrue);
  1752. sq_pushliteral(v, _SC("tcp"));
  1753. sq_newclass(v, SQFalse);
  1754. sq_settypetag(v,-1,(void*)SQ_tcp_TAG);
  1755. sq_insertfunc(v, _SC("constructor"), tcp_constructor, 1, _SC("x"), SQFalse);
  1756. sq_insertfunc(v, _SC("accept"), tcp_meth_accept, 1, _SC("x"), SQFalse);
  1757. sq_insertfunc(v, _SC("bind"), tcp_meth_bind, 3, _SC("xsi"), SQFalse);
  1758. sq_insertfunc(v, _SC("close"), tcp_meth_close, 1, _SC("x"), SQFalse);
  1759. sq_insertfunc(v, _SC("connect"), tcp_meth_connect, 3, _SC("xsi"), SQFalse);
  1760. sq_insertfunc(v, _SC("dirty"), tcp_meth_dirty, 1, _SC("x"), SQFalse);
  1761. sq_insertfunc(v, _SC("getfd"), tcp_meth_getfd, 1, _SC("x"), SQFalse);
  1762. sq_insertfunc(v, _SC("getpeername"), tcp_meth_getpeername, 1, _SC("x"), SQFalse);
  1763. sq_insertfunc(v, _SC("getsockname"), tcp_meth_getsockname, 1, _SC("x"), SQFalse);
  1764. sq_insertfunc(v, _SC("getstats"), tcp_meth_getstats, 1, _SC("x"), SQFalse);
  1765. sq_insertfunc(v, _SC("listen"), tcp_meth_listen, -1, _SC("xi"), SQFalse);
  1766. sq_insertfunc(v, _SC("receive"), tcp_meth_receive, -1, _SC("x i|s s"), SQFalse);
  1767. sq_insertfunc(v, _SC("send"), tcp_meth_send, -2, _SC("xsii"), SQFalse);
  1768. sq_insertfunc(v, _SC("setfd"), tcp_meth_setfd, 2, _SC("xi"), SQFalse);
  1769. sq_insertfunc(v, _SC("setoption"), tcp_meth_setoption, -2, _SC("xs s|n|b"), SQFalse);
  1770. sq_insertfunc(v, _SC("setstats"), tcp_meth_setstats, 4, _SC("xiii"), SQFalse);
  1771. sq_insertfunc(v, _SC("settimeout"), tcp_meth_settimeout, -2, _SC("xns"), SQFalse);
  1772. sq_insertfunc(v, _SC("shutdown"), tcp_meth_shutdown, 2, _SC("xs"), SQFalse);
  1773. sq_newslot(v,-3,SQTrue);
  1774. sq_pushliteral(v, _SC("udp"));
  1775. sq_newclass(v, SQFalse);
  1776. sq_settypetag(v,-1,(void*)SQ_udp_TAG);
  1777. sq_insertfunc(v, _SC("constructor"), udp_constructor, 1, _SC("x"), SQFalse);
  1778. sq_insertfunc(v, _SC("close"), udp_meth_close, 1, _SC("x"), SQFalse);
  1779. sq_insertfunc(v, _SC("dirty"), udp_meth_dirty, 1, _SC("x"), SQFalse);
  1780. sq_insertfunc(v, _SC("getfd"), udp_meth_getfd, 1, _SC("x"), SQFalse);
  1781. sq_insertfunc(v, _SC("getpeername"), udp_meth_getpeername, 1, _SC("x"), SQFalse);
  1782. sq_insertfunc(v, _SC("getsockname"), udp_meth_getsockname, 1, _SC("x"), SQFalse);
  1783. sq_insertfunc(v, _SC("receive"), udp_meth_receive, -1, _SC("xi"), SQFalse);
  1784. sq_insertfunc(v, _SC("receivefrom"), udp_meth_receivefrom, -1, _SC("xi"), SQFalse);
  1785. sq_insertfunc(v, _SC("send"), udp_meth_send, 2, _SC("xs"), SQFalse);
  1786. sq_insertfunc(v, _SC("sendto"), udp_meth_sendto, 4, _SC("xssi"), SQFalse);
  1787. sq_insertfunc(v, _SC("setfd"), udp_meth_setfd, 2, _SC("xi"), SQFalse);
  1788. sq_insertfunc(v, _SC("setpeername"), udp_meth_setpeername, -1, _SC("xsi"), SQFalse);
  1789. sq_insertfunc(v, _SC("setsockname"), udp_meth_setsockname, 3, _SC("xsi"), SQFalse);
  1790. sq_insertfunc(v, _SC("setoption"), udp_meth_setoption, -2, _SC("xs s|n|b"), SQFalse);
  1791. sq_insertfunc(v, _SC("settimeout"), udp_meth_settimeout, 2, _SC("xn"), SQFalse);
  1792. sq_newslot(v,-3,SQTrue);
  1793. #ifdef HAS_UNIX_DOMAIN_SOCKETS
  1794. sq_pushliteral(v, _SC("unix"));
  1795. sq_newclass(v, SQFalse);
  1796. sq_settypetag(v,-1,(void*)SQ_unix_TAG);
  1797. sq_insertfunc(v, _SC("_tostring"), unix__tostring, -1, _SC("x"), SQFalse),
  1798. sq_insertfunc(v, _SC("constructor"), unix_constructor, 1, _SC("x"), SQFalse);
  1799. sq_insertfunc(v, _SC("accept"), unix_meth_accept, 1, _SC("x"), SQFalse);
  1800. sq_insertfunc(v, _SC("bind"), unix_meth_bind, 2, _SC("xs"), SQFalse);
  1801. sq_insertfunc(v, _SC("close"), unix_meth_close, 1, _SC("x"), SQFalse);
  1802. sq_insertfunc(v, _SC("connect"), unix_meth_connect, 2, _SC("xs"), SQFalse);
  1803. sq_insertfunc(v, _SC("dirty"), unix_meth_dirty, 1, _SC("x"), SQFalse);
  1804. sq_insertfunc(v, _SC("getfd"), unix_meth_getfd, 1, _SC("x"), SQFalse);
  1805. sq_insertfunc(v, _SC("getstats"), unix_meth_getstats, 1, _SC("x"), SQFalse);
  1806. sq_insertfunc(v, _SC("listen"), unix_meth_listen, -1, _SC("xi"), SQFalse);
  1807. sq_insertfunc(v, _SC("receive"), unix_meth_receive, -1, _SC("x i|s s"), SQFalse);
  1808. sq_insertfunc(v, _SC("send"), unix_meth_send, -2, _SC("xsii"), SQFalse);
  1809. sq_insertfunc(v, _SC("setfd"), unix_meth_setfd, 2, _SC("xi"), SQFalse);
  1810. sq_insertfunc(v, _SC("setoption"), unix_meth_setoption, -2, _SC("xs s|n|b"), SQFalse);
  1811. sq_insertfunc(v, _SC("setstats"), unix_meth_setstats, 4, _SC("xiii"), SQFalse);
  1812. sq_insertfunc(v, _SC("settimeout"), unix_meth_settimeout, -2, _SC("xns"), SQFalse);
  1813. sq_insertfunc(v, _SC("shutdown"), unix_meth_shutdown, 2, _SC("xs"), SQFalse);
  1814. sq_newslot(v,-3,SQTrue);
  1815. #endif
  1816. sq_newslot(v,-3,SQTrue); //push socket table
  1817. return 0;
  1818. }
  1819. #ifdef __cplusplus
  1820. }
  1821. #endif