File: main.c

package info (click to toggle)
aolserver4 4.5.1-15.1
  • links: PTS, VCS
  • area: main
  • in suites: wheezy
  • size: 11,772 kB
  • sloc: ansic: 45,120; tcl: 5,532; sh: 1,021; makefile: 380; pascal: 219; php: 13
file content (1355 lines) | stat: -rw-r--r-- 30,382 bytes parent folder | download | duplicates (7)
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
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
/*
 * 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://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.
 */


/*
 * main.c --
 *
 *	The proxy-side library for external drivers. 
 */

static const char *RCSID = "@(#) $Header: /cvsroot/aolserver/aolserver/nspd/main.c,v 1.8 2003/03/07 18:08:49 vasiljevic Exp $, compiled: " __DATE__ " " __TIME__;

#include "pd.h"
#include "nspd.h"
#include <ctype.h>

#define CMDMAX 32768
#ifndef F_CLOEXEC
#define F_CLOEXEC 1
#endif
#define FILE_TEMPLATE "pdXXXXXX"
#define MAX_PATH      256
#define DIR_MAX       (MAX_PATH - 8)
#define UNIX_TMPDIR   "/var/tmp/"
#define MAXSTACK      1024

/*
 * Local functions defined in this file
 */

static int      RecvData(char *buf, int len);
static int      GetMsg(char *buf, char **cmdName, char **cmdArg);
static void     DispatchCmd(char *cmdName, char *cmdArg, void *dbhandle);
static void     PdPing(void);
static void     PdOpenFile(char *openParams);
static void     PdCloseFile(char *fdStr);
static void     PdReadFile(char *readParams);
static void     PdWriteFile(char *writeParams);
static void     PdDeleteFile(char *fileName);
static void     PdCreateTmpFile(void);
static char    *StringTrimRight(char *string);
static char    *StringTrimLeft(char *string);
static void     PdFindBin(char *pgm);
static int      PdPort(char *arg);
static void     PdCreateTmpFile(void);

/*
 * Static variables defined in this file
 */

static int      readInput = 1;
char           *pdBin;

/*
 *==========================================================================
 * API functions
 *==========================================================================
 */


/*
 *----------------------------------------------------------------------
 *
 * Ns_PdMain --
 *
 *	This runs the main loop for the proxy daemon. 
 *
 * Results:
 *	0. 
 *
 * Side effects:
 *	Will listen on the port and run callbacks; also forks and exits.
 *
 *----------------------------------------------------------------------
 */

int
Ns_PdMain(int argc, char **argv)
{
    int port;

    if (getppid() != 1) {
        if (fork() > 0) {
            exit(0);
        }
        setsid();
    }

    if (argc > 0) {
	PdFindBin(argv[0]);
    } else {
	PdFindBin("nsextd");
    }
    OpenLog();

    if (argc > 1) {
        port = PdPort(argv[1]);
        PdListen(port);
    } else {
        PdMainLoop();
    }
    CloseLog();
    return 0;
}


/*
 *----------------------------------------------------------------------
 *
 * Ns_PdExit --
 *
 *	Terminate with an exit code. 
 *
 * Results:
 *	None. 
 *
 * Side effects:
 *	None. 
 *
 *----------------------------------------------------------------------
 */

void
Ns_PdExit(int code)
{
    if (code == 0) {
        exit(0);
    }
    _exit(code);
}


/*
 *----------------------------------------------------------------------
 *
 * Ns_PdSendData --
 *
 *	Write data to the external driver. 
 *
 * Results:
 *	None. 
 *
 * Side effects:
 *	None. 
 *
 *----------------------------------------------------------------------
 */

void
Ns_PdSendData(char *data, int len)
{
    int writeReturn;

    do {
        writeReturn = write(1, data, (size_t)len);
    } while ((writeReturn < 0) && (errno == EINTR));
    if (writeReturn != len) {
        Ns_PdLog(Error, "nspd: "
		 "error '%s' writing %d bytes", strerror(errno), len);
    }
}


