File: nfsd.c

package info (click to toggle)
netstd 3.07-2hamm.5
  • links: PTS
  • area: main
  • in suites: hamm
  • size: 6,384 kB
  • ctags: 9,087
  • sloc: ansic: 72,547; cpp: 6,141; makefile: 1,681; yacc: 1,615; sh: 1,220; perl: 303; awk: 46
file content (1203 lines) | stat: -rw-r--r-- 29,137 bytes parent folder | download
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
/*
 * nfsd		This program handles RPC "NFS" data requests.
 *
 * Usage:	[rpc.]nfsd [-Fhnprv] [-f authfile] [-d debugfac]
 *
 * Authors:	Mark A. Shand, May 1988
 *		Donald J. Becker, <becker@super.org>
 *		Rick Sladkey, <jrs@world.std.com>
 *		Fred N. van Kempen, <waltje@uWalt.NL.Mugnet.ORG>
 *		Eric Kasten, <tigger@tigger.cl.msu.edu>
 *		Olaf Kirch, <okir@monad.swb.de>
 *
 *		Copyright 1988 Mark A. Shand
 *		This software maybe be used for any purpose provided
 *		the above copyright notice is retained.  It is supplied
 *		as is, with no warranty expressed or implied.
 */

#include "nfsd.h"
#include <rpc/pmap_clnt.h>
#include "getopt.h"
#include "fsusage.h"
#include "rpcmisc.h"
#include "failsafe.h"
#include "signals.h"
#ifdef __linux__ /* XXX - MvS: for UNIX sockets. */
#  include <sys/un.h>
#endif
#ifdef HAVE_SYSLOG_H
# include <syslog.h>
#endif

#define MULTIPLE_SERVERS

/* Flags for auth_fh */
#define CHK_READ	0
#define CHK_WRITE	1
#define CHK_NOACCESS	2

/* Make larger reads possible. Without crashing the machine :-) */
#undef NFS_MAXDATA
#define NFS_MAXDATA	(16 * 1024)

static char iobuf[NFS_MAXDATA];
static char pathbuf[NFS_MAXPATHLEN + NFS_MAXNAMLEN + 1];
static char pathbuf_1[NFS_MAXPATHLEN + NFS_MAXNAMLEN + 1];

extern char version[];
static char *program_name;

/*
 * Option table
 */
static struct option longopts[] =
{
      { "auth-deamon",		required_argument,	0,	'a' },
      { "debug",		required_argument,	0,	'd' },
      { "foreground",		0,			0,	'F' },
      { "exports-file",		required_argument,	0,	'f' },
      { "help",			0,			0,	'h' },
      { "log-transfers",	0,			0,	'l' },
      { "allow-non-root",	0,			0,	'n' },
      { "port",			required_argument,	0,	'P' },
      { "promiscuous",		0,			0,	'p' },
      { "re-export",		0,			0,	'r' },
      { "public-root",		required_argument,	0,	'R' },
      { "synchronous-writes",	0,			0,	's' },
      { "no-spoof-trace",	0,			0,	't' },
      { "version",		0,			0,	'v' },
      { "no-cross-mounts",	0,			0,	'x' },
      { "fail-safe",		optional_argument,	0,	'z' }, 

      { NULL,		0,	0, 0 }
};
static const char *	shortopts = "a:d:Ff:hlnP:prR:tvz::";

/*
 * Table of supported versions
 */
static int		nfsd_versions[] = {
	NFS_VERSION,
	0
};

nfs_client *		nfsclient = NULL;	/* the current client */
nfs_mount *		nfsmount = NULL;	/* the current mount point */
int			need_reinit = 0;	/* SIGHUP handling */
int			need_flush = 0;		/* flush fh cache */
int			read_only = 0;		/* Global ro forced */
int			cross_mounts = 1;	/* Transparently cross mnts */
int			log_transfers = 0;	/* Log transfers */
static svc_fh		public_fh;		/* Public NFSv2 FH */

static nfsstat	build_path(struct svc_req *rqstp, char *buf,
				diropargs *dopa, int flags);
static fhcache *auth_fh(struct svc_req *rqstp, nfs_fh *fh, 
				nfsstat *statp, int flags);
static void	usage(FILE *, int);
static void	terminate(void);
static RETSIGTYPE sigterm(int sig);
#ifdef SUPPORT_CDF
static char *	cdf_translate(char *tag);
#endif


#ifdef CALL_PROFILING
extern void	dump_stats(int sig);
#endif

/*
 * auth_fh
 *
 * This function authenticates the file handle provided by the client.
 * It also takes care of caching the client and mount point structures
 * in the fh cache entry, even though this may not be a huge benefit.
 */
