/Demo/pysvr/pysvr.c

http://unladen-swallow.googlecode.com/ · C · 370 lines · 293 code · 63 blank · 14 comment · 59 complexity · 2e3a3fb6e88e83fe4bd3c0790be30c80 MD5 · raw file

  1. /* A multi-threaded telnet-like server that gives a Python prompt.
  2. Usage: pysvr [port]
  3. For security reasons, it only accepts requests from the current host.
  4. This can still be insecure, but restricts violations from people who
  5. can log in on your machine. Use with caution!
  6. */
  7. #include <stdio.h>
  8. #include <stdlib.h>
  9. #include <string.h>
  10. #include <ctype.h>
  11. #include <errno.h>
  12. #include <sys/types.h>
  13. #include <sys/socket.h>
  14. #include <netinet/in.h>
  15. #include <pthread.h>
  16. #include <getopt.h>
  17. /* XXX Umpfh.
  18. Python.h defines a typedef destructor, which conflicts with pthread.h.
  19. So Python.h must be included after pthread.h. */
  20. #include "Python.h"
  21. extern int Py_VerboseFlag;
  22. #ifndef PORT
  23. #define PORT 4000
  24. #endif
  25. struct workorder {
  26. int conn;
  27. struct sockaddr_in addr;
  28. };
  29. /* Forward */
  30. static void init_python(void);
  31. static void usage(void);
  32. static void oprogname(void);
  33. static void main_thread(int);
  34. static void create_thread(int, struct sockaddr_in *);
  35. static void *service_thread(struct workorder *);
  36. static void run_interpreter(FILE *, FILE *);
  37. static int run_command(char *, PyObject *);
  38. static void ps(void);
  39. static char *progname = "pysvr";
  40. static PyThreadState *gtstate;
  41. main(int argc, char **argv)
  42. {
  43. int port = PORT;
  44. int c;
  45. if (argc > 0 && argv[0] != NULL && argv[0][0] != '\0')
  46. progname = argv[0];
  47. while ((c = getopt(argc, argv, "v")) != EOF) {
  48. switch (c) {
  49. case 'v':
  50. Py_VerboseFlag++;
  51. break;
  52. default:
  53. usage();
  54. }
  55. }
  56. if (optind < argc) {
  57. if (optind+1 < argc) {
  58. oprogname();
  59. fprintf(stderr, "too many arguments\n");
  60. usage();
  61. }
  62. port = atoi(argv[optind]);
  63. if (port <= 0) {
  64. fprintf(stderr, "bad port (%s)\n", argv[optind]);
  65. usage();
  66. }
  67. }
  68. main_thread(port);
  69. fprintf(stderr, "Bye.\n");
  70. exit(0);
  71. }
  72. static char usage_line[] = "usage: %s [port]\n";
  73. static void
  74. usage(void)
  75. {
  76. fprintf(stderr, usage_line, progname);
  77. exit(2);
  78. }
  79. static void
  80. main_thread(int port)
  81. {
  82. int sock, conn, size, i;
  83. struct sockaddr_in addr, clientaddr;
  84. sock = socket(PF_INET, SOCK_STREAM, 0);
  85. if (sock < 0) {
  86. oprogname();
  87. perror("can't create socket");
  88. exit(1);
  89. }
  90. #ifdef SO_REUSEADDR
  91. i = 1;
  92. setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, (char *) &i, sizeof i);
  93. #endif
  94. memset((char *)&addr, '\0', sizeof addr);
  95. addr.sin_family = AF_INET;
  96. addr.sin_port = htons(port);
  97. addr.sin_addr.s_addr = 0L;
  98. if (bind(sock, (struct sockaddr *)&addr, sizeof addr) < 0) {
  99. oprogname();
  100. perror("can't bind socket to address");
  101. exit(1);
  102. }
  103. if (listen(sock, 5) < 0) {
  104. oprogname();
  105. perror("can't listen on socket");
  106. exit(1);
  107. }
  108. fprintf(stderr, "Listening on port %d...\n", port);
  109. for (i = 0; ; i++) {
  110. size = sizeof clientaddr;
  111. memset((char *) &clientaddr, '\0', size);
  112. conn = accept(sock, (struct sockaddr *) &clientaddr, &size);
  113. if (conn < 0) {
  114. oprogname();
  115. perror("can't accept connection from socket");
  116. exit(1);
  117. }
  118. size = sizeof addr;
  119. memset((char *) &addr, '\0', size);
  120. if (getsockname(conn, (struct sockaddr *)&addr, &size) < 0) {
  121. oprogname();
  122. perror("can't get socket name of connection");
  123. exit(1);
  124. }
  125. if (clientaddr.sin_addr.s_addr != addr.sin_addr.s_addr) {
  126. oprogname();
  127. perror("connection from non-local host refused");
  128. fprintf(stderr, "(addr=%lx, clientaddr=%lx)\n",
  129. ntohl(addr.sin_addr.s_addr),
  130. ntohl(clientaddr.sin_addr.s_addr));
  131. close(conn);
  132. continue;
  133. }
  134. if (i == 4) {
  135. close(conn);
  136. break;
  137. }
  138. create_thread(conn, &clientaddr);
  139. }
  140. close(sock);
  141. if (gtstate) {
  142. PyEval_AcquireThread(gtstate);
  143. gtstate = NULL;
  144. Py_Finalize();
  145. /* And a second time, just because we can. */
  146. Py_Finalize(); /* This should be harmless. */
  147. }
  148. exit(0);
  149. }
  150. static void
  151. create_thread(int conn, struct sockaddr_in *addr)
  152. {
  153. struct workorder *work;
  154. pthread_t tdata;
  155. work = malloc(sizeof(struct workorder));
  156. if (work == NULL) {
  157. oprogname();
  158. fprintf(stderr, "out of memory for thread.\n");
  159. close(conn);
  160. return;
  161. }
  162. work->conn = conn;
  163. work->addr = *addr;
  164. init_python();
  165. if (pthread_create(&tdata, NULL, (void *)service_thread, work) < 0) {
  166. oprogname();
  167. perror("can't create new thread");
  168. close(conn);
  169. return;
  170. }
  171. if (pthread_detach(tdata) < 0) {
  172. oprogname();
  173. perror("can't detach from thread");
  174. }
  175. }
  176. static PyThreadState *the_tstate;
  177. static PyInterpreterState *the_interp;
  178. static PyObject *the_builtins;
  179. static void
  180. init_python(void)
  181. {
  182. if (gtstate)
  183. return;
  184. Py_Initialize(); /* Initialize the interpreter */
  185. PyEval_InitThreads(); /* Create (and acquire) the interpreter lock */
  186. gtstate = PyEval_SaveThread(); /* Release the thread state */
  187. }
  188. static void *
  189. service_thread(struct workorder *work)
  190. {
  191. FILE *input, *output;
  192. fprintf(stderr, "Start thread for connection %d.\n", work->conn);
  193. ps();
  194. input = fdopen(work->conn, "r");
  195. if (input == NULL) {
  196. oprogname();
  197. perror("can't create input stream");
  198. goto done;
  199. }
  200. output = fdopen(work->conn, "w");
  201. if (output == NULL) {
  202. oprogname();
  203. perror("can't create output stream");
  204. fclose(input);
  205. goto done;
  206. }
  207. setvbuf(input, NULL, _IONBF, 0);
  208. setvbuf(output, NULL, _IONBF, 0);
  209. run_interpreter(input, output);
  210. fclose(input);
  211. fclose(output);
  212. done:
  213. fprintf(stderr, "End thread for connection %d.\n", work->conn);
  214. close(work->conn);
  215. free(work);
  216. }
  217. static void
  218. oprogname(void)
  219. {
  220. int save = errno;
  221. fprintf(stderr, "%s: ", progname);
  222. errno = save;
  223. }
  224. static void
  225. run_interpreter(FILE *input, FILE *output)
  226. {
  227. PyThreadState *tstate;
  228. PyObject *new_stdin, *new_stdout;
  229. PyObject *mainmod, *globals;
  230. char buffer[1000];
  231. char *p, *q;
  232. int n, end;
  233. PyEval_AcquireLock();
  234. tstate = Py_NewInterpreter();
  235. if (tstate == NULL) {
  236. fprintf(output, "Sorry -- can't create an interpreter\n");
  237. return;
  238. }
  239. mainmod = PyImport_AddModule("__main__");
  240. globals = PyModule_GetDict(mainmod);
  241. Py_INCREF(globals);
  242. new_stdin = PyFile_FromFile(input, "<socket-in>", "r", NULL);
  243. new_stdout = PyFile_FromFile(output, "<socket-out>", "w", NULL);
  244. PySys_SetObject("stdin", new_stdin);
  245. PySys_SetObject("stdout", new_stdout);
  246. PySys_SetObject("stderr", new_stdout);
  247. for (n = 1; !PyErr_Occurred(); n++) {
  248. Py_BEGIN_ALLOW_THREADS
  249. fprintf(output, "%d> ", n);
  250. p = fgets(buffer, sizeof buffer, input);
  251. Py_END_ALLOW_THREADS
  252. if (p == NULL)
  253. break;
  254. if (p[0] == '\377' && p[1] == '\354')
  255. break;
  256. q = strrchr(p, '\r');
  257. if (q && q[1] == '\n' && q[2] == '\0') {
  258. *q++ = '\n';
  259. *q++ = '\0';
  260. }
  261. while (*p && isspace(*p))
  262. p++;
  263. if (p[0] == '#' || p[0] == '\0')
  264. continue;
  265. end = run_command(buffer, globals);
  266. if (end < 0)
  267. PyErr_Print();
  268. if (end)
  269. break;
  270. }
  271. Py_XDECREF(globals);
  272. Py_XDECREF(new_stdin);
  273. Py_XDECREF(new_stdout);
  274. Py_EndInterpreter(tstate);
  275. PyEval_ReleaseLock();
  276. fprintf(output, "Goodbye!\n");
  277. }
  278. static int
  279. run_command(char *buffer, PyObject *globals)
  280. {
  281. PyObject *m, *d, *v;
  282. fprintf(stderr, "run_command: %s", buffer);
  283. if (strchr(buffer, '\n') == NULL)
  284. fprintf(stderr, "\n");
  285. v = PyRun_String(buffer, Py_single_input, globals, globals);
  286. if (v == NULL) {
  287. if (PyErr_Occurred() == PyExc_SystemExit) {
  288. PyErr_Clear();
  289. return 1;
  290. }
  291. PyErr_Print();
  292. return 0;
  293. }
  294. Py_DECREF(v);
  295. return 0;
  296. }
  297. static void
  298. ps(void)
  299. {
  300. char buffer[100];
  301. PyOS_snprintf(buffer, sizeof(buffer),
  302. "ps -l -p %d </dev/null | sed 1d\n", getpid());
  303. system(buffer);
  304. }