/*
 *----------------------------------------------------------------------
 *
 * Ns_PdSendException --
 *
 *	Send an error message back to the external driver. 
 *
 * Results:
 *	None. 
 *
 * Side effects:
 *	None. 
 *
 *----------------------------------------------------------------------
 */

void
Ns_PdSendException(char *code, char *msg)
{
    char  exceptionBuf[EXCEPTION_CODE_MAX + EXCEPTION_MSG_MAX + 2];
    char *p = msg;

    /*
     * map all \n's in exception msg to ' '
     */
    
    while ((p = strchr(p, (int) '\n')) != NULL) {
        *p++ = ' ';
    }
    sprintf(exceptionBuf, "%s%c%s", code,
	    ARG_TOKEN_DELIMITER, msg);
    Ns_PdSendString(exceptionBuf);
}


/*
 *----------------------------------------------------------------------
 *
 * Ns_PdCloseonexec --
 *
 *	Set a file descriptor to close on exec. 
 *
 * Results:
 *	See fcntl. 
 *
 * Side effects:
 *	None. 
 *
 *----------------------------------------------------------------------
 */

int
Ns_PdCloseonexec(int fd)
{
    int i;

    i = fcntl(fd, F_GETFD);
    if (i != -1) {
        i |= F_CLOEXEC;
        i = fcntl(fd, F_SETFD, i);
    }
    return i;
}


/*
 *----------------------------------------------------------------------
 *
 * Ns_PdNewRowInfo --
 *
 *	Allocate a new RowInfo structure with space for ncols 
 *	columns. 
 *
 * Results:
 *	An empty Ns_PdRowInfo structure. 
 *
 * Side effects:
 *	The result is malloc'ed.
 *
 *----------------------------------------------------------------------
 */

Ns_PdRowInfo *
Ns_PdNewRowInfo(int ncols)
{
    Ns_PdRowInfo *rowInfo;

    if ((rowInfo = malloc(sizeof(Ns_PdRowInfo))) == NULL) {
        Ns_PdLog(Error, "nspd: rowinfo malloc(%d) error: '%s'",
		 sizeof(Ns_PdRowInfo), strerror(errno));
    } else {
        rowInfo->numColumns = ncols;
	rowInfo->rowData = malloc(sizeof(Ns_PdRowData) * ncols);
	if (rowInfo->rowData == NULL) {
            Ns_PdLog(Error, "nspd: "
		     "rowdata malloc(%d) error: '%s'",
		     sizeof(Ns_PdRowData) * ncols, strerror(errno));
            free(rowInfo);
            rowInfo = NULL;
        }
    }
    
    return rowInfo;
}


/*
 *----------------------------------------------------------------------
 *
 * Ns_PdFreeRowInfo --
 *
 *	Free a Ns_PdRowInfo structure allocated with Ns_PdNewRowInfo. 
 *
 * Results:
 *	None. 
 *
 * Side effects:
 *	Frees the structure, and if fFreeData is true, the data as well.
 *
 *----------------------------------------------------------------------
 */

void
Ns_PdFreeRowInfo(Ns_PdRowInfo * rowInfo, int fFreeData)
{
    int i;

    if (fFreeData) {
        for (i = 0; i < rowInfo->numColumns; i++) {
            free(rowInfo->rowData[i].elData);
        }
    }
    free(rowInfo->rowData);
    free(rowInfo);
}


/*
 *----------------------------------------------------------------------
 *
 * Ns_PdSendRowInfo --
 *
 *	Send a Ns_PdRowInfo structure to the external driver. 
 *
 * Results:
 *	None. 
 *
 * Side effects:
 *	None. 
 *
 *----------------------------------------------------------------------
 */

void
Ns_PdSendRowInfo(Ns_PdRowInfo * rowInfo)
{
    int  i;
    int  size;
    char countbuf[64];

    for (i = 0; i < rowInfo->numColumns; i++) {
        size = rowInfo->rowData[i].elSize;
        sprintf(countbuf, "%d", size);
        Ns_PdSendString(countbuf);
        if (size > 0) {
            Ns_PdSendData(rowInfo->rowData[i].elData, size);
        }
    }
    Ns_PdSendData(END_DATA, (int)strlen(END_DATA));
}