static fhcache *
auth_fh(struct svc_req *rqstp, nfs_fh *fh, nfsstat *statp, int flags)
{
	static int	total = 0, cached = 0;
	fhcache		*fhc;

	/* Try to map FH. If not cached, reconstruct path with root priv */
	fhc = fh_find((svc_fh *)fh, FHFIND_FEXISTS|FHFIND_CHECK);
	if (fhc == NULL) {
		*statp = NFSERR_STALE;
		return NULL;
	}

	/* Try to retrieve last client who accessed this fh */
	if (nfsclient == NULL) {
		struct in_addr	caddr;

		caddr = svc_getcaller(rqstp->rq_xprt)->sin_addr;
		if (fhc->last_clnt != NULL &&
		    fhc->last_clnt->clnt_addr.s_addr == caddr.s_addr) {
			nfsclient = fhc->last_clnt;
		} else if ((nfsclient = auth_clnt(rqstp)) == NULL) {
			*statp = NFSERR_ACCES;
			return NULL;
		}
	}

	if (fhc->last_clnt == nfsclient) {
		nfsmount = fhc->last_mount; /* get cached mount point */
		cached++;
	} else {
		nfsmount = auth_path(nfsclient, rqstp, fhc->path);
		if (nfsmount == NULL) {
			*statp = NFSERR_ACCES;
			return NULL;
		}
		fhc->last_clnt = nfsclient;
		fhc->last_mount = nfsmount;
	}
	total++;
	/*
	if (total % 1000 == 0)
		Dprintf(D_FHCACHE, "ratio of cached client ptrs %4.1f%%\n",
			100 * (double) cached / total);
	 */

	if (nfsmount->o.noaccess &&
	    ((flags & CHK_NOACCESS) || strcmp(nfsmount->path, fhc->path))) {
		struct in_addr	addr = svc_getcaller(rqstp->rq_xprt)->sin_addr;
		Dprintf(L_WARNING, "client %s tried to access %s (noaccess)\n",
				inet_ntoa(addr), fhc->path);
		*statp = NFSERR_ACCES;
		return NULL;
	}

	if ((flags & CHK_WRITE) && (nfsmount->o.read_only || read_only)) {
		*statp = NFSERR_ROFS;
		return NULL;
	}

	auth_user(nfsmount, rqstp);

	*statp = NFS_OK;
	return fhc;
}

/*
 * Build the full path name for a file specified by diropargs.
 */
static inline nfsstat
build_path(struct svc_req *rqstp, char *buf, diropargs *dopa, int flags)
{
	fhcache		*fhc;
	nfsstat		status;
	char		*path = buf, *sp;

	/* Authenticate directory file handle */
	if ((fhc = auth_fh(rqstp, &dopa->dir, &status, flags)) == NULL)
		return status;

	/* Get the directory path and append "/" + dopa->filename */
	sp = fhc->path;

	while (*sp)		/* strcpy(buf, fhc->path); */
		*buf++ = *sp++;
	*buf++ = '/';		/* strcat(buf, "/");  */
	sp = dopa->name;
	while (*sp) {		/* strcat(pathbuf, argp->where.name); */
		if (*sp == '/')
			return NFSERR_INVAL;
		*buf++ = *sp++;
	}
	*buf = '\0';

	if (strlen(path) > NFS_MAXPATHLEN)
		return NFSERR_NAMETOOLONG;

	if ((nfsmount = auth_path(nfsclient, rqstp, path)) == NULL) {
		return NFSERR_ACCES;
	}
	auth_user(nfsmount, rqstp);

	return (NFS_OK);
}

/*
 * Log a transfer to syslog.
 */
static void
nfsd_xferlog(struct svc_req *rqstp, char *inout, char *pathname)
{
	struct in_addr	addr = svc_getcaller(rqstp->rq_xprt)->sin_addr;

	syslog(LOG_INFO, "%s %s %s", inet_ntoa(addr), inout, pathname);
}

/*
 * The "wrappers" of the following functions came from `rpcgen -l nfs_prot.x`.
 * This normally generates the client routines, but it provides nice
 * prototypes for the server routines also.
 */
int
nfsd_nfsproc_null_2(void *argp, struct svc_req *rqstp)
{
	return (0);
}

int
nfsd_nfsproc_getattr_2(nfs_fh *argp, struct svc_req *rqstp)
{
	nfsstat status;
	fhcache *fhc;

	fhc = auth_fh(rqstp, argp, &status, CHK_READ);
	if (fhc == NULL)
		return status;

	return (fhc_getattr(fhc, &result.attrstat.attrstat_u.attributes,
						NULL, rqstp));
}

int
nfsd_nfsproc_setattr_2(sattrargs *argp, struct svc_req *rqstp)
{
	nfsstat status;
	fhcache *fhc;
	char *path;
	struct stat buf, *opt;

	fhc = auth_fh(rqstp, &(argp->file), &status, CHK_WRITE | CHK_NOACCESS);
	if (fhc == NULL)
		return status;
	path = fhc->path;

	errno = 0;
	/* Stat the file first and only change fields that are different. */
	if (lstat(path, &buf) < 0)
		goto failure;

	status = setattr(path, &argp->attributes, &buf, rqstp, SATTR_ALL);
	if (status != NFS_OK)
		return status;

	/* Oops: Don't optimize getattr when the setattr arguments didn't
	 * contain valid mtime... */
	opt = &buf;
	if (argp->attributes.mtime.seconds == -1)
		opt = NULL;
	return (fhc_getattr(fhc, &(result.attrstat.attrstat_u.attributes),
						opt, rqstp));

failure:
	return (nfs_errno());
}

