pysvr.c 7.13 KB
Newer Older
1 2 3 4 5 6 7 8 9 10
/* A multi-threaded telnet-like server that gives a Python prompt.

Usage: pysvr [port]

For security reasons, it only accepts requests from the current host.
This can still be insecure, but restricts violations from people who
can log in on your machine.  Use with caution!

*/

11 12 13 14 15 16 17 18 19 20 21
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <errno.h>

#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>

#include <pthread.h>
22
#include <getopt.h>
23 24 25 26 27 28 29

/* XXX Umpfh.
   Python.h defines a typedef destructor, which conflicts with pthread.h.
   So Python.h must be included after pthread.h. */

#include <Python.h>

30 31
extern int Py_VerboseFlag;

32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49
#ifndef PORT
#define PORT 4000
#endif

struct workorder {
	int conn;
	struct sockaddr_in addr;
};

/* Forward */
static void init_python(void);
static void usage(void);
static void oprogname(void);
static void main_thread(int);
static void create_thread(int, struct sockaddr_in *);
static void *service_thread(struct workorder *);
static void run_interpreter(FILE *, FILE *);
static int run_command(char *, PyObject *);
50
static void ps(void);
51 52 53

static char *progname = "pysvr";

54 55
static PyThreadState *gtstate;

56 57 58 59 60 61 62 63
main(int argc, char **argv)
{
	int port = PORT;
	int c;

	if (argc > 0 && argv[0] != NULL && argv[0][0] != '\0')
		progname = argv[0];

64
	while ((c = getopt(argc, argv, "v")) != EOF) {
65
		switch (c) {
66 67 68
		case 'v':
			Py_VerboseFlag++;
			break;
69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96
		default:
			usage();
		}
	}

	if (optind < argc) {
		if (optind+1 < argc) {
			oprogname();
			fprintf(stderr, "too many arguments\n");
			usage();
		}
		port = atoi(argv[optind]);
		if (port <= 0) {
			fprintf(stderr, "bad port (%s)\n", argv[optind]);
			usage();
		}
	}

	main_thread(port);

	fprintf(stderr, "Bye.\n");

	exit(0);
}

static char usage_line[] = "usage: %s [port]\n";

static void
97
usage(void)
98 99 100 101 102 103 104 105
{
	fprintf(stderr, usage_line, progname);
	exit(2);
}

static void
main_thread(int port)
{
106
	int sock, conn, size, i;
107
	struct sockaddr_in addr, clientaddr;
108 109 110 111 112 113 114 115

	sock = socket(PF_INET, SOCK_STREAM, 0);
	if (sock < 0) {
		oprogname();
		perror("can't create socket");
		exit(1);
	}

116 117 118 119 120
#ifdef SO_REUSEADDR
	i = 1;
	setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, (char *) &i, sizeof i);
#endif

121
	memset((char *)&addr, '\0', sizeof addr);
122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138
	addr.sin_family = AF_INET;
	addr.sin_port = htons(port);
	addr.sin_addr.s_addr = 0L;
	if (bind(sock, (struct sockaddr *)&addr, sizeof addr) < 0) {
		oprogname();
		perror("can't bind socket to address");
		exit(1);
	}

	if (listen(sock, 5) < 0) {
		oprogname();
		perror("can't listen on socket");
		exit(1);
	}

	fprintf(stderr, "Listening on port %d...\n", port);

139
	for (i = 0; ; i++) {
140
		size = sizeof clientaddr;
141
		memset((char *) &clientaddr, '\0', size);
142 143 144 145 146 147 148
		conn = accept(sock, (struct sockaddr *) &clientaddr, &size);
		if (conn < 0) {
			oprogname();
			perror("can't accept connection from socket");
			exit(1);
		}

149
		size = sizeof addr;
150
		memset((char *) &addr, '\0', size);
151 152 153 154 155 156 157 158 159 160 161 162 163 164
		if (getsockname(conn, (struct sockaddr *)&addr, &size) < 0) {
			oprogname();
			perror("can't get socket name of connection");
			exit(1);
		}
		if (clientaddr.sin_addr.s_addr != addr.sin_addr.s_addr) {
			oprogname();
			perror("connection from non-local host refused");
			fprintf(stderr, "(addr=%lx, clientaddr=%lx)\n",
				ntohl(addr.sin_addr.s_addr),
				ntohl(clientaddr.sin_addr.s_addr));
			close(conn);
			continue;
		}
165 166 167 168
		if (i == 4) {
			close(conn);
			break;
		}
169 170
		create_thread(conn, &clientaddr);
	}
171 172 173 174 175 176 177

	close(sock);

	if (gtstate) {
		PyEval_AcquireThread(gtstate);
		gtstate = NULL;
		Py_Finalize();
178 179
		/* And a second time, just because we can. */
		Py_Finalize(); /* This should be harmless. */
180 181
	}
	exit(0);
182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219
}