/*
 *----------------------------------------------------------------------
 *
 * Ns_PdSetRowInfoNumColumns --
 *
 *	Set the number of columns in a Ns_PdRowInfo structure. 
 *
 * Results:
 *	None. 
 *
 * Side effects:
 *	None. 
 *
 *----------------------------------------------------------------------
 */

void
Ns_PdSetRowInfoNumColumns(Ns_PdRowInfo * rowInfo, int numColumns)
{
    rowInfo->numColumns = numColumns;
}


/*
 *----------------------------------------------------------------------
 *
 * Ns_PdGetRowInfoNumColumns --
 *
 *	Returns the number of columns in a Ns_PdRowInfo structure. 
 *
 * Results:
 *	# of cols.
 *
 * Side effects:
 *	None. 
 *
 *----------------------------------------------------------------------
 */

int
Ns_PdGetRowInfoNumColumns(Ns_PdRowInfo * rowInfo)
{
    return rowInfo->numColumns;
}


/*
 *----------------------------------------------------------------------
 *
 * Ns_PdSetRowInfoItem --
 *
 *	Sets row info for one item (by index). 
 *
 * Results:
 *	None. 
 *
 * Side effects:
 *	None. 
 *
 *----------------------------------------------------------------------
 */

void
Ns_PdSetRowInfoItem(Ns_PdRowInfo * rowInfo, int index, char *data, int size)
{
    rowInfo->rowData[index].elData = data;
    rowInfo->rowData[index].elSize = size;
}


/*
 *----------------------------------------------------------------------
 *
 * Ns_PdGetRowInfoItem --
 *
 *	Get a rowinfo item by index 
 *
 * Results:
 *	None. 
 *
 * Side effects:
 *	Fills in data and size appropriately. 
 *
 *----------------------------------------------------------------------
 */

void
Ns_PdGetRowInfoItem(Ns_PdRowInfo * rowInfo, int index, char **data, int *size)
{
    *data = rowInfo->rowData[index].elData;
    *size = rowInfo->rowData[index].elSize;
}


/*
 *----------------------------------------------------------------------
 *
 * Ns_PdFindRowInfoValue --
 *
 *	Find a value in a Ns_PdRowInfo. Currently, 'value' will 
 *	always be a NULL-terminated string, We're using the len arg 
 *	and memcmp to support binary data (future). 
 *
 * Results:
 *	Index number of item, or -1 if not found.
 *
 * Side effects:
 *	None. 
 *
 *----------------------------------------------------------------------
 */

int
Ns_PdFindRowInfoValue(Ns_PdRowInfo * rowInfo, char *value, int len)
{
    int i;

    for (i = 0; i < rowInfo->numColumns; i++) {
        if (memcmp(rowInfo->rowData[i].elData, value, (size_t)len) == 0) {
            return i;
        }
    }
    return -1;
}


/*
 *----------------------------------------------------------------------
 *
 * Ns_PdParseOpenArgs --
 *
 *	Parses datasource#user#password#param, leaving missing 
 *	elements as NULL. 
 *
 * Results:
 *	None. 
 *
 * Side effects:
 *	Sets datasource, user, password, and param appopriately. 
 *
 *----------------------------------------------------------------------
 */

void
Ns_PdParseOpenArgs(char *openargs, char **datasource, char **user,
		   char **password, char **param)
{
    char *p, *lastp;
    char  dl = ARG_TOKEN_DELIMITER;

    Ns_PdLog(Trace, "Ns_PdParseOpenArgs: |%s|", openargs);
    *datasource = *user = *password = *param = NULL;
    lastp = openargs;
    if ((p = strchr(lastp, dl)) != NULL) {
        if (p != lastp) {
            *p = '\0';
            *datasource = strdup(lastp);
        }
        lastp = ++p;
        if ((p = strchr(lastp, dl)) != NULL) {
            if (p != lastp) {
                *p = '\0';
                *user = strdup(lastp);
            }
            lastp = ++p;
            if ((p = strchr(lastp, dl)) != NULL) {
                if (p != lastp) {
                    *p = '\0';
                    *password = strdup(lastp);
                }
                lastp = ++p;
                if (*lastp != '\0') {
                    *param = strdup(lastp);
                }
            }
        }
    }
}