int nfsd_nfsproc_root_2(argp, rqstp)
void *argp;
struct svc_req	*rqstp;
{
	return (0);
}

/*
 * Look up a file by name.
 * Multi-component lookups for webnfs are handled by fh_compose.
 */
int
nfsd_nfsproc_lookup_2(diropargs *argp, struct svc_req *rqstp)
{
	diropokres	*dp = &result.diropres.diropres_u.diropres;
	nfs_fh		*fh = &argp->dir;
	fhcache		*fhc;
	nfsstat		status;
	struct stat	sbuf;
	int		ispublic = 0;

	/* First check whether this is the public FH */
	if (((svc_fh *) fh)->psi == 0 && !memcmp(fh, &public_fh, FHSIZE)) {
		if (public_root_path == NULL)
			return NFSERR_ACCES;
		memcpy(&argp->dir, &public_root, NFS_FHSIZE);
		ispublic = 1;
	}


	/* Must authenticate dir FH to set fsuid/fsgid. Thanks to
	 * Stig Venaas for his bug report.
	 * Note this also sets the FHC_PUBLIC flag on the file handle.
	 */
	if (!(fhc = auth_fh(rqstp, fh, &status, CHK_READ)))
		return status;

	status = fh_compose(argp, &dp->file, &sbuf, -1, -1, ispublic);
	if (status != NFS_OK)
		return status;

	fhc = auth_fh(rqstp, &dp->file, &status, CHK_READ);
	if (fhc == NULL)
		return status;

	status = fhc_getattr(fhc, &dp->attributes, &sbuf, rqstp);
	if (status == NFS_OK)
		Dprintf(D_CALL, "\tnew_fh = %s\n", fh_pr(&(dp->file)));

	return (status);
}

#ifdef SUPPORT_CDF
static char *
cdf_translate(char *tag)
{
	static char	buffer[512];

	if (tag[0] == 'u' && !strcmp(tag, "uid"))
		sprintf(buffer, "%d", auth_uid);
	else if (tag[0] == 'h' && !strcmp(tag, "hostaddr"))
		sprintf(buffer, "%s", inet_ntoa(nfsclient->clnt_addr));
	else
		return NULL;
	return buffer;
}
#endif

int nfsd_nfsproc_readlink_2(argp, rqstp)
nfs_fh *argp;
struct svc_req	*rqstp;
{
	nfsstat status;
	fhcache *fhc;
	char *path;
	int cc;

	fhc = auth_fh(rqstp, argp, &status, CHK_READ | CHK_NOACCESS);
	if (fhc == NULL)
		return status;
	path = fhc->path;

	errno = 0;
	if ((cc = readlink(path, pathbuf, NFS_MAXPATHLEN)) < 0) {
		Dprintf(D_CALL, " >>> %s\n", strerror(errno));
		return (nfs_errno());
	}
	status = NFS_OK;
	pathbuf[cc] = '\0';	/* readlink() doesn't null terminate!! */
	result.readlinkres.readlinkres_u.data = pathbuf;

	if (nfsmount->o.link_relative && pathbuf[0] == '/') {
		/*
		 * We've got an absolute (locally) pathname, and we should
		 * translate to a relative pathname for the client.  We do
		 * this by prepending the correct number of "../"es to the
		 * path. This cannot work if the client does not mount the
		 * specified subtree of the filesystem.
		 */
		int slash_cnt = 0;
		char *p, *q;

		/* Count how many directories down we are. */
		for (p = path + 1; *p != '\0'; p++)
			if (*p == '/')
				slash_cnt++;

		/*
		 * Ok, now we are finished with the orginal file `path'
		 * and will only deal with the link target.
		 */
		p = &pathbuf[cc];	/* Point to the end and calculate */
		if (slash_cnt == 0)
			q = p + 1;	/* the extra space taken by a	*/
		else			/* prepended '.'  		*/
			q = p + 3 * slash_cnt - 1;	/* or '../.../..' */

		if (q >= pathbuf + NFS_MAXPATHLEN) {
			Dprintf(D_CALL, " [[NAME TOO LONG!!]]\n");
			return (NFSERR_NAMETOOLONG);
		} else {
			/* Add some space at the beginning of the string. */
			while (p >= pathbuf)
				*q-- = *p--;

			if (slash_cnt == 0)
				pathbuf[0] = '.';
			else {
				/*
				 * This overwrites the leading '/' on the
				 * last iteration.
				 */
				for (p = pathbuf; slash_cnt > 0; slash_cnt--) {
					*p++ = '.';
					*p++ = '.';
					*p++ = '/';
				}
			}
		}
	}
	Dprintf(D_CALL, " %s\n", result.readlinkres.readlinkres_u.data);
	return (NFS_OK);
}

