xref: /titanic_41/usr/src/cmd/fs.d/autofs/autod_nfs.c (revision 314609f3577728589434a6cda75ea45d075482c2)
1 /*
2  * CDDL HEADER START
3  *
4  * The contents of this file are subject to the terms of the
5  * Common Development and Distribution License (the "License").
6  * You may not use this file except in compliance with the License.
7  *
8  * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
9  * or http://www.opensolaris.org/os/licensing.
10  * See the License for the specific language governing permissions
11  * and limitations under the License.
12  *
13  * When distributing Covered Code, include this CDDL HEADER in each
14  * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
15  * If applicable, add the following below this CDDL HEADER, with the
16  * fields enclosed by brackets "[]" replaced with your own identifying
17  * information: Portions Copyright [yyyy] [name of copyright owner]
18  *
19  * CDDL HEADER END
20  */
21 /*
22  * Copyright 2006 Sun Microsystems, Inc.  All rights reserved.
23  * Use is subject to license terms.
24  */
25 
26 #pragma ident	"%Z%%M%	%I%	%E% SMI"
27 
28 #include <stdio.h>
29 #include <unistd.h>
30 #include <stdlib.h>
31 #include <ctype.h>
32 #include <syslog.h>
33 #include <string.h>
34 #include <deflt.h>
35 #include <kstat.h>
36 #include <sys/param.h>
37 #include <sys/types.h>
38 #include <sys/time.h>
39 #include <sys/stat.h>
40 #include <sys/wait.h>
41 #include <sys/socket.h>
42 #include <netinet/in.h>
43 #include <signal.h>
44 #include <sys/signal.h>
45 #include <rpc/rpc.h>
46 #include <rpc/pmap_clnt.h>
47 #include <sys/mount.h>
48 #include <sys/mntent.h>
49 #include <sys/mnttab.h>
50 #include <sys/fstyp.h>
51 #include <sys/fsid.h>
52 #include <arpa/inet.h>
53 #include <netdb.h>
54 #include <netconfig.h>
55 #include <netdir.h>
56 #include <errno.h>
57 #define	NFSCLIENT
58 #include <nfs/nfs.h>
59 #include <nfs/mount.h>
60 #include <rpcsvc/mount.h>
61 #include <rpc/nettype.h>
62 #include <locale.h>
63 #include <setjmp.h>
64 #include <sys/socket.h>
65 #include <thread.h>
66 #include <limits.h>
67 #include <nss_dbdefs.h>			/* for NSS_BUFLEN_HOSTS */
68 #include <nfs/nfs_sec.h>
69 #include <sys/sockio.h>
70 #include <net/if.h>
71 #include <assert.h>
72 #include <nfs/nfs_clnt.h>
73 #include <rpcsvc/nfs4_prot.h>
74 #define	NO_RDDIR_CACHE
75 #include "automount.h"
76 #include "replica.h"
77 #include "nfs_subr.h"
78 #include "webnfs.h"
79 #include <sys/sockio.h>
80 #include <net/if.h>
81 #include <assert.h>
82 #include <rpcsvc/daemon_utils.h>
83 #include <pwd.h>
84 #include <strings.h>
85 #include <tsol/label.h>
86 #include <zone.h>
87 
88 extern char *nfs_get_qop_name();
89 extern AUTH *nfs_create_ah();
90 extern enum snego_stat nfs_sec_nego();
91 
92 #define	MAXHOSTS	512
93 
94 /* number of transports to try */
95 #define	MNT_PREF_LISTLEN	2
96 #define	FIRST_TRY		1
97 #define	SECOND_TRY		2
98 
99 #define	MNTTYPE_CACHEFS "cachefs"
100 
101 /*
102  * host cache states
103  */
104 #define	NOHOST		0
105 #define	GOODHOST	1
106 #define	DEADHOST	2
107 
108 #define	NFS_ARGS_EXTB_secdata(args, secdata) \
109 	{ (args).nfs_args_ext = NFS_ARGS_EXTB, \
110 	(args).nfs_ext_u.nfs_extB.secdata = secdata; }
111 
112 struct cache_entry {
113 	struct	cache_entry *cache_next;
114 	char	*cache_host;
115 	time_t	cache_time;
116 	int	cache_state;
117 	rpcvers_t cache_reqvers;
118 	rpcvers_t cache_outvers;
119 	char	*cache_proto;
120 };
121 
122 struct mfs_snego_t {
123 	int sec_opt;
124 	bool_t snego_done;
125 	char *nfs_flavor;
126 	seconfig_t nfs_sec;
127 };
128 typedef struct mfs_snego_t mfs_snego_t;
129 
130 static struct cache_entry *cache_head = NULL;
131 rwlock_t cache_lock;	/* protect the cache chain */
132 
133 static enum nfsstat nfsmount(struct mapfs *, char *, char *, int, int,
134 	ucred_t *, action_list *);
135 static int is_nfs_port(char *);
136 
137 void netbuf_free(struct netbuf *);
138 struct knetconfig *get_knconf(struct netconfig *);
139 void free_knconf(struct knetconfig *);
140 static int get_pathconf(CLIENT *, char *, char *, struct pathcnf **, int);
141 static struct mapfs *enum_servers(struct mapent *, char *);
142 static struct mapfs *get_mysubnet_servers(struct mapfs *);
143 static int subnet_test(int af, struct sioc_addrreq *);
144 static	struct	netbuf *get_addr(char *, rpcprog_t, rpcvers_t,
145 	struct netconfig **, char *, ushort_t, struct t_info *);
146 
147 static	struct	netbuf *get_pubfh(char *, rpcvers_t, mfs_snego_t *,
148 	struct netconfig **, char *, ushort_t, struct t_info *, caddr_t *,
149 	bool_t, char *);
150 
151 static int create_homedir(const char *, const char *);
152 
153 enum type_of_stuff {
154 	SERVER_ADDR = 0,
155 	SERVER_PING = 1,
156 	SERVER_FH = 2
157 };
158 
159 void *get_server_stuff(enum type_of_stuff, char *, rpcprog_t,
160 	rpcvers_t, mfs_snego_t *, struct netconfig **, char *, ushort_t,
161 	struct t_info *, caddr_t *, bool_t, char *, enum clnt_stat *);
162 
163 void *get_the_stuff(enum type_of_stuff, char *, rpcprog_t,
164 	rpcvers_t, mfs_snego_t *, struct netconfig *, ushort_t, struct t_info *,
165 	caddr_t *, bool_t, char *, enum clnt_stat *);
166 
167 struct mapfs *add_mfs(struct mapfs *, int, struct mapfs **, struct mapfs **);
168 void free_mfs(struct mapfs *);
169 static void dump_mfs(struct mapfs *, char *, int);
170 static char *dump_distance(struct mapfs *);
171 static void cache_free(struct cache_entry *);
172 static int cache_check(char *, rpcvers_t *, char *);
173 static void cache_enter(char *, rpcvers_t, rpcvers_t, char *, int);
174 void destroy_auth_client_handle(CLIENT *cl);
175 
176 #ifdef CACHE_DEBUG
177 static void trace_host_cache();
178 static void trace_portmap_cache();
179 #endif /* CACHE_DEBUG */
180 
181 static int rpc_timeout = 20;
182 
183 #ifdef CACHE_DEBUG
184 /*
185  * host cache counters. These variables do not need to be protected
186  * by mutex's. They have been added to measure the utility of the
187  * goodhost/deadhost cache in the lazy hierarchical mounting scheme.
188  */
189 static int host_cache_accesses = 0;
190 static int host_cache_lookups = 0;
191 static int deadhost_cache_hits = 0;
192 static int goodhost_cache_hits = 0;
193 
194 /*
195  * portmap cache counters. These variables do not need to be protected
196  * by mutex's. They have been added to measure the utility of the portmap
197  * cache in the lazy hierarchical mounting scheme.
198  */
199 static int portmap_cache_accesses = 0;
200 static int portmap_cache_lookups = 0;
201 static int portmap_cache_hits = 0;
202 #endif /* CACHE_DEBUG */
203 
204 /*
205  * There are the defaults (range) for the client when determining
206  * which NFS version to use when probing the server (see above).
207  * These will only be used when the vers mount option is not used and
208  * these may be reset if /etc/default/nfs is configured to do so.
209  */
210 static rpcvers_t vers_max_default = NFS_VERSMAX_DEFAULT;
211 static rpcvers_t vers_min_default = NFS_VERSMIN_DEFAULT;
212 
213 /*
214  * list of support services needed
215  */
216 static char	*service_list[] = { STATD, LOCKD, NULL };
217 static char	*service_list_v4[] = { STATD, LOCKD, NFS4CBD, NFSMAPID, NULL };
218 
219 static void read_default_nfs(void);
220 static int is_v4_mount(char *);
221 static void start_nfs4cbd(void);
222 
223 int
224 mount_nfs(
225 	struct mapent *me,
226 	char *mntpnt,
227 	char *prevhost,
228 	int overlay,
229 	ucred_t	*cred,
230 	action_list **alpp)
231 {
232 	struct mapfs *mfs, *mp;
233 	int err = -1;
234 	int cached;
235 	action_list *alp;
236 
237 
238 	alp = *alpp;
239 
240 	read_default_nfs();
241 
242 	mfs = enum_servers(me, prevhost);
243 	if (mfs == NULL)
244 		return (ENOENT);
245 
246 	/*
247 	 * Try loopback if we have something on localhost; if nothing
248 	 * works, we will fall back to NFS
249 	 */
250 	if (is_nfs_port(me->map_mntopts)) {
251 		for (mp = mfs; mp; mp = mp->mfs_next) {
252 			if (self_check(mp->mfs_host)) {
253 				err = loopbackmount(mp->mfs_dir,
254 					mntpnt, me->map_mntopts, overlay);
255 				if (err) {
256 					mp->mfs_ignore = 1;
257 				} else {
258 					/*
259 					 * Free action_list if there
260 					 * is one as it is not needed.
261 					 * Make sure to set alpp to null
262 					 * so caller doesn't try to free it
263 					 * again.
264 					 */
265 					if (*alpp) {
266 						free(*alpp);
267 						*alpp = NULL;
268 					}
269 					break;
270 				}
271 			}
272 		}
273 	}
274 	if (err) {
275 		cached = strcmp(me->map_mounter, MNTTYPE_CACHEFS) == 0;
276 		err = nfsmount(mfs, mntpnt, me->map_mntopts,
277 				cached, overlay, cred, alp);
278 		if (err && trace > 1) {
279 			trace_prt(1, "	Couldn't mount %s:%s, err=%d\n",
280 				mfs->mfs_host, mfs->mfs_dir, err);
281 		}
282 	}
283 	free_mfs(mfs);
284 	return (err);
285 }
286 
287 
288 /*
289  * Using the new ioctl SIOCTONLINK to determine if a host is on the same
290  * subnet. Remove the old network, subnet check.
291  */
292 
293 static struct mapfs *
294 get_mysubnet_servers(struct mapfs *mfs_in)
295 {
296 	int s;
297 	struct mapfs *mfs, *p, *mfs_head = NULL, *mfs_tail = NULL;
298 
299 	struct netconfig *nconf;
300 	NCONF_HANDLE *nc = NULL;
301 	struct nd_hostserv hs;
302 	struct nd_addrlist *retaddrs;
303 	struct netbuf *nb;
304 	struct sioc_addrreq areq;
305 	int res;
306 	int af;
307 	int i;
308 	int sa_size;
309 
310 	hs.h_serv = "rpcbind";
311 
312 	for (mfs = mfs_in; mfs; mfs = mfs->mfs_next) {
313 		nc = setnetconfig();
314 
315 		while (nconf = getnetconfig(nc)) {
316 
317 			/*
318 			 * Care about INET family only. proto_done flag
319 			 * indicates if we have already covered this
320 			 * protocol family. If so skip it
321 			 */
322 			if (((strcmp(nconf->nc_protofmly, NC_INET6) == 0) ||
323 				(strcmp(nconf->nc_protofmly, NC_INET) == 0)) &&
324 				(nconf->nc_semantics == NC_TPI_CLTS)) {
325 			} else
326 				continue;
327 
328 			hs.h_host = mfs->mfs_host;
329 
330 			if (netdir_getbyname(nconf, &hs, &retaddrs) != ND_OK)
331 				continue;
332 
333 			/*
334 			 * For each host address see if it's on our
335 			 * local subnet.
336 			 */
337 
338 			if (strcmp(nconf->nc_protofmly, NC_INET6) == 0)
339 				af = AF_INET6;
340 			else
341 				af = AF_INET;
342 			nb = retaddrs->n_addrs;
343 			for (i = 0; i < retaddrs->n_cnt; i++, nb++) {
344 				memset(&areq.sa_addr, 0, sizeof (areq.sa_addr));
345 				memcpy(&areq.sa_addr, nb->buf, MIN(nb->len,
346 					sizeof (areq.sa_addr)));
347 				if (res = subnet_test(af, &areq)) {
348 					p = add_mfs(mfs, DIST_MYNET,
349 						&mfs_head, &mfs_tail);
350 					if (!p) {
351 						netdir_free(retaddrs,
352 							ND_ADDRLIST);
353 						endnetconfig(nc);
354 						return (NULL);
355 					}
356 					break;
357 				}
358 			}  /* end of every host */
359 			if (trace > 2) {
360 				trace_prt(1, "get_mysubnet_servers: host=%s "
361 					"netid=%s res=%s\n", mfs->mfs_host,
362 					nconf->nc_netid, res == 1?"SUC":"FAIL");
363 			}
364 
365 			netdir_free(retaddrs, ND_ADDRLIST);
366 		} /* end of while */
367 
368 		endnetconfig(nc);
369 
370 	} /* end of every map */
371 
372 	return (mfs_head);
373 
374 }
375 
376 int
377 subnet_test(int af, struct sioc_addrreq *areq)
378 {
379 	int s;
380 
381 	if ((s = socket(af, SOCK_DGRAM, 0)) < 0) {
382 		return (0);
383 	}
384 
385 	areq->sa_res = -1;
386 
387 	if (ioctl(s, SIOCTONLINK, (caddr_t)areq) < 0) {
388 		syslog(LOG_ERR, "subnet_test:SIOCTONLINK failed");
389 		return (0);
390 	}
391 	close(s);
392 	if (areq->sa_res == 1)
393 		return (1);
394 	else
395 		return (0);
396 
397 
398 }
399 
400 /*
401  * ping a bunch of hosts at once and sort by who responds first
402  */
403 static struct mapfs *
404 sort_servers(struct mapfs *mfs_in, int timeout)
405 {
406 	struct mapfs *m1 = NULL;
407 	enum clnt_stat clnt_stat;
408 
409 	if (!mfs_in)
410 		return (NULL);
411 
412 	clnt_stat = nfs_cast(mfs_in, &m1, timeout);
413 
414 	if (!m1) {
415 		char buff[2048] = {'\0'};
416 
417 		for (m1 = mfs_in; m1; m1 = m1->mfs_next) {
418 			(void) strcat(buff, m1->mfs_host);
419 			if (m1->mfs_next)
420 				(void) strcat(buff, ",");
421 		}
422 
423 		syslog(LOG_ERR, "servers %s not responding: %s",
424 			buff, clnt_sperrno(clnt_stat));
425 	}
426 
427 	return (m1);
428 }
429 
430 /*
431  * Add a mapfs entry to the list described by *mfs_head and *mfs_tail,
432  * provided it is not marked "ignored" and isn't a dupe of ones we've
433  * already seen.
434  */
435 struct mapfs *
436 add_mfs(struct mapfs *mfs, int distance, struct mapfs **mfs_head,
437 	struct mapfs **mfs_tail)
438 {
439 	struct mapfs *tmp, *new;
440 
441 	for (tmp = *mfs_head; tmp; tmp = tmp->mfs_next)
442 		if ((strcmp(tmp->mfs_host, mfs->mfs_host) == 0 &&
443 		    strcmp(tmp->mfs_dir, mfs->mfs_dir) == 0) ||
444 			mfs->mfs_ignore)
445 			return (*mfs_head);
446 	new = (struct mapfs *)malloc(sizeof (struct mapfs));
447 	if (!new) {
448 		syslog(LOG_ERR, "Memory allocation failed: %m");
449 		return (NULL);
450 	}
451 	bcopy(mfs, new, sizeof (struct mapfs));
452 	new->mfs_next = NULL;
453 	if (distance)
454 		new->mfs_distance = distance;
455 	if (!*mfs_head)
456 		*mfs_tail = *mfs_head = new;
457 	else {
458 		(*mfs_tail)->mfs_next = new;
459 		*mfs_tail = new;
460 	}
461 	return (*mfs_head);
462 }
463 
464 static void
465 dump_mfs(struct mapfs *mfs, char *message, int level)
466 {
467 	struct mapfs *m1;
468 
469 	if (trace <= level)
470 		return;
471 
472 	trace_prt(1, "%s", message);
473 	if (!mfs) {
474 		trace_prt(0, "mfs is null\n");
475 		return;
476 	}
477 	for (m1 = mfs; m1; m1 = m1->mfs_next)
478 		trace_prt(0, "%s[%s] ", m1->mfs_host, dump_distance(m1));
479 	trace_prt(0, "\n");
480 }
481 
482 static char *
483 dump_distance(struct mapfs *mfs)
484 {
485 	switch (mfs->mfs_distance) {
486 	case 0:			return ("zero");
487 	case DIST_SELF:		return ("self");
488 	case DIST_MYSUB:	return ("mysub");
489 	case DIST_MYNET:	return ("mynet");
490 	case DIST_OTHER:	return ("other");
491 	default:		return ("other");
492 	}
493 }
494 
495 /*
496  * Walk linked list "raw", building a new list consisting of members
497  * NOT found in list "filter", returning the result.
498  */
499 static struct mapfs *
500 filter_mfs(struct mapfs *raw, struct mapfs *filter)
501 {
502 	struct mapfs *mfs, *p, *mfs_head = NULL, *mfs_tail = NULL;
503 	int skip;
504 
505 	if (!raw)
506 		return (NULL);
507 	for (mfs = raw; mfs; mfs = mfs->mfs_next) {
508 		for (skip = 0, p = filter; p; p = p->mfs_next) {
509 			if (strcmp(p->mfs_host, mfs->mfs_host) == 0 &&
510 			    strcmp(p->mfs_dir, mfs->mfs_dir) == 0) {
511 				skip = 1;
512 				break;
513 			}
514 		}
515 		if (skip)
516 			continue;
517 		p = add_mfs(mfs, 0, &mfs_head, &mfs_tail);
518 		if (!p)
519 			return (NULL);
520 	}
521 	return (mfs_head);
522 }
523 
524 /*
525  * Walk a linked list of mapfs structs, freeing each member.
526  */
527 void
528 free_mfs(struct mapfs *mfs)
529 {
530 	struct mapfs *tmp;
531 
532 	while (mfs) {
533 		tmp = mfs->mfs_next;
534 		free(mfs);
535 		mfs = tmp;
536 	}
537 }
538 
539 /*
540  * New code for NFS client failover: we need to carry and sort
541  * lists of server possibilities rather than return a single
542  * entry.  It preserves previous behaviour of sorting first by
543  * locality (loopback-or-preferred/subnet/net/other) and then
544  * by ping times.  We'll short-circuit this process when we
545  * have ENOUGH or more entries.
546  */
547 static struct mapfs *
548 enum_servers(struct mapent *me, char *preferred)
549 {
550 	struct mapfs *p, *m1, *m2, *mfs_head = NULL, *mfs_tail = NULL;
551 
552 	/*
553 	 * Short-circuit for simple cases.
554 	 */
555 	if (!me->map_fs->mfs_next) {
556 		p = add_mfs(me->map_fs, DIST_OTHER, &mfs_head, &mfs_tail);
557 		if (!p)
558 			return (NULL);
559 		return (mfs_head);
560 	}
561 
562 	dump_mfs(me->map_fs, "	enum_servers: mapent: ", 2);
563 
564 	/*
565 	 * get addresses & see if any are myself
566 	 * or were mounted from previously in a
567 	 * hierarchical mount.
568 	 */
569 	if (trace > 2)
570 		trace_prt(1, "	enum_servers: looking for pref/self\n");
571 	for (m1 = me->map_fs; m1; m1 = m1->mfs_next) {
572 		if (m1->mfs_ignore)
573 			continue;
574 		if (self_check(m1->mfs_host) ||
575 		    strcmp(m1->mfs_host, preferred) == 0) {
576 			p = add_mfs(m1, DIST_SELF, &mfs_head, &mfs_tail);
577 			if (!p)
578 				return (NULL);
579 		}
580 	}
581 	if (trace > 2 && m1)
582 		trace_prt(1, "	enum_servers: pref/self found, %s\n",
583 			m1->mfs_host);
584 
585 	/*
586 	 * look for entries on this subnet
587 	 */
588 	dump_mfs(m1, "	enum_servers: input of get_mysubnet_servers: ", 2);
589 	m1 = get_mysubnet_servers(me->map_fs);
590 	dump_mfs(m1, "	enum_servers: output of get_mysubnet_servers: ", 3);
591 	if (m1 && m1->mfs_next) {
592 		m2 = sort_servers(m1, rpc_timeout / 2);
593 		dump_mfs(m2, "	enum_servers: output of sort_servers: ", 3);
594 		free_mfs(m1);
595 		m1 = m2;
596 	}
597 
598 	for (m2 = m1; m2; m2 = m2->mfs_next) {
599 		p = add_mfs(m2, 0, &mfs_head, &mfs_tail);
600 		if (!p)
601 			return (NULL);
602 	}
603 	if (m1)
604 		free_mfs(m1);
605 
606 	/*
607 	 * add the rest of the entries at the end
608 	 */
609 	m1 = filter_mfs(me->map_fs, mfs_head);
610 	dump_mfs(m1, "	enum_servers: etc: output of filter_mfs: ", 3);
611 	m2 = sort_servers(m1, rpc_timeout / 2);
612 	dump_mfs(m2, "	enum_servers: etc: output of sort_servers: ", 3);
613 	if (m1)
614 		free_mfs(m1);
615 	m1 = m2;
616 	for (m2 = m1; m2; m2 = m2->mfs_next) {
617 		p = add_mfs(m2, DIST_OTHER, &mfs_head, &mfs_tail);
618 		if (!p)
619 			return (NULL);
620 	}
621 	if (m1)
622 		free_mfs(m1);
623 
624 done:
625 	dump_mfs(mfs_head, "  enum_servers: output: ", 1);
626 	return (mfs_head);
627 }
628 
629 static enum nfsstat
630 nfsmount(
631 	struct mapfs *mfs_in,
632 	char *mntpnt, char *opts,
633 	int cached, int overlay,
634 	ucred_t	*cred,
635 	action_list *alp)
636 {
637 	CLIENT *cl;
638 	char remname[MAXPATHLEN], *mnttabtext = NULL;
639 	char mopts[MAX_MNTOPT_STR];
640 	char netname[MAXNETNAMELEN+1];
641 	char	*mntopts = NULL;
642 	int mnttabcnt = 0;
643 	int loglevel;
644 	struct mnttab m;
645 	struct nfs_args *argp = NULL, *head = NULL, *tail = NULL,
646 		*prevhead, *prevtail;
647 	int flags;
648 	struct fhstatus fhs;
649 	struct timeval timeout;
650 	enum clnt_stat rpc_stat;
651 	enum nfsstat status;
652 	struct stat stbuf;
653 	struct netconfig *nconf;
654 	rpcvers_t vers, versmin; /* used to negotiate nfs version in pingnfs */
655 				/* and mount version with mountd */
656 	rpcvers_t outvers;	/* final version to be used during mount() */
657 	rpcvers_t nfsvers;	/* version in map options, 0 if not there */
658 	rpcvers_t mountversmax;	/* tracks the max mountvers during retries */
659 
660 	/* used to negotiate nfs version using webnfs */
661 	rpcvers_t pubvers, pubversmin, pubversmax;
662 	int posix;
663 	struct nd_addrlist *retaddrs;
664 	struct mountres3 res3;
665 	nfs_fh3 fh3;
666 	char *fstype;
667 	int count, i;
668 	char scerror_msg[MAXMSGLEN];
669 	int *auths;
670 	int delay;
671 	int retries;
672 	char *nfs_proto = NULL;
673 	uint_t nfs_port = 0;
674 	char *p, *host, *dir;
675 	struct mapfs *mfs = NULL;
676 	int error, last_error = 0;
677 	int replicated;
678 	int entries = 0;
679 	int v2cnt = 0, v3cnt = 0, v4cnt = 0;
680 	int v2near = 0, v3near = 0, v4near = 0;
681 	int skipentry = 0;
682 	char *nfs_flavor;
683 	seconfig_t nfs_sec;
684 	int sec_opt, scerror;
685 	struct sec_data *secdata;
686 	int secflags;
687 	struct netbuf *syncaddr;
688 	bool_t	use_pubfh;
689 	ushort_t thisport;
690 	int got_val;
691 	mfs_snego_t mfssnego_init, mfssnego;
692 
693 	dump_mfs(mfs_in, "  nfsmount: input: ", 2);
694 	replicated = (mfs_in->mfs_next != NULL);
695 	m.mnt_mntopts = opts;
696 	if (replicated && hasmntopt(&m, MNTOPT_SOFT)) {
697 		if (verbose)
698 			syslog(LOG_WARNING,
699 		    "mount on %s is soft and will not be replicated.", mntpnt);
700 		replicated = 0;
701 	}
702 	if (replicated && !hasmntopt(&m, MNTOPT_RO)) {
703 		if (verbose)
704 			syslog(LOG_WARNING,
705 		    "mount on %s is not read-only and will not be replicated.",
706 			    mntpnt);
707 		replicated = 0;
708 	}
709 	if (replicated && cached) {
710 		if (verbose)
711 			syslog(LOG_WARNING,
712 		    "mount on %s is cached and will not be replicated.",
713 			mntpnt);
714 		replicated = 0;
715 	}
716 	if (replicated)
717 		loglevel = LOG_WARNING;
718 	else
719 		loglevel = LOG_ERR;
720 
721 	if (trace > 1) {
722 		if (replicated)
723 			trace_prt(1, "	nfsmount: replicated mount on %s %s:\n",
724 				mntpnt, opts);
725 		else
726 			trace_prt(1, "	nfsmount: standard mount on %s %s:\n",
727 				mntpnt, opts);
728 		for (mfs = mfs_in; mfs; mfs = mfs->mfs_next)
729 			trace_prt(1, "	  %s:%s\n",
730 				mfs->mfs_host, mfs->mfs_dir);
731 	}
732 
733 	/*
734 	 * Make sure mountpoint is safe to mount on
735 	 */
736 	if (lstat(mntpnt, &stbuf) < 0) {
737 		syslog(LOG_ERR, "Couldn't stat %s: %m", mntpnt);
738 		return (NFSERR_NOENT);
739 	}
740 
741 	/*
742 	 * Get protocol specified in options list, if any.
743 	 */
744 	if ((str_opt(&m, "proto", &nfs_proto)) == -1) {
745 		return (NFSERR_NOENT);
746 	}
747 
748 	/*
749 	 * Get port specified in options list, if any.
750 	 */
751 	got_val = nopt(&m, MNTOPT_PORT, (int *)&nfs_port);
752 	if (!got_val)
753 		nfs_port = 0;	/* "unspecified" */
754 	if (nfs_port > USHRT_MAX) {
755 		syslog(LOG_ERR, "%s: invalid port number %d", mntpnt, nfs_port);
756 		return (NFSERR_NOENT);
757 	}
758 
759 	/*
760 	 * Set mount(2) flags here, outside of the loop.
761 	 */
762 	flags = MS_OPTIONSTR;
763 	flags |= (hasmntopt(&m, MNTOPT_RO) == NULL) ? 0 : MS_RDONLY;
764 	flags |= (hasmntopt(&m, MNTOPT_NOSUID) == NULL) ? 0 : MS_NOSUID;
765 	flags |= overlay ? MS_OVERLAY : 0;
766 	if (mntpnt[strlen(mntpnt) - 1] != ' ')
767 		/* direct mount point without offsets */
768 		flags |= MS_OVERLAY;
769 
770 	use_pubfh = (hasmntopt(&m, MNTOPT_PUBLIC) == NULL) ? FALSE : TRUE;
771 
772 	(void) memset(&mfssnego_init, 0, sizeof (mfs_snego_t));
773 	if (hasmntopt(&m, MNTOPT_SECURE) != NULL) {
774 		if (++mfssnego_init.sec_opt > 1) {
775 			syslog(loglevel,
776 			    "conflicting security options");
777 			return (NFSERR_IO);
778 		}
779 		if (nfs_getseconfig_byname("dh", &mfssnego_init.nfs_sec)) {
780 			syslog(loglevel,
781 			    "error getting dh information from %s",
782 			    NFSSEC_CONF);
783 			return (NFSERR_IO);
784 		}
785 	}
786 
787 	/*
788 	 * Have to workaround the fact that hasmntopt() returns true
789 	 * when comparing "secure" (in &m) with "sec".
790 	 */
791 	if (hasmntopt(&m, "sec=") != NULL) {
792 		if ((str_opt(&m, MNTOPT_SEC,
793 			&mfssnego_init.nfs_flavor)) == -1) {
794 			syslog(LOG_ERR, "nfsmount: no memory");
795 			return (NFSERR_IO);
796 		}
797 	}
798 
799 	if (mfssnego_init.nfs_flavor) {
800 		if (++mfssnego_init.sec_opt > 1) {
801 			syslog(loglevel,
802 			    "conflicting security options");
803 			free(mfssnego_init.nfs_flavor);
804 			return (NFSERR_IO);
805 		}
806 		if (nfs_getseconfig_byname(mfssnego_init.nfs_flavor,
807 			&mfssnego_init.nfs_sec)) {
808 			syslog(loglevel,
809 			    "error getting %s information from %s",
810 			    mfssnego_init.nfs_flavor, NFSSEC_CONF);
811 			free(mfssnego_init.nfs_flavor);
812 			return (NFSERR_IO);
813 		}
814 		free(mfssnego_init.nfs_flavor);
815 	}
816 
817 nextentry:
818 	skipentry = 0;
819 
820 	got_val = nopt(&m, MNTOPT_VERS, (int *)&nfsvers);
821 	if (!got_val)
822 		nfsvers = 0;	/* "unspecified" */
823 	if (set_versrange(nfsvers, &vers, &versmin) != 0) {
824 		syslog(LOG_ERR, "Incorrect NFS version specified for %s",
825 			mntpnt);
826 		last_error = NFSERR_NOENT;
827 		goto ret;
828 	}
829 
830 	if (nfsvers != 0) {
831 		pubversmax = pubversmin = nfsvers;
832 	} else {
833 		pubversmax = vers;
834 		pubversmin = versmin;
835 	}
836 
837 	/*
838 	 * Walk the whole list, pinging and collecting version
839 	 * info so that we can make sure the mount will be
840 	 * homogeneous with respect to version.
841 	 *
842 	 * If we have a version preference, this is easy; we'll
843 	 * just reject anything that doesn't match.
844 	 *
845 	 * If not, we want to try to provide the best compromise
846 	 * that considers proximity, preference for a higher version,
847 	 * sorted order, and number of replicas.  We will count
848 	 * the number of V2 and V3 replicas and also the number
849 	 * which are "near", i.e. the localhost or on the same
850 	 * subnet.
851 	 */
852 	for (mfs = mfs_in; mfs; mfs = mfs->mfs_next) {
853 
854 
855 		if (mfs->mfs_ignore)
856 			continue;
857 
858 		host = mfs->mfs_host;
859 		(void) memcpy(&mfssnego, &mfssnego_init, sizeof (mfs_snego_t));
860 
861 		if (use_pubfh == TRUE || mfs->mfs_flags & MFS_URL) {
862 			char *path;
863 
864 			if (nfs_port != 0 && mfs->mfs_port != 0 &&
865 			    nfs_port != mfs->mfs_port) {
866 
867 				syslog(LOG_ERR, "nfsmount: port (%u) in nfs URL"
868 					" not the same as port (%d) in port "
869 					"option\n", mfs->mfs_port, nfs_port);
870 				last_error = NFSERR_IO;
871 				goto out;
872 
873 			} else if (nfs_port != 0)
874 				thisport = nfs_port;
875 			else
876 				thisport = mfs->mfs_port;
877 
878 			dir = mfs->mfs_dir;
879 
880 			if ((mfs->mfs_flags & MFS_URL) == 0) {
881 				path = malloc(strlen(dir) + 2);
882 				if (path == NULL) {
883 					syslog(LOG_ERR, "nfsmount: no memory");
884 					last_error = NFSERR_IO;
885 					goto out;
886 				}
887 				path[0] = (char)WNL_NATIVEPATH;
888 				(void) strcpy(&path[1], dir);
889 			} else {
890 				path = dir;
891 			}
892 
893 			argp = (struct nfs_args *)
894 				malloc(sizeof (struct nfs_args));
895 
896 			if (!argp) {
897 				if (path != dir)
898 					free(path);
899 				syslog(LOG_ERR, "nfsmount: no memory");
900 				last_error = NFSERR_IO;
901 				goto out;
902 			}
903 			(void) memset(argp, 0, sizeof (*argp));
904 
905 			/*
906 			 * RDMA support
907 			 * By now Mount argument struct has been allocated,
908 			 * either a pub_fh path will be taken or the regular
909 			 * one. So here if a protocol was specified and it
910 			 * was not rdma we let it be, else we set DO_RDMA.
911 			 * If no proto was there we advise on trying RDMA.
912 			 */
913 			if (nfs_proto) {
914 				if (strcmp(nfs_proto, "rdma") == 0) {
915 					free(nfs_proto);
916 					nfs_proto = NULL;
917 					argp->flags |= NFSMNT_DORDMA;
918 				}
919 			} else
920 				argp->flags |= NFSMNT_TRYRDMA;
921 
922 			for (pubvers = pubversmax; pubvers >= pubversmin;
923 			    pubvers--) {
924 
925 				nconf = NULL;
926 				argp->addr = get_pubfh(host, pubvers, &mfssnego,
927 				    &nconf, nfs_proto, thisport, NULL,
928 				    &argp->fh, TRUE, path);
929 
930 				if (argp->addr != NULL)
931 					break;
932 
933 				if (nconf != NULL)
934 					freenetconfigent(nconf);
935 			}
936 
937 			if (path != dir)
938 				free(path);
939 
940 			if (argp->addr != NULL) {
941 
942 				/*
943 				 * The use of llock option for NFSv4
944 				 * mounts is not required since file
945 				 * locking is included within the protocol
946 				 */
947 				if (pubvers != NFS_V4)
948 					argp->flags |= NFSMNT_LLOCK;
949 
950 				argp->flags |= NFSMNT_PUBLIC;
951 
952 				mfs->mfs_args = argp;
953 				mfs->mfs_version = pubvers;
954 				mfs->mfs_nconf = nconf;
955 				mfs->mfs_flags |= MFS_FH_VIA_WEBNFS;
956 
957 			} else {
958 				free(argp);
959 
960 				/*
961 				 * If -public was specified, give up
962 				 * on this entry now.
963 				 */
964 				if (use_pubfh == TRUE) {
965 					syslog(loglevel,
966 					    "%s: no public file handle support",
967 					    host);
968 					last_error = NFSERR_NOENT;
969 					mfs->mfs_ignore = 1;
970 					continue;
971 				}
972 
973 				/*
974 				 * Back off to a conventional mount.
975 				 *
976 				 * URL's can contain escape characters. Get
977 				 * rid of them.
978 				 */
979 				path = malloc(strlen(dir) + 2);
980 
981 				if (path == NULL) {
982 					syslog(LOG_ERR, "nfsmount: no memory");
983 					last_error = NFSERR_IO;
984 					goto out;
985 				}
986 
987 				strcpy(path, dir);
988 				URLparse(path);
989 				mfs->mfs_dir = path;
990 				mfs->mfs_flags |= MFS_ALLOC_DIR;
991 				mfs->mfs_flags &= ~MFS_URL;
992 			}
993 		}
994 
995 		if ((mfs->mfs_flags & MFS_FH_VIA_WEBNFS) ==  0) {
996 			i = pingnfs(host, get_retry(opts) + 1, &vers, versmin,
997 				0, FALSE, NULL, nfs_proto);
998 			if (i != RPC_SUCCESS) {
999 				if (i == RPC_PROGVERSMISMATCH) {
1000 					syslog(loglevel, "server %s: NFS "
1001 						"protocol version mismatch",
1002 						host);
1003 				} else {
1004 					syslog(loglevel, "server %s not "
1005 						"responding", host);
1006 				}
1007 				mfs->mfs_ignore = 1;
1008 				last_error = NFSERR_NOENT;
1009 				continue;
1010 			}
1011 			if (nfsvers != 0 && nfsvers != vers) {
1012 				if (nfs_proto == NULL)
1013 					syslog(loglevel,
1014 						"NFS version %d "
1015 						"not supported by %s",
1016 						nfsvers, host);
1017 				else
1018 					syslog(loglevel,
1019 						"NFS version %d "
1020 						"with proto %s "
1021 						"not supported by %s",
1022 						nfsvers, nfs_proto, host);
1023 				mfs->mfs_ignore = 1;
1024 				last_error = NFSERR_NOENT;
1025 				continue;
1026 			}
1027 		}
1028 
1029 		switch (vers) {
1030 		case NFS_V4: v4cnt++; break;
1031 		case NFS_V3: v3cnt++; break;
1032 		case NFS_VERSION: v2cnt++; break;
1033 		default: break;
1034 		}
1035 
1036 		/*
1037 		 * It's not clear how useful this stuff is if
1038 		 * we are using webnfs across the internet, but it
1039 		 * can't hurt.
1040 		 */
1041 		if (mfs->mfs_distance &&
1042 		    mfs->mfs_distance <= DIST_MYSUB) {
1043 			switch (vers) {
1044 			case NFS_V4: v4near++; break;
1045 			case NFS_V3: v3near++; break;
1046 			case NFS_VERSION: v2near++; break;
1047 			default: break;
1048 			}
1049 		}
1050 
1051 		/*
1052 		 * If the mount is not replicated, we don't want to
1053 		 * ping every entry, so we'll stop here.  This means
1054 		 * that we may have to go back to "nextentry" above
1055 		 * to consider another entry if there we can't get
1056 		 * all the way to mount(2) with this one.
1057 		 */
1058 		if (!replicated)
1059 			break;
1060 	}
1061 
1062 	if (nfsvers == 0) {
1063 		/*
1064 		 * Choose the NFS version.
1065 		 * We prefer higher versions, but will choose a one-
1066 		 * version downgrade in service if we can use a local
1067 		 * network interface and avoid a router.
1068 		 */
1069 		if (v4cnt && v4cnt >= v3cnt && (v4near || !v3near))
1070 			nfsvers = NFS_V4;
1071 		else if (v3cnt && v3cnt >= v2cnt && (v3near || !v2near))
1072 			nfsvers = NFS_V3;
1073 		else
1074 			nfsvers = NFS_VERSION;
1075 		if (trace > 2)
1076 			trace_prt(1,
1077 		    "  nfsmount: v4=%d[%d]v3=%d[%d],v2=%d[%d] => v%d.\n",
1078 			    v4cnt, v4near, v3cnt, v3near,
1079 			    v2cnt, v2near, nfsvers);
1080 	}
1081 
1082 	/*
1083 	 * Since we don't support different NFS versions in replicated
1084 	 * mounts, set fstype now.
1085 	 * Also take the opportunity to set
1086 	 * the mount protocol version as appropriate.
1087 	 */
1088 	switch (nfsvers) {
1089 	case NFS_V4:
1090 		fstype = MNTTYPE_NFS4;
1091 		break;
1092 	case NFS_V3:
1093 		fstype = MNTTYPE_NFS3;
1094 		if (use_pubfh == FALSE) {
1095 			mountversmax = MOUNTVERS3;
1096 			versmin = MOUNTVERS3;
1097 		}
1098 		break;
1099 	case NFS_VERSION:
1100 		fstype = MNTTYPE_NFS;
1101 		if (use_pubfh == FALSE) {
1102 			mountversmax = MOUNTVERS_POSIX;
1103 			versmin = MOUNTVERS;
1104 		}
1105 		break;
1106 	}
1107 
1108 	/*
1109 	 * Our goal here is to evaluate each of several possible
1110 	 * replicas and try to come up with a list we can hand
1111 	 * to mount(2).  If we don't have a valid "head" at the
1112 	 * end of this process, it means we have rejected all
1113 	 * potential server:/path tuples.  We will fail quietly
1114 	 * in front of mount(2), and will have printed errors
1115 	 * where we found them.
1116 	 * XXX - do option work outside loop w careful design
1117 	 * XXX - use macro for error condition free handling
1118 	 */
1119 	for (mfs = mfs_in; mfs; mfs = mfs->mfs_next) {
1120 
1121 		/*
1122 		 * Initialize retry and delay values on a per-server basis.
1123 		 */
1124 		retries = get_retry(opts);
1125 		delay = INITDELAY;
1126 retry:
1127 		if (mfs->mfs_ignore)
1128 			continue;
1129 
1130 		/*
1131 		 * If we don't have a fh yet, and if this is not a replicated
1132 		 * mount, we haven't done a pingnfs() on the next entry,
1133 		 * so we don't know if the next entry is up or if it
1134 		 * supports an NFS version we like.  So if we had a problem
1135 		 * with an entry, we need to go back and run through some new
1136 		 * code.
1137 		 */
1138 		if ((mfs->mfs_flags & MFS_FH_VIA_WEBNFS) == 0 &&
1139 		    !replicated && skipentry)
1140 			goto nextentry;
1141 
1142 		vers = mountversmax;
1143 		host = mfs->mfs_host;
1144 		dir = mfs->mfs_dir;
1145 		(void) sprintf(remname, "%s:%s", host, dir);
1146 		if (trace > 4 && replicated)
1147 			trace_prt(1, "	nfsmount: examining %s\n", remname);
1148 
1149 		/*
1150 		 * If it's cached we need to get cachefs to mount it.
1151 		 */
1152 		if (cached) {
1153 			char *copts = opts;
1154 
1155 			/*
1156 			 * If we started with a URL we need to turn on
1157 			 * -o public if not on already
1158 			 */
1159 			if (use_pubfh == FALSE &&
1160 			    (mfs->mfs_flags & MFS_FH_VIA_WEBNFS)) {
1161 
1162 				copts = malloc(strlen(opts) +
1163 					strlen(",public")+1);
1164 
1165 				if (copts == NULL) {
1166 					syslog(LOG_ERR, "nfsmount: no memory");
1167 					last_error = NFSERR_IO;
1168 					goto out;
1169 				}
1170 
1171 				strcpy(copts, opts);
1172 
1173 				if (strlen(copts) != 0)
1174 					strcat(copts, ",");
1175 
1176 				strcat(copts, "public");
1177 			}
1178 
1179 			last_error = mount_generic(remname, MNTTYPE_CACHEFS,
1180 				copts, mntpnt, overlay);
1181 
1182 			if (copts != opts)
1183 				free(copts);
1184 
1185 			if (last_error) {
1186 				skipentry = 1;
1187 				mfs->mfs_ignore = 1;
1188 				continue;
1189 			}
1190 			goto out;
1191 		}
1192 
1193 		if (mfs->mfs_args == NULL) {
1194 
1195 			/*
1196 			 * Allocate nfs_args structure
1197 			 */
1198 			argp = (struct nfs_args *)
1199 				malloc(sizeof (struct nfs_args));
1200 
1201 			if (!argp) {
1202 				syslog(LOG_ERR, "nfsmount: no memory");
1203 				last_error = NFSERR_IO;
1204 				goto out;
1205 			}
1206 
1207 			(void) memset(argp, 0, sizeof (*argp));
1208 
1209 			/*
1210 			 * RDMA support
1211 			 * By now Mount argument struct has been allocated,
1212 			 * either a pub_fh path will be taken or the regular
1213 			 * one. So here if a protocol was specified and it
1214 			 * was not rdma we let it be, else we set DO_RDMA.
1215 			 * If no proto was there we advise on trying RDMA.
1216 			 */
1217 			if (nfs_proto) {
1218 				if (strcmp(nfs_proto, "rdma") == 0) {
1219 					free(nfs_proto);
1220 					nfs_proto = NULL;
1221 					argp->flags |= NFSMNT_DORDMA;
1222 				}
1223 			} else
1224 				argp->flags |= NFSMNT_TRYRDMA;
1225 		} else {
1226 			argp = mfs->mfs_args;
1227 			mfs->mfs_args = NULL;
1228 
1229 			/*
1230 			 * Skip entry if we already have file handle but the
1231 			 * NFS version is wrong.
1232 			 */
1233 			if ((mfs->mfs_flags & MFS_FH_VIA_WEBNFS) &&
1234 			    mfs->mfs_version != nfsvers) {
1235 
1236 				free(argp);
1237 				skipentry = 1;
1238 				mfs->mfs_ignore = 1;
1239 				continue;
1240 			}
1241 		}
1242 
1243 		prevhead = head;
1244 		prevtail = tail;
1245 		if (!head)
1246 			head = tail = argp;
1247 		else
1248 			tail = tail->nfs_ext_u.nfs_extB.next = argp;
1249 
1250 		/*
1251 		 * WebNFS and NFSv4 behave similarly in that they
1252 		 * don't use the mount protocol.  Therefore, avoid
1253 		 * mount protocol like things when version 4 is being
1254 		 * used.
1255 		 */
1256 		if ((mfs->mfs_flags & MFS_FH_VIA_WEBNFS) == 0 &&
1257 			nfsvers != NFS_V4) {
1258 		    timeout.tv_usec = 0;
1259 		    timeout.tv_sec = rpc_timeout;
1260 		    rpc_stat = RPC_TIMEDOUT;
1261 
1262 		    /* Create the client handle. */
1263 
1264 		    if (trace > 1) {
1265 			trace_prt(1, "  nfsmount: Get mount version: request "
1266 			    "vers=%d min=%d\n", vers, versmin);
1267 		    }
1268 
1269 		    while ((cl = clnt_create_vers(host, MOUNTPROG, &outvers,
1270 			versmin, vers, "udp")) == NULL) {
1271 			if (trace > 4) {
1272 			    trace_prt(1,
1273 			    "  nfsmount: Can't get mount version: rpcerr=%d\n",
1274 			    rpc_createerr.cf_stat);
1275 			}
1276 			if (rpc_createerr.cf_stat == RPC_UNKNOWNHOST ||
1277 			    rpc_createerr.cf_stat == RPC_TIMEDOUT)
1278 				break;
1279 
1280 			/*
1281 			 * backoff and return lower version to retry the ping.
1282 			 * XXX we should be more careful and handle
1283 			 * RPC_PROGVERSMISMATCH here, because that error
1284 			 * is handled in clnt_create_vers(). It's not done to
1285 			 * stay in sync with the nfs mount command.
1286 			 */
1287 			vers--;
1288 			if (vers < versmin)
1289 				break;
1290 			if (trace > 4) {
1291 			    trace_prt(1, "  nfsmount: Try version=%d\n", vers);
1292 			}
1293 		    }
1294 
1295 		    if (cl == NULL) {
1296 			free(argp);
1297 			head = prevhead;
1298 			tail = prevtail;
1299 			if (tail)
1300 				tail->nfs_ext_u.nfs_extB.next = NULL;
1301 			last_error = NFSERR_NOENT;
1302 
1303 			if (rpc_createerr.cf_stat != RPC_UNKNOWNHOST &&
1304 			    rpc_createerr.cf_stat != RPC_PROGVERSMISMATCH &&
1305 			    retries-- > 0) {
1306 				DELAY(delay)
1307 				goto retry;
1308 			}
1309 
1310 			syslog(loglevel, "%s %s", host,
1311 				clnt_spcreateerror("server not responding"));
1312 			skipentry = 1;
1313 			mfs->mfs_ignore = 1;
1314 			continue;
1315 		    }
1316 		    if (trace > 1) {
1317 			trace_prt(1, "	nfsmount: mount version=%d\n", outvers);
1318 		    }
1319 #ifdef MALLOC_DEBUG
1320 		    add_alloc("CLNT_HANDLE", cl, 0, __FILE__, __LINE__);
1321 		    add_alloc("AUTH_HANDLE", cl->cl_auth, 0,
1322 			__FILE__, __LINE__);
1323 #endif
1324 
1325 		    if (__clnt_bindresvport(cl) < 0) {
1326 			free(argp);
1327 			head = prevhead;
1328 			tail = prevtail;
1329 			if (tail)
1330 				tail->nfs_ext_u.nfs_extB.next = NULL;
1331 			last_error = NFSERR_NOENT;
1332 
1333 			if (retries-- > 0) {
1334 				destroy_auth_client_handle(cl);
1335 				DELAY(delay);
1336 				goto retry;
1337 			}
1338 
1339 			syslog(loglevel, "mount %s: %s", host,
1340 				"Couldn't bind to reserved port");
1341 			destroy_auth_client_handle(cl);
1342 			skipentry = 1;
1343 			mfs->mfs_ignore = 1;
1344 			continue;
1345 		    }
1346 
1347 #ifdef MALLOC_DEBUG
1348 		    drop_alloc("AUTH_HANDLE", cl->cl_auth, __FILE__, __LINE__);
1349 #endif
1350 		    AUTH_DESTROY(cl->cl_auth);
1351 		    if ((cl->cl_auth = authsys_create_default()) == NULL) {
1352 			free(argp);
1353 			head = prevhead;
1354 			tail = prevtail;
1355 			if (tail)
1356 				tail->nfs_ext_u.nfs_extB.next = NULL;
1357 			last_error = NFSERR_NOENT;
1358 
1359 			if (retries-- > 0) {
1360 				destroy_auth_client_handle(cl);
1361 				DELAY(delay);
1362 				goto retry;
1363 			}
1364 
1365 			syslog(loglevel, "mount %s: %s", host,
1366 				"Failed creating default auth handle");
1367 			destroy_auth_client_handle(cl);
1368 			skipentry = 1;
1369 			mfs->mfs_ignore = 1;
1370 			continue;
1371 		    }
1372 #ifdef MALLOC_DEBUG
1373 		    add_alloc("AUTH_HANDLE", cl->cl_auth, 0,
1374 			__FILE__, __LINE__);
1375 #endif
1376 		} else
1377 		    cl = NULL;
1378 
1379 		/*
1380 		 * set security options
1381 		 */
1382 		sec_opt = 0;
1383 		(void) memset(&nfs_sec, 0, sizeof (nfs_sec));
1384 		if (hasmntopt(&m, MNTOPT_SECURE) != NULL) {
1385 			if (++sec_opt > 1) {
1386 				syslog(loglevel,
1387 				    "conflicting security options for %s",
1388 				    remname);
1389 				free(argp);
1390 				head = prevhead;
1391 				tail = prevtail;
1392 				if (tail)
1393 					tail->nfs_ext_u.nfs_extB.next = NULL;
1394 				last_error = NFSERR_IO;
1395 				destroy_auth_client_handle(cl);
1396 				skipentry = 1;
1397 				mfs->mfs_ignore = 1;
1398 				continue;
1399 			}
1400 			if (nfs_getseconfig_byname("dh", &nfs_sec)) {
1401 				syslog(loglevel,
1402 				    "error getting dh information from %s",
1403 				    NFSSEC_CONF);
1404 				free(argp);
1405 				head = prevhead;
1406 				tail = prevtail;
1407 				if (tail)
1408 					tail->nfs_ext_u.nfs_extB.next = NULL;
1409 				last_error = NFSERR_IO;
1410 				destroy_auth_client_handle(cl);
1411 				skipentry = 1;
1412 				mfs->mfs_ignore = 1;
1413 				continue;
1414 			}
1415 		}
1416 
1417 		nfs_flavor = NULL;
1418 		/*
1419 		 * Have to workaround the fact that hasmntopt() returns true
1420 		 * when comparing "secure" (in &m) with "sec".
1421 		 */
1422 		if (hasmntopt(&m, "sec=") != NULL) {
1423 			if ((str_opt(&m, MNTOPT_SEC, &nfs_flavor)) == -1) {
1424 				syslog(LOG_ERR, "nfsmount: no memory");
1425 				last_error = NFSERR_IO;
1426 				destroy_auth_client_handle(cl);
1427 				goto out;
1428 			}
1429 		}
1430 
1431 		if (nfs_flavor) {
1432 			if (++sec_opt > 1) {
1433 				syslog(loglevel,
1434 				    "conflicting security options for %s",
1435 				    remname);
1436 				free(nfs_flavor);
1437 				free(argp);
1438 				head = prevhead;
1439 				tail = prevtail;
1440 				if (tail)
1441 					tail->nfs_ext_u.nfs_extB.next = NULL;
1442 				last_error = NFSERR_IO;
1443 				destroy_auth_client_handle(cl);
1444 				skipentry = 1;
1445 				mfs->mfs_ignore = 1;
1446 				continue;
1447 			}
1448 			if (nfs_getseconfig_byname(nfs_flavor, &nfs_sec)) {
1449 				syslog(loglevel,
1450 				    "error getting %s information from %s",
1451 				    nfs_flavor, NFSSEC_CONF);
1452 				free(nfs_flavor);
1453 				free(argp);
1454 				head = prevhead;
1455 				tail = prevtail;
1456 				if (tail)
1457 					tail->nfs_ext_u.nfs_extB.next = NULL;
1458 				last_error = NFSERR_IO;
1459 				destroy_auth_client_handle(cl);
1460 				skipentry = 1;
1461 				mfs->mfs_ignore = 1;
1462 				continue;
1463 			}
1464 			free(nfs_flavor);
1465 		}
1466 
1467 		posix = (nfsvers != NFS_V4 &&
1468 				hasmntopt(&m, MNTOPT_POSIX) != NULL) ? 1 : 0;
1469 
1470 		if ((mfs->mfs_flags & MFS_FH_VIA_WEBNFS) == 0 &&
1471 			nfsvers != NFS_V4) {
1472 		    bool_t give_up_on_mnt;
1473 		    bool_t got_mnt_error;
1474 		/*
1475 		 * If we started with a URL, if first byte of path is not "/",
1476 		 * then the mount will likely fail, so we should try again
1477 		 * with a prepended "/".
1478 		 */
1479 		    if (mfs->mfs_flags & MFS_ALLOC_DIR && *dir != '/')
1480 			give_up_on_mnt = FALSE;
1481 		    else
1482 			give_up_on_mnt = TRUE;
1483 
1484 		    got_mnt_error = FALSE;
1485 
1486 try_mnt_slash:
1487 		    if (got_mnt_error == TRUE) {
1488 			int i, l;
1489 
1490 			give_up_on_mnt = TRUE;
1491 			l = strlen(dir);
1492 
1493 			/*
1494 			 * Insert a "/" to front of mfs_dir.
1495 			 */
1496 			for (i = l; i > 0; i--)
1497 				dir[i] = dir[i-1];
1498 
1499 			dir[0] = '/';
1500 		    }
1501 
1502 		    /* Get fhandle of remote path from server's mountd */
1503 
1504 		    switch (outvers) {
1505 		    case MOUNTVERS:
1506 			if (posix) {
1507 				free(argp);
1508 				head = prevhead;
1509 				tail = prevtail;
1510 				if (tail)
1511 					tail->nfs_ext_u.nfs_extB.next = NULL;
1512 				last_error = NFSERR_NOENT;
1513 				syslog(loglevel, "can't get posix info for %s",
1514 					host);
1515 				destroy_auth_client_handle(cl);
1516 				skipentry = 1;
1517 				mfs->mfs_ignore = 1;
1518 				continue;
1519 			}
1520 		    /* FALLTHRU */
1521 		    case MOUNTVERS_POSIX:
1522 			if (nfsvers == NFS_V3) {
1523 				free(argp);
1524 				head = prevhead;
1525 				tail = prevtail;
1526 				if (tail)
1527 					tail->nfs_ext_u.nfs_extB.next = NULL;
1528 				last_error = NFSERR_NOENT;
1529 				syslog(loglevel,
1530 					"%s doesn't support NFS Version 3",
1531 					host);
1532 				destroy_auth_client_handle(cl);
1533 				skipentry = 1;
1534 				mfs->mfs_ignore = 1;
1535 				continue;
1536 			}
1537 			rpc_stat = clnt_call(cl, MOUNTPROC_MNT,
1538 				xdr_dirpath, (caddr_t)&dir,
1539 				xdr_fhstatus, (caddr_t)&fhs, timeout);
1540 			if (rpc_stat != RPC_SUCCESS) {
1541 
1542 				if (give_up_on_mnt == FALSE) {
1543 					got_mnt_error = TRUE;
1544 					goto try_mnt_slash;
1545 				}
1546 
1547 				/*
1548 				 * Given the way "clnt_sperror" works, the "%s"
1549 				 * immediately following the "not responding"
1550 				 * is correct.
1551 				 */
1552 				free(argp);
1553 				head = prevhead;
1554 				tail = prevtail;
1555 				if (tail)
1556 					tail->nfs_ext_u.nfs_extB.next = NULL;
1557 				last_error = NFSERR_NOENT;
1558 
1559 				if (retries-- > 0) {
1560 					destroy_auth_client_handle(cl);
1561 					DELAY(delay);
1562 					goto retry;
1563 				}
1564 
1565 				if (trace > 3) {
1566 				    trace_prt(1,
1567 					"  nfsmount: mount RPC failed for %s\n",
1568 					host);
1569 				}
1570 				syslog(loglevel, "%s server not responding%s",
1571 				    host, clnt_sperror(cl, ""));
1572 				destroy_auth_client_handle(cl);
1573 				skipentry = 1;
1574 				mfs->mfs_ignore = 1;
1575 				continue;
1576 			}
1577 			if ((errno = fhs.fhs_status) != MNT_OK)  {
1578 
1579 				if (give_up_on_mnt == FALSE) {
1580 					got_mnt_error = TRUE;
1581 					goto try_mnt_slash;
1582 				}
1583 
1584 				free(argp);
1585 				head = prevhead;
1586 				tail = prevtail;
1587 				if (tail)
1588 					tail->nfs_ext_u.nfs_extB.next = NULL;
1589 				if (errno == EACCES) {
1590 					status = NFSERR_ACCES;
1591 				} else {
1592 					syslog(loglevel, "%s: %m", host);
1593 					status = NFSERR_IO;
1594 				}
1595 				if (trace > 3) {
1596 				    trace_prt(1, "  nfsmount: mount RPC gave"
1597 					" %d for %s:%s\n",
1598 					errno, host, dir);
1599 				}
1600 				last_error = status;
1601 				destroy_auth_client_handle(cl);
1602 				skipentry = 1;
1603 				mfs->mfs_ignore = 1;
1604 				continue;
1605 			}
1606 			argp->fh = malloc((sizeof (fhandle)));
1607 			if (!argp->fh) {
1608 				syslog(LOG_ERR, "nfsmount: no memory");
1609 				last_error = NFSERR_IO;
1610 				destroy_auth_client_handle(cl);
1611 				goto out;
1612 			}
1613 			(void) memcpy(argp->fh, &fhs.fhstatus_u.fhs_fhandle,
1614 				sizeof (fhandle));
1615 			break;
1616 		    case MOUNTVERS3:
1617 			posix = 0;
1618 			(void) memset((char *)&res3, '\0', sizeof (res3));
1619 			rpc_stat = clnt_call(cl, MOUNTPROC_MNT,
1620 				xdr_dirpath, (caddr_t)&dir,
1621 				xdr_mountres3, (caddr_t)&res3, timeout);
1622 			if (rpc_stat != RPC_SUCCESS) {
1623 
1624 				if (give_up_on_mnt == FALSE) {
1625 					got_mnt_error = TRUE;
1626 					goto try_mnt_slash;
1627 				}
1628 
1629 				/*
1630 				 * Given the way "clnt_sperror" works, the "%s"
1631 				 * immediately following the "not responding"
1632 				 * is correct.
1633 				 */
1634 				free(argp);
1635 				head = prevhead;
1636 				tail = prevtail;
1637 				if (tail)
1638 					tail->nfs_ext_u.nfs_extB.next = NULL;
1639 				last_error = NFSERR_NOENT;
1640 
1641 				if (retries-- > 0) {
1642 					destroy_auth_client_handle(cl);
1643 					DELAY(delay);
1644 					goto retry;
1645 				}
1646 
1647 				if (trace > 3) {
1648 				    trace_prt(1,
1649 					"  nfsmount: mount RPC failed for %s\n",
1650 					host);
1651 				}
1652 				syslog(loglevel, "%s server not responding%s",
1653 				    remname, clnt_sperror(cl, ""));
1654 				destroy_auth_client_handle(cl);
1655 				skipentry = 1;
1656 				mfs->mfs_ignore = 1;
1657 				continue;
1658 			}
1659 			if ((errno = res3.fhs_status) != MNT_OK)  {
1660 
1661 				if (give_up_on_mnt == FALSE) {
1662 					got_mnt_error = TRUE;
1663 					goto try_mnt_slash;
1664 				}
1665 
1666 				free(argp);
1667 				head = prevhead;
1668 				tail = prevtail;
1669 				if (tail)
1670 					tail->nfs_ext_u.nfs_extB.next = NULL;
1671 				if (errno == EACCES) {
1672 					status = NFSERR_ACCES;
1673 				} else {
1674 					syslog(loglevel, "%s: %m", remname);
1675 					status = NFSERR_IO;
1676 				}
1677 				if (trace > 3) {
1678 				    trace_prt(1, "  nfsmount: mount RPC gave"
1679 					" %d for %s:%s\n",
1680 					errno, host, dir);
1681 				}
1682 				last_error = status;
1683 				destroy_auth_client_handle(cl);
1684 				skipentry = 1;
1685 				mfs->mfs_ignore = 1;
1686 				continue;
1687 			}
1688 
1689 			/*
1690 			 *  Negotiate the security flavor for nfs_mount
1691 			 */
1692 			auths =
1693 		    res3.mountres3_u.mountinfo.auth_flavors.auth_flavors_val;
1694 			count =
1695 		    res3.mountres3_u.mountinfo.auth_flavors.auth_flavors_len;
1696 
1697 			if (sec_opt) {
1698 				for (i = 0; i < count; i++)
1699 					if (auths[i] == nfs_sec.sc_nfsnum) {
1700 						break;
1701 					}
1702 				if (i >= count) {
1703 					syslog(LOG_ERR,
1704 				    "%s: does not support security \"%s\"\n",
1705 					    remname, nfs_sec.sc_name);
1706 					clnt_freeres(cl, xdr_mountres3,
1707 					    (caddr_t)&res3);
1708 					free(argp);
1709 					head = prevhead;
1710 					tail = prevtail;
1711 					if (tail)
1712 				tail->nfs_ext_u.nfs_extB.next = NULL;
1713 					last_error = NFSERR_IO;
1714 					destroy_auth_client_handle(cl);
1715 					skipentry = 1;
1716 					mfs->mfs_ignore = 1;
1717 					continue;
1718 				}
1719 			} else {
1720 				if (count > 0) {
1721 					for (i = 0; i < count; i++) {
1722 					    if (!(scerror =
1723 				nfs_getseconfig_bynumber(auths[i], &nfs_sec))) {
1724 						sec_opt++;
1725 						break;
1726 					    }
1727 					}
1728 					if (i >= count) {
1729 						if (nfs_syslog_scerr(scerror,
1730 								scerror_msg)
1731 							!= -1) {
1732 							syslog(LOG_ERR,
1733 			"%s cannot be mounted because it is shared with "
1734 			"security flavor %d which %s",
1735 							remname,
1736 							auths[i-1],
1737 							scerror_msg);
1738 						}
1739 						clnt_freeres(cl, xdr_mountres3,
1740 						    (caddr_t)&res3);
1741 						free(argp);
1742 						head = prevhead;
1743 						tail = prevtail;
1744 						if (tail)
1745 					tail->nfs_ext_u.nfs_extB.next = NULL;
1746 						last_error = NFSERR_IO;
1747 						destroy_auth_client_handle(cl);
1748 						skipentry = 1;
1749 						mfs->mfs_ignore = 1;
1750 						continue;
1751 					}
1752 				}
1753 			}
1754 
1755 			fh3.fh3_length =
1756 			    res3.mountres3_u.mountinfo.fhandle.fhandle3_len;
1757 			(void) memcpy(fh3.fh3_u.data,
1758 			    res3.mountres3_u.mountinfo.fhandle.fhandle3_val,
1759 			    fh3.fh3_length);
1760 			clnt_freeres(cl, xdr_mountres3,
1761 			    (caddr_t)&res3);
1762 			argp->fh = malloc(sizeof (nfs_fh3));
1763 			if (!argp->fh) {
1764 				syslog(LOG_ERR, "nfsmount: no memory");
1765 				last_error = NFSERR_IO;
1766 				destroy_auth_client_handle(cl);
1767 				goto out;
1768 			}
1769 			(void) memcpy(argp->fh, &fh3, sizeof (nfs_fh3));
1770 			break;
1771 		    default:
1772 			free(argp);
1773 			head = prevhead;
1774 			tail = prevtail;
1775 			if (tail)
1776 				tail->nfs_ext_u.nfs_extB.next = NULL;
1777 			last_error = NFSERR_NOENT;
1778 			syslog(loglevel, "unknown MOUNT version %ld on %s",
1779 			    vers, remname);
1780 			destroy_auth_client_handle(cl);
1781 			skipentry = 1;
1782 			mfs->mfs_ignore = 1;
1783 			continue;
1784 		    } /* switch */
1785 		}
1786 		if (nfsvers == NFS_V4) {
1787 			argp->fh = strdup(dir);
1788 			if (argp->fh == NULL) {
1789 				syslog(LOG_ERR, "nfsmount: no memory");
1790 				last_error = NFSERR_IO;
1791 				goto out;
1792 			}
1793 		}
1794 
1795 		if (trace > 4)
1796 			trace_prt(1, "	nfsmount: have %s filehandle for %s\n",
1797 			    fstype, remname);
1798 
1799 		argp->flags |= NFSMNT_NEWARGS;
1800 		argp->flags |= NFSMNT_INT;	/* default is "intr" */
1801 		argp->hostname = strdup(host);
1802 		argp->flags |= NFSMNT_HOSTNAME;
1803 
1804 		/*
1805 		 * In this case, we want NFSv4 to behave like
1806 		 * non-WebNFS so that we get the server address.
1807 		 */
1808 		if ((mfs->mfs_flags & MFS_FH_VIA_WEBNFS) == 0) {
1809 			nconf = NULL;
1810 
1811 			if (nfs_port != 0)
1812 				thisport = nfs_port;
1813 			else
1814 				thisport = mfs->mfs_port;
1815 
1816 			/*
1817 			 * For NFSv4, we want to avoid rpcbind, so call
1818 			 * get_server_stuff() directly to tell it that
1819 			 * we want to go "direct_to_server".  Otherwise,
1820 			 * do what has always been done.
1821 			 */
1822 			if (nfsvers == NFS_V4) {
1823 				enum clnt_stat cstat;
1824 				argp->addr = get_server_stuff(SERVER_ADDR,
1825 					host, NFS_PROGRAM, nfsvers, NULL,
1826 					&nconf, nfs_proto, thisport, NULL,
1827 					NULL, TRUE, NULL, &cstat);
1828 			} else {
1829 				argp->addr = get_addr(host, NFS_PROGRAM,
1830 					nfsvers, &nconf, nfs_proto,
1831 					thisport, NULL);
1832 			}
1833 
1834 			if (argp->addr == NULL) {
1835 				if (argp->hostname)
1836 					free(argp->hostname);
1837 				free(argp->fh);
1838 				free(argp);
1839 				head = prevhead;
1840 				tail = prevtail;
1841 				if (tail)
1842 					tail->nfs_ext_u.nfs_extB.next = NULL;
1843 				last_error = NFSERR_NOENT;
1844 
1845 				if (retries-- > 0) {
1846 					destroy_auth_client_handle(cl);
1847 					DELAY(delay);
1848 					goto retry;
1849 				}
1850 
1851 				syslog(loglevel, "%s: no NFS service", host);
1852 				destroy_auth_client_handle(cl);
1853 				skipentry = 1;
1854 				mfs->mfs_ignore = 1;
1855 				continue;
1856 			}
1857 			if (trace > 4)
1858 				trace_prt(1,
1859 				    "\tnfsmount: have net address for %s\n",
1860 				    remname);
1861 
1862 		} else {
1863 			nconf = mfs->mfs_nconf;
1864 			mfs->mfs_nconf = NULL;
1865 		}
1866 
1867 		argp->flags |= NFSMNT_KNCONF;
1868 		argp->knconf = get_knconf(nconf);
1869 		if (argp->knconf == NULL) {
1870 			netbuf_free(argp->addr);
1871 			freenetconfigent(nconf);
1872 			if (argp->hostname)
1873 				free(argp->hostname);
1874 			free(argp->fh);
1875 			free(argp);
1876 			head = prevhead;
1877 			tail = prevtail;
1878 			if (tail)
1879 				tail->nfs_ext_u.nfs_extB.next = NULL;
1880 			last_error = NFSERR_NOSPC;
1881 			destroy_auth_client_handle(cl);
1882 			skipentry = 1;
1883 			mfs->mfs_ignore = 1;
1884 			continue;
1885 		}
1886 		if (trace > 4)
1887 			trace_prt(1,
1888 			    "\tnfsmount: have net config for %s\n",
1889 			    remname);
1890 
1891 		if (hasmntopt(&m, MNTOPT_SOFT) != NULL) {
1892 			argp->flags |= NFSMNT_SOFT;
1893 		}
1894 		if (hasmntopt(&m, MNTOPT_NOINTR) != NULL) {
1895 			argp->flags &= ~(NFSMNT_INT);
1896 		}
1897 		if (hasmntopt(&m, MNTOPT_NOAC) != NULL) {
1898 			argp->flags |= NFSMNT_NOAC;
1899 		}
1900 		if (hasmntopt(&m, MNTOPT_NOCTO) != NULL) {
1901 			argp->flags |= NFSMNT_NOCTO;
1902 		}
1903 		if (hasmntopt(&m, MNTOPT_FORCEDIRECTIO) != NULL) {
1904 			argp->flags |= NFSMNT_DIRECTIO;
1905 		}
1906 		if (hasmntopt(&m, MNTOPT_NOFORCEDIRECTIO) != NULL) {
1907 			argp->flags &= ~(NFSMNT_DIRECTIO);
1908 		}
1909 
1910 		/*
1911 		 * Set up security data for argp->nfs_ext_u.nfs_extB.secdata.
1912 		 */
1913 		if (mfssnego.snego_done) {
1914 			memcpy(&nfs_sec, &mfssnego.nfs_sec,
1915 				sizeof (seconfig_t));
1916 		} else if (!sec_opt) {
1917 			/*
1918 			 * Get default security mode.
1919 			 */
1920 			if (nfs_getseconfig_default(&nfs_sec)) {
1921 				syslog(loglevel,
1922 				    "error getting default security entry\n");
1923 				free_knconf(argp->knconf);
1924 				netbuf_free(argp->addr);
1925 				freenetconfigent(nconf);
1926 				if (argp->hostname)
1927 					free(argp->hostname);
1928 				free(argp->fh);
1929 				free(argp);
1930 				head = prevhead;
1931 				tail = prevtail;
1932 				if (tail)
1933 					tail->nfs_ext_u.nfs_extB.next = NULL;
1934 				last_error = NFSERR_NOSPC;
1935 				destroy_auth_client_handle(cl);
1936 				skipentry = 1;
1937 				mfs->mfs_ignore = 1;
1938 				continue;
1939 			}
1940 			argp->flags |= NFSMNT_SECDEFAULT;
1941 		}
1942 
1943 		/*
1944 		 * For AUTH_DH
1945 		 * get the network address for the time service on
1946 		 * the server.	If an RPC based time service is
1947 		 * not available then try the IP time service.
1948 		 *
1949 		 * Eventurally, we want to move this code to nfs_clnt_secdata()
1950 		 * when autod_nfs.c and mount.c can share the same
1951 		 * get_the_addr/get_the_stuff routine.
1952 		 */
1953 		secflags = 0;
1954 		syncaddr = NULL;
1955 		retaddrs = NULL;
1956 
1957 		if (nfs_sec.sc_rpcnum == AUTH_DH || nfsvers == NFS_V4) {
1958 		/*
1959 		 * If not using the public fh and not NFS_V4, we can try
1960 		 * talking RPCBIND. Otherwise, assume that firewalls
1961 		 * prevent us from doing that.
1962 		 */
1963 		    if ((mfs->mfs_flags & MFS_FH_VIA_WEBNFS) == 0 &&
1964 				nfsvers != NFS_V4) {
1965 			syncaddr = get_the_stuff(SERVER_ADDR, host, RPCBPROG,
1966 				RPCBVERS, NULL, nconf, 0, NULL, NULL, FALSE,
1967 				NULL, NULL);
1968 		    }
1969 
1970 		    if (syncaddr != NULL) {
1971 			/* for flags in sec_data */
1972 			secflags |= AUTH_F_RPCTIMESYNC;
1973 		    } else {
1974 			struct nd_hostserv hs;
1975 			int error;
1976 
1977 			hs.h_host = host;
1978 			hs.h_serv = "timserver";
1979 			error = netdir_getbyname(nconf, &hs, &retaddrs);
1980 
1981 			if (error != ND_OK && nfs_sec.sc_rpcnum == AUTH_DH) {
1982 				syslog(loglevel,
1983 				"%s: secure: no time service\n", host);
1984 				free_knconf(argp->knconf);
1985 				netbuf_free(argp->addr);
1986 				freenetconfigent(nconf);
1987 				if (argp->hostname)
1988 					free(argp->hostname);
1989 				free(argp->fh);
1990 				free(argp);
1991 				head = prevhead;
1992 				tail = prevtail;
1993 				if (tail)
1994 					tail->nfs_ext_u.nfs_extB.next = NULL;
1995 				last_error = NFSERR_IO;
1996 				destroy_auth_client_handle(cl);
1997 				skipentry = 1;
1998 				mfs->mfs_ignore = 1;
1999 				continue;
2000 			}
2001 
2002 			if (error == ND_OK)
2003 			    syncaddr = retaddrs->n_addrs;
2004 
2005 			/*
2006 			 * For potential usage by NFS V4 when AUTH_DH
2007 			 * is negotiated via SECINFO in the kernel.
2008 			 */
2009 			if (nfsvers == NFS_V4 && syncaddr &&
2010 				    host2netname(netname, host, NULL)) {
2011 			    argp->syncaddr = malloc(sizeof (struct netbuf));
2012 			    argp->syncaddr->buf = malloc(syncaddr->len);
2013 			    (void) memcpy(argp->syncaddr->buf,
2014 					syncaddr->buf, syncaddr->len);
2015 			    argp->syncaddr->len = syncaddr->len;
2016 			    argp->syncaddr->maxlen = syncaddr->maxlen;
2017 			    argp->netname = strdup(netname);
2018 			    argp->flags |= NFSMNT_SECURE;
2019 			}
2020 		    } /* syncaddr */
2021 		} /* AUTH_DH */
2022 
2023 		/*
2024 		 * TSOL notes: automountd in tsol extension
2025 		 * has "read down" capability, i.e. we allow
2026 		 * a user to trigger an nfs mount into a lower
2027 		 * labeled zone. We achieve this by always having
2028 		 * root issue the mount request so that the
2029 		 * lookup ops can go past /zone/<zone_name>
2030 		 * on the server side.
2031 		 */
2032 		if (is_system_labeled())
2033 			nfs_sec.sc_uid = (uid_t)0;
2034 		else
2035 			nfs_sec.sc_uid = ucred_geteuid(cred);
2036 		/*
2037 		 * If AUTH_DH is a chosen flavor now, its data will be stored
2038 		 * in the sec_data structure via nfs_clnt_secdata().
2039 		 */
2040 		if (!(secdata = nfs_clnt_secdata(&nfs_sec, host, argp->knconf,
2041 					syncaddr, secflags))) {
2042 			syslog(LOG_ERR,
2043 				"errors constructing security related data\n");
2044 			if (secflags & AUTH_F_RPCTIMESYNC)
2045 				netbuf_free(syncaddr);
2046 			else if (retaddrs)
2047 				netdir_free(retaddrs, ND_ADDRLIST);
2048 			if (argp->syncaddr)
2049 				netbuf_free(argp->syncaddr);
2050 			if (argp->netname)
2051 				free(argp->netname);
2052 			if (argp->hostname)
2053 				free(argp->hostname);
2054 			free_knconf(argp->knconf);
2055 			netbuf_free(argp->addr);
2056 			freenetconfigent(nconf);
2057 			free(argp->fh);
2058 			free(argp);
2059 			head = prevhead;
2060 			tail = prevtail;
2061 			if (tail)
2062 				tail->nfs_ext_u.nfs_extB.next = NULL;
2063 			last_error = NFSERR_IO;
2064 			destroy_auth_client_handle(cl);
2065 			skipentry = 1;
2066 			mfs->mfs_ignore = 1;
2067 			continue;
2068 		}
2069 		NFS_ARGS_EXTB_secdata(*argp, secdata);
2070 		/* end of security stuff */
2071 
2072 		if (trace > 4)
2073 			trace_prt(1,
2074 			    "  nfsmount: have secure info for %s\n", remname);
2075 
2076 		if (hasmntopt(&m, MNTOPT_GRPID) != NULL) {
2077 			argp->flags |= NFSMNT_GRPID;
2078 		}
2079 		if (nopt(&m, MNTOPT_RSIZE, &argp->rsize)) {
2080 			argp->flags |= NFSMNT_RSIZE;
2081 		}
2082 		if (nopt(&m, MNTOPT_WSIZE, &argp->wsize)) {
2083 			argp->flags |= NFSMNT_WSIZE;
2084 		}
2085 		if (nopt(&m, MNTOPT_TIMEO, &argp->timeo)) {
2086 			argp->flags |= NFSMNT_TIMEO;
2087 		}
2088 		if (nopt(&m, MNTOPT_RETRANS, &argp->retrans)) {
2089 			argp->flags |= NFSMNT_RETRANS;
2090 		}
2091 		if (nopt(&m, MNTOPT_ACTIMEO, &argp->acregmax)) {
2092 			argp->flags |= NFSMNT_ACREGMAX;
2093 			argp->flags |= NFSMNT_ACDIRMAX;
2094 			argp->flags |= NFSMNT_ACDIRMIN;
2095 			argp->flags |= NFSMNT_ACREGMIN;
2096 			argp->acdirmin = argp->acregmin = argp->acdirmax
2097 				= argp->acregmax;
2098 		} else {
2099 			if (nopt(&m, MNTOPT_ACREGMIN, &argp->acregmin)) {
2100 				argp->flags |= NFSMNT_ACREGMIN;
2101 			}
2102 			if (nopt(&m, MNTOPT_ACREGMAX, &argp->acregmax)) {
2103 				argp->flags |= NFSMNT_ACREGMAX;
2104 			}
2105 			if (nopt(&m, MNTOPT_ACDIRMIN, &argp->acdirmin)) {
2106 				argp->flags |= NFSMNT_ACDIRMIN;
2107 			}
2108 			if (nopt(&m, MNTOPT_ACDIRMAX, &argp->acdirmax)) {
2109 				argp->flags |= NFSMNT_ACDIRMAX;
2110 			}
2111 		}
2112 
2113 		if (posix) {
2114 			argp->pathconf = NULL;
2115 			if (error = get_pathconf(cl, dir, remname,
2116 			    &argp->pathconf, retries)) {
2117 				if (secflags & AUTH_F_RPCTIMESYNC)
2118 					netbuf_free(syncaddr);
2119 				else if (retaddrs)
2120 					netdir_free(retaddrs, ND_ADDRLIST);
2121 				free_knconf(argp->knconf);
2122 				netbuf_free(argp->addr);
2123 				freenetconfigent(nconf);
2124 				nfs_free_secdata(
2125 					argp->nfs_ext_u.nfs_extB.secdata);
2126 				if (argp->syncaddr)
2127 					netbuf_free(argp->syncaddr);
2128 				if (argp->netname)
2129 					free(argp->netname);
2130 				if (argp->hostname)
2131 					free(argp->hostname);
2132 				free(argp->fh);
2133 				free(argp);
2134 				head = prevhead;
2135 				tail = prevtail;
2136 				if (tail)
2137 					tail->nfs_ext_u.nfs_extB.next = NULL;
2138 				last_error = NFSERR_IO;
2139 
2140 				if (error == RET_RETRY && retries-- > 0) {
2141 					destroy_auth_client_handle(cl);
2142 					DELAY(delay);
2143 					goto retry;
2144 				}
2145 
2146 				destroy_auth_client_handle(cl);
2147 				skipentry = 1;
2148 				mfs->mfs_ignore = 1;
2149 				continue;
2150 			}
2151 			argp->flags |= NFSMNT_POSIX;
2152 			if (trace > 4)
2153 				trace_prt(1,
2154 				    "  nfsmount: have pathconf for %s\n",
2155 				    remname);
2156 		}
2157 
2158 		/*
2159 		 * free loop-specific data structures
2160 		 */
2161 		destroy_auth_client_handle(cl);
2162 		freenetconfigent(nconf);
2163 		if (secflags & AUTH_F_RPCTIMESYNC)
2164 			netbuf_free(syncaddr);
2165 		else if (retaddrs)
2166 			netdir_free(retaddrs, ND_ADDRLIST);
2167 
2168 		/*
2169 		 * Decide whether to use remote host's lockd or local locking.
2170 		 * If we are using the public fh, we've already turned
2171 		 * LLOCK on.
2172 		 */
2173 		if (hasmntopt(&m, MNTOPT_LLOCK))
2174 			argp->flags |= NFSMNT_LLOCK;
2175 		if (!(argp->flags & NFSMNT_LLOCK) && nfsvers == NFS_VERSION &&
2176 			remote_lock(host, argp->fh)) {
2177 			syslog(loglevel, "No network locking on %s : "
2178 			"contact admin to install server change", host);
2179 			argp->flags |= NFSMNT_LLOCK;
2180 		}
2181 
2182 		/*
2183 		 * Build a string for /etc/mnttab.
2184 		 * If possible, coalesce strings with same 'dir' info.
2185 		 */
2186 		if ((mfs->mfs_flags & MFS_URL) == 0) {
2187 			char *tmp;
2188 
2189 			if (mnttabcnt) {
2190 				p = strrchr(mnttabtext, (int)':');
2191 				if (!p || strcmp(p+1, dir) != 0) {
2192 					mnttabcnt += strlen(remname) + 2;
2193 				} else {
2194 					*p = '\0';
2195 					mnttabcnt += strlen(host) + 2;
2196 				}
2197 				if ((tmp = realloc(mnttabtext,
2198 				    mnttabcnt)) != NULL) {
2199 					mnttabtext = tmp;
2200 					strcat(mnttabtext, ",");
2201 				} else {
2202 					free(mnttabtext);
2203 					mnttabtext = NULL;
2204 				}
2205 			} else {
2206 				mnttabcnt = strlen(remname) + 1;
2207 				if ((mnttabtext = malloc(mnttabcnt)) != NULL)
2208 					mnttabtext[0] = '\0';
2209 			}
2210 
2211 			if (mnttabtext != NULL)
2212 				strcat(mnttabtext, remname);
2213 
2214 		} else {
2215 			char *tmp;
2216 			int more_cnt = 0;
2217 			char sport[16];
2218 
2219 			more_cnt += strlen("nfs://");
2220 			more_cnt += strlen(mfs->mfs_host);
2221 
2222 			if (mfs->mfs_port != 0) {
2223 				(void) sprintf(sport, ":%u", mfs->mfs_port);
2224 			} else
2225 				sport[0] = '\0';
2226 
2227 			more_cnt += strlen(sport);
2228 			more_cnt += 1; /* "/" */
2229 			more_cnt += strlen(mfs->mfs_dir);
2230 
2231 			if (mnttabcnt) {
2232 				more_cnt += 1; /* "," */
2233 				mnttabcnt += more_cnt;
2234 
2235 				if ((tmp = realloc(mnttabtext,
2236 				    mnttabcnt)) != NULL) {
2237 					mnttabtext = tmp;
2238 					strcat(mnttabtext, ",");
2239 				} else {
2240 					free(mnttabtext);
2241 					mnttabtext = NULL;
2242 				}
2243 			} else {
2244 				mnttabcnt = more_cnt + 1;
2245 				if ((mnttabtext = malloc(mnttabcnt)) != NULL)
2246 					mnttabtext[0] = '\0';
2247 			}
2248 
2249 			if (mnttabtext != NULL) {
2250 				strcat(mnttabtext, "nfs://");
2251 				strcat(mnttabtext, mfs->mfs_host);
2252 				strcat(mnttabtext, sport);
2253 				strcat(mnttabtext, "/");
2254 				strcat(mnttabtext, mfs->mfs_dir);
2255 			}
2256 		}
2257 
2258 		if (!mnttabtext) {
2259 			syslog(LOG_ERR, "nfsmount: no memory");
2260 			last_error = NFSERR_IO;
2261 			goto out;
2262 		}
2263 
2264 		/*
2265 		 * At least one entry, can call mount(2).
2266 		 */
2267 		entries++;
2268 
2269 		/*
2270 		 * If replication was defeated, don't do more work
2271 		 */
2272 		if (!replicated)
2273 			break;
2274 	}
2275 
2276 
2277 	/*
2278 	 * Did we get through all possibilities without success?
2279 	 */
2280 	if (!entries)
2281 		goto out;
2282 
2283 	/* Make "xattr" the default if "noxattr" is not specified. */
2284 	strcpy(mopts, opts);
2285 	if (!hasmntopt(&m, MNTOPT_NOXATTR) && !hasmntopt(&m, MNTOPT_XATTR)) {
2286 		if (strlen(mopts) > 0)
2287 			strcat(mopts, ",");
2288 		strcat(mopts, "xattr");
2289 	}
2290 
2291 	/*
2292 	 * enable services as needed.
2293 	 */
2294 	{
2295 		char **sl;
2296 
2297 		if (strcmp(fstype, MNTTYPE_NFS4) == 0)
2298 			sl = service_list_v4;
2299 		else
2300 			sl = service_list;
2301 
2302 		(void) _check_services(sl);
2303 	}
2304 
2305 	/*
2306 	 * Whew; do the mount, at last.
2307 	 */
2308 	if (trace > 1) {
2309 		trace_prt(1, "	mount %s %s (%s)\n", mnttabtext, mntpnt, mopts);
2310 	}
2311 
2312 	/*
2313 	 * If no action list pointer then do the mount, otherwise
2314 	 * build the actions list pointer with the mount information.
2315 	 * so the mount can be done in the kernel.
2316 	 */
2317 	if (alp == NULL) {
2318 		if (mount(mnttabtext, mntpnt, flags | MS_DATA, fstype,
2319 			head, sizeof (*head), mopts, MAX_MNTOPT_STR) < 0) {
2320 			if (trace > 1)
2321 				trace_prt(1, "	Mount of %s on %s: %d\n",
2322 					mnttabtext, mntpnt, errno);
2323 			if (errno != EBUSY || verbose)
2324 				syslog(LOG_ERR,
2325 				"Mount of %s on %s: %m", mnttabtext, mntpnt);
2326 			last_error = NFSERR_IO;
2327 			goto out;
2328 		}
2329 
2330 		last_error = NFS_OK;
2331 		if (stat(mntpnt, &stbuf) == 0) {
2332 			if (trace > 1) {
2333 				trace_prt(1, "	mount %s dev=%x rdev=%x OK\n",
2334 				mnttabtext, stbuf.st_dev, stbuf.st_rdev);
2335 			}
2336 		} else {
2337 			if (trace > 1) {
2338 				trace_prt(1, "	mount %s OK\n", mnttabtext);
2339 				trace_prt(1, "	stat of %s failed\n", mntpnt);
2340 			}
2341 
2342 		}
2343 	} else {
2344 		alp->action.action = AUTOFS_MOUNT_RQ;
2345 		alp->action.action_list_entry_u.mounta.spec =
2346 			strdup(mnttabtext);
2347 		alp->action.action_list_entry_u.mounta.dir = strdup(mntpnt);
2348 		alp->action.action_list_entry_u.mounta.flags =
2349 			flags | MS_DATA;
2350 		alp->action.action_list_entry_u.mounta.fstype =
2351 			strdup(fstype);
2352 		alp->action.action_list_entry_u.mounta.dataptr = (char *)head;
2353 		alp->action.action_list_entry_u.mounta.datalen =
2354 			sizeof (*head);
2355 		mntopts = malloc(strlen(mopts) + 1);
2356 		strcpy(mntopts, mopts);
2357 		mntopts[strlen(mopts)] = '\0';
2358 		alp->action.action_list_entry_u.mounta.optptr = mntopts;
2359 		alp->action.action_list_entry_u.mounta.optlen =
2360 			strlen(mntopts) + 1;
2361 		last_error = NFS_OK;
2362 		goto ret;
2363 	}
2364 
2365 out:
2366 	argp = head;
2367 	while (argp) {
2368 		if (argp->pathconf)
2369 			free(argp->pathconf);
2370 		free_knconf(argp->knconf);
2371 		netbuf_free(argp->addr);
2372 		if (argp->syncaddr)
2373 			netbuf_free(argp->syncaddr);
2374 		if (argp->netname) {
2375 			free(argp->netname);
2376 		}
2377 		if (argp->hostname)
2378 			free(argp->hostname);
2379 		nfs_free_secdata(argp->nfs_ext_u.nfs_extB.secdata);
2380 		free(argp->fh);
2381 		head = argp;
2382 		argp = argp->nfs_ext_u.nfs_extB.next;
2383 		free(head);
2384 	}
2385 ret:
2386 	if (nfs_proto)
2387 		free(nfs_proto);
2388 	if (mnttabtext)
2389 		free(mnttabtext);
2390 
2391 	for (mfs = mfs_in; mfs; mfs = mfs->mfs_next) {
2392 
2393 		if (mfs->mfs_flags & MFS_ALLOC_DIR) {
2394 			free(mfs->mfs_dir);
2395 			mfs->mfs_dir = NULL;
2396 			mfs->mfs_flags &= ~MFS_ALLOC_DIR;
2397 		}
2398 
2399 		if (mfs->mfs_args != NULL && alp == NULL) {
2400 			free(mfs->mfs_args);
2401 			mfs->mfs_args = NULL;
2402 		}
2403 
2404 		if (mfs->mfs_nconf != NULL) {
2405 			freenetconfigent(mfs->mfs_nconf);
2406 			mfs->mfs_nconf = NULL;
2407 		}
2408 	}
2409 
2410 	return (last_error);
2411 }
2412 
2413 /*
2414  * get_pathconf(cl, path, fsname, pcnf, cretries)
2415  * ugliness that requires that ppathcnf and pathcnf stay consistent
2416  * cretries is a copy of retries used to determine when to syslog
2417  * on retry situations.
2418  */
2419 static int
2420 get_pathconf(CLIENT *cl, char *path, char *fsname, struct pathcnf **pcnf,
2421 	int cretries)
2422 {
2423 	struct ppathcnf *p = NULL;
2424 	enum clnt_stat rpc_stat;
2425 	struct timeval timeout;
2426 
2427 	p = (struct ppathcnf *)malloc(sizeof (struct ppathcnf));
2428 	if (p == NULL) {
2429 		syslog(LOG_ERR, "get_pathconf: Out of memory");
2430 		return (RET_ERR);
2431 	}
2432 	memset((caddr_t)p, 0, sizeof (struct ppathcnf));
2433 
2434 	timeout.tv_sec = 10;
2435 	timeout.tv_usec = 0;
2436 	rpc_stat = clnt_call(cl, MOUNTPROC_PATHCONF,
2437 	    xdr_dirpath, (caddr_t)&path, xdr_ppathcnf, (caddr_t)p, timeout);
2438 	if (rpc_stat != RPC_SUCCESS) {
2439 		if (cretries-- <= 0) {
2440 			syslog(LOG_ERR,
2441 			    "get_pathconf: %s: server not responding: %s",
2442 			    fsname, clnt_sperror(cl, ""));
2443 		}
2444 		free(p);
2445 		return (RET_RETRY);
2446 	}
2447 	if (_PC_ISSET(_PC_ERROR, p->pc_mask)) {
2448 		syslog(LOG_ERR, "get_pathconf: no info for %s", fsname);
2449 		free(p);
2450 		return (RET_ERR);
2451 	}
2452 	*pcnf = (struct pathcnf *)p;
2453 	return (RET_OK);
2454 }
2455 
2456 struct knetconfig *
2457 get_knconf(nconf)
2458 	struct netconfig *nconf;
2459 {
2460 	struct stat stbuf;
2461 	struct knetconfig *k;
2462 
2463 	if (stat(nconf->nc_device, &stbuf) < 0) {
2464 		syslog(LOG_ERR, "get_knconf: stat %s: %m", nconf->nc_device);
2465 		return (NULL);
2466 	}
2467 	k = (struct knetconfig *)malloc(sizeof (*k));
2468 	if (k == NULL)
2469 		goto nomem;
2470 	k->knc_semantics = nconf->nc_semantics;
2471 	k->knc_protofmly = strdup(nconf->nc_protofmly);
2472 	if (k->knc_protofmly == NULL)
2473 		goto nomem;
2474 	k->knc_proto = strdup(nconf->nc_proto);
2475 	if (k->knc_proto == NULL)
2476 		goto nomem;
2477 	k->knc_rdev = stbuf.st_rdev;
2478 
2479 	return (k);
2480 
2481 nomem:
2482 	syslog(LOG_ERR, "get_knconf: no memory");
2483 	free_knconf(k);
2484 	return (NULL);
2485 }
2486 
2487 void
2488 free_knconf(k)
2489 	struct knetconfig *k;
2490 {
2491 	if (k == NULL)
2492 		return;
2493 	if (k->knc_protofmly)
2494 		free(k->knc_protofmly);
2495 	if (k->knc_proto)
2496 		free(k->knc_proto);
2497 	free(k);
2498 }
2499 
2500 void
2501 netbuf_free(nb)
2502 	struct netbuf *nb;
2503 {
2504 	if (nb == NULL)
2505 		return;
2506 	if (nb->buf)
2507 		free(nb->buf);
2508 	free(nb);
2509 }
2510 
2511 #define	SMALL_HOSTNAME		20
2512 #define	SMALL_PROTONAME		10
2513 #define	SMALL_PROTOFMLYNAME		10
2514 
2515 struct portmap_cache {
2516 	int cache_prog;
2517 	int cache_vers;
2518 	time_t cache_time;
2519 	char cache_small_hosts[SMALL_HOSTNAME + 1];
2520 	char *cache_hostname;
2521 	char *cache_proto;
2522 	char *cache_protofmly;
2523 	char cache_small_protofmly[SMALL_PROTOFMLYNAME + 1];
2524 	char cache_small_proto[SMALL_PROTONAME + 1];
2525 	struct netbuf cache_srv_addr;
2526 	struct portmap_cache *cache_prev, *cache_next;
2527 };
2528 
2529 rwlock_t portmap_cache_lock;
2530 static int portmap_cache_valid_time = 30;
2531 struct portmap_cache *portmap_cache_head, *portmap_cache_tail;
2532 
2533 #ifdef MALLOC_DEBUG
2534 void
2535 portmap_cache_flush()
2536 {
2537 	struct  portmap_cache *next = NULL, *cp;
2538 
2539 	(void) rw_wrlock(&portmap_cache_lock);
2540 	for (cp = portmap_cache_head; cp; cp = cp->cache_next) {
2541 		if (cp->cache_hostname != NULL &&
2542 		    cp->cache_hostname !=
2543 		    cp->cache_small_hosts)
2544 			free(cp->cache_hostname);
2545 		if (cp->cache_proto != NULL &&
2546 		    cp->cache_proto !=
2547 		    cp->cache_small_proto)
2548 			free(cp->cache_proto);
2549 		if (cp->cache_srv_addr.buf != NULL)
2550 			free(cp->cache_srv_addr.buf);
2551 		next = cp->cache_next;
2552 		free(cp);
2553 	}
2554 	portmap_cache_head = NULL;
2555 	portmap_cache_tail = NULL;
2556 	(void) rw_unlock(&portmap_cache_lock);
2557 }
2558 #endif
2559 
2560 /*
2561  * Returns 1 if the entry is found in the cache, 0 otherwise.
2562  */
2563 static int
2564 portmap_cache_lookup(hostname, prog, vers, nconf, addrp)
2565 	char *hostname;
2566 	rpcprog_t prog;
2567 	rpcvers_t vers;
2568 	struct netconfig *nconf;
2569 	struct netbuf *addrp;
2570 {
2571 	struct	portmap_cache *cachep, *prev, *next = NULL, *cp;
2572 	int	retval = 0;
2573 
2574 	timenow = time(NULL);
2575 
2576 	(void) rw_rdlock(&portmap_cache_lock);
2577 
2578 	/*
2579 	 * Increment the portmap cache counters for # accesses and lookups
2580 	 * Use a smaller factor (100 vs 1000 for the host cache) since
2581 	 * initial analysis shows this cache is looked up 10% that of the
2582 	 * host cache.
2583 	 */
2584 #ifdef CACHE_DEBUG
2585 	portmap_cache_accesses++;
2586 	portmap_cache_lookups++;
2587 	if ((portmap_cache_lookups%100) == 0)
2588 		trace_portmap_cache();
2589 #endif /* CACHE_DEBUG */
2590 
2591 	for (cachep = portmap_cache_head; cachep;
2592 		cachep = cachep->cache_next) {
2593 		if (timenow > cachep->cache_time) {
2594 			/*
2595 			 * We stumbled across an entry in the cache which
2596 			 * has timed out. Free up all the entries that
2597 			 * were added before it, which will positionally
2598 			 * be after this entry. And adjust neighboring
2599 			 * pointers.
2600 			 * When we drop the lock and re-acquire it, we
2601 			 * need to start from the beginning.
2602 			 */
2603 			(void) rw_unlock(&portmap_cache_lock);
2604 			(void) rw_wrlock(&portmap_cache_lock);
2605 			for (cp = portmap_cache_head;
2606 				cp && (cp->cache_time >= timenow);
2607 				cp = cp->cache_next)
2608 				;
2609 			if (cp == NULL)
2610 				goto done;
2611 			/*
2612 			 * Adjust the link of the predecessor.
2613 			 * Make the tail point to the new last entry.
2614 			 */
2615 			prev = cp->cache_prev;
2616 			if (prev == NULL) {
2617 				portmap_cache_head = NULL;
2618 				portmap_cache_tail = NULL;
2619 			} else {
2620 				prev->cache_next = NULL;
2621 				portmap_cache_tail = prev;
2622 			}
2623 			for (; cp; cp = next) {
2624 				if (cp->cache_hostname != NULL &&
2625 				    cp->cache_hostname !=
2626 				    cp->cache_small_hosts)
2627 					free(cp->cache_hostname);
2628 				if (cp->cache_proto != NULL &&
2629 				    cp->cache_proto !=
2630 				    cp->cache_small_proto)
2631 					free(cp->cache_proto);
2632 				if (cp->cache_srv_addr.buf != NULL)
2633 					free(cp->cache_srv_addr.buf);
2634 				next = cp->cache_next;
2635 				free(cp);
2636 			}
2637 			goto done;
2638 		}
2639 		if (cachep->cache_hostname == NULL ||
2640 		    prog != cachep->cache_prog || vers != cachep->cache_vers ||
2641 		    strcmp(nconf->nc_proto, cachep->cache_proto) != 0 ||
2642 		    strcmp(nconf->nc_protofmly, cachep->cache_protofmly) != 0 ||
2643 		    strcmp(hostname, cachep->cache_hostname) != 0)
2644 			continue;
2645 		/*
2646 		 * Cache Hit.
2647 		 */
2648 #ifdef CACHE_DEBUG
2649 		portmap_cache_hits++;	/* up portmap cache hit counter */
2650 #endif /* CACHE_DEBUG */
2651 		addrp->len = cachep->cache_srv_addr.len;
2652 		memcpy(addrp->buf, cachep->cache_srv_addr.buf, addrp->len);
2653 		retval = 1;
2654 		break;
2655 	}
2656 done:
2657 	(void) rw_unlock(&portmap_cache_lock);
2658 	return (retval);
2659 }
2660 
2661 static void
2662 portmap_cache_enter(hostname, prog, vers, nconf, addrp)
2663 	char *hostname;
2664 	rpcprog_t prog;
2665 	rpcvers_t vers;
2666 	struct netconfig *nconf;
2667 	struct netbuf *addrp;
2668 {
2669 	struct portmap_cache *cachep;
2670 	int protofmlylen;
2671 	int protolen, hostnamelen;
2672 
2673 	timenow = time(NULL);
2674 
2675 	cachep = malloc(sizeof (struct portmap_cache));
2676 	if (cachep == NULL)
2677 		return;
2678 	memset((char *)cachep, 0, sizeof (*cachep));
2679 
2680 	hostnamelen = strlen(hostname);
2681 	if (hostnamelen <= SMALL_HOSTNAME)
2682 		cachep->cache_hostname = cachep->cache_small_hosts;
2683 	else {
2684 		cachep->cache_hostname = malloc(hostnamelen + 1);
2685 		if (cachep->cache_hostname == NULL)
2686 			goto nomem;
2687 	}
2688 	strcpy(cachep->cache_hostname, hostname);
2689 	protolen = strlen(nconf->nc_proto);
2690 	if (protolen <= SMALL_PROTONAME)
2691 		cachep->cache_proto = cachep->cache_small_proto;
2692 	else {
2693 		cachep->cache_proto = malloc(protolen + 1);
2694 		if (cachep->cache_proto == NULL)
2695 			goto nomem;
2696 	}
2697 	protofmlylen = strlen(nconf->nc_protofmly);
2698 	if (protofmlylen <= SMALL_PROTOFMLYNAME)
2699 		cachep->cache_protofmly = cachep->cache_small_protofmly;
2700 	else {
2701 		cachep->cache_protofmly = malloc(protofmlylen + 1);
2702 		if (cachep->cache_protofmly == NULL)
2703 			goto nomem;
2704 	}
2705 
2706 	strcpy(cachep->cache_proto, nconf->nc_proto);
2707 	cachep->cache_prog = prog;
2708 	cachep->cache_vers = vers;
2709 	cachep->cache_time = timenow + portmap_cache_valid_time;
2710 	cachep->cache_srv_addr.len = addrp->len;
2711 	cachep->cache_srv_addr.buf = malloc(addrp->len);
2712 	if (cachep->cache_srv_addr.buf == NULL)
2713 		goto nomem;
2714 	memcpy(cachep->cache_srv_addr.buf, addrp->buf, addrp->maxlen);
2715 	cachep->cache_prev = NULL;
2716 	(void) rw_wrlock(&portmap_cache_lock);
2717 	/*
2718 	 * There's a window in which we could have multiple threads making
2719 	 * the same cache entry. This can be avoided by walking the cache
2720 	 * once again here to check and see if there are duplicate entries
2721 	 * (after grabbing the write lock). This isn't fatal and I'm not
2722 	 * going to bother with this.
2723 	 */
2724 #ifdef CACHE_DEBUG
2725 	portmap_cache_accesses++;	/* up portmap cache access counter */
2726 #endif /* CACHE_DEBUG */
2727 	cachep->cache_next = portmap_cache_head;
2728 	if (portmap_cache_head != NULL)
2729 		portmap_cache_head->cache_prev = cachep;
2730 	portmap_cache_head = cachep;
2731 	(void) rw_unlock(&portmap_cache_lock);
2732 	return;
2733 
2734 nomem:
2735 	syslog(LOG_ERR, "portmap_cache_enter: Memory allocation failed");
2736 	if (cachep->cache_srv_addr.buf)
2737 		free(cachep->cache_srv_addr.buf);
2738 	if (cachep->cache_proto && protolen > SMALL_PROTONAME)
2739 		free(cachep->cache_proto);
2740 	if (cachep->cache_hostname && hostnamelen > SMALL_HOSTNAME)
2741 		free(cachep->cache_hostname);
2742 	if (cachep->cache_protofmly && protofmlylen > SMALL_PROTOFMLYNAME)
2743 		free(cachep->cache_protofmly);
2744 	if (cachep)
2745 		free(cachep);
2746 	cachep = NULL;
2747 }
2748 
2749 static int
2750 get_cached_srv_addr(char *hostname, rpcprog_t prog, rpcvers_t vers,
2751 	struct netconfig *nconf, struct netbuf *addrp)
2752 {
2753 	if (portmap_cache_lookup(hostname, prog, vers, nconf, addrp))
2754 		return (1);
2755 	if (rpcb_getaddr(prog, vers, nconf, addrp, hostname) == 0)
2756 		return (0);
2757 	portmap_cache_enter(hostname, prog, vers, nconf, addrp);
2758 	return (1);
2759 }
2760 
2761 /*
2762  * Get the network address on "hostname" for program "prog"
2763  * with version "vers" by using the nconf configuration data
2764  * passed in.
2765  *
2766  * If the address of a netconfig pointer is null then
2767  * information is not sufficient and no netbuf will be returned.
2768  *
2769  * tinfo argument is for matching the get_the_addr() defined in
2770  * ../nfs/mount/mount.c
2771  */
2772 void *
2773 get_the_stuff(
2774 	enum type_of_stuff type_of_stuff,
2775 	char *hostname,
2776 	rpcprog_t prog,
2777 	rpcprog_t vers,
2778 	mfs_snego_t *mfssnego,
2779 	struct netconfig *nconf,
2780 	ushort_t port,
2781 	struct t_info *tinfo,
2782 	caddr_t *fhp,
2783 	bool_t direct_to_server,
2784 	char *fspath,
2785 	enum clnt_stat *cstat)
2786 
2787 {
2788 	struct netbuf *nb = NULL;
2789 	struct t_bind *tbind = NULL;
2790 	int fd = -1;
2791 	enum clnt_stat cs = RPC_TIMEDOUT;
2792 	CLIENT *cl = NULL;
2793 	struct timeval tv;
2794 	AUTH *ah = NULL;
2795 	AUTH *new_ah = NULL;
2796 	struct snego_t snego;
2797 
2798 	if (nconf == NULL) {
2799 		goto done;
2800 	}
2801 
2802 	if (prog == NFS_PROGRAM && vers == NFS_V4)
2803 		if (strncasecmp(nconf->nc_proto, NC_UDP, strlen(NC_UDP)) == 0)
2804 			goto done;
2805 
2806 	if ((fd = t_open(nconf->nc_device, O_RDWR, tinfo)) < 0) {
2807 		goto done;
2808 	}
2809 
2810 	/* LINTED pointer alignment */
2811 	if ((tbind = (struct t_bind *)t_alloc(fd, T_BIND, T_ADDR))
2812 		    == NULL) {
2813 			goto done;
2814 	}
2815 
2816 	if (direct_to_server == TRUE) {
2817 		struct nd_hostserv hs;
2818 		struct nd_addrlist *retaddrs;
2819 		hs.h_host = hostname;
2820 
2821 		if (trace > 1)
2822 			trace_prt(1, "	get_the_stuff: %s call "
2823 				"direct to server %s\n",
2824 				type_of_stuff == SERVER_FH ? "pub fh" :
2825 				type_of_stuff == SERVER_ADDR ? "get address" :
2826 				type_of_stuff == SERVER_PING ? "ping" :
2827 				"unknown", hostname);
2828 		if (port == 0)
2829 			hs.h_serv = "nfs";
2830 		else
2831 			hs.h_serv = NULL;
2832 
2833 		if (netdir_getbyname(nconf, &hs, &retaddrs) != ND_OK) {
2834 			goto done;
2835 		}
2836 		memcpy(tbind->addr.buf, retaddrs->n_addrs->buf,
2837 			retaddrs->n_addrs->len);
2838 		tbind->addr.len = retaddrs->n_addrs->len;
2839 		netdir_free((void *)retaddrs, ND_ADDRLIST);
2840 		if (port) {
2841 			/* LINTED pointer alignment */
2842 
2843 			if (strcmp(nconf->nc_protofmly, NC_INET) == NULL)
2844 				((struct sockaddr_in *)
2845 				tbind->addr.buf)->sin_port =
2846 					htons((ushort_t)port);
2847 			else if (strcmp(nconf->nc_protofmly, NC_INET6) == NULL)
2848 				((struct sockaddr_in6 *)
2849 				tbind->addr.buf)->sin6_port =
2850 					htons((ushort_t)port);
2851 		}
2852 
2853 		if (type_of_stuff == SERVER_FH) {
2854 			if (netdir_options(nconf, ND_SET_RESERVEDPORT, fd,
2855 				NULL) == -1)
2856 				if (trace > 1)
2857 					trace_prt(1, "\tget_the_stuff: "
2858 						"ND_SET_RESERVEDPORT(%s) "
2859 						"failed\n", hostname);
2860 		}
2861 
2862 		cl = clnt_tli_create(fd, nconf, &tbind->addr, prog,
2863 			vers, 0, 0);
2864 
2865 		if (trace > 1)
2866 			trace_prt(1, "	get_the_stuff: clnt_tli_create(%s) "
2867 				"returned %p\n", hostname, cl);
2868 		if (cl == NULL)
2869 			goto done;
2870 #ifdef MALLOC_DEBUG
2871 		add_alloc("CLNT_HANDLE", cl, 0, __FILE__, __LINE__);
2872 		add_alloc("AUTH_HANDLE", cl->cl_auth, 0,
2873 			__FILE__, __LINE__);
2874 #endif
2875 
2876 		switch (type_of_stuff) {
2877 		case SERVER_FH:
2878 		    {
2879 		    enum snego_stat sec;
2880 
2881 		    ah = authsys_create_default();
2882 		    if (ah != NULL) {
2883 #ifdef MALLOC_DEBUG
2884 			drop_alloc("AUTH_HANDLE", cl->cl_auth,
2885 				__FILE__, __LINE__);
2886 #endif
2887 			AUTH_DESTROY(cl->cl_auth);
2888 			cl->cl_auth = ah;
2889 #ifdef MALLOC_DEBUG
2890 			add_alloc("AUTH_HANDLE", cl->cl_auth, 0,
2891 				__FILE__, __LINE__);
2892 #endif
2893 		    }
2894 
2895 		    if (!mfssnego->snego_done && vers != NFS_V4) {
2896 			/*
2897 			 * negotiate sec flavor.
2898 			 */
2899 			snego.cnt = 0;
2900 			if ((sec = nfs_sec_nego(vers, cl, fspath, &snego)) ==
2901 				SNEGO_SUCCESS) {
2902 			    int jj;
2903 
2904 			/*
2905 			 * check if server supports the one
2906 			 * specified in the sec= option.
2907 			 */
2908 			    if (mfssnego->sec_opt) {
2909 				for (jj = 0; jj < snego.cnt; jj++) {
2910 				    if (snego.array[jj] ==
2911 					mfssnego->nfs_sec.sc_nfsnum) {
2912 					mfssnego->snego_done = TRUE;
2913 					break;
2914 				    }
2915 				}
2916 			    }
2917 
2918 			/*
2919 			 * find a common sec flavor
2920 			 */
2921 			    if (!mfssnego->snego_done) {
2922 				for (jj = 0; jj < snego.cnt; jj++) {
2923 				    if (!nfs_getseconfig_bynumber(
2924 					snego.array[jj], &mfssnego->nfs_sec)) {
2925 					mfssnego->snego_done = TRUE;
2926 					break;
2927 				    }
2928 				}
2929 			    }
2930 			    if (!mfssnego->snego_done)
2931 				return (NULL);
2932 
2933 			/*
2934 			 * Now that the flavor has been
2935 			 * negotiated, get the fh.
2936 			 *
2937 			 * First, create an auth handle using the negotiated
2938 			 * sec flavor in the next lookup to
2939 			 * fetch the filehandle.
2940 			 */
2941 			    new_ah = nfs_create_ah(cl, hostname,
2942 					&mfssnego->nfs_sec);
2943 			    if (new_ah == NULL)
2944 				goto done;
2945 #ifdef MALLOC_DEBUG
2946 			    drop_alloc("AUTH_HANDLE", cl->cl_auth,
2947 				__FILE__, __LINE__);
2948 #endif
2949 			    AUTH_DESTROY(cl->cl_auth);
2950 			    cl->cl_auth = new_ah;
2951 #ifdef MALLOC_DEBUG
2952 			    add_alloc("AUTH_HANDLE", cl->cl_auth, 0,
2953 				__FILE__, __LINE__);
2954 #endif
2955 			} else if (sec == SNEGO_ARRAY_TOO_SMALL ||
2956 			    sec == SNEGO_FAILURE) {
2957 			    goto done;
2958 			}
2959 			/*
2960 			 * Note that if sec == SNEGO_DEF_VALID
2961 			 * the default sec flavor is acceptable.
2962 			 * Use it to get the filehandle.
2963 			 */
2964 		    }
2965 		    }
2966 
2967 		    switch (vers) {
2968 		    case NFS_VERSION:
2969 			    {
2970 			    wnl_diropargs arg;
2971 			    wnl_diropres *res;
2972 
2973 			    memset((char *)&arg.dir, 0, sizeof (wnl_fh));
2974 			    arg.name = fspath;
2975 			    res = wnlproc_lookup_2(&arg, cl);
2976 
2977 			    if (res == NULL || res->status != NFS_OK)
2978 				    goto done;
2979 			    *fhp = malloc(sizeof (wnl_fh));
2980 
2981 			    if (*fhp == NULL) {
2982 				    syslog(LOG_ERR, "no memory\n");
2983 				    goto done;
2984 			    }
2985 
2986 			    memcpy((char *)*fhp,
2987 			    (char *)&res->wnl_diropres_u.wnl_diropres.file,
2988 				sizeof (wnl_fh));
2989 			    cs = RPC_SUCCESS;
2990 			    }
2991 			    break;
2992 		    case NFS_V3:
2993 			    {
2994 			    WNL_LOOKUP3args arg;
2995 			    WNL_LOOKUP3res *res;
2996 			    nfs_fh3 *fh3p;
2997 
2998 			    memset((char *)&arg.what.dir, 0, sizeof (wnl_fh3));
2999 			    arg.what.name = fspath;
3000 			    res = wnlproc3_lookup_3(&arg, cl);
3001 
3002 			    if (res == NULL || res->status != NFS3_OK)
3003 				    goto done;
3004 
3005 			    fh3p = (nfs_fh3 *)malloc(sizeof (*fh3p));
3006 
3007 			    if (fh3p == NULL) {
3008 				    syslog(LOG_ERR, "no memory\n");
3009 				    CLNT_FREERES(cl, xdr_WNL_LOOKUP3res,
3010 					(char *)res);
3011 				    goto done;
3012 			    }
3013 
3014 			    fh3p->fh3_length = res->
3015 				WNL_LOOKUP3res_u.res_ok.object.data.data_len;
3016 			    memcpy(fh3p->fh3_u.data, res->
3017 				WNL_LOOKUP3res_u.res_ok.object.data.data_val,
3018 				fh3p->fh3_length);
3019 
3020 			    *fhp = (caddr_t)fh3p;
3021 
3022 			    CLNT_FREERES(cl, xdr_WNL_LOOKUP3res, (char *)res);
3023 			    cs = RPC_SUCCESS;
3024 			    }
3025 			    break;
3026 		    case NFS_V4:
3027 			    *fhp = strdup(fspath);
3028 			    cs = RPC_SUCCESS;
3029 			    break;
3030 		    }
3031 		    break;
3032 		case SERVER_ADDR:
3033 		case SERVER_PING:
3034 			tv.tv_sec = 10;
3035 			tv.tv_usec = 0;
3036 			cs = clnt_call(cl, NULLPROC, xdr_void, 0,
3037 				xdr_void, 0, tv);
3038 			if (trace > 1)
3039 				trace_prt(1,
3040 					"get_the_stuff: clnt_call(%s) "
3041 					"returned %s\n",
3042 				hostname,
3043 					cs == RPC_SUCCESS ? "success" :
3044 					"failure");
3045 
3046 			if (cs != RPC_SUCCESS)
3047 				goto done;
3048 			break;
3049 		}
3050 
3051 	} else if (type_of_stuff != SERVER_FH) {
3052 
3053 		if (type_of_stuff == SERVER_ADDR) {
3054 			if (get_cached_srv_addr(hostname, prog, vers, nconf,
3055 			    &tbind->addr) == 0)
3056 				goto done;
3057 		}
3058 
3059 		if (port) {
3060 			/* LINTED pointer alignment */
3061 			if (strcmp(nconf->nc_protofmly, NC_INET) == NULL)
3062 				((struct sockaddr_in *)
3063 				tbind->addr.buf)->sin_port =
3064 					htons((ushort_t)port);
3065 			else if (strcmp(nconf->nc_protofmly, NC_INET6) == NULL)
3066 				((struct sockaddr_in6 *)
3067 				tbind->addr.buf)->sin6_port =
3068 					htons((ushort_t)port);
3069 			cl = clnt_tli_create(fd, nconf, &tbind->addr,
3070 				prog, vers, 0, 0);
3071 			if (cl == NULL)
3072 				goto done;
3073 #ifdef MALLOC_DEBUG
3074 			add_alloc("CLNT_HANDLE", cl, 0, __FILE__, __LINE__);
3075 			add_alloc("AUTH_HANDLE", cl->cl_auth, 0,
3076 				__FILE__, __LINE__);
3077 #endif
3078 			tv.tv_sec = 10;
3079 			tv.tv_usec = 0;
3080 			cs = clnt_call(cl, NULLPROC, xdr_void, 0, xdr_void,
3081 				0, tv);
3082 			if (cs != RPC_SUCCESS)
3083 				goto done;
3084 		}
3085 
3086 	} else {
3087 		/* can't happen */
3088 		goto done;
3089 	}
3090 
3091 	if (type_of_stuff != SERVER_PING) {
3092 
3093 		cs = RPC_SYSTEMERROR;
3094 
3095 		/*
3096 		 * Make a copy of the netbuf to return
3097 		 */
3098 		nb = (struct netbuf *)malloc(sizeof (struct netbuf));
3099 		if (nb == NULL) {
3100 			syslog(LOG_ERR, "no memory\n");
3101 			goto done;
3102 		}
3103 		*nb = tbind->addr;
3104 		nb->buf = (char *)malloc(nb->maxlen);
3105 		if (nb->buf == NULL) {
3106 			syslog(LOG_ERR, "no memory\n");
3107 			free(nb);
3108 			nb = NULL;
3109 			goto done;
3110 		}
3111 		(void) memcpy(nb->buf, tbind->addr.buf, tbind->addr.len);
3112 
3113 		cs = RPC_SUCCESS;
3114 	}
3115 
3116 done:
3117 	if (cl != NULL) {
3118 		if (ah != NULL) {
3119 #ifdef MALLOC_DEBUG
3120 			drop_alloc("AUTH_HANDLE", cl->cl_auth,
3121 				__FILE__, __LINE__);
3122 #endif
3123 			AUTH_DESTROY(cl->cl_auth);
3124 			cl->cl_auth = NULL;
3125 		}
3126 #ifdef MALLOC_DEBUG
3127 		drop_alloc("CLNT_HANDLE", cl, __FILE__, __LINE__);
3128 #endif
3129 		clnt_destroy(cl);
3130 	}
3131 
3132 	if (tbind) {
3133 		t_free((char *)tbind, T_BIND);
3134 		tbind = NULL;
3135 	}
3136 
3137 	if (fd >= 0)
3138 		(void) t_close(fd);
3139 
3140 	if (cstat != NULL)
3141 		*cstat = cs;
3142 
3143 	return (nb);
3144 }
3145 
3146 /*
3147  * Get a network address on "hostname" for program "prog"
3148  * with version "vers".  If the port number is specified (non zero)
3149  * then try for a TCP/UDP transport and set the port number of the
3150  * resulting IP address.
3151  *
3152  * If the address of a netconfig pointer was passed and
3153  * if it's not null, use it as the netconfig otherwise
3154  * assign the address of the netconfig that was used to
3155  * establish contact with the service.
3156  *
3157  * tinfo argument is for matching the get_addr() defined in
3158  * ../nfs/mount/mount.c
3159  */
3160 
3161 static struct netbuf *
3162 get_addr(char *hostname, rpcprog_t prog, rpcvers_t vers,
3163 	struct netconfig **nconfp, char *proto, ushort_t port,
3164 	struct t_info *tinfo)
3165 
3166 {
3167 	enum clnt_stat cstat;
3168 
3169 	return (get_server_stuff(SERVER_ADDR, hostname, prog, vers, NULL,
3170 		nconfp, proto, port, tinfo, NULL, FALSE, NULL, &cstat));
3171 }
3172 
3173 static struct netbuf *
3174 get_pubfh(char *hostname, rpcvers_t vers, mfs_snego_t *mfssnego,
3175 	struct netconfig **nconfp, char *proto, ushort_t port,
3176 	struct t_info *tinfo, caddr_t *fhp, bool_t get_pubfh, char *fspath)
3177 {
3178 	enum clnt_stat cstat;
3179 
3180 	return (get_server_stuff(SERVER_FH, hostname, NFS_PROGRAM, vers,
3181 		mfssnego, nconfp, proto, port, tinfo, fhp, get_pubfh, fspath,
3182 		&cstat));
3183 }
3184 
3185 static enum clnt_stat
3186 get_ping(char *hostname, rpcprog_t prog, rpcvers_t vers,
3187 	struct netconfig **nconfp, ushort_t port, bool_t direct_to_server)
3188 {
3189 	enum clnt_stat cstat;
3190 
3191 	(void) get_server_stuff(SERVER_PING, hostname, prog, vers, NULL, nconfp,
3192 		NULL, port, NULL, NULL, direct_to_server, NULL, &cstat);
3193 
3194 	return (cstat);
3195 }
3196 
3197 void *
3198 get_server_stuff(
3199 	enum type_of_stuff type_of_stuff,
3200 	char *hostname,
3201 	rpcprog_t prog,
3202 	rpcvers_t vers,
3203 	mfs_snego_t *mfssnego,
3204 	struct netconfig **nconfp,
3205 	char *proto,
3206 	ushort_t port,			/* may be zero */
3207 	struct t_info *tinfo,
3208 	caddr_t *fhp,
3209 	bool_t direct_to_server,
3210 	char *fspath,
3211 	enum clnt_stat *cstatp)
3212 {
3213 	struct netbuf *nb = NULL;
3214 	struct netconfig *nconf = NULL;
3215 	NCONF_HANDLE *nc = NULL;
3216 	int nthtry = FIRST_TRY;
3217 
3218 	if (nconfp && *nconfp)
3219 		return (get_the_stuff(type_of_stuff, hostname, prog, vers,
3220 			mfssnego, *nconfp, port, tinfo, fhp, direct_to_server,
3221 			fspath, cstatp));
3222 
3223 
3224 	/*
3225 	 * No nconf passed in.
3226 	 *
3227 	 * Try to get a nconf from /etc/netconfig.
3228 	 * First choice is COTS, second is CLTS unless proto
3229 	 * is specified.  When we retry, we reset the
3230 	 * netconfig list, so that we search the whole list
3231 	 * for the next choice.
3232 	 */
3233 	if ((nc = setnetpath()) == NULL)
3234 		goto done;
3235 
3236 	/*
3237 	 * If proto is specified, then only search for the match,
3238 	 * otherwise try COTS first, if failed, then try CLTS.
3239 	 */
3240 	if (proto) {
3241 
3242 		while (nconf = getnetpath(nc)) {
3243 			if (strcmp(nconf->nc_proto, proto))
3244 				continue;
3245 			/*
3246 			 * If the port number is specified then TCP/UDP
3247 			 * is needed. Otherwise any cots/clts will do.
3248 			 */
3249 			if (port)  {
3250 				if ((strcmp(nconf->nc_protofmly, NC_INET) &&
3251 				    strcmp(nconf->nc_protofmly, NC_INET6)) ||
3252 				    (strcmp(nconf->nc_proto, NC_TCP) &&
3253 				    strcmp(nconf->nc_proto, NC_UDP)))
3254 					continue;
3255 			}
3256 
3257 			nb = get_the_stuff(type_of_stuff, hostname, prog, vers,
3258 				mfssnego, nconf, port, tinfo, fhp,
3259 				direct_to_server, fspath, cstatp);
3260 
3261 			if (*cstatp == RPC_SUCCESS)
3262 				break;
3263 
3264 			assert(nb == NULL);
3265 
3266 		} /* end of while */
3267 
3268 		if (nconf == NULL)
3269 			goto done;
3270 
3271 	} else {
3272 retry:
3273 		while (nconf = getnetpath(nc)) {
3274 			if (nconf->nc_flag & NC_VISIBLE) {
3275 			    if (nthtry == FIRST_TRY) {
3276 				if ((nconf->nc_semantics == NC_TPI_COTS_ORD) ||
3277 					(nconf->nc_semantics == NC_TPI_COTS)) {
3278 				    if (port == 0)
3279 					break;
3280 				    if ((strcmp(nconf->nc_protofmly,
3281 					NC_INET) == 0 ||
3282 					strcmp(nconf->nc_protofmly,
3283 					NC_INET6) == 0) &&
3284 					(strcmp(nconf->nc_proto, NC_TCP) == 0))
3285 					break;
3286 				}
3287 			    }
3288 			    if (nthtry == SECOND_TRY) {
3289 				if (nconf->nc_semantics == NC_TPI_CLTS) {
3290 				    if (port == 0)
3291 					break;
3292 				    if ((strcmp(nconf->nc_protofmly,
3293 					NC_INET) == 0 ||
3294 					strcmp(nconf->nc_protofmly,
3295 					NC_INET6) == 0) &&
3296 					(strcmp(nconf->nc_proto, NC_UDP) == 0))
3297 					break;
3298 				}
3299 			    }
3300 			}
3301 		    } /* while */
3302 		    if (nconf == NULL) {
3303 			if (++nthtry <= MNT_PREF_LISTLEN) {
3304 				endnetpath(nc);
3305 				if ((nc = setnetpath()) == NULL)
3306 					goto done;
3307 				goto retry;
3308 			} else
3309 				goto done;
3310 		    } else {
3311 			nb = get_the_stuff(type_of_stuff, hostname, prog, vers,
3312 			    mfssnego, nconf, port, tinfo, fhp, direct_to_server,
3313 			    fspath, cstatp);
3314 			if (*cstatp != RPC_SUCCESS)
3315 				/*
3316 				 * Continue the same search path in the
3317 				 * netconfig db until no more matched nconf
3318 				 * (nconf == NULL).
3319 				 */
3320 				goto retry;
3321 		    }
3322 	} /* if !proto */
3323 
3324 	/*
3325 	 * Got nconf and nb.  Now dup the netconfig structure (nconf)
3326 	 * and return it thru nconfp.
3327 	 */
3328 	*nconfp = getnetconfigent(nconf->nc_netid);
3329 	if (*nconfp == NULL) {
3330 		syslog(LOG_ERR, "no memory\n");
3331 		free(nb);
3332 		nb = NULL;
3333 	}
3334 done:
3335 	if (nc)
3336 		endnetpath(nc);
3337 	return (nb);
3338 }
3339 
3340 
3341 /*
3342  * Sends a null call to the remote host's (NFS program, versp). versp
3343  * may be "NULL" in which case the default maximum version is used.
3344  * Upon return, versp contains the maximum version supported iff versp!= NULL.
3345  */
3346 enum clnt_stat
3347 pingnfs(
3348 	char *hostpart,
3349 	int attempts,
3350 	rpcvers_t *versp,
3351 	rpcvers_t versmin,
3352 	ushort_t port,			/* may be zeor */
3353 	bool_t usepub,
3354 	char *path,
3355 	char *proto)
3356 {
3357 	CLIENT *cl = NULL;
3358 	struct timeval rpc_to_new = {15, 0};
3359 	static struct timeval rpc_rtrans_new = {-1, -1};
3360 	enum clnt_stat clnt_stat;
3361 	int i, j;
3362 	rpcvers_t versmax;	/* maximum version to try against server */
3363 	rpcvers_t outvers;	/* version supported by host on last call */
3364 	rpcvers_t vers_to_try;	/* to try different versions against host */
3365 	char *hostname = hostpart;
3366 	struct netconfig *nconf;
3367 
3368 	if (path != NULL && strcmp(hostname, "nfs") == 0 &&
3369 	    strncmp(path, "//", 2) == 0) {
3370 		char *sport;
3371 
3372 		hostname = strdup(path+2);
3373 
3374 		if (hostname == NULL)
3375 			return (RPC_SYSTEMERROR);
3376 
3377 		path = strchr(hostname, '/');
3378 
3379 		/*
3380 		 * This cannot happen. If it does, give up
3381 		 * on the ping as this is obviously a corrupt
3382 		 * entry.
3383 		 */
3384 		if (path == NULL) {
3385 			free(hostname);
3386 			return (RPC_SUCCESS);
3387 		}
3388 
3389 		/*
3390 		 * Probable end point of host string.
3391 		 */
3392 		*path = '\0';
3393 
3394 		sport = strchr(hostname, ':');
3395 
3396 		if (sport != NULL && sport < path) {
3397 
3398 			/*
3399 			 * Actual end point of host string.
3400 			 */
3401 			*sport = '\0';
3402 			port = htons((ushort_t)atoi(sport+1));
3403 		}
3404 
3405 		usepub = TRUE;
3406 	}
3407 
3408 	/* Pick up the default versions and then set them appropriately */
3409 	if (versp) {
3410 		versmax = *versp;
3411 		/* use versmin passed in */
3412 	} else {
3413 		read_default_nfs();
3414 		set_versrange(0, &versmax, &versmin);
3415 	}
3416 
3417 	if (proto &&
3418 	    strncasecmp(proto, NC_UDP, strlen(NC_UDP)) == 0 &&
3419 	    versmax == NFS_V4) {
3420 		if (versmin == NFS_V4) {
3421 			if (versp) {
3422 				*versp = versmax - 1;
3423 				return (RPC_SUCCESS);
3424 			}
3425 			return (RPC_PROGUNAVAIL);
3426 		} else {
3427 			versmax--;
3428 		}
3429 	}
3430 
3431 	if (versp)
3432 		*versp = versmax;
3433 
3434 	switch (cache_check(hostname, versp, proto)) {
3435 	case GOODHOST:
3436 		if (hostname != hostpart)
3437 			free(hostname);
3438 		return (RPC_SUCCESS);
3439 	case DEADHOST:
3440 		if (hostname != hostpart)
3441 			free(hostname);
3442 		return (RPC_TIMEDOUT);
3443 	case NOHOST:
3444 	default:
3445 		break;
3446 	}
3447 
3448 	/*
3449 	 * XXX The retransmission time rpcbrmttime is a global defined
3450 	 * in the rpc library (rpcb_clnt.c). We use (and like) the default
3451 	 * value of 15 sec in the rpc library. The code below is to protect
3452 	 * us in case it changes. This need not be done under a lock since
3453 	 * any # of threads entering this function will get the same
3454 	 * retransmission value.
3455 	 */
3456 	if (rpc_rtrans_new.tv_sec == -1 && rpc_rtrans_new.tv_usec == -1) {
3457 		__rpc_control(CLCR_GET_RPCB_RMTTIME, (char *)&rpc_rtrans_new);
3458 		if (rpc_rtrans_new.tv_sec != 15 && rpc_rtrans_new.tv_sec != 0)
3459 			if (trace > 1)
3460 				trace_prt(1, "RPC library rttimer changed\n");
3461 	}
3462 
3463 	/*
3464 	 * XXX Manipulate the total timeout to get the number of
3465 	 * desired retransmissions. This code is heavily dependant on
3466 	 * the RPC backoff mechanism in clnt_dg_call (clnt_dg.c).
3467 	 */
3468 	for (i = 0, j = rpc_rtrans_new.tv_sec; i < attempts-1; i++) {
3469 		if (j < RPC_MAX_BACKOFF)
3470 			j *= 2;
3471 		else
3472 			j = RPC_MAX_BACKOFF;
3473 		rpc_to_new.tv_sec += j;
3474 	}
3475 
3476 	vers_to_try = versmax;
3477 
3478 	/*
3479 	 * check the host's version within the timeout
3480 	 */
3481 	if (trace > 1)
3482 		trace_prt(1, "	ping: %s timeout=%ld request vers=%d min=%d\n",
3483 				hostname, rpc_to_new.tv_sec, versmax, versmin);
3484 
3485 	if (usepub == FALSE) {
3486 	    do {
3487 		/*
3488 		 * If NFSv4, then we do the same thing as is used
3489 		 * for public filehandles so that we avoid rpcbind
3490 		 */
3491 		if (vers_to_try == NFS_V4) {
3492 			if (trace > 4) {
3493 				trace_prt(1, "  pingnfs: Trying ping via "
3494 					"\"circuit_v\"\n");
3495 				}
3496 
3497 			if ((cl = clnt_create_service_timed(hostname, "nfs",
3498 							    NFS_PROGRAM,
3499 							    vers_to_try,
3500 							    port, "circuit_v",
3501 							    &rpc_to_new))
3502 			    != NULL) {
3503 				outvers = vers_to_try;
3504 				break;
3505 			}
3506 			if (trace > 4) {
3507 				trace_prt(1, "  pingnfs: Can't ping via "
3508 					"\"circuit_v\" %s: RPC error=%d\n",
3509 					hostname, rpc_createerr.cf_stat);
3510 			}
3511 
3512 		} else {
3513 			if ((cl = clnt_create_vers_timed(hostname, NFS_PROGRAM,
3514 				&outvers, versmin, vers_to_try,
3515 				"datagram_v", &rpc_to_new))
3516 				!= NULL)
3517 				break;
3518 			if (trace > 4) {
3519 				trace_prt(1, "  pingnfs: Can't ping via "
3520 					"\"datagram_v\"%s: RPC error=%d\n",
3521 					hostname, rpc_createerr.cf_stat);
3522 			}
3523 			if (rpc_createerr.cf_stat == RPC_UNKNOWNHOST ||
3524 				rpc_createerr.cf_stat == RPC_TIMEDOUT)
3525 				break;
3526 			if (rpc_createerr.cf_stat == RPC_PROGNOTREGISTERED) {
3527 				if (trace > 4) {
3528 					trace_prt(1, "  pingnfs: Trying ping "
3529 						"via \"circuit_v\"\n");
3530 				}
3531 				if ((cl = clnt_create_vers_timed(hostname,
3532 					NFS_PROGRAM, &outvers,
3533 					versmin, vers_to_try,
3534 					"circuit_v", &rpc_to_new)) != NULL)
3535 					break;
3536 				if (trace > 4) {
3537 					trace_prt(1, "  pingnfs: Can't ping "
3538 						"via \"circuit_v\" %s: "
3539 						"RPC error=%d\n",
3540 						hostname,
3541 						rpc_createerr.cf_stat);
3542 				}
3543 			}
3544 		}
3545 
3546 		/*
3547 		 * backoff and return lower version to retry the ping.
3548 		 * XXX we should be more careful and handle
3549 		 * RPC_PROGVERSMISMATCH here, because that error is handled
3550 		 * in clnt_create_vers(). It's not done to stay in sync
3551 		 * with the nfs mount command.
3552 		 */
3553 		    vers_to_try--;
3554 		    if (vers_to_try < versmin)
3555 			    break;
3556 		    if (versp != NULL) {	/* recheck the cache */
3557 			    *versp = vers_to_try;
3558 			    if (trace > 4) {
3559 				trace_prt(1,
3560 				    "  pingnfs: check cache: vers=%d\n",
3561 				    *versp);
3562 			    }
3563 			    switch (cache_check(hostname, versp, proto)) {
3564 			    case GOODHOST:
3565 				    if (hostname != hostpart)
3566 					    free(hostname);
3567 				    return (RPC_SUCCESS);
3568 			    case DEADHOST:
3569 				    if (hostname != hostpart)
3570 					    free(hostname);
3571 				    return (RPC_TIMEDOUT);
3572 			    case NOHOST:
3573 			    default:
3574 				    break;
3575 			    }
3576 		    }
3577 		    if (trace > 4) {
3578 			trace_prt(1, "  pingnfs: Try version=%d\n",
3579 				vers_to_try);
3580 		    }
3581 	    } while (cl == NULL);
3582 
3583 
3584 	    if (cl == NULL) {
3585 		    if (verbose)
3586 			    syslog(LOG_ERR, "pingnfs: %s%s",
3587 				    hostname, clnt_spcreateerror(""));
3588 		    clnt_stat = rpc_createerr.cf_stat;
3589 	    } else {
3590 		    clnt_destroy(cl);
3591 		    clnt_stat = RPC_SUCCESS;
3592 	    }
3593 
3594 	} else {
3595 		for (vers_to_try = versmax; vers_to_try >= versmin;
3596 		    vers_to_try--) {
3597 
3598 			nconf = NULL;
3599 
3600 			if (trace > 4) {
3601 				trace_prt(1, "  pingnfs: Try version=%d "
3602 					"using get_ping()\n", vers_to_try);
3603 			}
3604 
3605 			clnt_stat = get_ping(hostname, NFS_PROGRAM,
3606 				vers_to_try, &nconf, port, TRUE);
3607 
3608 			if (nconf != NULL)
3609 				freenetconfigent(nconf);
3610 
3611 			if (clnt_stat == RPC_SUCCESS) {
3612 				outvers = vers_to_try;
3613 				break;
3614 			}
3615 		}
3616 	}
3617 
3618 	if (trace > 1)
3619 		clnt_stat == RPC_SUCCESS ?
3620 			trace_prt(1, "	pingnfs OK: nfs version=%d\n", outvers):
3621 			trace_prt(1, "	pingnfs FAIL: can't get nfs version\n");
3622 
3623 	if (clnt_stat == RPC_SUCCESS) {
3624 		cache_enter(hostname, versmax, outvers, proto, GOODHOST);
3625 		if (versp != NULL)
3626 			*versp = outvers;
3627 	} else
3628 		cache_enter(hostname, versmax, versmax, proto, DEADHOST);
3629 
3630 	if (hostpart != hostname)
3631 		free(hostname);
3632 
3633 	return (clnt_stat);
3634 }
3635 
3636 #define	MNTTYPE_LOFS	"lofs"
3637 
3638 int
3639 loopbackmount(fsname, dir, mntopts, overlay)
3640 	char *fsname;		/* Directory being mounted */
3641 	char *dir;		/* Directory being mounted on */
3642 	char *mntopts;
3643 	int overlay;
3644 {
3645 	struct mnttab mnt;
3646 	int flags = 0;
3647 	char fstype[] = MNTTYPE_LOFS;
3648 	int dirlen;
3649 	struct stat st;
3650 	char optbuf[MAX_MNTOPT_STR];
3651 
3652 	dirlen = strlen(dir);
3653 	if (dir[dirlen-1] == ' ')
3654 		dirlen--;
3655 
3656 	if (dirlen == strlen(fsname) &&
3657 		strncmp(fsname, dir, dirlen) == 0) {
3658 		syslog(LOG_ERR,
3659 			"Mount of %s on %s would result in deadlock, aborted\n",
3660 			fsname, dir);
3661 		return (RET_ERR);
3662 	}
3663 	mnt.mnt_mntopts = mntopts;
3664 	if (hasmntopt(&mnt, MNTOPT_RO) != NULL)
3665 		flags |= MS_RDONLY;
3666 
3667 	(void) strlcpy(optbuf, mntopts, sizeof (optbuf));
3668 
3669 	if (overlay)
3670 		flags |= MS_OVERLAY;
3671 
3672 	if (trace > 1)
3673 		trace_prt(1,
3674 			"  loopbackmount: fsname=%s, dir=%s, flags=%d\n",
3675 			fsname, dir, flags);
3676 
3677 	if (is_system_labeled()) {
3678 		if (create_homedir((const char *)fsname,
3679 		    (const char *)dir) == 0) {
3680 			return (NFSERR_NOENT);
3681 		}
3682 	}
3683 
3684 	if (mount(fsname, dir, flags | MS_DATA | MS_OPTIONSTR, fstype,
3685 	    NULL, 0, optbuf, sizeof (optbuf)) < 0) {
3686 		syslog(LOG_ERR, "Mount of %s on %s: %m", fsname, dir);
3687 		return (RET_ERR);
3688 	}
3689 
3690 	if (stat(dir, &st) == 0) {
3691 		if (trace > 1) {
3692 			trace_prt(1,
3693 			    "  loopbackmount of %s on %s dev=%x rdev=%x OK\n",
3694 			    fsname, dir, st.st_dev, st.st_rdev);
3695 		}
3696 	} else {
3697 		if (trace > 1) {
3698 			trace_prt(1,
3699 			    "  loopbackmount of %s on %s OK\n", fsname, dir);
3700 			trace_prt(1, "	stat of %s failed\n", dir);
3701 		}
3702 	}
3703 
3704 	return (0);
3705 }
3706 
3707 /*
3708  * Look for the value of a numeric option of the form foo=x.  If found, set
3709  * *valp to the value and return non-zero.  If not found or the option is
3710  * malformed, return zero.
3711  */
3712 
3713 int
3714 nopt(mnt, opt, valp)
3715 	struct mnttab *mnt;
3716 	char *opt;
3717 	int *valp;			/* OUT */
3718 {
3719 	char *equal;
3720 	char *str;
3721 
3722 	/*
3723 	 * We should never get a null pointer, but if we do, it's better to
3724 	 * ignore the option than to dump core.
3725 	 */
3726 
3727 	if (valp == NULL) {
3728 		syslog(LOG_DEBUG, "null pointer for %s option", opt);
3729 		return (0);
3730 	}
3731 
3732 	if (str = hasmntopt(mnt, opt)) {
3733 		if (equal = strchr(str, '=')) {
3734 			*valp = atoi(&equal[1]);
3735 			return (1);
3736 		} else {
3737 			syslog(LOG_ERR, "Bad numeric option '%s'", str);
3738 		}
3739 	}
3740 	return (0);
3741 }
3742 
3743 int
3744 nfsunmount(mnt)
3745 	struct mnttab *mnt;
3746 {
3747 	struct timeval timeout;
3748 	CLIENT *cl;
3749 	enum clnt_stat rpc_stat;
3750 	char *host, *path;
3751 	struct replica *list;
3752 	int i, count = 0;
3753 	int isv4mount = is_v4_mount(mnt->mnt_mountp);
3754 
3755 	if (trace > 1)
3756 		trace_prt(1, "	nfsunmount: umount %s\n", mnt->mnt_mountp);
3757 
3758 	if (umount(mnt->mnt_mountp) < 0) {
3759 		if (trace > 1)
3760 			trace_prt(1, "	nfsunmount: umount %s FAILED\n",
3761 				mnt->mnt_mountp);
3762 		if (errno)
3763 			return (errno);
3764 	}
3765 
3766 	/*
3767 	 * If this is a NFSv4 mount, the mount protocol was not used
3768 	 * so we just return.
3769 	 */
3770 	if (isv4mount) {
3771 		if (trace > 1)
3772 			trace_prt(1, "	nfsunmount: umount %s OK\n",
3773 				mnt->mnt_mountp);
3774 		return (0);
3775 	}
3776 
3777 	/*
3778 	 * If mounted with -o public, then no need to contact server
3779 	 * because mount protocol was not used.
3780 	 */
3781 	if (hasmntopt(mnt, MNTOPT_PUBLIC) != NULL) {
3782 		return (0);
3783 	}
3784 
3785 	/*
3786 	 * The rest of this code is advisory to the server.
3787 	 * If it fails return success anyway.
3788 	 */
3789 
3790 	list = parse_replica(mnt->mnt_special, &count);
3791 	if (!list) {
3792 		if (count >= 0)
3793 			syslog(LOG_ERR,
3794 			    "Memory allocation failed: %m");
3795 		return (ENOMEM);
3796 	}
3797 
3798 	for (i = 0; i < count; i++) {
3799 
3800 		host = list[i].host;
3801 		path = list[i].path;
3802 
3803 		/*
3804 		 * Skip file systems mounted using WebNFS, because mount
3805 		 * protocol was not used.
3806 		 */
3807 		if (strcmp(host, "nfs") == 0 && strncmp(path, "//", 2) == 0)
3808 			continue;
3809 
3810 		cl = clnt_create(host, MOUNTPROG, MOUNTVERS, "datagram_v");
3811 		if (cl == NULL)
3812 			break;
3813 #ifdef MALLOC_DEBUG
3814 		add_alloc("CLNT_HANDLE", cl, 0, __FILE__, __LINE__);
3815 		add_alloc("AUTH_HANDLE", cl->cl_auth, 0,
3816 			__FILE__, __LINE__);
3817 #endif
3818 		if (__clnt_bindresvport(cl) < 0) {
3819 			if (verbose)
3820 				syslog(LOG_ERR, "umount %s:%s: %s",
3821 					host, path,
3822 					"Couldn't bind to reserved port");
3823 			destroy_auth_client_handle(cl);
3824 			continue;
3825 		}
3826 #ifdef MALLOC_DEBUG
3827 		drop_alloc("AUTH_HANDLE", cl->cl_auth, __FILE__, __LINE__);
3828 #endif
3829 		AUTH_DESTROY(cl->cl_auth);
3830 		if ((cl->cl_auth = authsys_create_default()) == NULL) {
3831 			if (verbose)
3832 				syslog(LOG_ERR, "umount %s:%s: %s",
3833 					host, path,
3834 					"Failed creating default auth handle");
3835 			destroy_auth_client_handle(cl);
3836 			continue;
3837 		}
3838 #ifdef MALLOC_DEBUG
3839 		add_alloc("AUTH_HANDLE", cl->cl_auth, 0, __FILE__, __LINE__);
3840 #endif
3841 		timeout.tv_usec = 0;
3842 		timeout.tv_sec = 5;
3843 		rpc_stat = clnt_call(cl, MOUNTPROC_UMNT, xdr_dirpath,
3844 			    (caddr_t)&path, xdr_void, (char *)NULL, timeout);
3845 		if (verbose && rpc_stat != RPC_SUCCESS)
3846 			syslog(LOG_ERR, "%s: %s",
3847 				host, clnt_sperror(cl, "unmount"));
3848 		destroy_auth_client_handle(cl);
3849 	}
3850 
3851 	free_replica(list, count);
3852 
3853 	if (trace > 1)
3854 		trace_prt(1, "	nfsunmount: umount %s OK\n", mnt->mnt_mountp);
3855 
3856 done:
3857 	return (0);
3858 }
3859 
3860 /*
3861  * Put a new entry in the cache chain by prepending it to the front.
3862  * If there isn't enough memory then just give up.
3863  */
3864 static void
3865 cache_enter(host, reqvers, outvers, proto, state)
3866 	char *host;
3867 	rpcvers_t reqvers;
3868 	rpcvers_t outvers;
3869 	char *proto;
3870 	int state;
3871 {
3872 	struct cache_entry *entry;
3873 	int cache_time = 30;	/* sec */
3874 
3875 	timenow = time(NULL);
3876 
3877 	entry = (struct cache_entry *)malloc(sizeof (struct cache_entry));
3878 	if (entry == NULL)
3879 		return;
3880 	(void) memset((caddr_t)entry, 0, sizeof (struct cache_entry));
3881 	entry->cache_host = strdup(host);
3882 	if (entry->cache_host == NULL) {
3883 		cache_free(entry);
3884 		return;
3885 	}
3886 	entry->cache_reqvers = reqvers;
3887 	entry->cache_outvers = outvers;
3888 	entry->cache_proto = (proto == NULL ? NULL : strdup(proto));
3889 	entry->cache_state = state;
3890 	entry->cache_time = timenow + cache_time;
3891 	(void) rw_wrlock(&cache_lock);
3892 #ifdef CACHE_DEBUG
3893 	host_cache_accesses++;		/* up host cache access counter */
3894 #endif /* CACHE DEBUG */
3895 	entry->cache_next = cache_head;
3896 	cache_head = entry;
3897 	(void) rw_unlock(&cache_lock);
3898 }
3899 
3900 static int
3901 cache_check(host, versp, proto)
3902 	char *host;
3903 	rpcvers_t *versp;
3904 	char *proto;
3905 {
3906 	int state = NOHOST;
3907 	struct cache_entry *ce, *prev;
3908 
3909 	timenow = time(NULL);
3910 
3911 	(void) rw_rdlock(&cache_lock);
3912 
3913 #ifdef CACHE_DEBUG
3914 	/* Increment the lookup and access counters for the host cache */
3915 	host_cache_accesses++;
3916 	host_cache_lookups++;
3917 	if ((host_cache_lookups%1000) == 0)
3918 		trace_host_cache();
3919 #endif /* CACHE DEBUG */
3920 
3921 	for (ce = cache_head; ce; ce = ce->cache_next) {
3922 		if (timenow > ce->cache_time) {
3923 			(void) rw_unlock(&cache_lock);
3924 			(void) rw_wrlock(&cache_lock);
3925 			for (prev = NULL, ce = cache_head; ce;
3926 				prev = ce, ce = ce->cache_next) {
3927 				if (timenow > ce->cache_time) {
3928 					cache_free(ce);
3929 					if (prev)
3930 						prev->cache_next = NULL;
3931 					else
3932 						cache_head = NULL;
3933 					break;
3934 				}
3935 			}
3936 			(void) rw_unlock(&cache_lock);
3937 			return (state);
3938 		}
3939 		if (strcmp(host, ce->cache_host) != 0)
3940 			continue;
3941 		if ((proto == NULL && ce->cache_proto != NULL) ||
3942 		    (proto != NULL && ce->cache_proto == NULL))
3943 			continue;
3944 		if (proto != NULL &&
3945 		    strcmp(proto, ce->cache_proto) != 0)
3946 			continue;
3947 
3948 		if (versp == NULL ||
3949 			(versp != NULL && *versp == ce->cache_reqvers) ||
3950 			(versp != NULL && *versp == ce->cache_outvers)) {
3951 				if (versp != NULL)
3952 					*versp = ce->cache_outvers;
3953 				state = ce->cache_state;
3954 
3955 				/* increment the host cache hit counters */
3956 #ifdef CACHE_DEBUG
3957 				if (state == GOODHOST)
3958 					goodhost_cache_hits++;
3959 				if (state == DEADHOST)
3960 					deadhost_cache_hits++;
3961 #endif /* CACHE_DEBUG */
3962 				(void) rw_unlock(&cache_lock);
3963 				return (state);
3964 		}
3965 	}
3966 	(void) rw_unlock(&cache_lock);
3967 	return (state);
3968 }
3969 
3970 /*
3971  * Free a cache entry and all entries
3972  * further down the chain since they
3973  * will also be expired.
3974  */
3975 static void
3976 cache_free(entry)
3977 	struct cache_entry *entry;
3978 {
3979 	struct cache_entry *ce, *next = NULL;
3980 
3981 	for (ce = entry; ce; ce = next) {
3982 		if (ce->cache_host)
3983 			free(ce->cache_host);
3984 		if (ce->cache_proto)
3985 			free(ce->cache_proto);
3986 		next = ce->cache_next;
3987 		free(ce);
3988 	}
3989 }
3990 
3991 #ifdef MALLOC_DEBUG
3992 void
3993 cache_flush()
3994 {
3995 	(void) rw_wrlock(&cache_lock);
3996 	cache_free(cache_head);
3997 	cache_head = NULL;
3998 	(void) rw_unlock(&cache_lock);
3999 }
4000 
4001 void
4002 flush_caches()
4003 {
4004 	mutex_lock(&cleanup_lock);
4005 	cond_signal(&cleanup_start_cv);
4006 	(void) cond_wait(&cleanup_done_cv, &cleanup_lock);
4007 	mutex_unlock(&cleanup_lock);
4008 	cache_flush();
4009 	portmap_cache_flush();
4010 }
4011 #endif
4012 
4013 /*
4014  * Returns 1, if port option is NFS_PORT or
4015  *	nfsd is running on the port given
4016  * Returns 0, if both port is not NFS_PORT and nfsd is not
4017  *	running on the port.
4018  */
4019 
4020 static int
4021 is_nfs_port(char *opts)
4022 {
4023 	struct mnttab m;
4024 	uint_t nfs_port = 0;
4025 	struct servent sv;
4026 	char buf[256];
4027 	int got_port;
4028 
4029 	m.mnt_mntopts = opts;
4030 
4031 	/*
4032 	 * Get port specified in options list, if any.
4033 	 */
4034 	got_port = nopt(&m, MNTOPT_PORT, (int *)&nfs_port);
4035 
4036 	/*
4037 	 * if no port specified or it is same as NFS_PORT return nfs
4038 	 * To use any other daemon the port number should be different
4039 	 */
4040 	if (!got_port || nfs_port == NFS_PORT)
4041 		return (1);
4042 	/*
4043 	 * If daemon is nfsd, return nfs
4044 	 */
4045 	if (getservbyport_r(nfs_port, NULL, &sv, buf, 256) == &sv &&
4046 		strcmp(sv.s_name, "nfsd") == 0)
4047 		return (1);
4048 
4049 	/*
4050 	 * daemon is not nfs
4051 	 */
4052 	return (0);
4053 }
4054 
4055 
4056 /*
4057  * destroy_auth_client_handle(cl)
4058  * destroys the created client handle
4059  */
4060 void
4061 destroy_auth_client_handle(CLIENT *cl)
4062 {
4063 	if (cl) {
4064 		if (cl->cl_auth) {
4065 #ifdef MALLOC_DEBUG
4066 			drop_alloc("AUTH_HANDLE", cl->cl_auth,
4067 				__FILE__, __LINE__);
4068 #endif
4069 			AUTH_DESTROY(cl->cl_auth);
4070 			cl->cl_auth = NULL;
4071 		}
4072 #ifdef MALLOC_DEBUG
4073 		drop_alloc("CLNT_HANDLE", cl,
4074 			__FILE__, __LINE__);
4075 #endif
4076 		clnt_destroy(cl);
4077 	}
4078 }
4079 
4080 
4081 /*
4082  * Attempt to figure out which version of NFS to use in pingnfs().  If
4083  * the version number was specified (i.e., non-zero), then use it.
4084  * Otherwise, default to the compiled-in default or the default as set
4085  * by the /etc/default/nfs configuration (as read by read_default().
4086  */
4087 int
4088 set_versrange(rpcvers_t nfsvers, rpcvers_t *vers, rpcvers_t *versmin)
4089 {
4090 	switch (nfsvers) {
4091 	case 0:
4092 		*vers = vers_max_default;
4093 		*versmin = vers_min_default;
4094 		break;
4095 	case NFS_V4:
4096 		*vers = NFS_V4;
4097 		*versmin = NFS_V4;
4098 		break;
4099 	case NFS_V3:
4100 		*vers = NFS_V3;
4101 		*versmin = NFS_V3;
4102 		break;
4103 	case NFS_VERSION:
4104 		*vers = NFS_VERSION;		/* version 2 */
4105 		*versmin = NFS_VERSMIN;		/* version 2 */
4106 		break;
4107 	default:
4108 		return (-1);
4109 	}
4110 	return (0);
4111 }
4112 
4113 #ifdef CACHE_DEBUG
4114 /*
4115  * trace_portmap_cache()
4116  * traces the portmap cache values at desired points
4117  */
4118 static void
4119 trace_portmap_cache()
4120 {
4121 	syslog(LOG_ERR, "portmap_cache: accesses=%d lookups=%d hits=%d\n",
4122 		portmap_cache_accesses, portmap_cache_lookups,
4123 		portmap_cache_hits);
4124 }
4125 
4126 /*
4127  * trace_host_cache()
4128  * traces the host cache values at desired points
4129  */
4130 static void
4131 trace_host_cache()
4132 {
4133 	syslog(LOG_ERR,
4134 		"host_cache: accesses=%d lookups=%d deadhits=%d goodhits=%d\n",
4135 		host_cache_accesses, host_cache_lookups, deadhost_cache_hits,
4136 		goodhost_cache_hits);
4137 }
4138 #endif /* CACHE_DEBUG */
4139 
4140 /*
4141  * Read the /etc/default/nfs configuration file to determine if the
4142  * client has been configured for a new min/max for the NFS version to
4143  * use.
4144  */
4145 
4146 #define	NFS_DEFAULT_CHECK 60  /* Seconds to check for nfs default changes */
4147 
4148 static void
4149 read_default_nfs(void)
4150 {
4151 	static time_t lastread = 0;
4152 	struct stat buf;
4153 	char *defval;
4154 	int errno;
4155 	int tmp;
4156 
4157 	/*
4158 	 * Fail silently if we can't stat the default nfs config file
4159 	 */
4160 	if (stat(NFSADMIN, &buf))
4161 		return;
4162 
4163 	if (buf.st_mtime == lastread)
4164 		return;
4165 
4166 	/*
4167 	 * Fail silently if error in opening the default nfs config file
4168 	 * We'll check back in NFS_DEFAULT_CHECK seconds
4169 	 */
4170 	if ((defopen(NFSADMIN)) == 0) {
4171 		if ((defval = defread("NFS_CLIENT_VERSMIN=")) != NULL) {
4172 			errno = 0;
4173 			tmp = strtol(defval, (char **)NULL, 10);
4174 			if (errno == 0) {
4175 				vers_min_default = tmp;
4176 			}
4177 		}
4178 		if ((defval = defread("NFS_CLIENT_VERSMAX=")) != NULL) {
4179 			errno = 0;
4180 			tmp = strtol(defval, (char **)NULL, 10);
4181 			if (errno == 0) {
4182 				vers_max_default = tmp;
4183 			}
4184 		}
4185 		/* close defaults file */
4186 		defopen(NULL);
4187 
4188 		lastread = buf.st_mtime;
4189 
4190 		/*
4191 		 * Quick sanity check on the values picked up from the
4192 		 * defaults file.  Make sure that a mistake wasn't
4193 		 * made that will confuse things later on.
4194 		 * If so, reset to compiled-in defaults
4195 		 */
4196 		if (vers_min_default > vers_max_default ||
4197 			vers_min_default < NFS_VERSMIN ||
4198 			vers_max_default > NFS_VERSMAX) {
4199 			if (trace > 1) {
4200 				trace_prt(1,
4201 	"  read_default: version minimum/maximum incorrectly configured\n");
4202 				trace_prt(1,
4203 "  read_default: config is min=%d, max%d. Resetting to min=%d, max%d\n",
4204 					vers_min_default, vers_max_default,
4205 					NFS_VERSMIN_DEFAULT,
4206 					NFS_VERSMAX_DEFAULT);
4207 			}
4208 			vers_min_default = NFS_VERSMIN_DEFAULT;
4209 			vers_max_default = NFS_VERSMAX_DEFAULT;
4210 		}
4211 	}
4212 }
4213 
4214 /*
4215  *  Find the mnttab entry that corresponds to "name".
4216  *  We're not sure what the name represents: either
4217  *  a mountpoint name, or a special name (server:/path).
4218  *  Return the last entry in the file that matches.
4219  */
4220 static struct extmnttab *
4221 mnttab_find(dirname)
4222 	char *dirname;
4223 {
4224 	FILE *fp;
4225 	struct extmnttab mnt;
4226 	struct extmnttab *res = NULL;
4227 
4228 	fp = fopen(MNTTAB, "r");
4229 	if (fp == NULL) {
4230 		if (trace > 1)
4231 			trace_prt(1, "	mnttab_find: unable to open mnttab\n");
4232 		return (NULL);
4233 	}
4234 	while (getextmntent(fp, &mnt, sizeof (struct extmnttab)) == 0) {
4235 		if (strcmp(mnt.mnt_mountp, dirname) == 0 ||
4236 		    strcmp(mnt.mnt_special, dirname) == 0) {
4237 			if (res)
4238 				fsfreemnttab(res);
4239 			res = fsdupmnttab(&mnt);
4240 		}
4241 	}
4242 
4243 	resetmnttab(fp);
4244 	fclose(fp);
4245 	if (res == NULL) {
4246 		if (trace > 1)
4247 			trace_prt(1, "	mnttab_find: unable to find %s\n",
4248 				dirname);
4249 	}
4250 	return (res);
4251 }
4252 
4253 /*
4254  * This function's behavior is taken from nfsstat.
4255  * Trying to determine what NFS version was used for the mount.
4256  */
4257 static int
4258 is_v4_mount(char *mntpath)
4259 {
4260 	kstat_ctl_t *kc = NULL;		/* libkstat cookie */
4261 	kstat_t *ksp;
4262 	ulong_t fsid;
4263 	struct mntinfo_kstat mik;
4264 	struct extmnttab *mntp;
4265 	uint_t mnt_minor;
4266 
4267 	if ((mntp = mnttab_find(mntpath)) == NULL)
4268 		return (FALSE);
4269 
4270 	/* save the minor number and free the struct so we don't forget */
4271 	mnt_minor = mntp->mnt_minor;
4272 	fsfreemnttab(mntp);
4273 
4274 	if ((kc = kstat_open()) == NULL)
4275 		return (FALSE);
4276 
4277 	for (ksp = kc->kc_chain; ksp; ksp = ksp->ks_next) {
4278 		if (ksp->ks_type != KSTAT_TYPE_RAW)
4279 			continue;
4280 		if (strcmp(ksp->ks_module, "nfs") != 0)
4281 			continue;
4282 		if (strcmp(ksp->ks_name, "mntinfo") != 0)
4283 			continue;
4284 		if (mnt_minor != ksp->ks_instance)
4285 			continue;
4286 
4287 		if (kstat_read(kc, ksp, &mik) == -1)
4288 			continue;
4289 
4290 		(void) kstat_close(kc);
4291 		if (mik.mik_vers == 4)
4292 			return (TRUE);
4293 		else
4294 			return (FALSE);
4295 	}
4296 	(void) kstat_close(kc);
4297 
4298 	return (FALSE);
4299 }
4300 
4301 static int
4302 create_homedir(const char *src, const char *dst) {
4303 
4304 	struct stat stbuf;
4305 	char *dst_username;
4306 	struct passwd *pwd, pwds;
4307 	char buf_pwd[NSS_BUFLEN_PASSWD];
4308 	int homedir_len;
4309 	int dst_dir_len;
4310 	int src_dir_len;
4311 
4312 	if (trace > 1)
4313 		trace_prt(1, "entered create_homedir\n");
4314 
4315 	if (stat(src, &stbuf) == 0) {
4316 		if (trace > 1)
4317 			trace_prt(1, "src exists\n");
4318 		return (1);
4319 	}
4320 
4321 	dst_username = strrchr(dst, '/');
4322 	if (dst_username) {
4323 		dst_username++; /* Skip over slash */
4324 		pwd = getpwnam_r(dst_username, &pwds, buf_pwd,
4325 		    sizeof (buf_pwd));
4326 		if (pwd == NULL) {
4327 			return (0);
4328 		}
4329 	} else {
4330 		return (0);
4331 	}
4332 
4333 	homedir_len = strlen(pwd->pw_dir);
4334 	dst_dir_len = strlen(dst) - homedir_len;
4335 	src_dir_len = strlen(src) - homedir_len;
4336 
4337 	/* Check that the paths are in the same zone */
4338 	if (src_dir_len < dst_dir_len ||
4339 	    (strncmp(dst, src, dst_dir_len) != 0)) {
4340 		if (trace > 1)
4341 			trace_prt(1, "	paths don't match\n");
4342 		return (0);
4343 	}
4344 	/* Check that mountpoint is an auto_home entry */
4345 	if (dst_dir_len < 0 ||
4346 	    (strcmp(pwd->pw_dir, dst + dst_dir_len) != 0)) {
4347 		return (0);
4348 	}
4349 
4350 	/* Check that source is an home directory entry */
4351 	if (src_dir_len < 0 ||
4352 	    (strcmp(pwd->pw_dir, src + src_dir_len) != 0)) {
4353 		if (trace > 1)
4354 			trace_prt(1, "	homedir (2) doesn't match %s\n",
4355 		src+src_dir_len);
4356 		return (0);
4357 	}
4358 
4359 	if (mkdir(src,
4360 	    S_IRUSR | S_IWUSR | S_IXUSR | S_IXGRP | S_IXOTH) == -1) {
4361 		if (trace > 1) {
4362 			trace_prt(1, "	Couldn't mkdir %s\n", src);
4363 		}
4364 		return (0);
4365 	}
4366 
4367 	if (chown(src, pwd->pw_uid, pwd->pw_gid) == -1) {
4368 		unlink(src);
4369 		return (0);
4370 	}
4371 
4372 	/* Created new home directory for the user */
4373 	return (1);
4374 }
4375 
4376 void
4377 free_nfs_args(struct nfs_args *argp)
4378 {
4379 	struct nfs_args *oldp;
4380 	while (argp) {
4381 		if (argp->pathconf)
4382 			free(argp->pathconf);
4383 		if (argp->knconf)
4384 			free_knconf(argp->knconf);
4385 		if (argp->addr)
4386 			netbuf_free(argp->addr);
4387 		if (argp->syncaddr)
4388 			netbuf_free(argp->syncaddr);
4389 		if (argp->netname)
4390 			free(argp->netname);
4391 		if (argp->hostname)
4392 			free(argp->hostname);
4393 		if (argp->nfs_ext_u.nfs_extB.secdata)
4394 			nfs_free_secdata(argp->nfs_ext_u.nfs_extB.secdata);
4395 		if (argp->fh)
4396 			free(argp->fh);
4397 		if (argp->nfs_ext_u.nfs_extA.secdata) {
4398 			sec_data_t	*sd;
4399 			sd = argp->nfs_ext_u.nfs_extA.secdata;
4400 			if (sd == NULL)
4401 				break;
4402 			switch (sd->rpcflavor) {
4403 			case AUTH_NONE:
4404 			case AUTH_UNIX:
4405 			case AUTH_LOOPBACK:
4406 				break;
4407 			case AUTH_DES:
4408 			{
4409 				dh_k4_clntdata_t	*dhk4;
4410 				dhk4 = (dh_k4_clntdata_t *)sd->data;
4411 				if (dhk4 == NULL)
4412 					break;
4413 				if (dhk4->syncaddr.buf)
4414 					free(dhk4->syncaddr.buf);
4415 				if (dhk4->knconf->knc_protofmly)
4416 					free(dhk4->knconf->knc_protofmly);
4417 				if (dhk4->knconf->knc_proto)
4418 					free(dhk4->knconf->knc_proto);
4419 				if (dhk4->knconf)
4420 					free(dhk4->knconf);
4421 				if (dhk4->netname)
4422 					free(dhk4->netname);
4423 				free(dhk4);
4424 				break;
4425 			}
4426 			case RPCSEC_GSS:
4427 			{
4428 				gss_clntdata_t	*gss;
4429 				gss = (gss_clntdata_t *)sd->data;
4430 				if (gss == NULL)
4431 					break;
4432 				if (gss->mechanism.elements)
4433 					free(gss->mechanism.elements);
4434 				free(gss);
4435 				break;
4436 			}
4437 			}
4438 		}
4439 		oldp = argp;
4440 		if (argp->nfs_args_ext == NFS_ARGS_EXTB)
4441 			argp = argp->nfs_ext_u.nfs_extB.next;
4442 		else
4443 			argp = NULL;
4444 		free(oldp);
4445 	}
4446 }
4447