1/*
2 * Copyright (c) 2000-2001 Boris Popov
3 * All rights reserved.
4 *
5 * Portions Copyright (C) 2001 - 2014 Apple Inc. All rights reserved.
6 *
7 * Redistribution and use in source and binary forms, with or without
8 * modification, are permitted provided that the following conditions
9 * are met:
10 * 1. Redistributions of source code must retain the above copyright
11 *    notice, this list of conditions and the following disclaimer.
12 * 2. Redistributions in binary form must reproduce the above copyright
13 *    notice, this list of conditions and the following disclaimer in the
14 *    documentation and/or other materials provided with the distribution.
15 * 3. All advertising materials mentioning features or use of this software
16 *    must display the following acknowledgement:
17 *    This product includes software developed by Boris Popov.
18 * 4. Neither the name of the author nor the names of any co-contributors
19 *    may be used to endorse or promote products derived from this software
20 *    without specific prior written permission.
21 *
22 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
23 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
24 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
25 * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
26 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
27 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
28 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
29 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
30 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
31 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
32 * SUCH DAMAGE.
33 *
34 */
35/*
36 * various SMB requests. Most of the routines merely packs data into mbufs.
37 */
38#include <stdint.h>
39#include <sys/param.h>
40#include <sys/systm.h>
41#include <sys/kernel.h>
42#include <sys/malloc.h>
43#include <sys/proc.h>
44#include <sys/lock.h>
45#include <sys/sysctl.h>
46#include <sys/socket.h>
47#include <sys/uio.h>
48#include <sys/random.h>
49
50#include <sys/kpi_mbuf.h>
51#include <sys/smb_apple.h>
52#include <sys/utfconv.h>
53
54#include <netsmb/smb.h>
55#include <netsmb/smb_2.h>
56#include <netsmb/smb_subr.h>
57#include <netsmb/smb_rq.h>
58#include <netsmb/smb_rq_2.h>
59#include <netsmb/smb_conn.h>
60#include <netsmb/smb_conn_2.h>
61#include <netsmb/smb_tran.h>
62#include <netsmb/smb_gss.h>
63#include <smbfs/smbfs_subr.h>
64#include <netinet/in.h>
65#include <sys/kauth.h>
66#include <smbfs/smbfs.h>
67#include <netsmb/smb_converter.h>
68#include <netsmb/smb_dev.h>
69#include <smbclient/ntstatus.h>
70
71struct smb_dialect {
72	int				d_id;
73	const char *	d_name;
74};
75
76/*
77 * We no long support older  dialects, but leaving this
78 * information here for prosperity.
79 *
80 * SMB dialects that we have to deal with.
81 *
82 * The following are known servers that do not support NT LM 0.12 dialect:
83 * Windows for Workgroups and OS/2
84 *
85 * The following are known servers that do support NT LM 0.12 dialect:
86 * Windows 95, Windows 98, Windows NT (include 3.51), Windows 2000, Windows XP,
87 * Windows 2003, NetApp, EMC, Snap,  and SAMBA.
88 */
89
90enum smb_dialects {
91	SMB_DIALECT_NONE,
92	SMB_DIALECT_CORE,			/* PC NETWORK PROGRAM 1.0, PCLAN1.0 */
93	SMB_DIALECT_COREPLUS,		/* MICROSOFT NETWORKS 1.03 */
94	SMB_DIALECT_LANMAN1_0,		/* MICROSOFT NETWORKS 3.0, LANMAN1.0 */
95	SMB_DIALECT_LANMAN2_0,		/* LM1.2X002, DOS LM1.2X002, Samba */
96	SMB_DIALECT_LANMAN2_1,		/* DOS LANMAN2.1, LANMAN2.1 */
97	SMB_DIALECT_NTLM0_12,		/* NT LM 0.12 */
98	SMB_DIALECT_SMB2_002,		/* SMB 2.002 */
99	SMB_DIALECT_SMB2_000		/* SMB 2.??? */
100};
101
102/*
103 * MAX_DIALECT_STRING should alway be the largest dialect string length
104 * that we support. Currently we only support "NT LM 0.12" so 12 should
105 * be fine.
106 */
107#define MAX_DIALECT_STRING		12
108
109static struct smb_dialect smb_dialects[] = {
110/*
111 * The following are no longer supported by this
112 * client, but have been left here for historical
113 * reasons.
114 *
115	{SMB_DIALECT_CORE,	"PC NETWORK PROGRAM 1.0"},
116	{SMB_DIALECT_COREPLUS,	"MICROSOFT NETWORKS 1.03"},
117	{SMB_DIALECT_LANMAN1_0,	"MICROSOFT NETWORKS 3.0"},
118	{SMB_DIALECT_LANMAN1_0,	"LANMAN1.0"},
119	{SMB_DIALECT_LANMAN2_0,	"LM1.2X002"},
120	{SMB_DIALECT_LANMAN2_1,	"LANMAN2.1"},
121	{SMB_DIALECT_NTLM0_12,	"NT LANMAN 1.0"},
122 */
123	{SMB_DIALECT_NTLM0_12,	"NT LM 0.12"},
124	{SMB_DIALECT_SMB2_002,	"SMB 2.002"},
125	{SMB_DIALECT_SMB2_000,	"SMB 2.???"},
126    {-1,			NULL}
127};
128
129static struct smb_dialect smb1_dialects[] = {
130    /*
131     * The following are no longer supported by this
132     * client, but have been left here for historical
133     * reasons.
134     *
135     {SMB_DIALECT_CORE,	"PC NETWORK PROGRAM 1.0"},
136     {SMB_DIALECT_COREPLUS,	"MICROSOFT NETWORKS 1.03"},
137     {SMB_DIALECT_LANMAN1_0,	"MICROSOFT NETWORKS 3.0"},
138     {SMB_DIALECT_LANMAN1_0,	"LANMAN1.0"},
139     {SMB_DIALECT_LANMAN2_0,	"LM1.2X002"},
140     {SMB_DIALECT_LANMAN2_1,	"LANMAN2.1"},
141     {SMB_DIALECT_NTLM0_12,	"NT LANMAN 1.0"},
142     */
143	{SMB_DIALECT_NTLM0_12,	"NT LM 0.12"},
144    {-1,			NULL}
145};
146
147/*
148 * Really could be 128K - (SMBHDR + SMBREADANDX RESPONSE HDR), but 126K works better with the Finder.
149 *
150 * Note old Samba's are busted, they set the SMB_CAP_LARGE_READX and SMB_CAP_LARGE_WRITEX, but can't handle anything
151 * larger that 64K-1. This was fixed in Samba 3.0.23 and greater, but since Tiger is running 3.0.10 we need to work
152 * around this problem yuk! Samba has a way to set the transfer buffer size and our Leopard Samba was this set to
153 * a value larger than 60K. So here is the kludge that I would like to have removed in the future. If they support
154 * the SMB_CAP_LARGE_READX and SMB_CAP_LARGE_WRITEX, they say they are UNIX and they have a transfer buffer size
155 * greater than 60K then use the 126K buffer size.
156 */
157#define MIN_MAXTRANSBUFFER				1024
158#define SMB1_MAXTRANSBUFFER				0xffff
159#define MAX_LARGEX_READ_CAP_SIZE		128*1024
160#define MAX_LARGEX_WRITE_CAP_SIZE		128*1024
161#define SNOW_LARGEX_READ_CAP_SIZE		126*1024
162#define SNOW_LARGEX_WRITE_CAP_SIZE		126*1024
163#define WINDOWS_LARGEX_READ_CAP_SIZE	60*1024
164#define WINDOWS_LARGEX_WRITE_CAP_SIZE	60*1024
165
166static
167uint32_t smb_vc_maxread(struct smb_vc *vcp)
168{
169	uint32_t socksize = vcp->vc_sopt.sv_maxtx;
170	uint32_t maxmsgsize = vcp->vc_sopt.sv_maxtx;
171	uint32_t hdrsize = SMB_HDRLEN;
172
173	hdrsize += SMB_READANDX_HDRLEN; /* we only use ReadAndX */
174
175	/* Make sure we never use a size bigger than the socket can support */
176	SMB_TRAN_GETPARAM(vcp, SMBTP_RCVSZ, &socksize);
177	maxmsgsize = MIN(maxmsgsize, socksize);
178	maxmsgsize -= hdrsize;
179	/*
180	 * SNIA Specs say up to 64k data bytes, but it is wrong. Windows traffic
181	 * uses 60k... no doubt for some good reason.
182	 *
183	 * The NetBIOS Header supports up 128K for the whole message. Some Samba servers
184	 * can only handle reads of 64K minus 1. We want the read and writes to be mutilples of
185	 * each other. Remember we want IO request to not only be a multiple of our
186	 * max buffer size but they must land on a PAGE_SIZE boundry. See smbfs_vfs_getattr
187	 * more on this issue.
188	 *
189	 * NOTE: For NetBIOS-less connections the NetBIOS Header supports 24 bits for
190	 * the length field.
191	 */
192	if (VC_CAPS(vcp) & SMB_CAP_LARGE_READX) {
193		/* Leave the UNIX SERVER check for now, but in the futre we should drop it */
194		if (UNIX_SERVER(vcp) && (vcp->vc_saddr->sa_family != AF_NETBIOS)  &&
195			(maxmsgsize >= MAX_LARGEX_READ_CAP_SIZE)) {
196			/*
197			 * Once we do <rdar://problem/8753536> we should change the
198			 * maxmsgsize to be the following:
199			 *		maxmsgsize = (maxmsgsize / PAGE_SIZE) * PAGE_SIZE;
200			 * For now limit max size 128K.
201			 */
202			maxmsgsize = MAX_LARGEX_READ_CAP_SIZE;
203		} else if (UNIX_SERVER(vcp) && (maxmsgsize > WINDOWS_LARGEX_READ_CAP_SIZE)) {
204			maxmsgsize = SNOW_LARGEX_READ_CAP_SIZE;
205		} else {
206			socksize -= hdrsize;
207			maxmsgsize = MIN(WINDOWS_LARGEX_READ_CAP_SIZE, socksize);
208		}
209	}
210	SMB_LOG_IO("%s max = %d sock = %d sv_maxtx = %d\n", vcp->vc_srvname,
211			   maxmsgsize, socksize, vcp->vc_sopt.sv_maxtx);
212	return maxmsgsize;
213}
214
215/*
216 * Figure out the largest write we can do to the server.
217 */
218static uint32_t
219smb_vc_maxwrite(struct smb_vc *vcp)
220{
221	uint32_t socksize = vcp->vc_sopt.sv_maxtx;
222	uint32_t maxmsgsize = vcp->vc_sopt.sv_maxtx;
223	uint32_t hdrsize = SMB_HDRLEN;
224
225	hdrsize += SMB_WRITEANDX_HDRLEN;    /* we only use WriteAndX */
226
227	/* Make sure we never use a size bigger than the socket can support */
228	SMB_TRAN_GETPARAM(vcp, SMBTP_SNDSZ, &socksize);
229	maxmsgsize = MIN(maxmsgsize, socksize);
230	maxmsgsize -= hdrsize;
231	/*
232	 * SNIA Specs say up to 64k data bytes, but it is wrong. Windows traffic
233	 * uses 60k... no doubt for some good reason.
234	 *
235	 * The NetBIOS Header supports up 128K for the whole message. Samba will
236	 * handle up to 127K for writes. We want the read and writes to be mutilples of
237	 * each other. Remember we want IO request to not only be a multiple of our
238	 * max buffer size but they must land on a PAGE_SIZE boundry. See smbfs_vfs_getattr
239	 * more on this issue.
240	 *
241	 *
242	 * When doing packet signing Windows server will break the connection if you
243	 * use large writes. If we are going against SAMBA this should not be an issue.
244	 *
245	 * NOTE: Windows XP/2000/2003 support 126K writes, but not reads so for now we use 60K buffers
246	 *		 in both cases.
247	 *
248	 * NOTE: For NetBIOS-less connections the NetBIOS Header supports 24 bits for
249	 * the length field.
250	 */
251	if ((vcp->vc_hflags2 & SMB_FLAGS2_SECURITY_SIGNATURE) && (! UNIX_SERVER(vcp))) {
252		SMB_LOG_IO("%s %d - SIGNING ON\n", vcp->vc_srvname, maxmsgsize);
253		return maxmsgsize;
254	} else  if (VC_CAPS(vcp) & SMB_CAP_LARGE_WRITEX) {
255		/* Leave the UNIX SERVER check for now, but in the futre we should drop it */
256		if (UNIX_SERVER(vcp) && (vcp->vc_saddr->sa_family != AF_NETBIOS) &&
257			(maxmsgsize >= MAX_LARGEX_WRITE_CAP_SIZE)) {
258			/*
259			 * Once we do <rdar://problem/8753536> we should change the
260			 * maxmsgsize to be the following:
261			 *		maxmsgsize = (maxmsgsize / PAGE_SIZE) * PAGE_SIZE;
262			 * For now limit max size 128K.
263			 */
264			maxmsgsize = MAX_LARGEX_WRITE_CAP_SIZE;
265		} else if (UNIX_SERVER(vcp) && (maxmsgsize > WINDOWS_LARGEX_WRITE_CAP_SIZE)) {
266			maxmsgsize = SNOW_LARGEX_WRITE_CAP_SIZE;
267		} else {
268			socksize -= hdrsize;
269			maxmsgsize = MIN(WINDOWS_LARGEX_WRITE_CAP_SIZE, socksize);
270		}
271	}
272	SMB_LOG_IO("%s max = %d sock = %d sv_maxtx = %d\n", vcp->vc_srvname,
273			   maxmsgsize, socksize, vcp->vc_sopt.sv_maxtx);
274	return maxmsgsize;
275}
276
277int
278smb_smb_nomux(struct smb_vc *vcp, const char *name, vfs_context_t context)
279{
280	if (context == vcp->vc_iod->iod_context)
281		return 0;
282	SMBERROR("wrong function called(%s)\n", name);
283	return EINVAL;
284}
285
286int
287smb1_smb_negotiate(struct smb_vc *vcp, vfs_context_t user_context,
288                   int inReconnect, int onlySMB1, vfs_context_t context)
289{
290	struct smb_dialect *dp;
291	struct smb_sopt *sp = NULL;
292	struct smb_rq *rqp;
293	struct mbchain *mbp;
294	struct mdchain *mdp;
295	uint8_t wc = 0, stime[8], sblen;
296	uint16_t dindex, bc;
297	int error;
298	uint32_t maxqsz;
299	uint16_t toklen;
300	u_char security_mode;
301	uint32_t	original_caps;
302
303	if (smb_smb_nomux(vcp, __FUNCTION__, context) != 0)
304		return EINVAL;
305	vcp->vc_hflags = SMB_FLAGS_CASELESS;
306	/* Leave SMB_FLAGS2_UNICODE "off" - no need to do anything */
307	vcp->vc_hflags2 |= SMB_FLAGS2_ERR_STATUS;
308	sp = &vcp->vc_sopt;
309	original_caps = sp->sv_caps;
310	error = smb_rq_alloc(VCTOCP(vcp), SMB_COM_NEGOTIATE, 0, context, &rqp);
311	if (error)
312		return error;
313	smb_rq_getrequest(rqp, &mbp);
314	smb_rq_wstart(rqp);
315	smb_rq_wend(rqp);
316	smb_rq_bstart(rqp);
317
318	/*
319	 * The dialects are never in UNICODE, so just put the strings in by hand.
320	 */
321    if (onlySMB1 == 1) {
322        /* only advertise SMB 1 dialects */
323        for(dp = smb1_dialects; dp->d_id != -1; dp++) {
324            mb_put_uint8(mbp, SMB_DT_DIALECT);
325            mb_put_mem(mbp, dp->d_name, strlen(dp->d_name), MB_MSYSTEM);
326            mb_put_uint8(mbp, 0);
327        }
328    }
329    else {
330        /* Advertise SMB 1 and SMB 2/3 dialects */
331        for(dp = smb_dialects; dp->d_id != -1; dp++) {
332            mb_put_uint8(mbp, SMB_DT_DIALECT);
333            mb_put_mem(mbp, dp->d_name, strlen(dp->d_name), MB_MSYSTEM);
334            mb_put_uint8(mbp, 0);
335        }
336    }
337	smb_rq_bend(rqp);
338
339	error = smb_rq_simple(rqp);
340	if (error)
341		goto bad;
342
343    if (rqp->sr_extflags & SMB2_RESPONSE) {
344        /* Got a SMB 2/3 response, do SMB 2/3 Negotiate */
345        error = smb2_smb_negotiate(vcp, rqp, inReconnect, user_context, context);
346        smb_rq_done(rqp);
347        return (error);
348    }
349
350    /* SMB 1 does not support File IDs */
351    vcp->vc_misc_flags &= ~SMBV_HAS_FILEIDS;
352
353    /* Now get the response */
354	smb_rq_getreply(rqp, &mdp);
355
356	error = md_get_uint8(mdp, &wc);
357	/*
358	 * If they didn't return an error and word count is wrong then error out.
359	 * We always expect a work count of 17 now that we only support NTLM 012 dialect.
360	 */
361	 if ((error == 0) && (wc != 17)) {
362		 error = EBADRPC;
363		 goto bad;
364	 }
365
366	if (error == 0)
367		error = md_get_uint16le(mdp, &dindex);
368	if (error)
369		goto bad;
370	/*
371	 * The old code support more than one dialect. Since everything equal to or newer than
372	 * Windows 95 supports the NTLM 012 dialect we only request that dialect. So
373	 * if the server responded without an error then they must support our dialect.
374	 *
375	 * Seems some servers return a negative one.
376	 */
377	if (dindex != 0) {
378		/* In our case should always be zero! */
379		SMBERROR("Bad dialect (%d, %d)\n", dindex, wc);
380		error = ENOTSUP;
381		goto bad;
382	}
383
384	md_get_uint8(mdp, &security_mode);	/* Ge the server security modes */
385	vcp->vc_flags |= (security_mode & SMBV_SECURITY_MODE_MASK);
386	md_get_uint16le(mdp, &sp->sv_maxmux);
387	if (sp->sv_maxmux == 0) {
388		SMBERROR(" Maximum multiplexer is zero, not supported\n");
389		error = ENOTSUP;
390		goto bad;
391	}
392
393	md_get_uint16le(mdp, &sp->sv_maxvcs);
394	md_get_uint32le(mdp, &sp->sv_maxtx);
395	/* Was sv_maxraw, we never do raw reads or writes so just ignore */
396	md_get_uint32le(mdp, NULL);
397	md_get_uint32le(mdp, &sp->sv_skey);
398	md_get_uint32le(mdp, &sp->sv_caps);
399	md_get_mem(mdp, (caddr_t)stime, 8, MB_MSYSTEM);
400	/* Servers time zone no longer needed */
401	md_get_uint16le(mdp, NULL);
402	md_get_uint8(mdp, &sblen);
403	error = md_get_uint16le(mdp, &bc);
404	if (error)
405		goto bad;
406
407	if (vcp->vc_misc_flags & SMBV_CLIENT_SIGNING_REQUIRED) {
408		SMB_LOG_AUTH(" SMB Client requires Signing, server supports 0x%x\n", vcp->vc_flags);
409        if (vcp->vc_flags & (SMBV_SIGNING_REQUIRED | SMBV_SIGNING)) {
410            vcp->vc_flags |= SMBV_SIGNING_REQUIRED;
411        } else {
412            SMBERROR(" SMB Client requires Signing, server doesn't!\n");
413            error = EAUTH;
414            goto bad;
415        }
416    }
417	if (vcp->vc_flags & SMBV_SIGNING_REQUIRED)
418		vcp->vc_hflags2 |= SMB_FLAGS2_SECURITY_SIGNATURE;
419
420    if (!(sp->sv_caps & SMB_CAP_NT_SMBS) || !(sp->sv_caps & SMB_CAP_UNICODE))  {
421		SMBERROR("Support for the server %s has been deprecated (PreXP), disconnecting\n", vcp->vc_srvname);
422		error = SMB_ENETFSNOPROTOVERSSUPP;
423		goto bad;
424	}
425	/*
426	 * Is this a NT4 server, there is a very simple way to tell if it is a NT4 system. NT4
427	 * support SMB_CAP_LARGE_READX, but not SMB_CAP_LARGE_WRITEX. I suppose some other system could do
428	 * the same, but that shouldn't hurt since this is a very limited case we are checking.
429	 * If they say they are UNIX then they can't be a NT4 server
430	 */
431	if (((sp->sv_caps & SMB_CAP_UNIX) != SMB_CAP_UNIX) &&
432		((sp->sv_caps & SMB_CAP_LARGE_RDWRX) == SMB_CAP_LARGE_READX))
433		vcp->vc_flags |= SMBV_NT4;
434
435	/*
436	 * They don't do NT error codes.
437	 *
438	 * If we send requests with SMB_FLAGS2_ERR_STATUS set in Flags2, Windows 98, at least, appears to send
439	 * replies with that bit set even though it sends back  DOS error codes. (They probably just use the
440	 * request header as a template for the reply header, and don't bother clearing that bit.) Therefore, we
441	 * clear that bit in our vc_hflags2 field.
442	 */
443	if ((sp->sv_caps & SMB_CAP_STATUS32) != SMB_CAP_STATUS32)
444		vcp->vc_hflags2 &= ~SMB_FLAGS2_ERR_STATUS;
445
446	/* If the server doesn't do extended security then turn off the SMB_FLAGS2_EXT_SEC flag. */
447	if ((sp->sv_caps & SMB_CAP_EXT_SECURITY) != SMB_CAP_EXT_SECURITY)
448		vcp->vc_hflags2 &= ~SMB_FLAGS2_EXT_SEC;
449
450	/*
451	 * 3 cases here:
452	 *
453	 * 1) Extended security. Read bc bytes below for security blob.
454	 *
455	 * 2) No extended security, have challenge data and possibly a domain name (which might be zero
456	 * bytes long, meaning "missing"). Copy challenge stuff to vcp->vc_ch (sblen bytes),
457	 *
458	 * 3) No extended security, no challenge data, just possibly a domain name.
459	 */
460
461	/*
462	 * Sanity check: make sure the challenge length
463	 * isn't bigger than the byte count.
464	 */
465	if (sblen > bc) {
466		error = EBADRPC;
467		goto bad;
468	}
469	toklen = bc;
470
471	if (sblen && (sblen <= SMB_MAXCHALLENGELEN) && (vcp->vc_flags & SMBV_ENCRYPT_PASSWORD)) {
472		error = md_get_mem(mdp, (caddr_t)(vcp->vc_ch), sblen, MB_MSYSTEM);
473		if (error)
474			goto bad;
475		vcp->vc_chlen = sblen;
476		toklen -= sblen;
477	}
478	/* The server does extend security, find out what mech type they support. */
479	if (vcp->vc_hflags2 & SMB_FLAGS2_EXT_SEC) {
480        if (vcp->negotiate_token != NULL) {
481            SMB_FREE(vcp->negotiate_token, M_SMBTEMP);
482        }
483
484		/*
485		 * We don't currently use the GUID, now if no guid isn't that a
486		 * protocol error. For now lets just ignore, but really think this
487		 * should be an error
488		 */
489		(void)md_get_mem(mdp, NULL, SMB_GUIDLEN, MB_MSYSTEM);
490		toklen = (toklen >= SMB_GUIDLEN) ? toklen - SMB_GUIDLEN : 0;
491
492        if (toklen) {
493            SMB_MALLOC(vcp->negotiate_token, uint8_t *, toklen, M_SMBTEMP, M_WAITOK);
494        }
495        else {
496            vcp->negotiate_token = NULL;
497        }
498		if (vcp->negotiate_token) {
499			vcp->negotiate_tokenlen = toklen;
500			error = md_get_mem(mdp, (void *)vcp->negotiate_token, vcp->negotiate_tokenlen, MB_MSYSTEM);
501			/* If we get an error pretend we have no blob and force NTLMSSP */
502			if (error) {
503                if (vcp->negotiate_token != NULL) {
504                    SMB_FREE(vcp->negotiate_token, M_SMBTEMP);
505                }
506			}
507		}
508		/* If no token then say we have no length */
509		if (vcp->negotiate_token == NULL) {
510			vcp->negotiate_tokenlen = 0;
511		}
512		error = smb_gss_negotiate(vcp, user_context);
513		if (error)
514			goto bad;
515	}
516
517	if (sp->sv_maxtx < MIN_MAXTRANSBUFFER) {
518		error = EBADRPC;
519		goto bad;
520	}
521
522	vcp->vc_rxmax = smb_vc_maxread(vcp);
523	vcp->vc_wxmax = smb_vc_maxwrite(vcp);
524	/* Make sure the  socket buffer supports this size */
525	SMB_TRAN_GETPARAM(vcp, SMBTP_RCVSZ, &maxqsz);
526	vcp->vc_txmax = MIN(sp->sv_maxtx, maxqsz);
527	SMB_TRAN_GETPARAM(vcp, SMBTP_SNDSZ, &maxqsz);
528	vcp->vc_txmax = MIN(vcp->vc_txmax, maxqsz);
529	/*
530	 * SMB currently returns this buffer size in the SetupAndX message as a uint16_t
531	 * value even though the server can pass us a uint32_t value. Make sure it
532	 * fits in a uint16_t field.
533	 */
534	vcp->vc_txmax = MIN(vcp->vc_txmax, SMB1_MAXTRANSBUFFER);
535	SMBSDEBUG("CAPS = %x\n", sp->sv_caps);
536	SMBSDEBUG("MAXMUX = %d\n", sp->sv_maxmux);
537	SMBSDEBUG("MAXVCS = %d\n", sp->sv_maxvcs);
538	SMBSDEBUG("MAXTX = %d\n", sp->sv_maxtx);
539	SMBSDEBUG("TXMAX = %d\n", vcp->vc_txmax);
540	SMBSDEBUG("MAXWR = %d\n", vcp->vc_wxmax);
541	SMBSDEBUG("MAXRD = %d\n", vcp->vc_rxmax);
542
543
544	/* When doing a reconnect we never allow them to change the encode */
545	if (inReconnect) {
546		if (original_caps != sp->sv_caps)
547			SMBWARNING("Reconnecting with different sv_caps %x != %x\n", original_caps, sp->sv_caps);
548	}
549    vcp->vc_hflags2 |= SMB_FLAGS2_UNICODE;
550
551bad:
552	smb_rq_done(rqp);
553	return error;
554}
555
556/*
557 * smb_vc_caps:
558 *
559 * Given a virtual circut, determine our capabilities to send to the server
560 * as part of "ssandx" message.
561 */
562uint32_t
563smb_vc_caps(struct smb_vc *vcp)
564{
565	uint32_t caps =  SMB_CAP_LARGE_FILES | SMB_CAP_NT_SMBS | SMB_CAP_UNICODE;
566
567	if (vcp->vc_hflags2 & SMB_FLAGS2_ERR_STATUS)
568		caps |= SMB_CAP_STATUS32;
569
570	/* If they support it then we support it. */
571	if (VC_CAPS(vcp) & SMB_CAP_LARGE_READX)
572		caps |= SMB_CAP_LARGE_READX;
573
574	if (VC_CAPS(vcp) & SMB_CAP_LARGE_WRITEX)
575		caps |= SMB_CAP_LARGE_WRITEX;
576
577	if (VC_CAPS(vcp) & SMB_CAP_UNIX)
578		caps |= SMB_CAP_UNIX;
579
580	return (caps);
581
582}
583
584/*
585 * Retreive the OS and Lan Man Strings. The calling routines
586 */
587void
588parse_server_os_lanman_strings(struct smb_vc *vcp, void *refptr, uint16_t bc)
589{
590	struct mdchain *mdp = (struct mdchain *)refptr;
591	uint8_t *tmpbuf= NULL;
592	size_t oslen = 0, lanmanlen = 0, lanmanoffset = 0;
593	int error;
594#ifdef SMB_DEBUG
595	size_t domainoffset = 0;
596#endif // SMB_DEBUG
597
598	/*
599	 * Make sure we  have a byte count and the byte cound needs to be less that the
600	 * amount we negotiated. Also only get this info once, NTLMSSP will cause us to see
601	 * this message twice we only need to get it once.
602	 */
603	if ((bc == 0) || (bc > vcp->vc_txmax) || vcp->NativeOS || vcp->NativeLANManager)
604		goto done;
605    SMB_MALLOC(tmpbuf, uint8_t *, bc, M_SMBTEMP, M_WAITOK);
606	if (!tmpbuf)
607		goto done;
608
609	error = md_get_mem(mdp, (void *)tmpbuf, bc, MB_MSYSTEM);
610	if (error)
611		goto done;
612
613#ifdef SMB_DEBUG
614	smb_hexdump(__FUNCTION__, "BLOB = ", tmpbuf, bc);
615#endif // SMB_DEBUG
616
617	if (SMB_UNICODE_STRINGS(vcp)) {
618		/* Find the end of the OS String */
619		lanmanoffset = oslen = smb_utf16_strnsize((const uint16_t *)tmpbuf, bc);
620		lanmanoffset += 2;	/* Skip the null bytes */
621		if (lanmanoffset < bc) {
622			bc -= lanmanoffset;
623			/* Find the end of the Lanman String */
624			lanmanlen = smb_utf16_strnsize((const uint16_t *)&tmpbuf[lanmanoffset], bc);
625#ifdef SMB_DEBUG
626			domainoffset = lanmanlen;
627			domainoffset += 2;	/* Skip the null bytes */
628#endif // SMB_DEBUG
629		}
630	} else {
631		/* Find the end of the OS String */
632		lanmanoffset = oslen = strnlen((const char *)tmpbuf, bc);
633		lanmanoffset += 1;	/* Skip the null bytes */
634		if (lanmanoffset < bc) {
635			bc -= lanmanoffset;
636			/* Find the end of the Lanman String */
637			lanmanlen = strnlen((const char *)&tmpbuf[lanmanoffset], bc);
638#ifdef SMB_DEBUG
639			domainoffset = lanmanlen;
640			domainoffset += 1;	/* Skip the null bytes */
641#endif // SMB_DEBUG
642		}
643	}
644
645#ifdef SMB_DEBUG
646	if (domainoffset && (domainoffset < bc)) {
647		bc -= domainoffset;
648	} else {
649		bc = 0;
650	}
651	smb_hexdump(__FUNCTION__, "OS = ", tmpbuf, oslen);
652	smb_hexdump(__FUNCTION__, "LANMAN = ", &tmpbuf[lanmanoffset], lanmanlen);
653	smb_hexdump(__FUNCTION__, "DOMAIN = ", &tmpbuf[domainoffset+lanmanoffset], bc);
654#endif // SMB_DEBUG
655
656	vcp->vc_flags &= ~(SMBV_WIN2K_XP | SMBV_DARWIN);
657	if (oslen) {
658		vcp->NativeOS = smbfs_ntwrkname_tolocal((const char *)tmpbuf, &oslen,
659												SMB_UNICODE_STRINGS(vcp));
660		if (vcp->NativeOS) {
661			/*
662			 * Windows 2000 and Windows XP don't handle zero fill correctly. See
663			 * if this is a Windows 2000 or Windows XP by checking the OS name
664			 * string. Windows 2000 has an OS name of "Windows 5.0" and XP has a
665			 * OS name of "Windows 5.1".  Windows 2003 returns a totally different
666			 * OS name.
667			 */
668			if ((oslen >= strlen(WIN2K_XP_UTF8_NAME)) &&
669				(strncasecmp(vcp->NativeOS, WIN2K_XP_UTF8_NAME,
670							 strlen(WIN2K_XP_UTF8_NAME)) == 0)) {
671				vcp->vc_flags |= SMBV_WIN2K_XP;
672			}
673			/* Now see this is a Darwin smbx server */
674			if ((oslen >= strlen(DARWIN_UTF8_NAME)) &&
675				(strncasecmp(vcp->NativeOS, DARWIN_UTF8_NAME,
676							 strlen(DARWIN_UTF8_NAME)) == 0)) {
677				vcp->vc_flags |= SMBV_DARWIN;
678			}
679		}
680	}
681	if (lanmanlen) {
682		vcp->NativeLANManager= smbfs_ntwrkname_tolocal((const char *)&tmpbuf[lanmanoffset], &lanmanlen, SMB_UNICODE_STRINGS(vcp));
683	}
684	SMB_LOG_AUTH("NativeOS = %s NativeLANManager = %s server type 0x%x\n",
685			   (vcp->NativeOS) ? vcp->NativeOS : "NULL",
686			   (vcp->NativeLANManager) ? vcp->NativeLANManager : "NULL",
687			   (vcp->vc_flags & SMBV_SERVER_MODE_MASK));
688
689done:
690    if (tmpbuf != NULL) {
691        SMB_FREE(tmpbuf, M_SMBTEMP);
692    }
693}
694
695static char *
696upper_casify_string(const char *string)
697{
698    size_t string_len, i;
699    char *ucstrbuf;
700
701    string_len = strlen(string);
702    SMB_MALLOC(ucstrbuf, char *, string_len + 1, M_SMBTEMP, M_WAITOK | M_ZERO);
703
704    for (i = 0; i < string_len; i++) {
705        if ((string[i] >= 'a') && (string[i] <= 'z')) {
706            ucstrbuf[i] = string[i] - 32;
707        }
708        else {
709            ucstrbuf[i] = string[i];
710        }
711    }
712
713    return (ucstrbuf);
714}
715
716static u_char *
717add_name_to_blob(u_char *blobnames, const u_char *name, size_t namelen,
718                 int nametype, int uppercase)
719{
720    struct ntlmv2_namehdr namehdr;
721    char *namebuf;
722    u_int16_t *uninamebuf;
723    size_t uninamelen;
724
725    if (name != NULL) {
726        SMB_MALLOC(uninamebuf, u_int16_t *, 2 * namelen, M_SMBTEMP, M_WAITOK | M_ZERO);
727        if (uppercase) {
728            namebuf = upper_casify_string((char *) name);
729            uninamelen = smb_strtouni(uninamebuf, namebuf, namelen,
730                                      UTF_PRECOMPOSED|UTF_NO_NULL_TERM);
731            if (namebuf) {
732                SMB_FREE(namebuf, M_SMBTEMP);
733            }
734        } else {
735            uninamelen = smb_strtouni(uninamebuf, (char *)name, namelen,
736                                      UTF_PRECOMPOSED|UTF_NO_NULL_TERM);
737		}
738    } else {
739        uninamelen = 0;
740        uninamebuf = NULL;
741    }
742    namehdr.type = htoles(nametype);
743    namehdr.len = htoles(uninamelen);
744    bcopy(&namehdr, blobnames, sizeof namehdr);
745    blobnames += sizeof namehdr;
746    if (uninamebuf != NULL) {
747        bcopy(uninamebuf, blobnames, uninamelen);
748        blobnames += uninamelen;
749        if (uninamebuf) {
750            SMB_FREE(uninamebuf, M_SMBTEMP);
751        }
752    }
753    return blobnames;
754}
755
756static u_char *
757make_ntlmv2_blob(struct smb_vc *vcp, char *dom, u_int64_t client_nonce, size_t *bloblen)
758{
759    u_char *blob;
760    size_t blobsize;
761    size_t domainlen, srvlen;
762    struct ntlmv2_blobhdr *blobhdr;
763    struct timespec now;
764    u_int64_t timestamp;
765    u_char *blobnames;
766
767    /*
768     * XXX - the information at
769     *
770     * http://davenport.sourceforge.net/ntlm.html#theNtlmv2Response
771     *
772     * says that the "target information" comes from the Type 2 message,
773     * but, as we're not doing NTLMSSP, we don't have that.
774     *
775     * Should we use the names from the NegProt response?  Can we trust
776     * the NegProt response?  (I've seen captures where the primary
777     * domain name has an extra byte in front of it.)
778     *
779     * For now, we don't trust it - we use vcp->vc_domain and
780     * vcp->vc_srvname, instead.  We upper-case them and convert
781     * them to Unicode, as that's what's supposed to be in the blob.
782     */
783    domainlen = strlen(dom);
784    srvlen = strlen(vcp->vc_srvname);
785    blobsize = sizeof(struct ntlmv2_blobhdr) +
786               (3 * sizeof (struct ntlmv2_namehdr))
787               + 4 + (2 * domainlen) + (2 * srvlen);
788    SMB_MALLOC(blob, u_char *, blobsize, M_SMBTEMP, M_WAITOK | M_ZERO);
789    blobhdr = (struct ntlmv2_blobhdr *)blob;
790    blobhdr->header = htolel(0x00000101);
791    nanotime(&now);
792
793    /*
794     * %%%
795     * I would prefer not to change this yet. Once I am done with reconnects
796     * and the new auth methods, We should relook at this again.
797     *
798     * Really should not force this to be on a two second interval.
799     */
800    smb_time_local2NT(&now, &timestamp, 1);
801    blobhdr->timestamp = htoleq(timestamp);
802    blobhdr->client_nonce = client_nonce;
803    blobnames = blob + sizeof (struct ntlmv2_blobhdr);
804    blobnames = add_name_to_blob(blobnames, (u_char *)dom, domainlen,
805                                 NAMETYPE_DOMAIN_NB, 1);
806
807    //	blobnames = add_name_to_blob(blobnames, vcp, (u_char *)vcp->vc_srvname,
808    //				     srvlen, NAMETYPE_MACHINE_NB, 1);
809    blobnames = add_name_to_blob(blobnames, NULL, 0, NAMETYPE_EOL, 0);
810    *bloblen = blobnames - blob;
811    return (blob);
812}
813
814/*
815 * If the server supports extended security then we let smb_gss_ssnsetup handle
816 * that work. For the older systems that don't support extended security, either
817 * samba in share level, or some system pre-Windows2000.
818 *
819 * So we support the following:
820 *
821 *	NTLMv2
822 *	NTLM with the ASCII password
823 *
824 * if the server supports encrypted passwords, or
825 * plain-text with the ASCII password
826 *
827 */
828#define kSTATE_NTLMv2 0
829#define kSTATE_NTLMv1 1
830
831int
832smb_smb_ssnsetup(struct smb_vc *vcp, int inReconnect, vfs_context_t context)
833{
834	struct smb_rq *rqp;
835	struct mbchain *mbp;
836	struct mdchain *mdp;
837	uint8_t wc;
838	const char *pp = NULL;		/* Holds the information used in the case insesitive password field */
839	size_t plen = 0, uniplen = 0;
840	int error = 0;
841	uint32_t caps;
842	uint16_t action;
843	uint16_t bc;
844	uint16_t maxtx = vcp->vc_txmax;
845	uint8_t lm[24] = {0};
846	uint8_t ntlm[24] = {0};
847	int state = kSTATE_NTLMv2;
848	u_int64_t client_nonce;
849    u_char v2hash[16];
850	u_char *upper_case_userp = NULL;
851	u_int16_t string_len;
852	char *upper_case_domainp = NULL;
853	char *encrypted_password = NULL;
854    u_char *v2_blob = NULL;
855	size_t v2_bloblen;
856	smb_uniptr unipp = NULL, nt_encrypt_password = NULL;
857
858	if (smb_smb_nomux(vcp, __FUNCTION__, context) != 0) {
859		error = EINVAL;
860		goto ssn_exit;
861	}
862
863	if ((VC_CAPS(vcp) & SMB_CAP_EXT_SECURITY)) {
864		error = smb_gss_ssnsetup(vcp, context);
865
866        if (!(inReconnect) && (vcp->vc_flags & SMBV_SMB2)) {
867            /* Not in reconnect, its now safe to start up crediting */
868            smb2_rq_credit_start(vcp, 0);
869        }
870
871        goto ssn_exit;
872	}
873
874	caps = smb_vc_caps(vcp);
875
876again:
877	vcp->vc_smbuid = SMB_UID_UNKNOWN;
878
879	/*
880	 * Domain name must be upper-case, as that's what's used
881	 * when computing LMv2 and NTLMv2 responses - and, for NTLMv2,
882	 * the domain name in the request has to be upper-cased as well.
883	 * (That appears not to be the case for the user name.  Go
884	 * figure.)
885	 *
886	 * Don't need to uppercase domain. It's already uppercase UTF-8.
887	 *
888	 * NOTE: We use to copy the vc_domain into an allocated buffer and then
889	 * copy it into the mbuf, not sure why. Now we just copy vc_domain straight
890	 * in to the mbuf.
891	 */
892	string_len = strlen(vcp->vc_domain) + 1 /* strlen doesn't count null */;
893    SMB_MALLOC(upper_case_domainp, char *, string_len, M_SMBTEMP, M_WAITOK);
894	memcpy(upper_case_domainp, vcp->vc_domain, string_len);
895
896	if (!(vcp->vc_flags & SMBV_USER_SECURITY)) {
897		/*
898		 * In the share security mode password will be used
899		 * only in the tree authentication
900		 */
901		pp = "";
902		plen = 1;
903		uniplen = 0;
904	} else if ((vcp->vc_flags & SMBV_ENCRYPT_PASSWORD) != SMBV_ENCRYPT_PASSWORD) {
905		/*
906		 * Clear text passwords. The smb library already check the preferences to
907		 * make sure its enabled.
908		 *
909		 * We no longer uppercase the clear text password. May cause problems for
910		 * older servers, but in the worst case the user can type it in uppercase.
911		 *
912		 * When doing clear text password the old code never sent the case insesitive
913		 * password, so neither will we.
914		 *
915		 * We need to turn off UNICODE for clear text passwords.
916		 */
917		vcp->vc_hflags2 &= ~SMB_FLAGS2_UNICODE;
918
919		pp = smb_vc_getpass(vcp);
920		plen = strnlen(pp, SMB_MAXPASSWORDLEN + 1);
921		uniplen = 0;
922	} else if (vcp->vc_hflags2 & SMB_FLAGS2_SECURITY_SIGNATURE) {
923        /*
924         * The server wants NTLMv1/v2 without going through Extended Security
925         * Negotiation. We no longer support this if signing is on.
926         */
927        SMBERROR("SIGNING REQUIRED: Server %s needs to enable extended security negotiation for NTLM authentication, disconnecting\n", vcp->vc_srvname);
928		error = SMB_ENETFSNOPROTOVERSSUPP;
929        goto ssn_exit;
930	}
931    else {
932        SMBERROR("%s doesn't support extended security, this server will be deprecated in the future!\n",
933                 vcp->vc_srvname);
934
935        if (state == kSTATE_NTLMv2) {
936            /* Do NTLMv2 authentication */
937
938            /*
939             * Compute the LMv2 and NTLMv2 responses,
940             * derived from the challenge, the user name,
941             * the domain/workgroup into which we're
942             * logging, and the Unicode password.
943             */
944
945            /*
946             * Construct the client nonce by getting
947             * a bunch of random data.
948             */
949            read_random((void *)&client_nonce, sizeof(client_nonce));
950
951            /*
952             * For anonymous login with packet signing we
953             * need a null domain as well as a null user
954             * and password.
955             */
956            if ((vcp->vc_hflags2 & SMB_FLAGS2_SECURITY_SIGNATURE) &&
957                (vcp->vc_username[0] == '\0')) {
958                *upper_case_domainp = '\0';
959            }
960
961            /*
962             * Convert the user name to upper-case, as
963             * that's what's used when computing LMv2
964             * and NTLMv2 responses.
965             */
966            upper_case_userp = (u_char *)upper_casify_string(vcp->vc_username);
967
968            smb_ntlmv2hash((u_char *)smb_vc_getpass(vcp), upper_case_userp,
969                           (u_char *)upper_case_domainp, &v2hash[0]);
970
971            if (upper_case_userp) {
972                SMB_FREE(upper_case_userp, M_SMBTEMP);
973            }
974
975            /*
976             * Compute the LMv2 response, derived
977             * from the v2hash, the server challenge,
978             * and the client nonce.
979             */
980            smb_ntlmv2response(v2hash, vcp->vc_ch,
981                               (u_char *)&client_nonce, sizeof(client_nonce),
982                               (u_char**)&encrypted_password, &plen);
983            pp = encrypted_password;
984
985            /*
986             * Construct the blob.
987             */
988            v2_blob = make_ntlmv2_blob(vcp, upper_case_domainp, client_nonce,
989                                       &v2_bloblen);
990
991            /*
992             * Compute the NTLMv2 response, derived
993             * from the server challenge, the
994             * user name, the domain/workgroup
995             * into which we're logging, the
996             * blob, and the Unicode password.
997             */
998            smb_ntlmv2response(v2hash, vcp->vc_ch, v2_blob, v2_bloblen,
999                               (u_char**)&nt_encrypt_password, &uniplen);
1000            if (v2_blob) {
1001                SMB_FREE(v2_blob, M_SMBTEMP);
1002            }
1003            unipp = nt_encrypt_password;
1004        }
1005        else {
1006            /* Do NTLMv1 authentication */
1007            plen = sizeof(lm);
1008            pp = (char *)lm;
1009            uniplen = sizeof(ntlm);
1010            smb_ntlmresponse((u_char *)smb_vc_getpass(vcp), vcp->vc_ch, (u_char*)ntlm);
1011            unipp = (smb_uniptr) ntlm;
1012        }
1013	}
1014
1015	error = smb_rq_alloc(VCTOCP(vcp), SMB_COM_SESSION_SETUP_ANDX, 0, context, &rqp);
1016    if (error) {
1017        goto ssn_exit;
1018    }
1019
1020	smb_rq_wstart(rqp);
1021    smb_rq_getrequest(rqp, &mbp);
1022	/*
1023	 * We now have a flag telling us to attempt an anonymous connection. All
1024	 * this means is have no user name, password or domain.
1025	 */
1026	if (vcp->vc_flags & SMBV_ANONYMOUS_ACCESS) /*  anon */
1027		plen = uniplen = 0;
1028
1029	mb_put_uint8(mbp, 0xff);
1030	mb_put_uint8(mbp, 0);
1031	mb_put_uint16le(mbp, 0);
1032	mb_put_uint16le(mbp, maxtx);
1033	mb_put_uint16le(mbp, vcp->vc_sopt.sv_maxmux);
1034	mb_put_uint16le(mbp, vcp->vc_number);
1035	mb_put_uint32le(mbp, vcp->vc_sopt.sv_skey);
1036
1037	mb_put_uint16le(mbp, plen);
1038	mb_put_uint16le(mbp, uniplen);
1039	mb_put_uint32le(mbp, 0);		/* reserved */
1040	mb_put_uint32le(mbp, caps);		/* my caps */
1041	smb_rq_wend(rqp);
1042	smb_rq_bstart(rqp);
1043	mb_put_mem(mbp, pp, plen, MB_MSYSTEM); /* password */
1044	if (uniplen) {
1045		mb_put_mem(mbp, (caddr_t)unipp, uniplen, MB_MSYSTEM);
1046	}
1047	smb_put_dstring(mbp, SMB_UNICODE_STRINGS(vcp), vcp->vc_username,
1048                    SMB_MAXUSERNAMELEN + 1, NO_SFM_CONVERSIONS); /* user */
1049	smb_put_dstring(mbp, SMB_UNICODE_STRINGS(vcp), vcp->vc_domain,
1050                    SMB_MAXNetBIOSNAMELEN + 1, NO_SFM_CONVERSIONS); /* domain */
1051
1052	smb_put_dstring(mbp, SMB_UNICODE_STRINGS(vcp), SMBFS_NATIVEOS,
1053                    sizeof(SMBFS_NATIVEOS), NO_SFM_CONVERSIONS);	/* Native OS */
1054	smb_put_dstring(mbp, SMB_UNICODE_STRINGS(vcp), SMBFS_LANMAN,
1055                    sizeof(SMBFS_LANMAN), NO_SFM_CONVERSIONS);	/* LAN Mgr */
1056
1057	smb_rq_bend(rqp);
1058
1059    if (nt_encrypt_password) {
1060		SMB_FREE(nt_encrypt_password, M_SMBTEMP);
1061		nt_encrypt_password = NULL;
1062	}
1063
1064    if (upper_case_domainp) {
1065        SMB_FREE(upper_case_domainp, M_SMBTEMP);
1066        upper_case_domainp = NULL;
1067    }
1068
1069	error = smb_rq_simple_timed(rqp, SMBSSNSETUPTIMO);
1070	if (error) {
1071		SMBDEBUG("error = %d, rpflags2 = 0x%x, sr_ntstatus = 0x%x\n", error,
1072				 rqp->sr_rpflags2, rqp->sr_ntstatus);
1073	}
1074
1075	if (error) {
1076		if (error == EACCES) {
1077			error = EAUTH;
1078		}
1079		if (rqp->sr_ntstatus != STATUS_MORE_PROCESSING_REQUIRED) {
1080			goto bad;
1081		}
1082	}
1083	vcp->vc_smbuid = rqp->sr_rpuid;
1084	smb_rq_getreply(rqp, &mdp);
1085	do {
1086		error = md_get_uint8(mdp, &wc);
1087		if (error)
1088			break;
1089		error = EBADRPC;
1090		if (wc != 3)
1091			break;
1092		md_get_uint8(mdp, NULL);	/* secondary cmd */
1093		md_get_uint8(mdp, NULL);	/* mbz */
1094		md_get_uint16le(mdp, NULL);	/* andxoffset */
1095		md_get_uint16le(mdp, &action);	/* action */
1096		md_get_uint16le(mdp, &bc); /* remaining bytes */
1097		/* server OS, LANMGR, & Domain here */
1098
1099		/*
1100		 * If we are doing UNICODE then byte count is always on an odd boundry
1101		 * so we need to always deal with the pad byte.
1102		 */
1103		if (bc > 0) {
1104			md_get_uint8(mdp, NULL);	/* Skip Pad Byte */
1105			bc -= 1;
1106		}
1107		/*
1108		 * Now see if we can get the NativeOS and NativeLANManager strings. We
1109		 * use these strings to tell if the server is a Win2k or XP system,
1110		 * also Shared Computers wants this info.
1111		 */
1112		parse_server_os_lanman_strings(vcp, mdp, bc);
1113		error = 0;
1114	} while (0);
1115bad:
1116	/*
1117	 * We are in user level security, got log in as guest, but we are not
1118     * using guest access. We need to log off and return an error.
1119	 */
1120	if ((error == 0) && (vcp->vc_flags & SMBV_USER_SECURITY) &&
1121		!SMBV_HAS_GUEST_ACCESS(vcp) &&
1122        !SMBV_HAS_ANONYMOUS_ACCESS(vcp) &&
1123        (action & SMB_ACT_GUEST)) {
1124		/*
1125		 * Wanted to only login the users as guest if they ask to be login ask guest. Window system will
1126		 * login any bad user name as guest if guest is turn on. The problem here is with XPHome. XPHome
1127		 * doesn't care if the user is real or made up, it always logs them is as guest.
1128		 */
1129		SMBWARNING("Got guess access, but wanted real access.\n");
1130		(void)smb_smb_ssnclose(vcp, context);
1131		error = EAUTH;
1132	}
1133    else {
1134        if ((error) && (vcp->vc_flags & SMBV_USER_SECURITY) && (state == kSTATE_NTLMv2)) {
1135            if (vcp->vc_flags & SMBV_NO_NTLMV1) {
1136                SMBERROR("NTLMv1 is not allowed!\n");
1137                error = SMB_ENETFSNOAUTHMECHSUPP;
1138            }
1139            else {
1140                SMBDEBUG("Trying NTLMv1 \n");
1141                state = kSTATE_NTLMv1;
1142                smb_rq_done(rqp);
1143                goto again;
1144            }
1145        }
1146    }
1147
1148	smb_rq_done(rqp);
1149
1150ssn_exit:
1151
1152	if ((vcp->vc_flags & SMBV_ENCRYPT_PASSWORD) != SMBV_ENCRYPT_PASSWORD) {
1153		/* We turned off UNICODE for Clear Text Password turn it back on */
1154		vcp->vc_hflags2 |= SMB_FLAGS2_UNICODE;
1155	}
1156
1157    if (error) {
1158        /* Reset the signature info */
1159        smb_reset_sig(vcp);
1160    }
1161
1162    if (error && (error != EAUTH)) {
1163        SMBWARNING("SetupAndX failed error = %d\n", error);
1164    }
1165
1166    return (error);
1167}
1168
1169int
1170smb1_smb_ssnclose(struct smb_vc *vcp, vfs_context_t context)
1171{
1172	struct smb_rq *rqp;
1173	struct mbchain *mbp;
1174	int error;
1175
1176	if (vcp->vc_smbuid == SMB_UID_UNKNOWN)
1177		return 0;
1178
1179	if (smb_smb_nomux(vcp, __FUNCTION__, context) != 0)
1180		return EINVAL;
1181
1182	error = smb_rq_alloc(VCTOCP(vcp), SMB_COM_LOGOFF_ANDX, 0, context, &rqp);
1183	if (error)
1184		return error;
1185    smb_rq_getrequest(rqp, &mbp);
1186	smb_rq_wstart(rqp);
1187	mb_put_uint8(mbp, 0xff);
1188	mb_put_uint8(mbp, 0);
1189	mb_put_uint16le(mbp, 0);
1190	smb_rq_wend(rqp);
1191	smb_rq_bstart(rqp);
1192	smb_rq_bend(rqp);
1193	error = smb_rq_simple(rqp);
1194	SMBSDEBUG("%d\n", error);
1195	smb_rq_done(rqp);
1196	return error;
1197}
1198
1199/*
1200 * Get the type of file system this share is exporting, we treat all unknown
1201 * file system types as FAT. This should hurt since this is only used for
1202 * Dfs failover currently. If we ever expand its use we should rethink name
1203 * pipes.
1204 */
1205static void
1206smb_get_share_fstype(struct smb_vc *vcp, struct smb_share *share,
1207					 struct mdchain *mdp)
1208{
1209	char *tmpbuf = NULL;
1210	char *fsname = NULL;
1211	uint16_t bc;
1212	size_t fs_nmlen, fs_offset;
1213	int error;
1214
1215	/* We always default to saying its a fat file system type */
1216	share->ss_fstype = SMB_FS_FAT;
1217	/* Get the remaining number of bytes */
1218	md_get_uint16le(mdp, &bc);
1219	SMBDEBUG("tree bc = %d\n", bc);
1220	if ((bc == 0) || (bc >= vcp->vc_txmax)) {
1221		/* Nothing here just get out we are done */
1222		return;
1223	}
1224
1225	SMB_MALLOC(tmpbuf, char *, bc+1, M_SMBFSDATA, M_WAITOK | M_ZERO);
1226	if (! tmpbuf) {
1227		/* Couldn't allocate the buffer just get out */
1228		return;
1229	}
1230	error = md_get_mem(mdp, (void *)tmpbuf, bc, MB_MSYSTEM);
1231	if (error) {
1232        if (tmpbuf) {
1233            SMB_FREE(tmpbuf, M_SMBFSDATA);
1234        }
1235		return;
1236	}
1237	/*
1238	 * Skip over the service type:
1239	 * Service (variable): The type of the shared resource to which the
1240	 * TID is connected. The Service field MUST be encoded as a
1241	 * null-terminated array of OEM characters, even if the client and
1242	 * server have negotiated to use Unicode strings.
1243	 *
1244	 * Note we allocated the buffer 1 byte bigger so tmpbuf is always
1245	 * null terminated
1246	 */
1247	SMBDEBUG("Service type = %s\n", tmpbuf);
1248	/* Get the offset to the file system name, skip the null byte */
1249	fs_offset = strnlen(tmpbuf, bc) + 1;
1250	if (fs_offset >= bc) {
1251        if (tmpbuf) {
1252            SMB_FREE(tmpbuf, M_SMBFSDATA);
1253        }
1254		return;
1255	}
1256	/*
1257	 * Pad(variable): Padding bytes. If Unicode support has been enabled and
1258	 * SMB_FLAGS2_UNICODE is set in SMB_Header.Flags2, this field MUST contain
1259	 * zero or one null padding byte as needed to ensure that the
1260	 * NativeFileSystem string is aligned on a 16-bit boundary.
1261	 *
1262	 * We always start on an odd boundry, because of word count. So if fs_offset
1263	 * is even then we need to pad.
1264	 */
1265	if (!(fs_offset & 1) && (SMB_UNICODE_STRINGS(vcp))) {
1266			fs_offset += 1;
1267	}
1268	/*
1269	 * NativeFileSystem (variable): The name of the file system on the local
1270	 * resource to which the returned TID is connected. If SMB_FLAGS2_UNICODE
1271	 * is set in the Flags2 field of the SMB Header of the response, this value
1272	 * MUST be a null-terminated string of Unicode characters. Otherwise, this
1273	 * field MUST be a null-terminated string of OEM characters. For resources
1274	 * that are not backed by a file system, such as the IPC$ share used for
1275	 * named pipes, this field MUST be set to the empty string.
1276	 *
1277	 * The smbfs_ntwrkname_tolocal routine doesn't expect null terminated
1278	 * unicode strings, so figure out how long the string is without the
1279	 * null bytes.
1280	 */
1281	if (SMB_UNICODE_STRINGS(vcp)) {
1282		fs_nmlen = smb_utf16_strnsize((const uint16_t *)&tmpbuf[fs_offset],
1283									  bc - fs_offset);
1284	} else {
1285		fs_nmlen = bc - fs_offset;
1286	}
1287	SMBDEBUG("fs_offset = %d fs_nmlen = %d\n", (int)fs_offset, (int)fs_nmlen);
1288	fsname = smbfs_ntwrkname_tolocal(&tmpbuf[fs_offset], &fs_nmlen, SMB_UNICODE_STRINGS(vcp));
1289	/*
1290	 * Since we default to FAT the following can be ignored:
1291	 *		"FAT", "FAT12", "FAT16", "FAT32"
1292	 */
1293	if (strncmp(fsname, "CDFS", fs_nmlen) == 0) {
1294		share->ss_fstype = SMB_FS_CDFS;
1295	} else if (strncmp(fsname, "UDF", fs_nmlen) == 0) {
1296		share->ss_fstype = SMB_FS_UDF;
1297	} else if (strncmp(fsname, "NTFS", fs_nmlen) == 0) {
1298		share->ss_fstype = SMB_FS_NTFS;
1299	}
1300	SMBDEBUG("fsname = %s fs_nmlen = %d ss_fstype = %d\n", fsname,
1301			 (int)fs_nmlen, share->ss_fstype);
1302
1303    if (tmpbuf != NULL) {
1304        SMB_FREE(tmpbuf, M_SMBFSDATA);
1305    }
1306    if (fsname != NULL) {
1307        SMB_FREE(fsname, M_SMBFSDATA);
1308    }
1309	return;
1310}
1311
1312#define SMB_ANY_SHARE_NAME		"?????"
1313#define SMB_DISK_SHARE_NAME		"A:"
1314#define SMB_PRINTER_SHARE_NAME	SMB_ANY_SHARE_NAME
1315#define SMB_PIPE_SHARE_NAME		"IPC"
1316#define SMB_COMM_SHARE_NAME		"COMM"
1317
1318static int
1319smb1_treeconnect_internal(struct smb_vc *vcp, struct smb_share *share,
1320						 const char *serverName, size_t serverNameLen,
1321						 vfs_context_t context)
1322{
1323	struct smb_rq *rqp;
1324	struct mbchain *mbp;
1325	struct mdchain *mdp;
1326	uint8_t wc = 0;
1327	const char *pp;
1328	char *pbuf, *encpass;
1329	int error;
1330	uint16_t plen;
1331
1332	share->ss_tid = SMB_TID_UNKNOWN;
1333	error = smb_rq_alloc(SSTOCP(share), SMB_COM_TREE_CONNECT_ANDX, 0, context, &rqp);
1334	if (error)
1335		goto treeconnect_exit;
1336	if (vcp->vc_flags & SMBV_USER_SECURITY) {
1337		plen = 1;
1338		pp = "";
1339		pbuf = NULL;
1340		encpass = NULL;
1341	} else {
1342        SMB_MALLOC(pbuf, char *, SMB_MAXPASSWORDLEN + 1, M_SMBTEMP, M_WAITOK);
1343        SMB_MALLOC(encpass, char *, 24, M_SMBTEMP,  M_WAITOK);
1344		strlcpy(pbuf, smb_share_getpass(share), SMB_MAXPASSWORDLEN+1);
1345		pbuf[SMB_MAXPASSWORDLEN] = '\0';
1346
1347		if (vcp->vc_flags & SMBV_ENCRYPT_PASSWORD) {
1348			plen = 24;
1349			smb_lmresponse((u_char *)pbuf, vcp->vc_ch, (u_char *)encpass);
1350			pp = encpass;
1351		} else {
1352			plen = (uint16_t)strnlen(pbuf, SMB_MAXPASSWORDLEN + 1) + 1;
1353			pp = pbuf;
1354		}
1355	}
1356    smb_rq_getrequest(rqp, &mbp);
1357	smb_rq_wstart(rqp);
1358	mb_put_uint8(mbp, 0xff);
1359	mb_put_uint8(mbp, 0);
1360	mb_put_uint16le(mbp, 0);
1361	mb_put_uint16le(mbp, TREE_CONNECT_ANDX_EXTENDED_RESPONSE);
1362	mb_put_uint16le(mbp, plen);
1363	smb_rq_wend(rqp);
1364	smb_rq_bstart(rqp);
1365	error = mb_put_mem(mbp, pp, plen, MB_MSYSTEM);
1366	if (error) {
1367		SMBERROR("error %d from mb_put_mem for pp\n", error);
1368		goto bad;
1369	}
1370	smb_put_dmem(mbp, "\\\\", 2, NO_SFM_CONVERSIONS, SMB_UNICODE_STRINGS(vcp), NULL);
1371	/*
1372	 * User land code now passes down the server name in the proper format that
1373	 * can be used in a tree connection. This is two complicated of an issue to
1374	 * be handle in the kernel, but we do know the following:
1375	 *
1376	 * The server's NetBIOS name will always work, but we can't always get it because
1377	 * of firewalls. Window cluster system require the name to be a NetBIOS
1378	 * name or the cluster's fully qualified dns domain name.
1379	 *
1380	 * Windows XP will not allow DNS names to be used and in fact requires a
1381	 * name that must fit in a NetBIOS name. So if we don't have the NetBIOS
1382	 * name we can send the IPv4 address in presentation form (xxx.xxx.xxx.xxx).
1383	 *
1384	 * If we are doing IPv6 then it looks like we can just send the server name
1385	 * provided by the user. The same goes for Bonjour names.
1386	 *
1387	 * We now always use the name passed in and let the calling routine decide.
1388	 */
1389	error = smb_put_dmem(mbp, serverName, serverNameLen, NO_SFM_CONVERSIONS,SMB_UNICODE_STRINGS(vcp),  NULL);
1390	if (error) {
1391		SMBERROR("error %d from smb_put_dmem for srvname\n", error);
1392		goto bad;
1393	}
1394	smb_put_dmem(mbp, "\\", 1, NO_SFM_CONVERSIONS, SMB_UNICODE_STRINGS(vcp), NULL);
1395
1396	error = smb_put_dstring(mbp, SMB_UNICODE_STRINGS(vcp), share->ss_name, SMB_MAXSHARENAMELEN+1, NO_SFM_CONVERSIONS);
1397	if (error) {
1398		SMBERROR("error %d from smb_put_dstring for ss_name\n", error);
1399		goto bad;
1400	}
1401	/* The type name is always ASCII */
1402	error = mb_put_mem(mbp, SMB_ANY_SHARE_NAME, sizeof(SMB_ANY_SHARE_NAME), MB_MSYSTEM);
1403	if (error) {
1404		SMBERROR("error %d from mb_put_mem for share type\n", error);
1405		goto bad;
1406	}
1407	smb_rq_bend(rqp);
1408	error = smb_rq_simple(rqp);
1409	SMBSDEBUG("%d\n", error);
1410	if (error)
1411		goto bad;
1412
1413	smb_rq_getreply(rqp, &mdp);
1414	md_get_uint8(mdp, &wc);
1415	if ((wc != TREE_CONNECT_NORMAL_WDCNT) && (wc != TREE_CONNECT_EXTENDED_WDCNT)) {
1416		SMBERROR("Malformed tree connect with a bad word count! wc= %d \n", wc);
1417		error = EBADRPC;
1418		goto bad;
1419	}
1420	md_get_uint8(mdp, NULL);	/* AndXCommand */
1421	md_get_uint8(mdp, NULL);	/* AndXReserved */
1422	md_get_uint16le(mdp, NULL);	/* AndXOffset */
1423	md_get_uint16le(mdp, &share->optionalSupport);	/* OptionalSupport */
1424	/*
1425	 * If extended response the we need to get the maximal access of the share.
1426	 */
1427	if (wc == TREE_CONNECT_EXTENDED_WDCNT) {
1428		if (md_get_uint32le(mdp, &share->maxAccessRights)) {
1429			share->maxAccessRights = SA_RIGHT_FILE_ALL_ACCESS | STD_RIGHT_ALL_ACCESS;
1430		} else {
1431			SMB_LOG_ACCESS("maxAccessRights = 0x%x \n", share->maxAccessRights);
1432		}
1433
1434		if (md_get_uint32le(mdp, &share->maxGuestAccessRights)) {
1435			share->maxGuestAccessRights = SA_RIGHT_FILE_ALL_ACCESS | STD_RIGHT_ALL_ACCESS;
1436		}
1437	} else {
1438		share->maxAccessRights = SA_RIGHT_FILE_ALL_ACCESS | STD_RIGHT_ALL_ACCESS;
1439		share->maxGuestAccessRights = SA_RIGHT_FILE_ALL_ACCESS | STD_RIGHT_ALL_ACCESS;
1440	}
1441	smb_get_share_fstype(vcp, share, mdp);
1442
1443	share->ss_tid = rqp->sr_rptid;
1444	lck_mtx_lock(&share->ss_stlock);
1445	share->ss_flags |= SMBS_CONNECTED;
1446	lck_mtx_unlock(&share->ss_stlock);
1447bad:
1448    if (encpass) {
1449        SMB_FREE(encpass, M_SMBTEMP);
1450    }
1451
1452    if (pbuf) {
1453        SMB_FREE(pbuf, M_SMBTEMP);
1454    }
1455
1456    smb_rq_done(rqp);
1457treeconnect_exit:
1458	return error;
1459}
1460
1461/*
1462 * XP requires the tree connect server name to either contain the NetBIOS
1463 * name or IPv4 in the dot presentation format. Windows Cluster wants the
1464 * cluster NetBIOS name or the cluster dns name. So if we resolved using
1465 * NetBIOS then we always use the NetBIOS name, otherwise we use the name
1466 * that we use to resolve the address. Now if the treeconnect fails then
1467 * attempt to use the IPv4 dot presentation name.
1468 */
1469int
1470smb_smb_treeconnect(struct smb_share *share, vfs_context_t context)
1471{
1472	struct smb_vc *vcp = SSTOVC(share);
1473	int error;
1474	size_t srvnamelen;
1475	char *serverName;
1476
1477	/* No IPv4 or IPv6 dot name so use the real server name in the tree connect */
1478	if (vcp->ipv4v6DotName[0] == 0) {
1479		serverName = vcp->vc_srvname;
1480		srvnamelen = strnlen(serverName, SMB_MAX_DNS_SRVNAMELEN+1);
1481        if (vcp->vc_flags & SMBV_SMB2) {
1482            error = smb2_smb_tree_connect(vcp, share, serverName, srvnamelen,
1483                                          context);
1484       }
1485        else {
1486            error = smb1_treeconnect_internal(vcp, share, serverName,
1487                                              srvnamelen, context);
1488        }
1489
1490		/*
1491         * See if we can get the IPv4 or IPv6 presentation format.
1492         * If so, see if we can Tree Connect with that address instead
1493         */
1494        if (error) {
1495            if (vcp->vc_saddr->sa_family == AF_INET) {
1496                /* IPv4 */
1497                struct sockaddr_in *in = (struct sockaddr_in *)vcp->vc_saddr;
1498                (void)inet_ntop(AF_INET, &in->sin_addr.s_addr, vcp->ipv4v6DotName, sizeof(vcp->ipv4v6DotName));
1499                SMBWARNING("treeconnect failed using server name %s with error %d\n", serverName, error);
1500            }
1501            else if (vcp->vc_saddr->sa_family == AF_INET6) {
1502                /* IPv6 - returns with no brackets */
1503                struct sockaddr_in *in = (struct sockaddr_in *)vcp->vc_saddr;
1504                (void)inet_ntop(AF_INET6, &in->sin_addr.s_addr, vcp->ipv4v6DotName, sizeof(vcp->ipv4v6DotName));
1505                SMBWARNING("treeconnect failed using server name %s with error %d\n", serverName, error);
1506            }
1507		}
1508    }
1509
1510	/* Use the IPv4 or IPv6 dot name in the tree connect */
1511	if (vcp->ipv4v6DotName[0] != 0) {
1512		serverName = vcp->ipv4v6DotName;
1513		srvnamelen = strnlen(serverName, SMB_MAXNetBIOSNAMELEN+1);
1514        if (vcp->vc_flags & SMBV_SMB2) {
1515            error = smb2_smb_tree_connect(vcp, share, serverName, srvnamelen,
1516                                          context);
1517        }
1518        else {
1519            error = smb1_treeconnect_internal(vcp, share, serverName,
1520                                              srvnamelen, context);
1521        }
1522		if (error)
1523			vcp->ipv4v6DotName[0] = 0;	/* We failed don't use it again */
1524	}
1525	return error;
1526}
1527
1528int
1529smb1_smb_treedisconnect(struct smb_share *share, vfs_context_t context)
1530{
1531	struct smb_rq *rqp;
1532	int error;
1533
1534	if (share->ss_tid == SMB_TID_UNKNOWN) {
1535		return 0;
1536    }
1537
1538	error = smb_rq_alloc(SSTOCP(share), SMB_COM_TREE_DISCONNECT, 0, context, &rqp);
1539	if (error)
1540		return error;
1541	smb_rq_wstart(rqp);
1542	smb_rq_wend(rqp);
1543	smb_rq_bstart(rqp);
1544	smb_rq_bend(rqp);
1545	error = smb_rq_simple(rqp);
1546	SMBSDEBUG("%d\n", error);
1547	smb_rq_done(rqp);
1548	share->ss_tid = SMB_TID_UNKNOWN;
1549	return error;
1550}
1551
1552/*
1553 * The calling routine must hold a reference on the share
1554 */
1555static __inline int
1556smb_smb_readx(struct smb_share *share, SMBFID fid, user_ssize_t *len,
1557	user_ssize_t *rresid, uint16_t *available, uio_t uio, vfs_context_t context)
1558{
1559	struct smb_rq *rqp;
1560	struct mbchain *mbp;
1561	struct mdchain *mdp;
1562	uint8_t wc;
1563	int error;
1564	uint16_t residhi, residlo, off, doff;
1565	uint32_t resid;
1566    uint16_t smb1_fid = (uint16_t) fid;
1567
1568	error = smb_rq_alloc(SSTOCP(share), SMB_COM_READ_ANDX, 0, context, &rqp);
1569	if (error)
1570		return error;
1571	smb_rq_getrequest(rqp, &mbp);
1572	smb_rq_wstart(rqp);
1573	mb_put_uint8(mbp, 0xff);	/* no secondary command */
1574	mb_put_uint8(mbp, 0);		/* MBZ */
1575	mb_put_uint16le(mbp, 0);	/* offset to secondary */
1576	mb_put_mem(mbp, (caddr_t)&smb1_fid, sizeof(smb1_fid), MB_MSYSTEM);
1577	mb_put_uint32le(mbp, (uint32_t)uio_offset(uio));
1578	*len = MIN(SSTOVC(share)->vc_rxmax, *len);
1579
1580	mb_put_uint16le(mbp, (uint16_t)*len);	/* MaxCount */
1581	mb_put_uint16le(mbp, (uint16_t)*len);	/* MinCount (only indicates blocking) */
1582	mb_put_uint32le(mbp, (uint32_t)((user_size_t)*len >> 16));	/* MaxCountHigh */
1583	mb_put_uint16le(mbp, (uint16_t)*len);	/* Remaining ("obsolete") */
1584	mb_put_uint32le(mbp, (uint32_t)(uio_offset(uio) >> 32));
1585	smb_rq_wend(rqp);
1586	smb_rq_bstart(rqp);
1587	smb_rq_bend(rqp);
1588	do {
1589		error = smb_rq_simple(rqp);
1590		if (error)
1591			break;
1592		smb_rq_getreply(rqp, &mdp);
1593		off = SMB_HDRLEN;
1594		md_get_uint8(mdp, &wc);
1595		off++;
1596		if (wc != 12) {
1597			error = EBADRPC;
1598			break;
1599		}
1600		md_get_uint8(mdp, NULL);
1601		off++;
1602		md_get_uint8(mdp, NULL);
1603		off++;
1604		md_get_uint16le(mdp, NULL);
1605		off += 2;
1606		/*
1607		 * Available (2 bytes): This field is valid when reading from named pipes
1608		 * or I/O devices. This field indicates the number of bytes remaining to
1609		 * be read after the requested read was completed. If the client reads
1610		 * from a disk file, this field MUST be set to -1 (0xFFFF). <62>
1611		 */
1612		*available = 0;
1613		md_get_uint16le(mdp, available);
1614		off += 2;
1615		md_get_uint16le(mdp, NULL);	/* data compaction mode */
1616		off += 2;
1617		md_get_uint16le(mdp, NULL);
1618		off += 2;
1619		md_get_uint16le(mdp, &residlo);
1620		off += 2;
1621		md_get_uint16le(mdp, &doff);	/* data offset */
1622		off += 2;
1623		md_get_uint16le(mdp, &residhi);
1624		off += 2;
1625		resid = (residhi << 16) | residlo;
1626		md_get_mem(mdp, NULL, 4 * 2, MB_MSYSTEM);
1627		off += 4*2;
1628		md_get_uint16le(mdp, NULL);	/* ByteCount */
1629		off += 2;
1630		if (doff > off)	/* pad byte(s)? */
1631			md_get_mem(mdp, NULL, doff - off, MB_MSYSTEM);
1632		if (resid == 0) {
1633			*rresid = resid;
1634			break;
1635		}
1636		error = md_get_uio(mdp, uio, resid);
1637		if (error)
1638			break;
1639		*rresid = resid;
1640	} while(0);
1641	smb_rq_done(rqp);
1642	return (error);
1643}
1644
1645/*
1646 * The calling routine must hold a reference on the share
1647 */
1648static __inline int
1649smb_writex(struct smb_share *share, SMBFID fid, user_ssize_t *len,
1650		   user_ssize_t *rresid, uio_t uio, uint16_t writeMode, vfs_context_t context)
1651{
1652	int supportsLargeWrites = (VC_CAPS(SSTOVC(share)) & SMB_CAP_LARGE_FILES) ? TRUE : FALSE;
1653	struct smb_rq *rqp;
1654	struct mbchain *mbp;
1655	struct mdchain *mdp;
1656	int error;
1657	uint8_t wc;
1658	uint16_t resid;
1659	uint16_t *dataOffsetPtr;
1660    uint16_t smb1_fid = (uint16_t) fid;
1661
1662	/* vc_wxmax now holds the max buffer size the server supports for writes */
1663	*len = MIN(*len, SSTOVC(share)->vc_wxmax);
1664
1665	error = smb_rq_alloc(SSTOCP(share), SMB_COM_WRITE_ANDX, 0, context, &rqp);
1666	if (error)
1667		return (error);
1668	smb_rq_getrequest(rqp, &mbp);
1669	smb_rq_wstart(rqp);
1670	mb_put_uint8(mbp, 0xff);	/* AndXCommand */
1671	mb_put_uint8(mbp, 0);		/* Reserved */
1672	mb_put_uint16le(mbp, 0);	/* AndXOffset */
1673	/*
1674	 * [MS-CIFS]
1675	 * FID (2 bytes): This field MUST be a valid FID indicating the file to
1676	 * which the data SHOULD be written.
1677	 *
1678	 * NOTE: Currently the fid always stays in the wire format.
1679	 */
1680	mb_put_mem(mbp, (caddr_t)&smb1_fid, sizeof(smb1_fid), MB_MSYSTEM);
1681	/*
1682	 * [MS-CIFS]
1683	 * Offset (4 bytes): If WordCount is 0x0C, this field represents a 32-bit
1684	 * offset, measured in bytes, of where the write SHOULD start relative to the
1685	 * beginning of the file. If WordCount is 0xE, this field represents the
1686	 * lower 32 bits of a 64-bit offset.
1687	 */
1688	mb_put_uint32le(mbp, (uint32_t)uio_offset(uio));
1689	/*
1690	 * [MS-CIFS]
1691	 * Timeout (4 bytes): This field represents the amount of time, in milliseconds,
1692	 * that a server MUST wait before sending a response. It is used only when
1693	 * writing to a named pipe or I/O device and does not apply when writing to
1694	 * a disk file. Support for this field is optional. Two values have special
1695	 * meaning in this field:
1696	 * If the Timeout value is -1 (0xFFFFFFFF, "wait forever"), the server MUST
1697	 * wait until all bytes of data are written to the device before returning a
1698	 * response to the client.
1699	 * If the Timeout value is -2 (0xFFFFFFFE, "default"), the server MUST wait
1700	 * for the default time-out associated with the named pipe or I/O device.
1701	 *
1702	 * NOTE: We have always set it to zero and so does Windows Clients.
1703	 */
1704	mb_put_uint32le(mbp, 0);	/* Timeout  */
1705	/*
1706	 * [MS-CIFS]
1707	 * WriteMode (2 bytes): A 16-bit field containing flags defined as follows:
1708	 * WritethroughMode 0x0001
1709	 *		If set the server MUST NOT respond to the client before the data is
1710	 *		written to disk (write-through).
1711	 * ReadBytesAvailable 0x0002
1712	 *		If set the server SHOULD set the Response.SMB_Parameters.Available
1713	 *		field correctly for writes to named pipes or I/O devices.
1714	 * RAW_MODE 0x0004
1715	 *		Applicable to named pipes only. If set, the named pipe MUST be written
1716	 *		to in raw mode (no translation).
1717	 * MSG_START 0x0008
1718	 *		Applicable to named pipes only. If set, this data is the start of a message.
1719	 */
1720	mb_put_uint16le(mbp, writeMode);
1721	/*
1722	 * [MS-CIFS]
1723	 * Remaining (2 bytes): This field is an advisory field telling the server
1724	 * approximately how many bytes are to be written to this file before the next
1725	 * non-write operation. It SHOULD include the number of bytes to be written
1726	 * by this request. The server MAY either ignore this field or use it to
1727	 * perform optimizations.
1728	 */
1729	mb_put_uint16le(mbp, 0);
1730	/*
1731	 * [MS-CIFS]
1732	 * Reserved (2 bytes): This field MUST be 0x0000.
1733	 *
1734	 * Wrong only zero if the server doesn't support SMB_CAP_LARGE_WRITEX otherwise
1735	 * contains the DataLengthHigh. If the server doesn't support SMB_CAP_LARGE_WRITEX
1736	 * then the upper part of length will zero.
1737	 */
1738	mb_put_uint16le(mbp, (uint16_t)((user_size_t)*len >> 16));
1739	/*
1740	 * [MS-CIFS]
1741	 * DataLength (2 bytes): This field is the number of bytes included in the
1742	 * SMB_Data that are to be written to the file.
1743	 */
1744	mb_put_uint16le(mbp, (uint16_t)*len);
1745	/*
1746	 * [MS-CIFS]
1747	 * DataOffset (2 bytes): The offset in bytes from the start of the SMB header
1748	 * to the start of the data that is to be written to the file. Specifying this
1749	 * offset allows a client to efficiently align the data buffer.
1750	 */
1751	dataOffsetPtr = (uint16_t *)mb_reserve(mbp, sizeof(uint16_t));
1752	/*
1753	 * [MS-CIFS]
1754	 * OffsetHigh (4 bytes): This field is optional. If WordCount is 0x0C, this
1755	 * field is not included in the request. If WordCount is 0x0E, this field
1756	 * represents the upper 32 bits of a 64-bit offset, measured in bytes, of
1757	 * where the write SHOULD start relative to the beginning of the file.
1758	 */
1759	if (!supportsLargeWrites && ((uint32_t)(uio_offset(uio) >> 32))) {
1760		error = ENOTSUP;
1761		goto done;
1762	}
1763	mb_put_uint32le(mbp, (uint32_t)(uio_offset(uio) >> 32));
1764	smb_rq_wend(rqp);
1765	smb_rq_bstart(rqp);
1766	do {
1767
1768		/*
1769		 * [MS-CIFS]
1770		 * Pad (1 byte): Padding byte that MUST be ignored.
1771		 */
1772		mb_put_uint8(mbp, 0);
1773
1774		*dataOffsetPtr = htoles(mb_fixhdr(mbp));
1775		error = mb_put_uio(mbp, uio, (int)*len);
1776		if (error)
1777			break;
1778		smb_rq_bend(rqp);
1779		error = smb_rq_simple_timed(rqp, SMBWRTTIMO);
1780		if (error)
1781			break;
1782		smb_rq_getreply(rqp, &mdp);
1783		/*
1784		 * [MS-CIFS]
1785		 * WordCount (1 byte): This field MUST be 0x06. The length in two-byte
1786		 * words of the remaining SMB_Parameters.
1787		 */
1788		md_get_uint8(mdp, &wc);
1789		if (wc != 6) {
1790			error = EBADRPC;
1791			break;
1792		}
1793		md_get_uint8(mdp, NULL);	/* AndXCommand */
1794		md_get_uint8(mdp, NULL);	/* AndXReserved */
1795		md_get_uint16le(mdp, NULL);	/* AndXOffset */
1796		/*
1797		 * [MS-CIFS]
1798		 * Count (2 bytes): The number of bytes written to the file.
1799		 */
1800		md_get_uint16le(mdp, &resid);
1801		*rresid = resid;
1802		/*
1803		 * [MS-CIFS]
1804		 * Available (2 bytes): This field is valid when writing to named pipes
1805		 * or I/O devices. This field indicates the number of bytes remaining to
1806		 * be read after the requested write was completed. If the client wrote
1807		 * to a disk file, this field MUST be set to -1 (0xFFFF).
1808		 */
1809		md_get_uint16le(mdp, NULL);
1810		/*
1811		 * [MS-CIFS]
1812		 * Reserved (4 bytes): This field MUST be 0x00000000.
1813		 *
1814		 * NOTE: Wrong the first two bytes are the high count field and the
1815		 * last two bytes should be zero.
1816		 */
1817		md_get_uint16le(mdp, &resid);
1818		*rresid |= resid << 16;
1819		md_get_uint16le(mdp, NULL);
1820	} while(0);
1821
1822done:
1823	smb_rq_done(rqp);
1824	return (error);
1825}
1826
1827/*
1828 * The calling routine must hold a reference on the share
1829 */
1830int
1831smb1_read(struct smb_share *share, SMBFID fid, uio_t uio,
1832          vfs_context_t context)
1833{
1834	user_ssize_t tsize, len, resid = 0;
1835	int error = 0;
1836	uint16_t available;
1837
1838	tsize = uio_resid(uio);
1839	while (tsize > 0) {
1840		len = tsize;
1841		error = smb_smb_readx(share, fid, &len, &resid, &available, uio, context);
1842		if (error)
1843			break;
1844		tsize -= resid;
1845		/* Nothing else to read we are done */
1846		if (!resid) {
1847			SMB_LOG_IO("Server zero bytes read\n");
1848			break;
1849		}
1850		/*
1851		 * Available (2 bytes): This field is valid when reading from named pipes
1852		 * or I/O devices. This field indicates the number of bytes remaining to
1853		 * be read after the requested read was completed. If the client reads
1854		 * from a disk file, this field MUST be set to -1 (0xFFFF). <62>
1855		 */
1856		if (resid < len) {
1857			if (available == 0xffff) {
1858				/* They didn't read all the data, log it and keep trying */
1859				SMB_LOG_IO("Disk IO: Server returns %lld we request %lld\n", resid, len);
1860			} else if (available) {
1861				/* They didn't read all the data, log it and keep trying */
1862				SMB_LOG_IO("PIPE IO: Server returns %lld we request %lld available = %d\n",
1863						   resid, len, available);
1864			} else {
1865				/* Nothing left to read, we are done */
1866				break;
1867			}
1868
1869		}
1870	}
1871	return error;
1872}
1873
1874/*
1875 * The calling routine must hold a reference on the share
1876 */
1877int
1878smb1_write(struct smb_share *share, SMBFID fid, uio_t uio, int ioflag,
1879			  vfs_context_t context)
1880{
1881	int error = 0;
1882	user_ssize_t  old_resid, len, tsize, resid = 0;
1883	off_t  old_offset;
1884	uint16_t writeMode = (ioflag & IO_SYNC) ? WritethroughMode : 0;
1885
1886	tsize = old_resid = uio_resid(uio);
1887	old_offset = uio_offset(uio);
1888
1889	while (tsize > 0) {
1890		len = tsize;
1891		error  = smb_writex(share, fid, &len, &resid, uio, writeMode, context);
1892		if (error)
1893			break;
1894		if (resid < len) {
1895			error = EIO;
1896			break;
1897		}
1898		tsize -= resid;
1899	}
1900	if (error) {
1901		/*
1902		 * Errors can happen on the copyin, the rpc, etc.  So they
1903		 * imply resid is unreliable.  The only safe thing is
1904		 * to pretend zero bytes made it.  We needn't restore the
1905		 * iovs because callers don't depend on them in error
1906		 * paths - uio_resid and uio_offset are what matter.
1907		 */
1908		uio_setresid(uio, old_resid);
1909		uio_setoffset(uio, old_offset);
1910	}
1911	return error;
1912}
1913
1914/*
1915 * This call is done on the vc not the share. Really should be an async call
1916 * if we ever get the request queue to work async.
1917 */
1918int
1919smb1_echo(struct smb_vc *vcp, int timo, uint32_t EchoCount,
1920         vfs_context_t context)
1921{
1922	struct smb_rq *rqp;
1923	struct mbchain *mbp;
1924	int error;
1925
1926	error = smb_rq_alloc(VCTOCP(vcp), SMB_COM_ECHO, 0, context, &rqp);
1927	if (error)
1928		return error;
1929    smb_rq_getrequest(rqp, &mbp);
1930	smb_rq_wstart(rqp);
1931	mb_put_uint16le(mbp, 1); /* echo count */
1932	smb_rq_wend(rqp);
1933	smb_rq_bstart(rqp);
1934	mb_put_uint32le(mbp, EchoCount);
1935	smb_rq_bend(rqp);
1936	error = smb_rq_simple_timed(rqp, timo);
1937	smb_rq_done(rqp);
1938	return error;
1939}
1940
1941/*
1942 * The calling routine must hold a reference on the share
1943 */
1944int smb_checkdir(struct smb_share *share, struct smbnode *dnp, const char *name,
1945					 size_t nmlen, vfs_context_t context)
1946{
1947	struct smb_rq *rqp;
1948	struct mbchain *mbp;
1949	int error;
1950
1951	error = smb_rq_alloc(SSTOCP(share), SMB_COM_CHECK_DIRECTORY, 0, context, &rqp);
1952	if (error)
1953		return error;
1954	smb_rq_getrequest(rqp, &mbp);
1955	smb_rq_wstart(rqp);
1956	smb_rq_wend(rqp);
1957	smb_rq_bstart(rqp);
1958	mb_put_uint8(mbp, SMB_DT_ASCII);
1959	smbfs_fullpath(mbp, dnp, name, &nmlen, UTF_SFM_CONVERSIONS,
1960				   SMB_UNICODE_STRINGS(SSTOVC(share)), '\\');
1961	smb_rq_bend(rqp);
1962	error = smb_rq_simple(rqp);
1963	smb_rq_done(rqp);
1964	return error;
1965}
1966