/*
 *----------------------------------------------------------------------
 *
 * Ns_PdSqlbufEnough --
 *
 *	Reallocate a buffer if need be. 
 *
 * Results:
 *	NS_OK/NS_ERROR 
 *
 * Side effects:
 *	May realloc *buf and set buf and size by ref 
 *
 *----------------------------------------------------------------------
 */

int
Ns_PdSqlbufEnough(char **buf, int *size, int howmuch)
{
    int status = NS_OK;

    if (*size < howmuch) {
        Ns_PdLog(Notice, "nspd: "
		 "reallocing sqlbuf from %d to %d", *size, howmuch);
        if ((*buf = (char *) realloc(*buf, (size_t)howmuch)) == NULL) {
            Ns_PdLog(Error, "nspd: realloc error '%s'", strerror(errno));
            status = NS_ERROR;
        } else {
            *size = howmuch;
        }
    }
    return status;
}


/*
 *----------------------------------------------------------------------
 *
 * Ns_PdStringTrim --
 *
 *	Trim leading and trailing white space from a string. 
 *
 * Results:
 *	The modified string. 
 *
 * Side effects:
 *	Will modify the string. 
 *
 *----------------------------------------------------------------------
 */

char *
Ns_PdStringTrim(char *string)
{
    return StringTrimLeft(StringTrimRight(string));
}

/*
 *==========================================================================
 * Exported functions
 *==========================================================================
 */


/*
 *----------------------------------------------------------------------
 *
 * PdMainLoop --
 *
 *	Loop forever and ever, running callbacks as needed. 
 *
 * Results:
 *	None. 
 *
 * Side effects:
 *	None. 
 *
 *----------------------------------------------------------------------
 */

void
PdMainLoop(void)
{
    static char    buf[CMDMAX];
    char           *cmdName;
    char           *cmdArg;
    void           *dbhandle;

    Ns_PdLog(Notice, "nspd: starting");
    if ((dbhandle = Ns_PdDbInit()) == NULL) {
        Ns_PdLog(Error, "nspd: initialization failure");
    } else {
        while (readInput) {
            if (GetMsg(buf, &cmdName, &cmdArg) == NS_OK) {
                DispatchCmd(cmdName, cmdArg, dbhandle);
            } else {
                readInput = 0;
            }
        }
        Ns_PdDbCleanup(dbhandle);
    }
}

/*
 *==========================================================================
 * Static functions
 *==========================================================================
 */


/*
 *----------------------------------------------------------------------
 *
 * PdPort --
 *
 *	Convert a string port number to an integer, and make sure 
 *	it's valid. 
 *
 * Results:
 *	A port number. 
 *
 * Side effects:
 *	Exits if invalid. 
 *
 *----------------------------------------------------------------------
 */

static int
PdPort(char *arg)
{
    int             port;

    port = atoi(arg);
    if (port <= 0 || port >= 65535) {
        Ns_PdLog(Error, "nspd: invalid port '%s'", arg);
        Ns_PdExit(1);
    }
    return port;
}


/*
 *----------------------------------------------------------------------
 *
 * GetMsg --
 *
 *	Read a message from the external driver. 
 *
 * Results:
 *	NS_OK/NS_ERROR 
 *
 * Side effects:
 *	None. 
 *
 *----------------------------------------------------------------------
 */

