sq_socket.cpp 69 KB

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