int nfsd_nfsproc_read_2(argp, rqstp)
readargs *argp;
struct svc_req	*rqstp;
{
	nfsstat status;
	fhcache *fhc;
	readokres *res = &result.readres.readres_u.reply;
	int	fd, len;

	fhc = auth_fh(rqstp, &(argp->file), &status, CHK_READ | CHK_NOACCESS);
	if (fhc == NULL)
		return status;

	if ((fd = fh_fd(fhc, &status, O_RDONLY)) < 0) {
		return ((int) status);
	}
	errno = 0;
	(void) lseek(fd, (long) argp->offset, L_SET);
	if (!errno) {
		res->data.data_val = iobuf;
		if ((len = argp->count) > NFS_MAXDATA)
			len = NFS_MAXDATA;
		res->data.data_len = read(fd, iobuf, len);
	}
	fd_inactive(fd);
	if (errno)
		return (nfs_errno());

	/* Write record to syslog */
	if (argp->offset == 0 && log_transfers)
		nfsd_xferlog(rqstp, "<", fhc->path);

	return (fhc_getattr(fhc, &(res->attributes), NULL, rqstp));
}

int nfsd_nfsproc_writecache_2(argp, rqstp)
void *argp;
struct svc_req	*rqstp;
{
	return (0);
}

int
nfsd_nfsproc_write_2(writeargs *argp, struct svc_req *rqstp)
{
	nfsstat status;
	fhcache *fhc;
	int	fd;
	u_int	count;

	fhc = auth_fh(rqstp, &(argp->file), &status, CHK_WRITE | CHK_NOACCESS);
	if (fhc == NULL)
		return status;

	/* Check args. I've seen one client send a length of -1 */
	count = argp->totalcount;
	if (count > NFS_MAXDATA || count > argp->data.data_len) {
		Dprintf(L_NOTICE,
			"strange write req from %s: count %lu len %lu",
			nfsclient->clnt_name, count, argp->data.data_len);
		return NFSERR_IO;
	}

	if ((fd = fh_fd(fhc, &status, O_WRONLY)) < 0) {
		return ((int) status);
	}
	errno = 0;
	(void) lseek(fd, (long) argp->offset, L_SET);
	if (errno == 0) {	/* We should never fail. */
		if (write(fd, argp->data.data_val, argp->data.data_len) !=
		    argp->data.data_len) {
			Dprintf(D_CALL, " Write failure, errno is %d.\n", errno);
		}
	}
	fd_inactive(fd);
	if (errno)
		return (nfs_errno());

	/* Write record to syslog */
	if (argp->offset == 0 && log_transfers)
		nfsd_xferlog(rqstp, ">", fhc->path);

	return (fhc_getattr(fhc, &(result.attrstat.attrstat_u.attributes),
							NULL, rqstp));
}

/* This used to be O_RDWR, but O_WRONLY is correct */
#define CREATE_OMODE O_WRONLY