static int
GetMsg(char *buf, char **cmdName, char **cmdArg)
{
    int             status = NS_ERROR;
    int             bytesRead;  
    int             argsize;
    char           *pargsize;
    char           *p;

    if ((bytesRead = RecvData(buf, CMDMAX)) > 0) {
        if ((p = strchr(buf, '\n')) == NULL) {
            Ns_PdLog(Error, "nspd: protocol error: "
		     "no newline terminator for command name");
        } else {
            *p++ = '\0';
            *cmdName = buf;
            pargsize = p;
            if ((p = strchr(pargsize, '\n')) == NULL) {
                Ns_PdLog(Error, "nspd: protocol error: "
			 "no newline terminator for arglen of command: '%s'",
			 *cmdName);
            } else {
                *p++ = '\0';
                argsize = atoi(pargsize);
		if (argsize > (CMDMAX - (p - buf))) {
                    Ns_PdLog(Error, "nspd: "
			     "arglen of %d for %s command is greater than "
			     "configured max %d", argsize, *cmdName, CMDMAX);
                } else {
		    int msgSize;
		    int readError = 0;
		    int readRet;
		    /*
		     * total msg size is sum of cmd\nargsize\nargdata
		     */
		    
		    msgSize = strlen(*cmdName) + strlen(pargsize) +
			argsize + 2;
		    while (bytesRead < msgSize && !readError) {
			if ((readRet = RecvData(&buf[bytesRead],
						msgSize - bytesRead)) > 0) {
			    
			    bytesRead += readRet;
			} else {
			    readError = 1;
			}
		    }
		    if (!readError) {
			*(p + argsize) = '\0';
			*cmdArg = p;
			status = NS_OK;
		    }
                }
            }
        }
    }
    return status;
}


/*
 *----------------------------------------------------------------------
 *
 * DispatchCmd --
 *
 *	Run proxy callbacks when a command comes in. 
 *
 * Results:
 *	None. 
 *
 * Side effects:
 *	None. 
 *
 *----------------------------------------------------------------------
 */

static void
DispatchCmd(char *cmd, char *arg, void *dbhandle)
{
    Ns_ExtDbCommandCode cmdcode;

    if ((cmdcode = Ns_ExtDbMsgNameToCode(cmd)) == NS_ERROR) {
        Ns_PdLog(Error, "nspd: unknown dispatch message '%s'", cmd);
    } else if (arg == NULL && Ns_ExtDbMsgRequiresArg(cmdcode)) {
        Ns_PdLog(Error, "nspd: dispatch message requires argument");
    } else {
        switch (cmdcode) {
        case Flush:
            Ns_PdDbFlush(dbhandle);
            break;
        case Cancel:
            Ns_PdDbCancel(dbhandle);
            break;
        case Exec:
            Ns_PdDbExec(dbhandle, arg);
            break;
        case BindRow:
            Ns_PdDbBindRow(dbhandle);
            break;
        case GetRow:
            Ns_PdDbGetRow(dbhandle, arg);
            break;
        case GetTableInfo:
	    Ns_PdLog(Error, "nspd: unsupported dispatch command: GetTableInfo");
            break;
        case TableList:
	    Ns_PdLog(Error, "nspd: unsupported dispatch command: TableList");
            break;
        case BestRowId:
	    Ns_PdLog(Error, "nspd: unsupported dispatch command: BestRowId");
            break;
        case Close:
            Ns_PdDbClose(dbhandle);
            readInput = 0;
            break;
        case Open:
            Ns_PdDbOpen(dbhandle, arg);
            break;
        case Identify:
            Ns_PdDbIdentify(dbhandle);
            break;
        case GetTypes:
            Ns_PdDbGetTypes(dbhandle);
            break;
        case ResultId:
            Ns_PdDbResultId(dbhandle);
            break;
        case ResultRows:
            Ns_PdDbResultRows(dbhandle);
            break;
        case SetMaxRows:
            Ns_PdDbSetMaxRows(dbhandle, arg);
            break;
	case ResetHandle:
            Ns_PdDbResetHandle(dbhandle); 
            break;
	case SpStart:
	    Ns_PdDbSpStart(dbhandle, arg);
	    break;
	case SpSetParam:
	    Ns_PdDbSpSetParam(dbhandle, arg);
	    break;
	case SpExec:
	    Ns_PdDbSpExec(dbhandle);
	    break;
	case SpReturnCode:
	    Ns_PdDbSpReturnCode(dbhandle);
	    break;
        case SpGetParams:
	    /*
	     * Should arg be passed here? Possible bug--the original
	     * implementation had it here but not in nssybpd.
	     */
            Ns_PdDbSpGetParams(dbhandle);
            break;
            /*
             * The commands below are not DB-specific, so they're handled in
             * this file
             */
        case Ping:
            PdPing();
            break;
        case TraceOn:
            PdTraceOn(arg);
            break;
        case TraceOff:
            PdTraceOff();
            break;
        case OpenF:
            PdOpenFile(arg);
            break;
        case CloseF:
            PdCloseFile(arg);
            break;
        case ReadF:
            PdReadFile(arg);
            break;
        case WriteF:
            PdWriteFile(arg);
            break;
        case DeleteF:
            PdDeleteFile(arg);
            break;
        case CreateTmpF:
            PdCreateTmpFile();
            break;
        default:
            assert(0);
	    /*
	     * msg validity verified in
	     * DbMsgNameToCode above
	     */
            break;
        }
    }
}


