-
Notifications
You must be signed in to change notification settings - Fork 36
/
nscp.c
584 lines (518 loc) · 14.3 KB
/
nscp.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
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
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
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
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
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
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
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
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
/*
* The contents of this file are subject to the AOLserver Public License
* Version 1.1 (the "License"); you may not use this file except in
* compliance with the License. You may obtain a copy of the License at
* http:https://aolserver.com/.
*
* Software distributed under the License is distributed on an "AS IS"
* basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See
* the License for the specific language governing rights and limitations
* under the License.
*
* The Original Code is AOLserver Code and related documentation
* distributed by AOL.
*
* The Initial Developer of the Original Code is America Online,
* Inc. Portions created by AOL are Copyright (C) 1999 America Online,
* Inc. All Rights Reserved.
*
* Alternatively, the contents of this file may be used under the terms
* of the GNU General Public License (the "GPL"), in which case the
* provisions of GPL are applicable instead of those above. If you wish
* to allow use of your version of this file only under the terms of the
* GPL and not to allow others to use your version of this file under the
* License, indicate your decision by deleting the provisions above and
* replace them with the notice and other provisions required by the GPL.
* If you do not delete the provisions above, a recipient may use your
* version of this file under either the License or the GPL.
*/
/*
* nscp.c --
*
* Simple control port module for AOLserver which allows
* one to telnet to a specified port, login, and issue
* Tcl commands.
*/
static const char *RCSID = "@(#) $Header: /Users/dossy/Desktop/cvs/aolserver/nscp/nscp.c,v 1.25 2008/06/20 08:06:32 gneumann Exp $, compiled: " __DATE__ " " __TIME__;
#include "ns.h"
/*
* The following structure is allocated each instance of
* the loaded module.
*/
typedef struct Mod {
Tcl_HashTable users;
char *server;
char *addr;
int port;
int echo;
int commandLogging;
} Mod;
static Ns_ThreadProc EvalThread;
/*
* The following structure is allocated for each session.
*/
typedef struct Sess {
Mod *modPtr;
char *user;
int id;
SOCKET sock;
struct sockaddr_in sa;
} Sess;
static Ns_SockProc AcceptProc;
static Tcl_CmdProc ExitCmd;
static int Login(Sess *sessPtr, Tcl_DString *unameDS);
static int GetLine(SOCKET sock, char *prompt, Tcl_DString *dsPtr, int echo);
static Ns_ArgProc ArgProc;
/*
* The following values are sent to the telnet client to enable
* and disable password prompt echo.
*/
#define TN_IAC 255
#define TN_WILL 251
#define TN_WONT 252
#define TN_DO 253
#define TN_DONT 254
#define TN_EOF 236
#define TN_IP 244
#define TN_ECHO 1
static unsigned char do_echo[] = {TN_IAC, TN_DO, TN_ECHO};
static unsigned char dont_echo[] = {TN_IAC, TN_DONT, TN_ECHO};
static unsigned char will_echo[] = {TN_IAC, TN_WILL, TN_ECHO};
static unsigned char wont_echo[] = {TN_IAC, TN_WONT, TN_ECHO};
/*
*----------------------------------------------------------------------
*
* NsCp_ModInit --
*
* Load the config parameters, setup the structures, and
* listen on the control port.
*
* Results:
* None.
*
* Side effects:
* Server will listen for control connections on specified
* address and port.
*
*----------------------------------------------------------------------
*/
int
NsCp_ModInit(char *server, char *module)
{
Mod *modPtr;
char *path, *addr, *pass, *user, *key, *end;
int i, new, port;
SOCKET lsock;
Ns_Set *set;
Tcl_HashEntry *hPtr;
/*
* Create the listening socket and callback.
*/
path = Ns_ConfigGetPath(server, module, NULL);
if (((addr = Ns_ConfigGetValue(path, "address")) == NULL)
|| (!Ns_ConfigGetInt(path, "port", &port)) ) {
Ns_Log(Error, "nscp: address and port must be specified in config");
return NS_ERROR;
}
lsock = Ns_SockListen(addr, port);
if (lsock == INVALID_SOCKET) {
Ns_Log(Error, "nscp: could not listen on %s:%d", addr, port);
return NS_ERROR;
}
Ns_Log(Notice, "nscp: listening on %s:%d", addr, port);
/*
* Create a new Mod structure for this instance.
*/
modPtr = ns_malloc(sizeof(Mod));
modPtr->server = server;
modPtr->addr = addr;
modPtr->port = port;
if (!Ns_ConfigGetBool(path, "echopassword", &modPtr->echo)) {
modPtr->echo = 1;
}
if (!Ns_ConfigGetBool(path, "cpcmdlogging", &modPtr->commandLogging)) {
modPtr->commandLogging = 0; /* Default to off */
}
/*
* Initialize the hash table of authorized users. Entry values
* are either NULL indicating authorization should be checked
* via the Ns_AuthorizeUser() API or contain a Unix crypt(3)
* sytle encrypted password. For the later, the entry is
* compatible with /etc/passwd (i.e., username followed by
* password separated by colons).
*/
Tcl_InitHashTable(&modPtr->users, TCL_STRING_KEYS);
path = Ns_ConfigGetPath(server, module, "users", NULL);
set = Ns_ConfigGetSection(path);
for (i = 0; set != NULL && i < Ns_SetSize(set); ++i) {
key = Ns_SetKey(set, i);
user = Ns_SetValue(set, i);
if (!STRIEQ(key, "user") || (pass = strchr(user, ':')) == NULL) {
continue;
}
*pass = '\0';
hPtr = Tcl_CreateHashEntry(&modPtr->users, user, &new);
if (new) {
Ns_Log(Notice, "nscp: added user: %s", user);
} else {
Ns_Log(Warning, "nscp: duplicate user: %s", user);
ns_free(Tcl_GetHashValue(hPtr));
}
*pass++ = ':';
end = strchr(pass, ':');
if (end != NULL) {
*end = '\0';
}
pass = ns_strdup(pass);
if (end != NULL) {
*end = ':';
}
Tcl_SetHashValue(hPtr, pass);
}
if (modPtr->users.numEntries == 0) {
Ns_Log(Warning, "nscp: no authorized users");
}
Ns_SockCallback(lsock, AcceptProc, modPtr, NS_SOCK_READ|NS_SOCK_EXIT);
Ns_RegisterProcInfo((void *)AcceptProc, "nscp", ArgProc);
return NS_OK;
}
/*
*----------------------------------------------------------------------
*
* ArgProc --
*
* Append listen port info for query callback.
*
* Results:
* None
*
* Side effects:
* None.
*
*----------------------------------------------------------------------
*/
static void
ArgProc(Tcl_DString *dsPtr, void *arg)
{
Mod *modPtr = arg;
char buf[20];
sprintf(buf, "%d", modPtr->port);
Tcl_DStringStartSublist(dsPtr);
Tcl_DStringAppendElement(dsPtr, modPtr->addr);
Tcl_DStringAppendElement(dsPtr, buf);
Tcl_DStringEndSublist(dsPtr);
}
/*
*----------------------------------------------------------------------
*
* AcceptProc --
*
* Socket callback to accept a new connection.
*
* Results:
* NS_TRUE to keep listening unless shutdown is in progress.
*
* Side effects:
* New EvalThread will be created.
*
*----------------------------------------------------------------------
*/
static int
AcceptProc(SOCKET lsock, void *arg, int why)
{
Mod *modPtr = arg;
Sess *sessPtr;
int len;
static int next;
if (why == NS_SOCK_EXIT) {
Ns_Log(Notice, "nscp: shutdown");
ns_sockclose(lsock);
return NS_FALSE;
}
sessPtr = ns_malloc(sizeof(Sess));
sessPtr->modPtr = modPtr;
len = sizeof(struct sockaddr_in);
sessPtr->sock = Ns_SockAccept(lsock, (struct sockaddr *) &sessPtr->sa, &len);
if (sessPtr->sock == INVALID_SOCKET) {
Ns_Log(Error, "nscp: accept() failed: %s",
ns_sockstrerror(ns_sockerrno));
ns_free(sessPtr);
} else {
sessPtr->id = ++next;
Ns_ThreadCreate(EvalThread, sessPtr, 0, NULL);
}
return NS_TRUE;
}
/*
*----------------------------------------------------------------------
*
* EvalThread --
*
* Thread to read and evaluate commands from remote.
*
* Results:
* None.
*
* Side effects:
* Depends on commands.
*
*----------------------------------------------------------------------
*/
static void
EvalThread(void *arg)
{
Tcl_Interp *interp;
Tcl_DString ds;
Tcl_DString unameDS;
char buf[64], *res;
int n, len, ncmd, stop;
Sess *sessPtr = arg;
char *server = sessPtr->modPtr->server;
/*
* Initialize the thread and login the user.
*/
interp = NULL;
Tcl_DStringInit(&ds);
Tcl_DStringInit(&unameDS);
sprintf(buf, "-nscp:%d-", sessPtr->id);
Ns_ThreadSetName(buf);
Ns_Log(Notice, "nscp: %s connected", ns_inet_ntoa(sessPtr->sa.sin_addr));
if (!Login(sessPtr, &unameDS)) {
goto done;
}
sessPtr->user = Tcl_DStringValue(&unameDS);
/*
* Loop until the remote shuts down, evaluating complete
* commands.
*/
interp = Ns_TclAllocateInterp(server);
/*
* Create a special exit command for this interp only.
*/
stop = 0;
Tcl_CreateCommand(interp, "exit", ExitCmd, (ClientData) &stop, NULL);
ncmd = 0;
while (!stop) {
Tcl_DStringTrunc(&ds, 0);
++ncmd;
retry:
sprintf(buf, "%s:nscp %d> ", server, ncmd);
while (1) {
if (!GetLine(sessPtr->sock, buf, &ds, 1)) {
goto done;
}
if (Tcl_CommandComplete(ds.string)) {
break;
}
sprintf(buf, "%s:nscp %d>>> ", server, ncmd);
}
while (ds.length > 0 && ds.string[ds.length-1] == '\n') {
Tcl_DStringTrunc(&ds, ds.length-1);
}
if (STREQ(ds.string, "")) {
goto retry; /* Empty command - try again. */
}
if (sessPtr->modPtr->commandLogging) {
Ns_Log(Notice, "nscp: %s %d: %s", sessPtr->user, ncmd, ds.string);
}
if (Tcl_RecordAndEval(interp, ds.string, 0) != TCL_OK) {
Ns_TclLogError(interp);
}
Tcl_AppendResult(interp, "\r\n", NULL);
res = Tcl_GetStringResult(interp);
len = strlen(res);
while (len > 0) {
if ((n = send(sessPtr->sock, res, len, 0)) <= 0) goto done;
len -= n;
res += n;
}
if (sessPtr->modPtr->commandLogging) {
Ns_Log(Notice, "nscp: %s %d: done", sessPtr->user, ncmd);
}
}
done:
Tcl_DStringFree(&ds);
Tcl_DStringFree(&unameDS);
if (interp != NULL) {
Ns_TclDeAllocateInterp(interp);
}
Ns_Log(Notice, "nscp: %s disconnected", ns_inet_ntoa(sessPtr->sa.sin_addr));
ns_sockclose(sessPtr->sock);
ns_free(sessPtr);
}
/*
*----------------------------------------------------------------------
*
* GetLine --
*
* Prompt for a line of input from the remote. \r\n sequences
* are translated to \n.
*
* Results:
* 1 if line received, 0 if remote dropped.
*
* Side effects:
* None.
*
*----------------------------------------------------------------------
*/
static int
GetLine(SOCKET sock, char *prompt, Tcl_DString *dsPtr, int echo)
{
unsigned char buf[2048];
int n;
int result = 0;
int retry = 0;
/*
* Suppress output on things like password prompts.
*/
if (!echo) {
send(sock, will_echo, 3, 0);
send(sock, dont_echo, 3, 0);
recv(sock, buf, sizeof(buf), 0); /* flush client ack thingies */
}
n = strlen(prompt);
if (send(sock, prompt, n, 0) != n) {
result = 0;
goto bail;
}
do {
if ((n = recv(sock, buf, sizeof(buf), 0)) <= 0) {
result = 0;
goto bail;
}
if (n > 1 && buf[n-1] == '\n' && buf[n-2] == '\r') {
buf[n-2] = '\n';
--n;
}
/*
* This EOT checker cannot happen in the context of telnet.
*/
if (n == 1 && buf[0] == 4) {
result = 0;
goto bail;
}
/*
* Deal with telnet IAC commands in some sane way.
*/
if (n > 1 && buf[0] == TN_IAC) {
if ( buf[1] == TN_EOF) {
result = 0;
goto bail;
} else if (buf[1] == TN_IP) {
result = 0;
goto bail;
} else if ((buf[1] == TN_WONT) && (retry < 2)) {
/*
* It seems like the flush at the bottom of this func
* does not always get all the acks, thus an echo ack
* showing up here. Not clear why this would be. Need
* to investigate further. For now, breeze past these
* (within limits).
*/
retry++;
continue;
} else {
Ns_Log(Warning, "nscp: "
"unsupported telnet IAC code received from client");
result = 0;
goto bail;
}
}
Tcl_DStringAppend(dsPtr, buf, n);
result = 1;
} while (buf[n-1] != '\n');
bail:
if (!echo) {
send(sock, wont_echo, 3, 0);
send(sock, do_echo, 3, 0);
recv(sock, buf, sizeof(buf), 0); /* flush client ack thingies */
}
return result;
}
/*
*----------------------------------------------------------------------
*
* Login --
*
* Attempt to login the user.
*
* Results:
* 1 if login ok, 0 otherwise.
*
* Side effects:
* Stores user's login name into unameDSPtr.
*
*----------------------------------------------------------------------
*/
static int
Login(Sess *sessPtr, Tcl_DString *unameDSPtr)
{
Tcl_HashEntry *hPtr;
Tcl_DString uds, pds;
char *encpass, *user, *pass, msg[255], buf[30];
int ok;
user = NULL;
ok = 0;
Tcl_DStringInit(&uds);
Tcl_DStringInit(&pds);
if (GetLine(sessPtr->sock, "login: ", &uds, 1) &&
GetLine(sessPtr->sock, "Password: ", &pds, sessPtr->modPtr->echo)) {
user = Ns_StrTrim(uds.string);
pass = Ns_StrTrim(pds.string);
hPtr = Tcl_FindHashEntry(&sessPtr->modPtr->users, user);
if (hPtr != NULL) {
encpass = Tcl_GetHashValue(hPtr);
Ns_Encrypt(pass, encpass, buf);
if (STREQ(buf, encpass)) {
ok = 1;
}
}
}
if (ok) {
Ns_Log(Notice, "nscp: %s logged in", user);
Tcl_DStringAppend(unameDSPtr, user, -1);
sprintf(msg, "\nWelcome to %s running at %s (pid %d)\n"
"%s/%s (%s) for %s built on %s\nCVS Tag: %s\n",
sessPtr->modPtr->server,
Ns_InfoNameOfExecutable(), Ns_InfoPid(),
Ns_InfoServerName(), Ns_InfoServerVersion(), Ns_InfoLabel(),
Ns_InfoPlatform(), Ns_InfoBuildDate(), Ns_InfoTag());
} else {
Ns_Log(Warning, "nscp: login failed: '%s'", user ? user : "?");
sprintf(msg, "Access denied!\n");
}
(void) send(sessPtr->sock, msg, (int)strlen(msg), 0);
Tcl_DStringFree(&uds);
Tcl_DStringFree(&pds);
return ok;
}
/*
*----------------------------------------------------------------------
*
* ExitCmd --
*
* Special exit command for nscp.
*
* Results:
* Standard Tcl result.
*
* Side effects:
* None.
*
*----------------------------------------------------------------------
*/
static int
ExitCmd(ClientData arg, Tcl_Interp *interp, int argc, CONST char **argv)
{
int *stopPtr;
if (argc != 1) {
Tcl_AppendResult(interp, "wrong # args: should be \"",
(char*)argv[0], "\"", NULL);
return TCL_ERROR;
}
stopPtr = (int *) arg;
*stopPtr = 1;
Tcl_SetResult(interp, "\nGoodbye!", TCL_STATIC);
return TCL_OK;
}