int
nfsd_nfsproc_create_2(createargs *argp, struct svc_req *rqstp)
{
	nfsstat status;
	diropokres *res;
	int tmpfd, flags;
	struct stat sbuf;
	int is_borc;
	int dev;
	int exists;
#ifdef __linux__ /* XXX - MvS: to create UNIX sockets. */
	struct sockaddr_un sa;
	int s;
#endif

	/*
	 * We get the access status and file handle here, but check the
	 * status later. This is to let an "echo >/dev/null" from SunOS
	 * clients succeed on RO-filesystems.
	 */
	status = build_path(rqstp, pathbuf, &argp->where,
					CHK_WRITE | CHK_NOACCESS);
	if (status != NFS_OK && status != NFSERR_ROFS)
		return ((int) status);
	Dprintf(D_CALL, "\tfullpath='%s'\n", pathbuf);
	errno = 0;

	exists = lstat(pathbuf, &sbuf) == 0;

	/* Compensate for a really bizarre bug in SunOS derived clients. */
	if ((argp->attributes.mode & S_IFMT) == 0) {
		argp->attributes.mode |= exists
			? (sbuf.st_mode & S_IFMT) : S_IFREG;
		if (!S_ISREG(argp->attributes.mode)) {
			/* This branch is excuted only if the file exists
			 * and is a special file. */
			status = NFS_OK;
			argp->attributes.size = sbuf.st_rdev;
		}
	}
	if (status != NFS_OK)
		return ((int)status);

	/* First handle any unusual file-types. */
	if (!S_ISREG(argp->attributes.mode)) {
		if (S_ISBLK(argp->attributes.mode)
		    || S_ISCHR(argp->attributes.mode)) {
			is_borc = 1;
#if 0
			/* This is probably better than just using
			   the size field by itself, but not by much. */
			dev = makedev(((argp->attributes.size >> 8) & 0xff),
			    (argp->attributes.size & 0xff));
#else
			/* We must not assume anything about the layout of
			 * the client's dev_t. Either the value fits into
			 * our dev_t or not...
			 */
			dev = (dev_t) argp->attributes.size;
			if (dev != argp->attributes.size)
				return NFSERR_INVAL;
#endif

			/* MvS: Some clients use chardev 0xFFFF for a FIFO. */
			if (S_ISCHR(argp->attributes.mode) && dev == 0xFFFF) {
				is_borc = 0;
				dev = 0;
				argp->attributes.mode &= ~S_IFMT;
				argp->attributes.mode |= S_IFIFO;
			}
		}
		else {
			is_borc = 0;
			dev = 0;
		}
		/* mknod will fail for EEXIST, we'll let it succeed. */
		if (!exists) {
#ifdef __linux__ /* XXX - MvS */
			/* Can't make UNIX sockets with mknod. */
			if (S_ISSOCK(argp->attributes.mode)) {
			  if ((s = socket(AF_UNIX, SOCK_STREAM, 0)) < 0)
			          return(nfs_errno());
			  sa.sun_family = AF_UNIX;
			  strncpy(sa.sun_path, pathbuf, sizeof(sa.sun_path));
			  if (bind(s, (struct sockaddr *)&sa, sizeof(sa)) < 0) {
				(void) close(s);
			        return(nfs_errno());
			  }
			  (void) close(s);
			} else
#endif
			if (mknod(pathbuf, argp->attributes.mode, dev) < 0)
				return (nfs_errno());
			if (stat(pathbuf, &sbuf) < 0)
				return (nfs_errno());
		}
		else {
			/* But make sure it's the same kind of special file. */
			if ((argp->attributes.mode & S_IFMT)
			    != (sbuf.st_mode & S_IFMT))
				return (NFSERR_EXIST);
			/* And that the major and minor numbers agree. */
			if (is_borc && dev != sbuf.st_rdev)
				return (NFSERR_EXIST);
		}
		tmpfd = -1;
	}
	else {
		flags = (argp->attributes.size == 0 ?
			CREATE_OMODE | O_TRUNC : CREATE_OMODE);
		if (!exists)
			flags |= O_CREAT;
		tmpfd = path_open(pathbuf, flags, 
				argp->attributes.mode & ~S_IFMT);
		if (tmpfd < 0)
			goto failure;
		(void) fstat(tmpfd, &sbuf);
	}

	/* creat() is equivalent to open(..., O_CREAT|O_TRUNC|O_WRONLY) */
	if (!exists) {
#ifndef ALLOW_SGIDDIR
		argp->attributes.gid = -1;
#endif
		/* Note: we ignore the size attribute because some clients
		 * create files with mode 0444. Since the file didn't exist
		 * previously, its length is zero anyway.
		 */
		status = setattr(pathbuf, &argp->attributes, &sbuf,
					rqstp, SATTR_ALL & ~SATTR_SIZE);
	} else {
		status = setattr(pathbuf, &argp->attributes, &sbuf,
					rqstp, SATTR_SIZE);
	}
	if (status != NFS_OK)
		return status;

	res = &result.diropres.diropres_u.diropres;
	status = fh_compose(&argp->where, &res->file, &sbuf,
			    tmpfd, CREATE_OMODE, 0);
	if (status != NFS_OK)
		goto failure;
	status = fh_getattr(&res->file, &res->attributes, &sbuf, rqstp);
	if (status != NFS_OK) {
		tmpfd = -1;	/* fd already stored in fh cache */
		goto failure;
	}
	Dprintf(D_CALL, "\tnew_fh = %s\n", fh_pr(&(res->file)));
	return (status);

failure:
	Dprintf(D_CALL, "\tcreate failed -- errno returned=%d.\n", errno);
	if (tmpfd != -1)
		close(tmpfd);
	return (errno? nfs_errno(): status);
}

#undef CREATE_OMODE

int
nfsd_nfsproc_remove_2(diropargs *argp, struct svc_req *rqstp)
{
	nfsstat status;

	status = build_path(rqstp, pathbuf, argp, CHK_WRITE | CHK_NOACCESS);
	if (status != NFS_OK)
		return ((int) status);

	Dprintf(D_CALL, "\tfullpath='%s'\n", pathbuf);

	/* Remove the file handle from our cache. */
	fh_remove(pathbuf);

	if (unlink(pathbuf) != 0)
		return (nfs_errno());
	else
		return (NFS_OK);
}

int nfsd_nfsproc_rename_2(argp, rqstp)
renameargs *argp;
struct svc_req	*rqstp;
{
	nfsstat status;

	status = build_path(rqstp, pathbuf, &argp->from, CHK_WRITE | CHK_NOACCESS);
	if (status != NFS_OK)
		return ((int) status);
	status = build_path(rqstp, pathbuf_1, &argp->to, CHK_WRITE | CHK_NOACCESS);
	if (status != NFS_OK)
		return ((int) status);

