PageRenderTime 45ms CodeModel.GetById 15ms RepoModel.GetById 0ms app.codeStats 1ms

/server/src/Rconnection.h

https://github.com/Filirom1/r-node
C Header | 444 lines | 279 code | 95 blank | 70 comment | 30 complexity | a29908689587799f4669b1006692d78b MD5 | raw file
  1. /*
  2. * C++ Interface to Rserve
  3. * Copyright (C) 2004-8 Simon Urbanek, All rights reserved.
  4. *
  5. * This program is free software; you can redistribute it and/or modify
  6. * it under the terms of the GNU Lesser General Public License as published by
  7. * the Free Software Foundation; version 2.1 of the License
  8. *
  9. * This program is distributed in the hope that it will be useful,
  10. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. * GNU Leser General Public License for more details.
  13. *
  14. * You should have received a copy of the GNU Lesser General Public License
  15. * along with this program; if not, write to the Free Software
  16. * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
  17. *
  18. * Although this code is licensed under LGPL v2.1, we strongly encourage
  19. * everyone modifying this software to contribute back any improvements and
  20. * bugfixes to the project for the benefit all other users. Thank you.
  21. *
  22. * $Id: Rconnection.h 265 2009-01-28 20:58:14Z urbanek $
  23. *
  24. * -------------------------------------------------------------------------
  25. *
  26. * Additions and changes to this code Copyright 2010 Jamie Love.
  27. */
  28. /* external defines:
  29. SWAPEND - needs to be defined for platforms with inverse endianess related to Intel
  30. MAIN - should be defined in just one file that will contain the fn definitions and variables
  31. (this is inherited from Rsrv.h and sisocks.h)
  32. */
  33. #ifndef __RCONNECTION_H__
  34. #define __RCONNECTION_H__
  35. #if defined __GNUC__ && !defined unix && !defined Win32 && !defined WIN32
  36. #define unix
  37. #endif
  38. #include <iostream>
  39. #include <stdio.h>
  40. #include "sisocks.h"
  41. #include "Rsrv.h"
  42. typedef unsigned int Rsize_t;
  43. //=== Rconnection error codes
  44. #define CERR_connect_failed -1
  45. #define CERR_handshake_failed -2
  46. #define CERR_invalid_id -3
  47. #define CERR_protocol_not_supp -4
  48. #define CERR_not_connected -5
  49. #define CERR_peer_closed -7
  50. #define CERR_malformed_packet -8
  51. #define CERR_send_error -9
  52. #define CERR_out_of_mem -10
  53. #define CERR_not_supported -11
  54. #define CERR_io_error -12
  55. // this one is custom - authentication method required by
  56. // the server is not supported in this client
  57. #define CERR_auth_unsupported -20
  58. #define A_required 0x001
  59. #define A_crypt 0x002
  60. #define A_plain 0x004
  61. //===================================== Rmessage ---- QAP1 storage
  62. class Rexp;
  63. class Rmessage {
  64. public:
  65. struct phdr head;
  66. char *data;
  67. Rsize_t len;
  68. int complete;
  69. int sending;
  70. int receiving;
  71. int bytesReceived;
  72. // the following is avaliable only for parsed messages (max 16 pars)
  73. int pars;
  74. unsigned int *par[16];
  75. Rmessage();
  76. Rmessage(int cmd); // 0 data
  77. Rmessage(int cmd, const char *txt); // DT_STRING data
  78. Rmessage(int cmd, int i); // DT_INT data (1 entry)
  79. Rmessage(int cmd, const void *buf, int len, int raw_data=0); // raw data or DT_BYTESTREAM
  80. virtual ~Rmessage();
  81. int command() { return complete?head.cmd:-1; }
  82. Rsize_t length() { return complete?head.len:-1; }
  83. int is_complete() { return complete; }
  84. bool sendComplete() { return sending == 2; }
  85. bool receiveComplete() { return receiving == 4; }
  86. int read(int s);
  87. void parse();
  88. int send(int s);
  89. Rexp *toRexp();
  90. };
  91. //===================================== Rexp --- basis for all SEXPs
  92. class Rexp {
  93. public:
  94. Rmessage *msg;
  95. unsigned int *pos;
  96. Rsize_t len;
  97. Rexp *attr;
  98. int type;
  99. /* memory manegement for data/len:
  100. - content is in a message and this Rexp is the master of that message:
  101. master=0; msg=<source message>;
  102. - content is in a message, but this Rexp is not the master
  103. master=<master Rexp>; msg=0
  104. - content is all self-allocated with no message associated
  105. master=this; msg=0 */
  106. char *data, *next;
  107. protected:
  108. // the next two are only cached if requested, no direct access allowed
  109. int attribs;
  110. const char **attrnames;
  111. Rexp *master; // if this is set then this Rexp allocated the memory for us, so we are not supposed to free anything; if this is set to "this" then the content is self-allocated, including any data
  112. int rcount; // reference count - only for a master - it counts how many children still exist
  113. public:
  114. Rexp(Rmessage *msg);
  115. Rexp(unsigned int *pos, Rmessage *msg=0);
  116. Rexp(int type, const char *data=0, int len=0, Rexp *attr=0);
  117. virtual ~Rexp();
  118. void set_master(Rexp *m);
  119. char *parse(unsigned int *pos);
  120. virtual Rsize_t storageSize() { return len+((len>0x7fffff)?8:4); }
  121. virtual void store(char *buf);
  122. Rexp *attribute(const char *name);
  123. const char **attributeNames();
  124. virtual Rsize_t length() { return len; }
  125. friend std::ostream& operator<< (std::ostream& os, const Rexp& exp) {
  126. return ((Rexp&)exp).os_print(os);
  127. }
  128. friend std::ostream& operator<< (std::ostream& os, const Rexp* exp) {
  129. return ((Rexp*)exp)->os_print(os);
  130. }
  131. virtual std::ostream& os_print(std::ostream& os) {
  132. return os << "Rexp[type=" << type << ",len=" << len <<"]";
  133. }
  134. };
  135. //===================================== Rint --- XT_INT/XT_ARRAY_INT
  136. class Rinteger : public Rexp {
  137. public:
  138. Rinteger(Rmessage *msg) : Rexp(msg) { fix_content(); }
  139. Rinteger(unsigned int *ipos, Rmessage *imsg) : Rexp(ipos, imsg) { fix_content(); }
  140. Rinteger(int *array, int count) : Rexp(XT_ARRAY_INT, (char*)array, count*sizeof(int)) { fix_content(); }
  141. int *intArray() { return (int*) data; }
  142. int intAt(int pos) { return (pos>=0 && (unsigned)pos<len/4)?((int*)data)[pos]:0; }
  143. virtual Rsize_t length() { return len/4; }
  144. virtual std::ostream& os_print (std::ostream& os) {
  145. return os << "Rinteger[" << (len/4) <<"]";
  146. }
  147. private:
  148. void fix_content();
  149. };
  150. //===================================== Rdouble --- XT_DOUBLE/XT_ARRAY_DOUBLE
  151. class Rdouble : public Rexp {
  152. public:
  153. Rdouble(Rmessage *msg) : Rexp(msg) { fix_content(); }
  154. Rdouble(unsigned int *ipos, Rmessage *imsg) : Rexp(ipos, imsg) { fix_content(); }
  155. Rdouble(double *array, int count) : Rexp(XT_ARRAY_DOUBLE, (char*)array, count*sizeof(double)) { fix_content(); }
  156. double *doubleArray() { return (double*) data; }
  157. double doubleAt(int pos) { return (pos>=0 && (unsigned)pos<len/8)?((double*)data)[pos]:0; }
  158. virtual Rsize_t length() { return len/8; }
  159. virtual std::ostream& os_print (std::ostream& os) {
  160. return os << "Rdouble[" << (len/8) <<"]";
  161. }
  162. private:
  163. void fix_content();
  164. };
  165. //===================================== Rsymbol --- XT_SYM
  166. class Rsymbol : public Rexp {
  167. protected:
  168. const char *name;
  169. public:
  170. Rsymbol(Rmessage *msg) : Rexp(msg)
  171. { name=""; fix_content(); }
  172. Rsymbol(unsigned int *ipos, Rmessage *imsg) : Rexp(ipos, imsg)
  173. { name=""; fix_content(); }
  174. const char *symbolName() { return name; }
  175. virtual std::ostream& os_print (std::ostream& os) {
  176. return os << "Rsymbol[" << symbolName() <<"]";
  177. }
  178. private:
  179. void fix_content();
  180. };
  181. //===================================== Rstrings --- XT_ARRAY_STR
  182. // NOTE: XT_ARRAY_STR is new in 0103 and ths class is just a
  183. // very crude implementation. It replaces Rstring because
  184. // XT_STR has been deprecated.
  185. // FIXME: it should be a subclass of Rvector!
  186. class Rstrings : public Rexp {
  187. char **cont;
  188. unsigned int nel;
  189. public:
  190. Rstrings(Rmessage *msg) : Rexp(msg) { decode(); }
  191. Rstrings(unsigned int *ipos, Rmessage *imsg) : Rexp(ipos, imsg) { decode(); }
  192. /*Rstring(const char *str) : Rexp(XT_STR, str, strlen(str)+1) {}*/
  193. char **strings() { return cont; }
  194. char *stringAt(unsigned int i) { return (i<0||i>=nel)?0:cont[i]; }
  195. char *string() { return stringAt(0); }
  196. unsigned int count() { return nel; }
  197. int indexOfString(const char *str);
  198. virtual std::ostream& os_print (std::ostream& os) {
  199. return os << "char*[" << nel <<"]\"" << string() <<"\"..";
  200. }
  201. private:
  202. void decode() {
  203. char *c = (char*) data;
  204. unsigned int i = 0;
  205. nel = 0;
  206. while (i < len) { if (!c[i]) nel++; i++; }
  207. if (nel) {
  208. i = 0;
  209. cont = (char**) malloc(sizeof(char*)*nel);
  210. while (i < nel) {
  211. cont[i] = strdup(c);
  212. while (*c) c++;
  213. c++; i++;
  214. }
  215. } else
  216. cont = 0;
  217. }
  218. };
  219. //===================================== Rstring --- XT_STR
  220. class Rstring : public Rexp {
  221. public:
  222. Rstring(Rmessage *msg) : Rexp(msg) {}
  223. Rstring(unsigned int *ipos, Rmessage *imsg) : Rexp(ipos, imsg) {}
  224. Rstring(const char *str) : Rexp(XT_STR, str, strlen(str)+1) {}
  225. char *string() { return (char*) data; }
  226. virtual std::ostream& os_print (std::ostream& os) {
  227. return os << "\"" << string() <<"\"";
  228. }
  229. };
  230. //===================================== Rlist --- XT_LIST (CONS lists)
  231. class Rlist : public Rexp {
  232. public:
  233. Rexp *head, *tag;
  234. Rlist *tail;
  235. Rlist(Rmessage *msg) : Rexp(msg)
  236. { head=tag=0; tail=0; fix_content(); }
  237. Rlist(unsigned int *ipos, Rmessage *imsg) : Rexp(ipos, imsg)
  238. { head=tag=0; tail=0; fix_content(); }
  239. /* this is a sort of special constructor that allows to create a Rlist
  240. based solely on its content. This is necessary since 0.5 because
  241. each LISTSXP is no longer represented by its own encoded SEXP
  242. but they are packed in one content list instead */
  243. Rlist(int type, Rexp *head, Rexp *tag, char *next, Rmessage *imsg) : Rexp(type, 0, 0, 0) { this->head = head; this->tag = tag; tail = 0; this->next = next; this->msg = imsg; master = 0; }
  244. virtual ~Rlist();
  245. Rexp *entryByTagName(const char *tagName) {
  246. if (tag && (tag->type==XT_SYM || tag->type==XT_SYMNAME) && !strcmp(((Rsymbol*)tag)->symbolName(),tagName)) return head;
  247. if (tail) return tail->entryByTagName(tagName);
  248. return 0;
  249. }
  250. virtual std::ostream& os_print (std::ostream& os) {
  251. os << "Rlist[tag=";
  252. if (tag) os << *tag; else os << "<none>";
  253. os << ",head=";
  254. if (head) os << *head; else os << "<none>";
  255. if (tail) os << ",tail=" << *tail;
  256. return os << "]";
  257. }
  258. private:
  259. void fix_content();
  260. };
  261. //===================================== Rvecotr --- XT_VECTOR (general lists)
  262. class Rvector : public Rexp {
  263. protected:
  264. Rexp **cont;
  265. int count;
  266. // cached
  267. char **strs;
  268. public:
  269. Rvector(Rmessage *msg) : Rexp(msg)
  270. { cont=0; count=0; strs=0; fix_content(); }
  271. Rvector(unsigned int *ipos, Rmessage *imsg) : Rexp(ipos, imsg)
  272. { cont=0; count=0; strs=0; fix_content(); }
  273. virtual ~Rvector();
  274. char **strings();
  275. int indexOf(Rexp *exp);
  276. int indexOfString(const char *str);
  277. char *stringAt(int i) {
  278. if (i<0 || i>count || !cont[i] || cont[i]->type!=XT_STR) return 0;
  279. return ((Rstring*)cont[i])->string();
  280. }
  281. Rexp* byName(const char *name);
  282. virtual std::ostream& os_print (std::ostream& os) {
  283. os << "Rvector[count=" << count << ":";
  284. int i=0;
  285. while (i<count) {
  286. if (cont[i]) os << *cont[i]; else os << "NULL";
  287. i++;
  288. if (i<count) os << ",";
  289. }
  290. return os << "]";
  291. }
  292. private:
  293. int capacity;
  294. void fix_content();
  295. };
  296. //===================================== Rconnection ---- Rserve interface class
  297. class Rconnection {
  298. protected:
  299. char *host;
  300. int port;
  301. SOCKET s;
  302. int family;
  303. int auth;
  304. char salt[2];
  305. char IDstring[33];
  306. int receivedCharsFromIDstring;
  307. int _connected;
  308. public:
  309. /** host - either host name or unix socket path
  310. port - either TCP port or -1 if unix sockets should be used */
  311. Rconnection(const char *host="127.0.0.1", int port=default_Rsrv_port);
  312. virtual ~Rconnection();
  313. int connect();
  314. int disconnect();
  315. int pollConnection();
  316. int connected() {
  317. return _connected; // nonzero == connected
  318. }
  319. SOCKET getSocket();
  320. /**--- low-level functions (should not be used directly) --- */
  321. int request(Rmessage *msg, int cmd, int len=0, void *par=0);
  322. int request(Rmessage *targetMsg, Rmessage *contents);
  323. /** --- high-level functions --- */
  324. int assign(const char *symbol, Rexp *exp);
  325. int voidEval(const char *cmd);
  326. Rexp *eval(const char *cmd, int *status=0, int opt=0);
  327. int login(const char *user, const char *pwd);
  328. bool needsLogin () {
  329. return this->auth & A_required;
  330. };
  331. char *getSalt () {
  332. return salt;
  333. };
  334. int shutdown(const char *key);
  335. /* ( I/O functions ) */
  336. int openFile(const char *fn);
  337. int createFile(const char *fn);
  338. int readFile(char *buf, unsigned int len);
  339. int writeFile(const char *buf, unsigned int len);
  340. int closeFile();
  341. int removeFile(const char *fn);
  342. #ifdef CMD_ctrl
  343. /* server control functions (need Rserve 0.6-0 or higher) */
  344. int serverEval(const char *cmd);
  345. int serverSource(const char *fn);
  346. int serverShutdown();
  347. #endif
  348. };
  349. #endif