/*
 *----------------------------------------------------------------------
 *
 * PdPing --
 *
 *	Respond to a ping request. 
 *
 * Results:
 *	None. 
 *
 * Side effects:
 *	None. 
 *
 *----------------------------------------------------------------------
 */

static void
PdPing()
{
    Ns_PdLog(Trace, "nspd: responding to ping");
    Ns_PdSendString(OK_STATUS);
}


/*
 *----------------------------------------------------------------------
 *
 * PdOpenFile --
 *
 *	Open a local file, as requested by external driver. 
 *
 * Results:
 *	None. 
 *
 * Side effects:
 *	None. 
 *
 *----------------------------------------------------------------------
 */

static void
PdOpenFile(char *openParams)
{
    int  fd;
    char errbuf[512];
    char fdStr[8];
    int  matchedArgs;
    char pathName[512];
    int  oflags;

    Ns_PdLog(Trace, "PdOpenFile:");
    matchedArgs = sscanf(openParams, "%d#%s", &oflags, pathName);
    if (matchedArgs != 2) {
        sprintf(errbuf, "Error parsing open parameters: %s",
            openParams);
        Ns_PdLog(Error, "nspd: '%s'", errbuf);
        Ns_PdSendString(errbuf);
    } else if ((fd = open(pathName, oflags, 0)) < 0) {
        sprintf(errbuf, "Can't open file %s (oflags=%d): %s",
            pathName, oflags, strerror(errno));
        Ns_PdLog(Error, "nspd: '%s'", errbuf);
        Ns_PdSendString(errbuf);
    } else {
        Ns_PdSendString(OK_STATUS);
        sprintf(fdStr, "%d", fd);
        Ns_PdSendString(fdStr);
    }
}


/*
 *----------------------------------------------------------------------
 *
 * PdCloseFile --
 *
 *	Close a file, as requested by the external driver. 
 *
 * Results:
 *	None. 
 *
 * Side effects:
 *	None. 
 *
 *----------------------------------------------------------------------
 */

static void
PdCloseFile(char *fdStr)
{
    int  fd;
    char errbuf[512];

    Ns_PdLog(Trace, "PdCloseFile:");
    fd = atoi(fdStr);
    if (close(fd) < 0) {
        sprintf(errbuf, "Close error on file descriptor %d: %s",
            fd, strerror(errno));
        Ns_PdLog(Error, "nspd: failed closing file '%s'", errbuf);
        Ns_PdSendString(errbuf);
    } else {
        Ns_PdSendString(OK_STATUS);
    }
}


/*
 *----------------------------------------------------------------------
 *
 * PdReadFile --
 *
 *	Read a file and send it to the external driver. 
 *
 * Results:
 *	None. 
 *
 * Side effects:
 *	None. 
 *
 *----------------------------------------------------------------------
 */