	Dprintf(D_CALL, "\tpathfrom='%s' pathto='%s'\n", pathbuf, pathbuf_1);

	/* Remove any file handle from our cache. */
	fh_remove(pathbuf);
	fh_remove(pathbuf_1);

	if (rename(pathbuf, pathbuf_1) != 0)
		return (nfs_errno());

	return (NFS_OK);
}

/* For now, we disallow hardlinks between different volumes for
 * security reasons. If we tried harder, we might be able to 
 * support them, but I'm not sure if it's worth it...
 */
int nfsd_nfsproc_link_2(argp, rqstp)
linkargs *argp;
struct svc_req	*rqstp;
{
	nfs_mount *mountp1;
	nfsstat status;
	fhcache *fhc;
	char *path;

	fhc = auth_fh(rqstp, &(argp->from), &status, CHK_WRITE | CHK_NOACCESS);
	if (fhc == NULL)
		return status;
	mountp1 = nfsmount;
	path = fhc->path;

	status = build_path(rqstp, pathbuf_1, &argp->to, CHK_WRITE | CHK_NOACCESS);
	if (status != NFS_OK)
		return ((int) status);

	Dprintf(D_CALL, "\tpathfrom='%s' pathto='%s'\n", path, pathbuf_1);

	if (nfsmount != mountp1) {
		Dprintf(D_CALL, "\tdenied link between different exports\n");
		return NFSERR_ACCES;
	}

	if (link(path, pathbuf_1) != 0)
		return (nfs_errno());
	return (NFS_OK);
}

int nfsd_nfsproc_symlink_2(argp, rqstp)
symlinkargs *argp;
struct svc_req	*rqstp;
{
	nfsstat status;

	status = build_path(rqstp, pathbuf, &argp->from, CHK_WRITE | CHK_NOACCESS);
	if (status != NFS_OK)
		return ((int) status);

	Dprintf(D_CALL, "\tstring='%s' filename='%s'\n", argp->to, pathbuf);

	if (symlink(argp->to, pathbuf) != 0)
		return (nfs_errno());

	/*
         * NFS version 2 documentation says "On UNIX servers the
	 * attributes are never used...". IMHO, utimes and maybe even
	 * owner may still matter.
         */
#ifndef ALLOW_SGIDDIR
	argp->attributes.gid = -1;
#endif
	status = setattr(pathbuf, &argp->attributes, NULL, rqstp,
				SATTR_CHOWN|SATTR_UTIMES);

	return status;
}

int
nfsd_nfsproc_mkdir_2(createargs *argp, struct svc_req *rqstp)
{
	nfsstat status;
	struct stat sbuf;
	diropokres *res;

	status = build_path(rqstp, pathbuf, &argp->where, CHK_WRITE | CHK_NOACCESS);
	if (status != NFS_OK)
		return ((int) status);

	Dprintf(D_CALL, "\tfullpath='%s'\n", pathbuf);

	if (mkdir(pathbuf, argp->attributes.mode) != 0)
		return (nfs_errno());

	res = &result.diropres.diropres_u.diropres;
	status = fh_compose(&(argp->where), &(res->file), &sbuf, -1, -1, 0);
	if (status != NFS_OK)
		return ((int) status);

#ifndef ALLOW_SGIDDIR
	argp->attributes.gid = -1;
#endif
	/* Inherit setgid bit from directory */
	argp->attributes.mode |= (sbuf.st_mode & S_ISGID);
	status = setattr(pathbuf, &argp->attributes, &sbuf, rqstp,
				SATTR_CHOWN|SATTR_CHMOD|SATTR_UTIMES);
	if (status != NFS_OK)
		return status;

	/* Note that the spb buffer is now invalid! */
	status = fh_getattr(&(res->file), &(res->attributes), NULL, rqstp);
	if (status == NFS_OK)
		Dprintf(D_CALL, "\tnew_fh = %s\n", fh_pr(&(res->file)));
	return ((int) status);
}

int nfsd_nfsproc_rmdir_2(argp, rqstp)
diropargs *argp;
struct svc_req	*rqstp;
{
	nfsstat status;

	status = build_path(rqstp, pathbuf, argp, CHK_WRITE | CHK_NOACCESS);
	if (status != NFS_OK)
		return ((int) status);

	Dprintf(D_CALL, "\tfullpath='%s'\n", pathbuf);

	/* Remove that file handle from our cache. */
	fh_remove(pathbuf);

	if (rmdir(pathbuf) != 0)
		return (nfs_errno());

	return (NFS_OK);
}

/* More Mark Shand code. */
static int dpsize(dp)
struct dirent *dp;
{
#define DP_SLOP	16
#define MAX_E_SIZE sizeof(entry) + NAME_MAX + DP_SLOP
	return (sizeof(entry) + NLENGTH(dp) + DP_SLOP);
}

