sq_socket.cpp 70 KB

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