|
| 1 | +/* A multi-threaded telnet-like server that gives a Python prompt. |
| 2 | +
|
| 3 | +Usage: pysvr [port] |
| 4 | +
|
| 5 | +For security reasons, it only accepts requests from the current host. |
| 6 | +This can still be insecure, but restricts violations from people who |
| 7 | +can log in on your machine. Use with caution! |
| 8 | +
|
| 9 | +*/ |
| 10 | + |
1 | 11 | #include <stdio.h> |
2 | 12 | #include <stdlib.h> |
3 | 13 | #include <string.h> |
@@ -88,8 +98,8 @@ usage() |
88 | 98 | static void |
89 | 99 | main_thread(int port) |
90 | 100 | { |
91 | | - int sock; |
92 | | - struct sockaddr_in addr; |
| 101 | + int sock, conn, size; |
| 102 | + struct sockaddr_in addr, clientaddr; |
93 | 103 |
|
94 | 104 | sock = socket(PF_INET, SOCK_STREAM, 0); |
95 | 105 | if (sock < 0) { |
@@ -117,16 +127,29 @@ main_thread(int port) |
117 | 127 | fprintf(stderr, "Listening on port %d...\n", port); |
118 | 128 |
|
119 | 129 | for (;;) { |
120 | | - struct sockaddr_in clientaddr; |
121 | | - int conn, size; |
122 | | - |
| 130 | + size = sizeof clientaddr; |
123 | 131 | conn = accept(sock, (struct sockaddr *) &clientaddr, &size); |
124 | 132 | if (conn < 0) { |
125 | 133 | oprogname(); |
126 | 134 | perror("can't accept connection from socket"); |
127 | 135 | exit(1); |
128 | 136 | } |
129 | 137 |
|
| 138 | + size = sizeof addr; |
| 139 | + if (getsockname(conn, (struct sockaddr *)&addr, &size) < 0) { |
| 140 | + oprogname(); |
| 141 | + perror("can't get socket name of connection"); |
| 142 | + exit(1); |
| 143 | + } |
| 144 | + if (clientaddr.sin_addr.s_addr != addr.sin_addr.s_addr) { |
| 145 | + oprogname(); |
| 146 | + perror("connection from non-local host refused"); |
| 147 | + fprintf(stderr, "(addr=%lx, clientaddr=%lx)\n", |
| 148 | + ntohl(addr.sin_addr.s_addr), |
| 149 | + ntohl(clientaddr.sin_addr.s_addr)); |
| 150 | + close(conn); |
| 151 | + continue; |
| 152 | + } |
130 | 153 | create_thread(conn, &clientaddr); |
131 | 154 | } |
132 | 155 | } |
|
0 commit comments