int nfsd_nfsproc_readdir_2(argp, rqstp)
readdirargs *argp;
struct svc_req	*rqstp;
{
	static readdirres oldres;
	entry **e;
	__u32 dloc;
	DIR *dirp;
	struct dirent *dp;
	struct stat sbuf;
	int res_size;
	fhcache *h;
	nfsstat status;
	int hideit;

	/* Free the previous result, since it has 'malloc'ed strings.  */
	xdr_free((xdrproc_t)xdr_readdirres, (caddr_t) & oldres);

	h = auth_fh(rqstp, &(argp->dir), &status, CHK_READ);
	if (h == NULL)
		return status;
	hideit = ((!re_export && (h->flags & FHC_NFSMOUNTED))
			|| nfsmount->o.noaccess);

	/* This code is from Mark Shand's version */
	errno = 0;
	if (lstat(h->path, &sbuf) < 0 || !(S_ISDIR(sbuf.st_mode)))
		return (NFSERR_NOTDIR);
	if ((dirp = opendir(h->path)) == NULL)
		return ((errno ? nfs_errno() : NFSERR_NAMETOOLONG));

	res_size = 0;
	memcpy(&dloc, argp->cookie, sizeof(dloc));
	if (dloc != 0)
		seekdir(dirp, ntohl(dloc));
	e = &(result.readdirres.readdirres_u.reply.entries);
	while (((res_size + MAX_E_SIZE) < argp->count
		|| e == &(result.readdirres.readdirres_u.reply.entries))
	       && (dp = readdir(dirp)) != NULL) {
		if (hideit && strcmp(dp->d_name, ".") != 0
		    && strcmp(dp->d_name, "..") != 0) {
			dp = NULL;
			break;
		}
		*e = (entry *) xmalloc(sizeof(entry));
		(*e)->fileid = pseudo_inode(dp->d_ino, sbuf.st_dev);
		(*e)->name = xmalloc(NLENGTH(dp) + 1);
		strcpy((*e)->name, dp->d_name);
		dloc = htonl(telldir(dirp));
		memcpy(((*e)->cookie), &dloc, sizeof(nfscookie));
		e = &((*e)->nextentry);
		res_size += dpsize(dp);
	}
	*e = NULL;
	result.readdirres.readdirres_u.reply.eof = (dp == NULL);
	closedir(dirp);
	oldres = result.readdirres;
	return (result.readdirres.status);
}

/*
 * Only reports free space correctly for the filesystem that the
 * mount point is on.  Actually it will work fine for any file
 * handle (e.g. sub mounts) but the NFS spec calls for root_fh
 * to be used by the client when calling this.
 */
int nfsd_nfsproc_statfs_2(argp, rqstp)
nfs_fh *argp;
struct svc_req	*rqstp;
{
	nfsstat status;
	fhcache *fhc;
	char *path;
	struct fs_usage fs;

	fhc = auth_fh(rqstp, argp, &status, CHK_READ | CHK_NOACCESS);
	if (fhc == NULL)
		return status;
	path = fhc->path;

	if (get_fs_usage(path, NULL, &fs) < 0)
		return (nfs_errno());
	result.statfsres.status = NFS_OK;
	result.statfsres.statfsres_u.reply.tsize = 8*1024;
	result.statfsres.statfsres_u.reply.bsize = 512;
	result.statfsres.statfsres_u.reply.blocks = fs.fsu_blocks;
	result.statfsres.statfsres_u.reply.bfree = fs.fsu_bfree;
	result.statfsres.statfsres_u.reply.bavail = fs.fsu_bavail;

	return (NFS_OK);
}