static void
PdReadFile(char *readParams)
{
    char errbuf[512];
    char readBuf[4096];
    int  bytesRead;
    char bytesReadStr[64];
    int  matchedArgs;
    int  fd, offset, bytecount;

    Ns_PdLog(Trace, "PdReadFile:");
    matchedArgs = sscanf(readParams, "%d#%d#%d",
			 &fd, &offset, &bytecount);
    if (matchedArgs != 3) {
        sprintf(errbuf, "Error parsing read parameters: %s",
		readParams);
        Ns_PdLog(Error, "nspd: failed reading file: '%s'", errbuf);
        Ns_PdSendString(errbuf);
    } else {
        lseek(fd, offset, SEEK_SET);
        if ((bytesRead = read(fd, readBuf, (size_t)bytecount)) < 0) {
            sprintf(errbuf, "Read error on fd %d (%d bytes): %s",
		    fd, bytecount, strerror(errno));
            Ns_PdLog(Error, "failed reading file: '%s'", errbuf);
            Ns_PdSendString(errbuf);
        } else {
            Ns_PdSendString(OK_STATUS);
            sprintf(bytesReadStr, "%d", bytesRead);
            Ns_PdSendString(bytesReadStr);
            Ns_PdSendData(readBuf, bytesRead);
            Ns_PdSendData(END_DATA, (int)strlen(END_DATA));
        }
    }

}


/*
 *----------------------------------------------------------------------
 *
 * PdWriteFile --
 *
 *	Write a file from the external driver. 
 *
 * Results:
 *	None. 
 *
 * Side effects:
 *	None. 
 *
 *----------------------------------------------------------------------
 */

static void
PdWriteFile(char *writeParams)
{
    char  errbuf[512];
    int   matchedArgs;
    int   fd, offset, bytecount, hashcount = 0;
    char *pw;

    Ns_PdLog(Trace, "PdWriteFile:");
    matchedArgs = sscanf(writeParams, "%d#%d#%d#",
			 &fd, &offset, &bytecount);
    if (matchedArgs != 3) {
        sprintf(errbuf, "Error parsing write parameters: %s",
		writeParams);
        Ns_PdLog(Error, "nspd: failed writing file: '%s'", errbuf);
        Ns_PdSendString(errbuf);
    } else {
        for (pw = writeParams; *pw;) {
            if (*pw++ == '#') {
                if (++hashcount == matchedArgs) {
                    break;
                }
            }
        }
        lseek(fd, offset, SEEK_SET);
        if (write(fd, pw, (size_t)bytecount) != bytecount) {
            sprintf(errbuf, "Write error to fd %d (%d bytes): %s",
		    fd, bytecount, strerror(errno));
            Ns_PdLog(Error, "nspd: failed writing file: '%s'", errbuf);
            Ns_PdSendString(errbuf);
        } else {
            Ns_PdSendString(OK_STATUS);
        }
    }
}


/*
 *----------------------------------------------------------------------
 *
 * PdDeleteFile --
 *
 *	Delete a file, as requested by the external driver. 
 *
 * Results:
 *	None. 
 *
 * Side effects:
 *	None. 
 *
 *----------------------------------------------------------------------
 */

static void
PdDeleteFile(char *fileName)
{
    char errbuf[512];

    Ns_PdLog(Trace, "PdDeleteFile:");
    if (unlink(fileName) < 0) {
        sprintf(errbuf, "Can't delete file %s: %s",
            fileName, strerror(errno));
        Ns_PdLog(Error, "nspd: failed deleting file: '%s'", errbuf);
        Ns_PdSendString(errbuf);
    } else {
        Ns_PdSendString(OK_STATUS);
    }
}


/*
 *----------------------------------------------------------------------
 *
 * PdCreateTmpFile --
 *
 *	Create a temp file, as requested by the external driver. 
 *
 * Results:
 *	None. 
 *
 * Side effects:
 *	None. 
 *
 *----------------------------------------------------------------------
 */