static void
create_thread(int conn, struct sockaddr_in *addr)
{
	struct workorder *work;
	pthread_t tdata;

	work = malloc(sizeof(struct workorder));
	if (work == NULL) {
		oprogname();
		fprintf(stderr, "out of memory for thread.\n");
		close(conn);
		return;
	}
	work->conn = conn;
	work->addr = *addr;

	init_python();

	if (pthread_create(&tdata, NULL, (void *)service_thread, work) < 0) {
		oprogname();
		perror("can't create new thread");
		close(conn);
		return;
	}

	if (pthread_detach(tdata) < 0) {
		oprogname();
		perror("can't detach from thread");
	}
}

static PyThreadState *the_tstate;
static PyInterpreterState *the_interp;
static PyObject *the_builtins;

static void
220
init_python(void)
221
{
222 223 224 225 226
	if (gtstate)
		return;
	Py_Initialize(); /* Initialize the interpreter */
	PyEval_InitThreads(); /* Create (and acquire) the interpreter lock */
	gtstate = PyEval_SaveThread(); /* Release the thread state */
227 228 229 230 231 232 233 234 235
}

static void *
service_thread(struct workorder *work)
{
	FILE *input, *output;

	fprintf(stderr, "Start thread for connection %d.\n", work->conn);

236 237
	ps();

238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267
	input = fdopen(work->conn, "r");
	if (input == NULL) {
		oprogname();
		perror("can't create input stream");
		goto done;
	}

	output = fdopen(work->conn, "w");
	if (output == NULL) {
		oprogname();
		perror("can't create output stream");
		fclose(input);
		goto done;
	}

	setvbuf(input, NULL, _IONBF, 0);
	setvbuf(output, NULL, _IONBF, 0);

	run_interpreter(input, output);

	fclose(input);
	fclose(output);

  done:
	fprintf(stderr, "End thread for connection %d.\n", work->conn);
	close(work->conn);
	free(work);
}

static void
268
oprogname(void)
269 270 271 272 273 274 275 276 277 278 279
{
	int save = errno;
	fprintf(stderr, "%s: ", progname);
	errno = save;
}

static void
run_interpreter(FILE *input, FILE *output)
{
	PyThreadState *tstate;
	PyObject *new_stdin, *new_stdout;
280
	PyObject *mainmod, *globals;
281 282 283 284
	char buffer[1000];
	char *p, *q;
	int n, end;

285 286 287 288 289 290
	PyEval_AcquireLock();
	tstate = Py_NewInterpreter();
	if (tstate == NULL) {
		fprintf(output, "Sorry -- can't create an interpreter\n");
		return;
	}
291

292 293 294
	mainmod = PyImport_AddModule("__main__");
	globals = PyModule_GetDict(mainmod);
	Py_INCREF(globals);
295 296 297 298

	new_stdin = PyFile_FromFile(input, "<socket-in>", "r", NULL);
	new_stdout = PyFile_FromFile(output, "<socket-out>", "w", NULL);

299 300 301 302
	PySys_SetObject("stdin", new_stdin);
	PySys_SetObject("stdout", new_stdout);
	PySys_SetObject("stderr", new_stdout);

303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336
	for (n = 1; !PyErr_Occurred(); n++) {
		Py_BEGIN_ALLOW_THREADS
		fprintf(output, "%d> ", n);
		p = fgets(buffer, sizeof buffer, input);
		Py_END_ALLOW_THREADS

		if (p == NULL)
			break;
		if (p[0] == '\377' && p[1] == '\354')
			break;

		q = strrchr(p, '\r');
		if (q && q[1] == '\n' && q[2] == '\0') {
			*q++ = '\n';
			*q++ = '\0';
		}

		while (*p && isspace(*p))
			p++;
		if (p[0] == '#' || p[0] == '\0')
			continue;

		end = run_command(buffer, globals);
		if (end < 0)
			PyErr_Print();

		if (end)
			break;
	}

	Py_XDECREF(globals);
	Py_XDECREF(new_stdin);
	Py_XDECREF(new_stdout);

337 338
	Py_EndInterpreter(tstate);
	PyEval_ReleaseLock();
339 340 341 342 343 344 345 346

	fprintf(output, "Goodbye!\n");
}

static int
run_command(char *buffer, PyObject *globals)
{
	PyObject *m, *d, *v;
347 348 349
	fprintf(stderr, "run_command: %s", buffer);
	if (strchr(buffer, '\n') == NULL)
		fprintf(stderr, "\n");
350 351 352 353 354 355 356 357 358 359 360 361
	v = PyRun_String(buffer, Py_single_input, globals, globals);
	if (v == NULL) {
		if (PyErr_Occurred() == PyExc_SystemExit) {
			PyErr_Clear();
			return 1;
		}
		PyErr_Print();
		return 0;
	}
	Py_DECREF(v);
	return 0;
}
362 363

static void
364
ps(void)
365 366 367 368 369
{
	char buffer[100];
	sprintf(buffer, "ps -l -p %d </dev/null | tail +2l\n", getpid());
	system(buffer);
}