int main(argc, argv)
int argc;
char *argv[];
{
	char	*auth_file = NULL;
	int	foreground = 0;
	int	nfsport = 0;
	int	failsafe_level = 0;
	int	c;
#ifdef MULTIPLE_SERVERS
	int	i, ncopies = 1;
#endif

	program_name = argv[0];
	chdir("/");

	/* Parse the command line options and arguments. */
	opterr = 0;
	while ((c = getopt_long(argc, argv, shortopts, longopts, NULL)) != EOF)
		switch (c) {
		case 'a':
			auth_daemon = optarg;
			break;
		case 'h':
			usage(stdout, 0);
			break;
		case 'd':
			enable_logging(optarg);
			break;
		case 'F':
			foreground = 1;
			break;
		case 'f':
			auth_file = optarg;
			break;
		case 'l':
			log_transfers = 1;
			break;
		case 'n':
			allow_non_root = 1;
			break;
		case 'P':
			nfsport = atoi(optarg);
			if (nfsport <= 0) {
				fprintf(stderr, "nfsd: bad port number: %s\n",
					optarg);
				usage(stderr, 1);
			}
			break;
		case 'p':
			promiscuous = 1;
			break;
		case 'r':
			re_export = 1;
			break;
		case 'R':
			public_root_path = xstrdup(optarg);
			break;
		case 't':
			trace_spoof = 0;
			break;
		case 'v':
			printf("%s\n", version);
			exit(0);
		case 'x':
			cross_mounts = 0;
			break;
		case 'z':
			if (optarg)
				failsafe_level = atoi(optarg);
			else
				failsafe_level = 1;
			break;
		case 0:
			break;
		case '?':
		default:
			usage(stderr, 1);
		}

#ifdef MULTIPLE_SERVERS
	if (optind == argc-1 && isdigit(argv[optind][0])) {
		ncopies = atoi(argv[optind++]);
		if (ncopies <= 0) {
			fprintf(stderr, 
			    "nfsd: illegal number of servers requested: %s\n",
						argv[optind]);
			exit (1);
		}
		if (foreground) {
			fprintf(stderr, "nfsd: warning: can run only "
					"one server in debug mode\n");
			ncopies = 1;
		}
	}
#endif

	/* No more arguments allowed. */
	if (optind != argc)
		usage(stderr, 1);

	/* Get the default NFS port */
	if (!nfsport) {
		struct servent	*sp;

		if (!(sp = getservbyname("nfs", "udp"))) {
			nfsport = NFS_PORT;
		} else {
			nfsport = ntohs(sp->s_port);
		}
	}

	/* Initialize logging. */
	log_open("nfsd", foreground);

	/* Initialize RPC stuff */
	rpc_init("nfsd", NFS_PROGRAM, nfsd_versions, nfs_dispatch,
				nfsport, NFS_MAXDATA);

	/* No more than 1 copy when run from inetd */
	if (_rpcpmstart && ncopies > 1) {
		Dprintf(L_WARNING,
				"nfsd: warning: can run only "
				"one server in inetd mode\n");
		ncopies = 1;
	}

#ifndef MULTIPLE_SERVERS_READWRITE
	if (ncopies > 1)
		read_only = 1;
#endif

	/* We first fork off a child. */
	if (!foreground) {
		if ((c = fork()) > 0)
			exit(0);
		if (c < 0) {
			Dprintf(L_FATAL, "nfsd: cannot fork: %s\n",
						strerror(errno));
		}
	}

	/* Initialize the AUTH module. */
	auth_init(auth_file);

	if (failsafe_level == 0) {
		/* Start multiple copies of the server */
		for (i = 1; i < ncopies; i++) {
			Dprintf(D_GENERAL, "Forking server thread...\n");
			if ((c = fork()) < 0) {
				Dprintf(L_ERROR, "Unable to fork: %s",
					strerror(errno));
			} else if (c == 0) {
				/* Child process */
				break;
			}
		}
	} else {
		/* Init for failsafe mode */
		failsafe(failsafe_level, ncopies);
	}

	/* Now that we've done all the required forks, we make do all the
	 * session magic.
	 */
	if (!foreground) {
		/* No more logging to stderr */
		background_logging();

		/* Now we remove ourselves from the foreground. */
		close(0);
		close(1);
		close(2);
#ifdef HAVE_SETSID
		setsid();
#else
		{
			int fd;
	
			if ((fd = open("/dev/tty", O_RDWR)) >= 0) {
				ioctl(fd, TIOCNOTTY, (char *) NULL);
				close(fd);
			}
		}
#endif
	}

	/* Initialize the FH module.
	 * This must happen after the fork(), otherwise the alarm timer
	 * will be reset.
	 */
	fh_init();

	/* Enable the LOG toggle with a signal. */
	install_signal_handler(SIGUSR1, toggle_logging);
#ifdef CALL_PROFILING
	install_signal_handler(SIGIOT,  dump_stats);
#endif
	install_signal_handler(SIGHUP,  reinitialize);
	install_signal_handler(SIGTERM, sigterm);
	atexit(terminate);

	/* Run the NFS server. */
	svc_run();

	Dprintf(L_ERROR, "Oh no Mr. Bill... nfs_server() returned!\n");
	exit(1);
}

static void usage(fp, n)
FILE *fp;
int n;
{
	fprintf(fp,"Usage: %s [-Fhnpv] [-d kind] [-f exports-file] [-P port]\n",
						program_name);
	fprintf(fp,"       [--debug kind] [--help] [--allow-non-root]\n");
	fprintf(fp,"       [--promiscuous] [--version] [--foreground]\n");
	fprintf(fp,"       [--exports-file=file] [--port port]\n");
	exit(n);
}

static RETSIGTYPE
sigterm(int sig)
{
	terminate();
	exit(1);
}

static void
terminate(void)
{
	rpc_exit(NFS_PROGRAM, nfsd_versions);
}

RETSIGTYPE reinitialize(sig)
{
	static volatile int	inprogress = 0;

	if (_rpcsvcdirty) {
		need_reinit = 1;
		return;
	}
	if (inprogress++)	/* Probably non-atomic. Yuck */
		return;
	auth_override_uid(0);	/* May need root privs to read exports */
	fh_flush(1);
	auth_init(NULL);	/* auth_init saves the exports file name */
	inprogress = 0;
	need_reinit = 0;
}