static void
PdCreateTmpFile()
{
    char tmpName[MAX_PATH];
    char errbuf[256];
    int  fd;
    int  status = NS_OK;

    Ns_PdLog(Trace, "PdCreateTmpFile:");

    sprintf(tmpName, "%s%s", UNIX_TMPDIR, FILE_TEMPLATE);

    if (status == NS_OK) {
        mktemp(tmpName);
        if (tmpName[0] == '\0') {
            sprintf(errbuf, "mktemp of %s failed", tmpName);
            Ns_PdSendString(errbuf);
            Ns_PdLog(Error, "nspd: failed to create temp file: '%s'", errbuf);
        } else if ((fd = open(tmpName,
			      O_CREAT | O_TRUNC | O_RDWR, 0644)) < 0) {
	    
            sprintf(errbuf, "open/create of %s failed: %s",
		    tmpName, strerror(errno));
            Ns_PdSendString(errbuf);
            Ns_PdLog(Error, "nspd: "
		     "failed to open/create temp file: '%s'", errbuf);
        } else {
            close(fd);
            Ns_PdSendString(OK_STATUS);
            Ns_PdSendString(tmpName);
        }
    }
}



/*
 *----------------------------------------------------------------------
 *
 * Ns_PdSendString --
 *
 *	Send a string, followed by \n per the protocol. Since we're 
 *	tacking on the \n, the string is copied into another (larger) 
 *	buffer. (This is still more efficient than a separate write 
 *	system call for the the additional '\n'. 
 *
 * Results:
 *	None. 
 *
 * Side effects:
 *	None. 
 *
 *----------------------------------------------------------------------
 */

void
Ns_PdSendString(char *rsp)
{
    char  outbuf[MAXSTACK];
    char *pout = outbuf;
    int   alloced = 0;
    int   len;

    len = strlen(rsp);
    if (len > MAXSTACK - 1) {
	/*
	 * rare event
	 */
        if ((pout = malloc((size_t)(len + 1))) == NULL) {
            Ns_PdLog(Error, "nspd: "
		     "data truncated; malloc failed to get %d bytes", len + 1);
            rsp[MAXSTACK - 1] = '\0';
            pout = outbuf;
        } else {
            alloced = 1;
        }
    }
    sprintf(pout, "%s\n", rsp);
    Ns_PdSendData(pout, len + 1);
    if (alloced) {
        free(pout);
    }
}


/*
 *----------------------------------------------------------------------
 *
 * RecvData --
 *
 *	Recieve data from the external driver. 
 *
 * Results:
 *	Numberof bytes read, or <0 on error. 
 *
 * Side effects:
 *	None. 
 *
 *----------------------------------------------------------------------
 */

static int
RecvData(char *buf, int len)
{
    int readReturn;

    do {
        readReturn = read(0, buf, (size_t)len);
    } while ((readReturn < 0) && (errno == EINTR));
    if (readReturn < 0) {
        Ns_PdLog(Error, "nspd: read error while reading %d bytes: '%s'",
		 strerror(errno), len);
    }
    return readReturn;
}


/*
 *----------------------------------------------------------------------
 *
 * StringTrimLeft --
 *
 *	Trim leading white space from a string. 
 *
 * Results:
 *	A pointer into the original string after whitespace. 
 *
 * Side effects:
 *	None. 
 *
 *----------------------------------------------------------------------
 */

static char *
StringTrimLeft(char *string)
{
    assert(string != NULL);
    while (isspace((unsigned int)*string)) {
        ++string;
    }
    return string;
}


/*
 *----------------------------------------------------------------------
 *
 * Ns_StrTrimRight --
 *
 *	Trim trailing white space from a string. 
 *
 * Results:
 *	A pointer to the original string. 
 *
 * Side effects:
 *	Modifies string. 
 *
 *----------------------------------------------------------------------
 */

static char *
StringTrimRight(char *string)
{
    int len;

    assert(string != NULL);

    len = strlen(string);
    while ((len-- >= 0) 
	   && (isspace((unsigned int)string[len]) || string[len] == '\n')) {
        string[len] = '\0';
    }
    return string;
}


/*
 *----------------------------------------------------------------------
 *
 * PdFindBin --
 *
 *	Set the bin directory and cd /. 
 *
 * Results:
 *	None. 
 *
 * Side effects:
 *	None. 
 *
 *----------------------------------------------------------------------
 */

static void
PdFindBin(char *pgm)
{

    pdBin = pgm;
    chdir("/");
}