Added wine_server_release_fd function to release the fd returned by
[wine] / files / smb.c
1 /*
2  * Copyright (C) 2002 Mike McCormack
3  *
4  * CIFS implementation for WINE
5  *
6  * This is a WINE's implementation of the Common Internet File System
7  *
8  * for specification see:
9  *
10  * http://www.codefx.com/CIFS_Explained.htm
11  * http://www.ubiqx.org/cifs/rfc-draft/rfc1002.html
12  * http://www.ubiqx.org/cifs/rfc-draft/draft-leach-cifs-v1-spec-02.html
13  * http://ubiqx.org/cifs/
14  * http://www.samba.org
15  *
16  * This library is free software; you can redistribute it and/or
17  * modify it under the terms of the GNU Lesser General Public
18  * License as published by the Free Software Foundation; either
19  * version 2.1 of the License, or (at your option) any later version.
20  *
21  * This library is distributed in the hope that it will be useful,
22  * but WITHOUT ANY WARRANTY; without even the implied warranty of
23  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
24  * Lesser General Public License for more details.
25  *
26  * You should have received a copy of the GNU Lesser General Public
27  * License along with this library; if not, write to the Free Software
28  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
29  *
30  *
31  * FIXME:
32  *
33  *   - There is a race condition when two threads try to read from the same
34  *     SMB handle. Either we need to lock the SMB handle for the time we
35  *     use it in the client, or do all reading and writing to the socket
36  *     fd in the server.
37  *
38  *   - Each new handle opens up a new connection to the SMB server. This
39  *     is not ideal, since operations can be multiplexed on one socket. For
40  *     this to work properly we would need to have some way of discovering
41  *     connections that are already open.
42  *
43  *   - All access is currently anonymous. Password protected shares cannot
44  *     be accessed.  We need some way of organising passwords, storing them
45  *     in the config file, or putting up a dialog box for the user.
46  *
47  *   - We don't deal with SMB dialects at all.
48  *
49  *   - SMB supports passing unicode over the wire, should use this if possible.
50  *
51  *   - Implement ability to read named pipes over the network. Would require
52  *     integrate this code with the named pipes code in the server, and
53  *     possibly implementing some support for security tokens.
54  */
55
56 #include "config.h"
57 #include "wine/port.h"
58
59 #include <assert.h>
60 #include <ctype.h>
61 #include <fcntl.h>
62 #include <stdlib.h>
63 #include <stdarg.h>
64 #include <stdio.h>
65 #include <string.h>
66 #include <sys/types.h>
67 #include <sys/stat.h>
68 #ifdef HAVE_SYS_MMAN_H
69 #include <sys/mman.h>
70 #endif
71 #ifdef HAVE_SYS_TIME_H
72 # include <sys/time.h>
73 #endif
74 #ifdef HAVE_SYS_POLL_H
75 # include <sys/poll.h>
76 #endif
77 #include <time.h>
78 #ifdef HAVE_UNISTD_H
79 # include <unistd.h>
80 #endif
81 #ifdef HAVE_UTIME_H
82 # include <utime.h>
83 #endif
84 #ifdef HAVE_SYS_SOCKET_H
85 # include <sys/socket.h>
86 #endif
87 #include <sys/types.h>
88 #ifdef HAVE_NETINET_IN_SYSTM_H
89 #include <netinet/in_systm.h>
90 #endif
91 #ifdef HAVE_NETINET_IN_H
92 #include <netinet/in.h>
93 #endif
94 #ifdef HAVE_NETINET_IP_H
95 #include <netinet/ip.h>
96 #endif
97 #ifdef HAVE_ARPA_INET_H
98 #include <arpa/inet.h>
99 #endif
100 #ifdef HAVE_NETDB_H
101 #include <netdb.h>
102 #endif
103
104 #define NONAMELESSUNION
105 #define NONAMELESSSTRUCT
106 #include "winerror.h"
107 #include "ntstatus.h"
108 #include "windef.h"
109 #include "winbase.h"
110 #include "winnls.h"
111 #include "file.h"
112
113 #include "smb.h"
114 #include "winternl.h"
115
116 #include "wine/server.h"
117 #include "wine/debug.h"
118
119 WINE_DEFAULT_DEBUG_CHANNEL(file);
120
121 #define NBR_ADDWORD(p,word) { (p)[1] = (word & 0xff); (p)[0] = ((word)>>8)&0xff; }
122 #define NBR_GETWORD(p) ( (((p)[0])<<8) | ((p)[1]) )
123
124 #define SMB_ADDWORD(p,word) { (p)[0] = (word & 0xff); (p)[1] = ((word)>>8)&0xff; }
125 #define SMB_GETWORD(p) ( (((p)[1])<<8) | ((p)[0]) )
126 #define SMB_ADDDWORD(p,w) { (p)[3]=((w)>>24)&0xff; (p)[2]=((w)>>16)&0xff; (p)[1]=((w)>>8)&0xff; (p)[0]=(w)&0xff; }
127 #define SMB_GETDWORD(p) ( (((p)[3])<<24) | (((p)[2])<<16) | (((p)[1])<<8) | ((p)[0]) )
128
129 #define SMB_COM_CREATE_DIRECTORY       0x00
130 #define SMB_COM_DELETE_DIRECTORY       0x01
131 #define SMB_COM_OPEN                   0x02
132 #define SMB_COM_CREATE                 0x03
133 #define SMB_COM_CLOSE                  0x04
134 #define SMB_COM_FLUSH                  0x05
135 #define SMB_COM_DELETE                 0x06
136 #define SMB_COM_RENAME                 0x07
137 #define SMB_COM_QUERY_INFORMATION      0x08
138 #define SMB_COM_SET_INFORMATION        0x09
139 #define SMB_COM_READ                   0x0A
140 #define SMB_COM_WRITE                  0x0B
141 #define SMB_COM_LOCK_BYTE_RANGE        0x0C
142 #define SMB_COM_UNLOCK_BYTE_RANGE      0x0D
143 #define SMB_COM_CREATE_TEMPORARY       0x0E
144 #define SMB_COM_CREATE_NEW             0x0F
145 #define SMB_COM_CHECK_DIRECTORY        0x10
146 #define SMB_COM_PROCESS_EXIT           0x11
147 #define SMB_COM_SEEK                   0x12
148 #define SMB_COM_LOCK_AND_READ          0x13
149 #define SMB_COM_WRITE_AND_UNLOCK       0x14
150 #define SMB_COM_READ_RAW               0x1A
151 #define SMB_COM_READ_MPX               0x1B
152 #define SMB_COM_READ_MPX_SECONDARY     0x1C
153 #define SMB_COM_WRITE_RAW              0x1D
154 #define SMB_COM_WRITE_MPX              0x1E
155 #define SMB_COM_WRITE_COMPLETE         0x20
156 #define SMB_COM_SET_INFORMATION2       0x22
157 #define SMB_COM_QUERY_INFORMATION2     0x23
158 #define SMB_COM_LOCKING_ANDX           0x24
159 #define SMB_COM_TRANSACTION            0x25
160 #define SMB_COM_TRANSACTION_SECONDARY  0x26
161 #define SMB_COM_IOCTL                  0x27
162 #define SMB_COM_IOCTL_SECONDARY        0x28
163 #define SMB_COM_COPY                   0x29
164 #define SMB_COM_MOVE                   0x2A
165 #define SMB_COM_ECHO                   0x2B
166 #define SMB_COM_WRITE_AND_CLOSE        0x2C
167 #define SMB_COM_OPEN_ANDX              0x2D
168 #define SMB_COM_READ_ANDX              0x2E
169 #define SMB_COM_WRITE_ANDX             0x2F
170 #define SMB_COM_CLOSE_AND_TREE_DISC    0x31
171 #define SMB_COM_TRANSACTION2           0x32
172 #define SMB_COM_TRANSACTION2_SECONDARY 0x33
173 #define SMB_COM_FIND_CLOSE2            0x34
174 #define SMB_COM_FIND_NOTIFY_CLOSE      0x35
175 #define SMB_COM_TREE_CONNECT           0x70
176 #define SMB_COM_TREE_DISCONNECT        0x71
177 #define SMB_COM_NEGOTIATE              0x72
178 #define SMB_COM_SESSION_SETUP_ANDX     0x73
179 #define SMB_COM_LOGOFF_ANDX            0x74
180 #define SMB_COM_TREE_CONNECT_ANDX      0x75
181 #define SMB_COM_QUERY_INFORMATION_DISK 0x80
182 #define SMB_COM_SEARCH                 0x81
183 #define SMB_COM_FIND                   0x82
184 #define SMB_COM_FIND_UNIQUE            0x83
185 #define SMB_COM_NT_TRANSACT            0xA0
186 #define SMB_COM_NT_TRANSACT_SECONDARY  0xA1
187 #define SMB_COM_NT_CREATE_ANDX         0xA2
188 #define SMB_COM_NT_CANCEL              0xA4
189 #define SMB_COM_OPEN_PRINT_FILE        0xC0
190 #define SMB_COM_WRITE_PRINT_FILE       0xC1
191 #define SMB_COM_CLOSE_PRINT_FILE       0xC2
192 #define SMB_COM_GET_PRINT_QUEUE        0xC3
193
194 #define TRANS2_FIND_FIRST2             0x01
195 #define TRANS2_FIND_NEXT2              0x02
196
197 #define MAX_HOST_NAME 15
198 #define NB_TIMEOUT 10000
199
200 /* We only need the A versions locally currently */
201 static inline int SMB_isSepA (CHAR c) {return (c == '\\' || c == '/');}
202 static inline int SMB_isUNCA (LPCSTR filename) {return (filename && SMB_isSepW (filename[0]) && SMB_isSepW (filename[1]));}
203 static inline CHAR *SMB_nextSepA (CHAR *s) {while (*s && !SMB_isSepA (*s)) s++; return (*s? s : 0);}
204 /* NB SM_nextSepA cannot return const CHAR * since it is going to be used for
205  * replacing separators with null characters
206  */
207
208 static USHORT SMB_MultiplexId = 0;
209
210 struct NB_Buffer
211 {
212     unsigned char *buffer;
213     int len;
214 };
215
216 static int netbios_name(const char *p, unsigned char *buffer)
217 {
218     char ch;
219     int i,len=0;
220
221     buffer[len++]=' ';
222     for(i=0; i<=MAX_HOST_NAME; i++)
223     {
224         if(i<MAX_HOST_NAME)
225         {
226             if(*p)
227                 ch = *p++&0xdf; /* add character from hostname */
228             else
229                 ch = ' ';  /* add padding */
230         }
231         else
232             ch = 0;        /* add terminator */
233         buffer[len++] = ((ch&0xf0) >> 4) + 'A';
234         buffer[len++] =  (ch&0x0f) + 'A';
235     }
236     buffer[len++] = 0;     /* add second terminator */
237     return len;
238 }
239
240 static DWORD NB_NameReq(LPCSTR host, unsigned char *buffer, int len)
241 {
242     int trn = 1234,i=0;
243
244     NBR_ADDWORD(&buffer[i],trn);    i+=2;
245     NBR_ADDWORD(&buffer[i],0x0110); i+=2;
246     NBR_ADDWORD(&buffer[i],0x0001); i+=2;
247     NBR_ADDWORD(&buffer[i],0x0000); i+=2;
248     NBR_ADDWORD(&buffer[i],0x0000); i+=2;
249     NBR_ADDWORD(&buffer[i],0x0000); i+=2;
250
251     i += netbios_name(host,&buffer[i]);
252
253     NBR_ADDWORD(&buffer[i],0x0020); i+=2;
254     NBR_ADDWORD(&buffer[i],0x0001); i+=2;
255
256     TRACE("packet is %d bytes in length\n",i);
257
258     {
259         int j;
260         for(j=0; j<i; j++)
261             printf("%02x%c",buffer[j],(((j+1)%16)&&((j+1)!=j))?' ':'\n');
262     }
263
264     return i;
265 }
266
267 /* unc = \\hostname\share\file... */
268 static BOOL UNC_SplitName(LPSTR unc, LPSTR *hostname, LPSTR *share, LPSTR *file)
269 {
270     char *p;
271
272     TRACE("%s\n",unc);
273
274     if (!SMB_isUNCA (unc))
275         return FALSE;
276     p = unc + 2;
277     *hostname=p;
278
279     p = SMB_nextSepA (p);
280     if(!p)
281         return FALSE;
282     *p=0;
283     *share = ++p;
284
285     p = SMB_nextSepA (p);
286     if(!p)
287         return FALSE;
288     *p=0;
289     *file = ++p;
290
291     return TRUE;
292 }
293
294 static BOOL NB_Lookup(LPCSTR host, struct sockaddr_in *addr)
295 {
296     int fd,on=1,r,len,i,fromsize;
297     struct pollfd fds;
298     struct sockaddr_in sin,fromaddr;
299     unsigned char buffer[256];
300
301     fd = socket(PF_INET, SOCK_DGRAM, IPPROTO_UDP);
302     if(fd<0)
303         return FALSE;
304
305     r = setsockopt(fd, SOL_SOCKET, SO_BROADCAST, &on, sizeof(on));
306     if(r<0)
307         goto err;
308
309     if(0==inet_aton("255.255.255.255", (struct in_addr *)&sin.sin_addr.s_addr))
310     {
311         FIXME("Error getting bcast address\n");
312         goto err;
313     }
314     sin.sin_family = AF_INET;
315     sin.sin_port    = htons(137);
316
317     len = NB_NameReq(host,buffer,sizeof(buffer));
318     if(len<=0)
319         goto err;
320
321     r = sendto(fd, buffer, len, 0, (struct sockaddr*)&sin, sizeof(sin));
322     if(r<0)
323     {
324         FIXME("Error sending packet\n");
325         goto err;
326     }
327
328     fds.fd = fd;
329     fds.events = POLLIN;
330     fds.revents = 0;
331
332     /* FIXME: this is simple and easily fooled logic
333      *  we should loop until we receive the correct packet or timeout
334      */
335     r = poll(&fds,1,NB_TIMEOUT);
336     if(r!=1)
337         goto err;
338
339     TRACE("Got response!\n");
340
341     fromsize = sizeof (fromaddr);
342     r = recvfrom(fd, buffer, sizeof(buffer), 0, (struct sockaddr*)&fromaddr, &fromsize);
343     if(r<0)
344         goto err;
345
346     TRACE("%d bytes received\n",r);
347
348     if(r!=62)
349         goto err;
350
351     for(i=0; i<r; i++)
352         DPRINTF("%02X%c",buffer[i],(((i+1)!=r)&&((i+1)%16))?' ':'\n');
353     DPRINTF("\n");
354
355     if(0x0f & buffer[3])
356         goto err;
357
358     TRACE("packet is OK\n");
359
360     memcpy(&addr->sin_addr, &buffer[58], sizeof(addr->sin_addr));
361
362     close(fd);
363     return TRUE;
364
365 err:
366     close(fd);
367     return FALSE;
368 }
369
370 #define NB_FIRST 0x40
371
372 #define NB_HDRSIZE 4
373
374 #define NB_SESSION_MSG 0x00
375 #define NB_SESSION_REQ 0x81
376
377 /* RFC 1002, section 4.3.2 */
378 static BOOL NB_SessionReq(int fd, const char *called, const char *calling)
379 {
380     unsigned char buffer[0x100];
381     int len = 0,r;
382     struct pollfd fds;
383
384     TRACE("called %s, calling %s\n",called,calling);
385
386     buffer[0] = NB_SESSION_REQ;
387     buffer[1] = NB_FIRST;
388
389     netbios_name(called, &buffer[NB_HDRSIZE]);
390     len += 34;
391     netbios_name(calling, &buffer[NB_HDRSIZE+len]);
392     len += 34;
393
394     NBR_ADDWORD(&buffer[2],len);
395
396     /* for(i=0; i<(len+NB_HDRSIZE); i++)
397         DPRINTF("%02X%c",buffer[i],(((i+1)!=(len+4))&&((i+1)%16))?' ':'\n'); */
398
399     r = write(fd,buffer,len+4);
400     if(r<0)
401     {
402         ERR("Write failed\n");
403         return FALSE;
404     }
405
406     fds.fd = fd;
407     fds.events = POLLIN;
408     fds.revents = 0;
409
410     r = poll(&fds,1,NB_TIMEOUT);
411     if(r!=1)
412     {
413         ERR("Poll failed\n");
414         return FALSE;
415     }
416
417     r = read(fd, buffer, NB_HDRSIZE);
418     if((r!=NB_HDRSIZE) || (buffer[0]!=0x82))
419     {
420         TRACE("Received %d bytes\n",r);
421         TRACE("%02x %02x %02x %02x\n", buffer[0],buffer[1],buffer[2],buffer[3]);
422         return FALSE;
423     }
424
425     return TRUE;
426 }
427
428 static BOOL NB_SendData(int fd, struct NB_Buffer *out)
429 {
430     unsigned char buffer[NB_HDRSIZE];
431     int r;
432
433     /* CHECK: is it always OK to do this in two writes?   */
434     /*        perhaps use scatter gather sendmsg instead? */
435
436     buffer[0] = NB_SESSION_MSG;
437     buffer[1] = NB_FIRST;
438     NBR_ADDWORD(&buffer[2],out->len);
439
440     r = write(fd, buffer, NB_HDRSIZE);
441     if(r!=NB_HDRSIZE)
442         return FALSE;
443
444     r = write(fd, out->buffer, out->len);
445     if(r!=out->len)
446     {
447         ERR("write failed\n");
448         return FALSE;
449     }
450
451     return TRUE;
452 }
453
454 static BOOL NB_RecvData(int fd, struct NB_Buffer *rx)
455 {
456     int r;
457     unsigned char buffer[NB_HDRSIZE];
458
459     r = read(fd, buffer, NB_HDRSIZE);
460     if((r!=NB_HDRSIZE) || (buffer[0]!=NB_SESSION_MSG))
461     {
462         ERR("Received %d bytes\n",r);
463         return FALSE;
464     }
465
466     rx->len = NBR_GETWORD(&buffer[2]);
467
468     rx->buffer = RtlAllocateHeap(GetProcessHeap(), 0, rx->len);
469     if(!rx->buffer)
470         return FALSE;
471
472     r = read(fd, rx->buffer, rx->len);
473     if(rx->len!=r)
474     {
475         TRACE("Received %d bytes\n",r);
476         RtlFreeHeap(GetProcessHeap(), 0, rx->buffer);
477         rx->buffer = 0;
478         rx->len = 0;
479         return FALSE;
480     }
481
482     return TRUE;
483 }
484
485 static BOOL NB_Transaction(int fd, struct NB_Buffer *in, struct NB_Buffer *out)
486 {
487     int r;
488     struct pollfd fds;
489
490     if(TRACE_ON(file))
491     {
492         int i;
493     DPRINTF("Sending request:\n");
494         for(i=0; i<in->len; i++)
495             DPRINTF("%02X%c",in->buffer[i],(((i+1)!=in->len)&&((i+1)%16))?' ':'\n');
496     }
497
498     if(!NB_SendData(fd,in))
499         return FALSE;
500
501     fds.fd = fd;
502     fds.events = POLLIN;
503     fds.revents = 0;
504
505     r = poll(&fds,1,NB_TIMEOUT);
506     if(r!=1)
507     {
508         ERR("Poll failed\n");
509         return FALSE;
510     }
511
512     if(!NB_RecvData(fd, out))
513         return FALSE;
514
515     if(TRACE_ON(file))
516     {
517         int i;
518     DPRINTF("Got response:\n");
519         for(i=0; i<out->len; i++)
520             DPRINTF("%02X%c",out->buffer[i],(((i+1)!=out->len)&&((i+1)%16))?' ':'\n');
521     }
522
523     return TRUE;
524 }
525
526 #define SMB_ADDHEADER(b,l) { b[(l)++]=0xff; b[(l)++]='S'; b[(l)++]='M'; b[(l)++]='B'; }
527 #define SMB_ADDERRINFO(b,l) { b[(l)++]=0; b[(l)++]=0; b[(l)++]=0; b[(l)++]=0; }
528 #define SMB_ADDPADSIG(b,l) { memset(&b[l],0,12); l+=12; }
529
530 #define SMB_ERRCLASS 5
531 #define SMB_ERRCODE  7
532 #define SMB_TREEID  24
533 #define SMB_PROCID  26
534 #define SMB_USERID  28
535 #define SMB_PLEXID  30
536 #define SMB_PCOUNT  32
537 #define SMB_HDRSIZE 33
538
539 static DWORD SMB_GetError(unsigned char *buffer)
540 {
541     const char *err_class;
542
543     switch(buffer[SMB_ERRCLASS])
544     {
545     case 0:
546         return STATUS_SUCCESS;
547     case 1:
548         err_class = "DOS";
549         break;
550     case 2:
551         err_class = "net server";
552         break;
553     case 3:
554         err_class = "hardware";
555         break;
556     case 0xff:
557         err_class = "smb";
558         break;
559     default:
560         err_class = "unknown";
561         break;
562     }
563
564     ERR("%s error %d \n",err_class, buffer[SMB_ERRCODE]);
565
566     /* FIXME: return propper error codes */
567     return STATUS_INVALID_PARAMETER;
568 }
569
570 static int SMB_Header(unsigned char *buffer, unsigned char command, USHORT tree_id, USHORT user_id)
571 {
572     int len = 0;
573     DWORD id;
574
575     /* 0 */
576     SMB_ADDHEADER(buffer,len);
577
578     /* 4 */
579     buffer[len++] = command;
580
581     /* 5 */
582     SMB_ADDERRINFO(buffer,len)
583
584     /* 9 */
585     buffer[len++] = 0x00; /* flags */
586     SMB_ADDWORD(&buffer[len],1); len += 2; /* flags2 */
587
588     /* 12 */
589     SMB_ADDPADSIG(buffer,len)
590
591     /* 24 */
592     SMB_ADDWORD(&buffer[len],tree_id); len += 2; /* treeid */
593     id = GetCurrentThreadId();
594     SMB_ADDWORD(&buffer[len],id); len += 2; /* process id */
595     SMB_ADDWORD(&buffer[len],user_id); len += 2; /* user id */
596     SMB_ADDWORD(&buffer[len],SMB_MultiplexId); len += 2; /* multiplex id */
597     SMB_MultiplexId++;
598
599     return len;
600 }
601
602 static const char *SMB_ProtocolDialect = "NT LM 0.12";
603 /* = "Windows for Workgroups 3.1a"; */
604
605 /* FIXME: support multiple SMB dialects */
606 static BOOL SMB_NegotiateProtocol(int fd, USHORT *dialect)
607 {
608     unsigned char buf[0x100];
609     int buflen = 0;
610     struct NB_Buffer tx, rx;
611
612     TRACE("\n");
613
614     memset(buf,0,sizeof(buf));
615
616     tx.buffer = buf;
617     tx.len = SMB_Header(tx.buffer, SMB_COM_NEGOTIATE, 0, 0);
618
619     /* parameters */
620     tx.buffer[tx.len++] = 0; /* no parameters */
621
622     /* command buffer */
623     buflen = strlen(SMB_ProtocolDialect)+2;  /* include type and nul byte */
624     SMB_ADDWORD(&tx.buffer[tx.len],buflen); tx.len += 2;
625
626     tx.buffer[tx.len] = 0x02;
627     strcpy(&tx.buffer[tx.len+1],SMB_ProtocolDialect);
628     tx.len += buflen;
629
630     rx.buffer = NULL;
631     rx.len = 0;
632     if(!NB_Transaction(fd, &tx, &rx))
633     {
634         ERR("Failed\n");
635         return FALSE;
636     }
637
638     if(!rx.buffer)
639         return FALSE;
640
641     /* FIXME: check response */
642     if(SMB_GetError(rx.buffer))
643     {
644         ERR("returned error\n");
645         RtlFreeHeap(GetProcessHeap(),0,rx.buffer);
646         return FALSE;
647     }
648
649     RtlFreeHeap(GetProcessHeap(),0,rx.buffer);
650
651     *dialect = 0;
652
653     return TRUE;
654 }
655
656 #define SMB_PARAM_COUNT(buffer) ((buffer)[SMB_PCOUNT])
657 #define SMB_PARAM(buffer,n) SMB_GETWORD(&(buffer)[SMB_HDRSIZE+2*(n)])
658 #define SMB_BUFFER_COUNT(buffer)  SMB_GETWORD(buffer+SMB_HDRSIZE+2*SMB_PARAM_COUNT(buffer))
659 #define SMB_BUFFER(buffer,n) ((buffer)[SMB_HDRSIZE + 2*SMB_PARAM_COUNT(buffer) + 2 + (n) ])
660
661 static BOOL SMB_SessionSetup(int fd, USHORT *userid)
662 {
663     unsigned char buf[0x100];
664     int pcount,bcount;
665     struct NB_Buffer rx, tx;
666
667     memset(buf,0,sizeof(buf));
668     tx.buffer = buf;
669
670     tx.len = SMB_Header(tx.buffer, SMB_COM_SESSION_SETUP_ANDX, 0, 0);
671
672     tx.buffer[tx.len++] = 0;    /* no parameters? */
673
674     tx.buffer[tx.len++] = 0xff; /* AndXCommand: secondary request */
675     tx.buffer[tx.len++] = 0x00; /* AndXReserved */
676     SMB_ADDWORD(&tx.buffer[tx.len],0);     /* AndXOffset */
677     tx.len += 2;
678     SMB_ADDWORD(&tx.buffer[tx.len],0x400); /* MaxBufferSize */
679     tx.len += 2;
680     SMB_ADDWORD(&tx.buffer[tx.len],1);     /* MaxMpxCount */
681     tx.len += 2;
682     SMB_ADDWORD(&tx.buffer[tx.len],0);     /* VcNumber */
683     tx.len += 2;
684     SMB_ADDWORD(&tx.buffer[tx.len],0);     /* SessionKey */
685     tx.len += 2;
686     SMB_ADDWORD(&tx.buffer[tx.len],0);     /* SessionKey */
687     tx.len += 2;
688     SMB_ADDWORD(&tx.buffer[tx.len],0);     /* Password length */
689     tx.len += 2;
690     SMB_ADDWORD(&tx.buffer[tx.len],0);     /* Reserved */
691     tx.len += 2;
692     SMB_ADDWORD(&tx.buffer[tx.len],0);     /* Reserved */
693     tx.len += 2;
694
695     /* FIXME: add name and password here */
696     tx.buffer[tx.len++] = 0; /* number of bytes in password */
697
698     rx.buffer = NULL;
699     rx.len = 0;
700     if(!NB_Transaction(fd, &tx, &rx))
701         return FALSE;
702
703     if(!rx.buffer)
704         return FALSE;
705
706     if(SMB_GetError(rx.buffer))
707         goto done;
708
709     pcount = SMB_PARAM_COUNT(rx.buffer);
710
711     if( (SMB_HDRSIZE+pcount*2) > rx.len )
712     {
713         ERR("Bad parameter count %d\n",pcount);
714         goto done;
715     }
716
717     if(TRACE_ON(file))
718     {
719         int i;
720     DPRINTF("SMB_COM_SESSION_SETUP response, %d args: ",pcount);
721     for(i=0; i<pcount; i++)
722             DPRINTF("%04x ",SMB_PARAM(rx.buffer,i));
723     DPRINTF("\n");
724     }
725
726     bcount = SMB_BUFFER_COUNT(rx.buffer);
727     if( (SMB_HDRSIZE+pcount*2+2+bcount) > rx.len )
728     {
729         ERR("parameter count %x, buffer count %x, len %x\n",pcount,bcount,rx.len);
730         goto done;
731     }
732
733     if(TRACE_ON(file))
734     {
735         int i;
736     DPRINTF("response buffer %d bytes: ",bcount);
737     for(i=0; i<bcount; i++)
738     {
739             unsigned char ch = SMB_BUFFER(rx.buffer,i);
740         DPRINTF("%c", isprint(ch)?ch:' ');
741     }
742     DPRINTF("\n");
743     }
744
745     *userid = SMB_GETWORD(&rx.buffer[SMB_USERID]);
746
747     RtlFreeHeap(GetProcessHeap(),0,rx.buffer);
748     return TRUE;
749
750 done:
751     RtlFreeHeap(GetProcessHeap(),0,rx.buffer);
752     return FALSE;
753 }
754
755
756 static BOOL SMB_TreeConnect(int fd, USHORT user_id, LPCSTR share_name, USHORT *treeid)
757 {
758     unsigned char buf[0x100];
759     int slen;
760     struct NB_Buffer rx,tx;
761
762     TRACE("%s\n",share_name);
763
764     memset(buf,0,sizeof(buf));
765     tx.buffer = buf;
766
767     tx.len = SMB_Header(tx.buffer, SMB_COM_TREE_CONNECT, 0, user_id);
768
769     tx.buffer[tx.len++] = 4; /* parameters */
770
771     tx.buffer[tx.len++] = 0xff; /* AndXCommand: secondary request */
772     tx.buffer[tx.len++] = 0x00; /* AndXReserved */
773     SMB_ADDWORD(&tx.buffer[tx.len],0); /* AndXOffset */
774     tx.len += 2;
775     SMB_ADDWORD(&tx.buffer[tx.len],0); /* Flags */
776     tx.len += 2;
777     SMB_ADDWORD(&tx.buffer[tx.len],1); /* Password length */
778     tx.len += 2;
779
780     /* SMB command buffer */
781     SMB_ADDWORD(&tx.buffer[tx.len],3); /* command buffer len */
782     tx.len += 2;
783     tx.buffer[tx.len++] = 0; /* null terminated password */
784
785     slen = strlen(share_name);
786     if(slen<(sizeof(buf)-tx.len))
787         strcpy(&tx.buffer[tx.len], share_name);
788     else
789         return FALSE;
790     tx.len += slen+1;
791
792     /* name of the service */
793     tx.buffer[tx.len++] = 0;
794
795     rx.buffer = NULL;
796     rx.len = 0;
797     if(!NB_Transaction(fd, &tx, &rx))
798         return FALSE;
799
800     if(!rx.buffer)
801         return FALSE;
802
803     if(SMB_GetError(rx.buffer))
804     {
805         RtlFreeHeap(GetProcessHeap(),0,rx.buffer);
806         return FALSE;
807     }
808
809     *treeid = SMB_GETWORD(&rx.buffer[SMB_TREEID]);
810
811     RtlFreeHeap(GetProcessHeap(),0,rx.buffer);
812     TRACE("OK, treeid = %04x\n", *treeid);
813
814     return TRUE;
815 }
816
817 #if 0  /* not yet */
818 static BOOL SMB_NtCreateOpen(int fd, USHORT tree_id, USHORT user_id, USHORT dialect,
819                               LPCSTR filename, DWORD access, DWORD sharing,
820                               LPSECURITY_ATTRIBUTES sa, DWORD creation,
821                               DWORD attributes, HANDLE template, USHORT *file_id )
822 {
823     unsigned char buffer[0x100];
824     int len = 0,slen;
825
826     TRACE("%s\n",filename);
827
828     memset(buffer,0,sizeof(buffer));
829
830     len = SMB_Header(buffer, SMB_COM_NT_CREATE_ANDX, tree_id, user_id);
831
832     /* 0 */
833     buffer[len++] = 24; /* parameters */
834
835     buffer[len++] = 0xff; /* AndXCommand: secondary request */
836     buffer[len++] = 0x00; /* AndXReserved */
837     SMB_ADDWORD(&buffer[len],0); len += 2; /* AndXOffset */
838
839     buffer[len++] = 0;                     /* reserved */
840     slen = strlen(filename);
841     SMB_ADDWORD(&buffer[len],slen);    len += 2; /* name length */
842
843     /* 0x08 */
844     SMB_ADDDWORD(&buffer[len],0);      len += 4; /* flags */
845     SMB_ADDDWORD(&buffer[len],0);      len += 4; /* root directory fid */
846     /* 0x10 */
847     SMB_ADDDWORD(&buffer[len],access); len += 4; /* access */
848     SMB_ADDDWORD(&buffer[len],0);      len += 4; /* allocation size */
849     /* 0x18 */
850     SMB_ADDDWORD(&buffer[len],0);      len += 4; /* root directory fid */
851
852     /* 0x1c */
853     SMB_ADDDWORD(&buffer[len],0);      len += 4; /* initial allocation */
854     SMB_ADDDWORD(&buffer[len],0);      len += 4;
855
856     /* 0x24 */
857     SMB_ADDDWORD(&buffer[len],attributes);      len += 4; /* ExtFileAttributes*/
858
859     /* 0x28 */
860     SMB_ADDDWORD(&buffer[len],sharing);      len += 4; /* ShareAccess */
861
862     /* 0x2c */
863     TRACE("creation = %08lx\n",creation);
864     SMB_ADDDWORD(&buffer[len],creation);      len += 4; /* CreateDisposition */
865
866     /* 0x30 */
867     SMB_ADDDWORD(&buffer[len],creation);      len += 4; /* CreateOptions */
868
869     /* 0x34 */
870     SMB_ADDDWORD(&buffer[len],0);      len += 4; /* Impersonation */
871
872     /* 0x38 */
873     buffer[len++] = 0;                     /* security flags */
874
875     /* 0x39 */
876     SMB_ADDWORD(&buffer[len],slen); len += 2; /* size of buffer */
877
878     if(slen<(sizeof(buffer)-len))
879         strcpy(&buffer[len], filename);
880     else
881         return FALSE;
882     len += slen+1;
883
884     /* name of the file */
885     buffer[len++] = 0;
886
887     if(!NB_Transaction(fd, buffer, len, &len))
888         return FALSE;
889
890     if(SMB_GetError(buffer))
891         return FALSE;
892
893     TRACE("OK\n");
894
895     /* FIXME */
896     /* *file_id = SMB_GETWORD(&buffer[xxx]); */
897     *file_id = 0;
898     return FALSE;
899
900     return TRUE;
901 }
902 #endif
903
904 static USHORT SMB_GetMode(DWORD access, DWORD sharing)
905 {
906     USHORT mode=0;
907
908     switch(access&(GENERIC_READ|GENERIC_WRITE))
909     {
910     case GENERIC_READ:
911         mode |= OF_READ;
912         break;
913     case GENERIC_WRITE:
914         mode |= OF_WRITE;
915         break;
916     case (GENERIC_READ|GENERIC_WRITE):
917         mode |= OF_READWRITE;
918         break;
919     }
920
921     switch(sharing&(FILE_SHARE_READ|FILE_SHARE_WRITE))
922     {
923     case (FILE_SHARE_READ|FILE_SHARE_WRITE):
924         mode |= OF_SHARE_DENY_NONE;
925         break;
926     case FILE_SHARE_READ:
927         mode |= OF_SHARE_DENY_WRITE;
928         break;
929     case FILE_SHARE_WRITE:
930         mode |= OF_SHARE_DENY_READ;
931         break;
932     default:
933         mode |= OF_SHARE_EXCLUSIVE;
934         break;
935     }
936
937     return mode;
938 }
939
940 #if 0  /* not yet */
941 /* inverse of FILE_ConvertOFMode */
942 static BOOL SMB_OpenAndX(int fd, USHORT tree_id, USHORT user_id, USHORT dialect,
943                               LPCSTR filename, DWORD access, DWORD sharing,
944                               DWORD creation, DWORD attributes, USHORT *file_id )
945 {
946     unsigned char buffer[0x100];
947     int len = 0;
948     USHORT mode;
949
950     TRACE("%s\n",filename);
951
952     mode = SMB_GetMode(access,sharing);
953
954     memset(buffer,0,sizeof(buffer));
955
956     len = SMB_Header(buffer, SMB_COM_OPEN_ANDX, tree_id, user_id);
957
958     /* 0 */
959     buffer[len++] = 15; /* parameters */
960     buffer[len++] = 0xff; /* AndXCommand: secondary request */
961     buffer[len++] = 0x00; /* AndXReserved */
962     SMB_ADDWORD(buffer+len,0); len+=2; /* AndXOffset */
963     SMB_ADDWORD(buffer+len,0); len+=2; /* Flags */
964     SMB_ADDWORD(buffer+len,mode); len+=2; /* desired access */
965     SMB_ADDWORD(buffer+len,0); len+=2; /* search attributes */
966     SMB_ADDWORD(buffer+len,0); len+=2;
967
968     /*FIXME: complete */
969     return FALSE;
970 }
971 #endif
972
973
974 static BOOL SMB_Open(int fd, USHORT tree_id, USHORT user_id, USHORT dialect,
975                               LPCSTR filename, DWORD access, DWORD sharing,
976                               DWORD creation, DWORD attributes, USHORT *file_id )
977 {
978     unsigned char buf[0x100];
979     int slen,pcount,i;
980     USHORT mode = SMB_GetMode(access,sharing);
981     struct NB_Buffer rx,tx;
982
983     TRACE("%s\n",filename);
984
985     memset(buf,0,sizeof(buf));
986
987     tx.buffer = buf;
988     tx.len = SMB_Header(tx.buffer, SMB_COM_OPEN, tree_id, user_id);
989
990     /* 0 */
991     tx.buffer[tx.len++] = 2; /* parameters */
992     SMB_ADDWORD(tx.buffer+tx.len,mode); tx.len+=2;
993     SMB_ADDWORD(tx.buffer+tx.len,0);    tx.len+=2; /* search attributes */
994
995     slen = strlen(filename)+2;   /* inc. nul and BufferFormat */
996     SMB_ADDWORD(tx.buffer+tx.len,slen); tx.len+=2;
997
998     tx.buffer[tx.len] = 0x04;  /* BufferFormat */
999     strcpy(&tx.buffer[tx.len+1],filename);
1000     tx.len += slen;
1001
1002     rx.buffer = NULL;
1003     rx.len = 0;
1004     if(!NB_Transaction(fd, &tx, &rx))
1005         return FALSE;
1006
1007     if(!rx.buffer)
1008         return FALSE;
1009
1010     if(SMB_GetError(rx.buffer))
1011         return FALSE;
1012
1013     pcount = SMB_PARAM_COUNT(rx.buffer);
1014
1015     if( (SMB_HDRSIZE+pcount*2) > rx.len )
1016     {
1017         ERR("Bad parameter count %d\n",pcount);
1018         return FALSE;
1019     }
1020
1021     TRACE("response, %d args: ",pcount);
1022     for(i=0; i<pcount; i++)
1023         TRACE("%04x ",SMB_PARAM(rx.buffer,i));
1024     TRACE("\n");
1025
1026     *file_id = SMB_PARAM(rx.buffer,0);
1027
1028     TRACE("file_id = %04x\n",*file_id);
1029
1030     return TRUE;
1031 }
1032
1033
1034 static BOOL SMB_Read(int fd, USHORT tree_id, USHORT user_id, USHORT dialect,
1035        USHORT file_id, DWORD offset, LPVOID out, USHORT count, USHORT* read)
1036 {
1037     int buf_size,n,i;
1038     struct NB_Buffer rx,tx;
1039
1040     TRACE("user %04x tree %04x file %04x count %04x offset %08lx\n",
1041         user_id, tree_id, file_id, count, offset);
1042
1043     buf_size = count+0x100;
1044     tx.buffer = (unsigned char *) RtlAllocateHeap(GetProcessHeap(),0,buf_size);
1045
1046     memset(tx.buffer,0,buf_size);
1047
1048     tx.len = SMB_Header(tx.buffer, SMB_COM_READ, tree_id, user_id);
1049
1050     tx.buffer[tx.len++] = 5;
1051     SMB_ADDWORD(&tx.buffer[tx.len],file_id); tx.len += 2;
1052     SMB_ADDWORD(&tx.buffer[tx.len],count);   tx.len += 2;
1053     SMB_ADDDWORD(&tx.buffer[tx.len],offset); tx.len += 4;
1054     SMB_ADDWORD(&tx.buffer[tx.len],0);       tx.len += 2; /* how many more bytes will be read */
1055
1056     tx.buffer[tx.len++] = 0;
1057
1058     rx.buffer = NULL;
1059     rx.len = 0;
1060     if(!NB_Transaction(fd, &tx, &rx))
1061     {
1062         RtlFreeHeap(GetProcessHeap(),0,tx.buffer);
1063         return FALSE;
1064     }
1065
1066     if(SMB_GetError(rx.buffer))
1067     {
1068         RtlFreeHeap(GetProcessHeap(),0,rx.buffer);
1069         RtlFreeHeap(GetProcessHeap(),0,tx.buffer);
1070         return FALSE;
1071     }
1072
1073     n = SMB_PARAM_COUNT(rx.buffer);
1074
1075     if( (SMB_HDRSIZE+n*2) > rx.len )
1076     {
1077         RtlFreeHeap(GetProcessHeap(),0,rx.buffer);
1078         RtlFreeHeap(GetProcessHeap(),0,tx.buffer);
1079         ERR("Bad parameter count %d\n",n);
1080         return FALSE;
1081     }
1082
1083     TRACE("response, %d args: ",n);
1084     for(i=0; i<n; i++)
1085         TRACE("%04x ",SMB_PARAM(rx.buffer,i));
1086     TRACE("\n");
1087
1088     n = SMB_PARAM(rx.buffer,5) - 3;
1089     if(n>count)
1090         n=count;
1091
1092     memcpy( out, &SMB_BUFFER(rx.buffer,3), n);
1093
1094     TRACE("Read %d bytes\n",n);
1095     *read = n;
1096
1097     RtlFreeHeap(GetProcessHeap(),0,tx.buffer);
1098     RtlFreeHeap(GetProcessHeap(),0,rx.buffer);
1099
1100     return TRUE;
1101 }
1102
1103
1104 /*
1105  * setup_count : number of USHORTs in the setup string
1106  */
1107 struct SMB_Trans2Info
1108 {
1109     struct NB_Buffer buf;
1110     unsigned char *setup;
1111     int setup_count;
1112     unsigned char *params;
1113     int param_count;
1114     unsigned char *data;
1115     int data_count;
1116 };
1117
1118 /*
1119  * Do an SMB transaction
1120  *
1121  * This function allocates memory in the recv structure. It is
1122  * the caller's responsibility to free the memory if it finds
1123  * that recv->buf.buffer is nonzero.
1124  */
1125 static BOOL SMB_Transaction2(int fd, int tree_id, int user_id,
1126                  struct SMB_Trans2Info *send,
1127                  struct SMB_Trans2Info *recv)
1128 {
1129     int buf_size;
1130     const int retmaxparams = 0xf000;
1131     const int retmaxdata = 1024;
1132     const int retmaxsetup = 0; /* FIXME */
1133     const int flags = 0;
1134     const int timeout = 0;
1135     int param_ofs, data_ofs;
1136     struct NB_Buffer tx;
1137     BOOL ret = FALSE;
1138
1139     buf_size = 0x100 + send->setup_count*2 + send->param_count + send->data_count ;
1140     tx.buffer = (unsigned char *) RtlAllocateHeap(GetProcessHeap(),0,buf_size);
1141
1142     tx.len = SMB_Header(tx.buffer, SMB_COM_TRANSACTION2, tree_id, user_id);
1143
1144     tx.buffer[tx.len++] = 14 + send->setup_count;
1145     SMB_ADDWORD(&tx.buffer[tx.len],send->param_count); /* total param bytes sent */
1146     tx.len += 2;
1147     SMB_ADDWORD(&tx.buffer[tx.len],send->data_count);  /* total data bytes sent */
1148     tx.len += 2;
1149     SMB_ADDWORD(&tx.buffer[tx.len],retmaxparams); /*max parameter bytes to return */
1150     tx.len += 2;
1151     SMB_ADDWORD(&tx.buffer[tx.len],retmaxdata);  /* max data bytes to return */
1152     tx.len += 2;
1153     tx.buffer[tx.len++] = retmaxsetup;
1154     tx.buffer[tx.len++] = 0;                     /* reserved1 */
1155
1156     SMB_ADDWORD(&tx.buffer[tx.len],flags);       /* flags */
1157     tx.len += 2;
1158     SMB_ADDDWORD(&tx.buffer[tx.len],timeout);    /* timeout */
1159     tx.len += 4;
1160     SMB_ADDWORD(&tx.buffer[tx.len],0);           /* reserved2 */
1161     tx.len += 2;
1162     SMB_ADDWORD(&tx.buffer[tx.len],send->param_count); /* parameter count - this buffer */
1163     tx.len += 2;
1164
1165     param_ofs = tx.len;                          /* parameter offset */
1166     tx.len += 2;
1167     SMB_ADDWORD(&tx.buffer[tx.len],send->data_count);  /* data count */
1168     tx.len += 2;
1169
1170     data_ofs = tx.len;                           /* data offset */
1171     tx.len += 2;
1172     tx.buffer[tx.len++] = send->setup_count;     /* setup count */
1173     tx.buffer[tx.len++] = 0;                     /* reserved3 */
1174
1175     memcpy(&tx.buffer[tx.len], send->setup, send->setup_count*2); /* setup */
1176     tx.len += send->setup_count*2;
1177
1178     /* add string here when implementing SMB_COM_TRANS */
1179
1180     SMB_ADDWORD(&tx.buffer[param_ofs], tx.len);
1181     memcpy(&tx.buffer[tx.len], send->params, send->param_count); /* parameters */
1182     tx.len += send->param_count;
1183     if(tx.len%2)
1184         tx.len ++;                                      /* pad2 */
1185
1186     SMB_ADDWORD(&tx.buffer[data_ofs], tx.len);
1187     if(send->data_count && send->data)
1188     {
1189         memcpy(&tx.buffer[tx.len], send->data, send->data_count); /* data */
1190         tx.len += send->data_count;
1191     }
1192
1193     recv->buf.buffer = NULL;
1194     recv->buf.len = 0;
1195     if(!NB_Transaction(fd, &tx, &recv->buf))
1196         goto done;
1197
1198     if(!recv->buf.buffer)
1199         goto done;
1200
1201     if(SMB_GetError(recv->buf.buffer))
1202         goto done;
1203
1204     /* reuse these two offsets to check the received message */
1205     param_ofs = SMB_PARAM(recv->buf.buffer,4);
1206     data_ofs = SMB_PARAM(recv->buf.buffer,7);
1207
1208     if( (recv->param_count + param_ofs) > recv->buf.len )
1209         goto done;
1210
1211     if( (recv->data_count + data_ofs) > recv->buf.len )
1212         goto done;
1213
1214     TRACE("Success\n");
1215
1216     recv->setup = NULL;
1217     recv->setup_count = 0;
1218
1219     recv->param_count = SMB_PARAM(recv->buf.buffer,0);
1220     recv->params = &recv->buf.buffer[param_ofs];
1221
1222     recv->data_count = SMB_PARAM(recv->buf.buffer,6);
1223     recv->data = &recv->buf.buffer[data_ofs];
1224
1225    /*
1226     TRACE("%d words\n",SMB_PARAM_COUNT(recv->buf.buffer));
1227     TRACE("total parameters = %d\n",SMB_PARAM(recv->buf.buffer,0));
1228     TRACE("total data       = %d\n",SMB_PARAM(recv->buf.buffer,1));
1229     TRACE("parameters       = %d\n",SMB_PARAM(recv->buf.buffer,3));
1230     TRACE("parameter offset = %d\n",SMB_PARAM(recv->buf.buffer,4));
1231     TRACE("param displace   = %d\n",SMB_PARAM(recv->buf.buffer,5));
1232
1233     TRACE("data count       = %d\n",SMB_PARAM(recv->buf.buffer,6));
1234     TRACE("data offset      = %d\n",SMB_PARAM(recv->buf.buffer,7));
1235     TRACE("data displace    = %d\n",SMB_PARAM(recv->buf.buffer,8));
1236    */
1237
1238     ret = TRUE;
1239
1240 done:
1241     if(tx.buffer)
1242         RtlFreeHeap(GetProcessHeap(),0,tx.buffer);
1243
1244     return ret;
1245 }
1246
1247 static BOOL SMB_SetupFindFirst(struct SMB_Trans2Info *send, LPSTR filename)
1248 {
1249     int search_attribs = FILE_ATTRIBUTE_DIRECTORY | FILE_ATTRIBUTE_HIDDEN | FILE_ATTRIBUTE_SYSTEM;
1250     int search_count = 10;
1251     int flags = 0;
1252     int infolevel = 0x104; /* SMB_FILE_BOTH_DIRECTORY_INFO */
1253     int storagetype = 0;
1254     int len, buf_size;
1255
1256     memset(send,0,sizeof(send));
1257
1258     send->setup_count = 1;
1259     send->setup = RtlAllocateHeap(GetProcessHeap(),0,send->setup_count*2);
1260     if(!send->setup)
1261         return FALSE;
1262
1263     buf_size = 0x10 + strlen(filename);
1264     send->params = RtlAllocateHeap(GetProcessHeap(),0,buf_size);
1265     if(!send->params)
1266     {
1267         RtlFreeHeap(GetProcessHeap(),0,send->setup);
1268         return FALSE;
1269     }
1270
1271     SMB_ADDWORD(send->setup,TRANS2_FIND_FIRST2);
1272
1273     len = 0;
1274     memset(send->params,0,buf_size);
1275     SMB_ADDWORD(&send->params[len],search_attribs); len += 2;
1276     SMB_ADDWORD(&send->params[len],search_count); len += 2;
1277     SMB_ADDWORD(&send->params[len],flags); len += 2;
1278     SMB_ADDWORD(&send->params[len],infolevel); len += 2;
1279     SMB_ADDDWORD(&send->params[len],storagetype); len += 4;
1280
1281     strcpy(&send->params[len],filename);
1282     len += strlen(filename)+1;
1283
1284     send->param_count = len;
1285     send->data = NULL;
1286     send->data_count = 0;
1287
1288     return TRUE;
1289 }
1290
1291 static SMB_DIR *SMB_Trans2FindFirst(int fd, USHORT tree_id,
1292                     USHORT user_id, USHORT dialect, LPSTR filename )
1293 {
1294     int num;
1295     BOOL ret;
1296     /* char *filename = "\\*"; */
1297     struct SMB_Trans2Info send, recv;
1298     SMB_DIR *smbdir = NULL;
1299
1300     TRACE("pattern = %s\n",filename);
1301
1302     if(!SMB_SetupFindFirst(&send, filename))
1303         return FALSE;
1304
1305     memset(&recv,0,sizeof(recv));
1306
1307     ret = SMB_Transaction2(fd, tree_id, user_id, &send, &recv);
1308     RtlFreeHeap(GetProcessHeap(),0,send.params);
1309     RtlFreeHeap(GetProcessHeap(),0,send.setup);
1310
1311     if(!ret)
1312         goto done;
1313
1314     if(recv.setup_count)
1315         goto done;
1316
1317     if(recv.param_count != 10)
1318         goto done;
1319
1320     num = SMB_GETWORD(&recv.params[2]);
1321     TRACE("Success, search id: %d\n",num);
1322
1323     if(SMB_GETWORD(&recv.params[4]))
1324         FIXME("need to read more!\n");
1325
1326     smbdir = RtlAllocateHeap(GetProcessHeap(),0,sizeof(*smbdir));
1327     if(smbdir)
1328     {
1329         int i, ofs=0;
1330
1331         smbdir->current = 0;
1332         smbdir->num_entries = num;
1333         smbdir->entries = RtlAllocateHeap(GetProcessHeap(), 0, sizeof(unsigned char*)*num);
1334         if(!smbdir->entries)
1335             goto done;
1336         smbdir->buffer = recv.buf.buffer; /* save to free later */
1337
1338         for(i=0; i<num; i++)
1339         {
1340             int size = SMB_GETDWORD(&recv.data[ofs]);
1341
1342             smbdir->entries[i] = &recv.data[ofs];
1343
1344             if(TRACE_ON(file))
1345             {
1346                 int j;
1347                 for(j=0; j<size; j++)
1348                     DPRINTF("%02x%c",recv.data[ofs+j],((j+1)%16)?' ':'\n');
1349             }
1350             TRACE("file %d : %s\n", i, &recv.data[ofs+0x5e]);
1351             ofs += size;
1352             if(ofs>recv.data_count)
1353                 goto done;
1354         }
1355
1356         ret = TRUE;
1357     }
1358
1359 done:
1360     if(!ret)
1361     {
1362         if( recv.buf.buffer )
1363             RtlFreeHeap(GetProcessHeap(),0,recv.buf.buffer);
1364         if( smbdir )
1365         {
1366             if( smbdir->entries )
1367                 RtlFreeHeap(GetProcessHeap(),0,smbdir->entries);
1368             RtlFreeHeap(GetProcessHeap(),0,smbdir);
1369         }
1370         smbdir = NULL;
1371     }
1372
1373     return smbdir;
1374 }
1375
1376 static int SMB_GetSocket(LPCSTR host)
1377 {
1378     int fd=-1,r;
1379     struct sockaddr_in sin;
1380     struct hostent *he;
1381
1382     TRACE("host %s\n",host);
1383
1384     he = gethostbyname(host);
1385     if(he)
1386     {
1387         memcpy(&sin.sin_addr,he->h_addr, sizeof (sin.sin_addr));
1388         goto connect;
1389     }
1390
1391     if(NB_Lookup(host,&sin))
1392         goto connect;
1393
1394     /* FIXME: resolve by WINS too */
1395
1396     ERR("couldn't resolve SMB host %s\n", host);
1397
1398     return -1;
1399
1400 connect:
1401     sin.sin_family = AF_INET;
1402     sin.sin_port   = htons(139);  /* netbios session */
1403
1404     fd = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);
1405     if(fd<0)
1406         return fd;
1407
1408     {
1409         unsigned char *x = (unsigned char *)&sin.sin_addr;
1410         TRACE("Connecting to %d.%d.%d.%d ...\n", x[0],x[1],x[2],x[3]);
1411     }
1412     r = connect(fd, (struct sockaddr*)&sin, sizeof(sin));
1413
1414     if(!NB_SessionReq(fd, "*SMBSERVER", "WINE"))
1415     {
1416         close(fd);
1417         return -1;
1418     }
1419
1420     return fd;
1421 }
1422
1423 static BOOL SMB_LoginAndConnect(int fd, LPCSTR host, LPCSTR share, USHORT *tree_id, USHORT *user_id, USHORT *dialect)
1424 {
1425     LPSTR name=NULL;
1426
1427     TRACE("host %s share %s\n",host,share);
1428
1429     if(!SMB_NegotiateProtocol(fd, dialect))
1430         return FALSE;
1431
1432     if(!SMB_SessionSetup(fd, user_id))
1433         return FALSE;
1434
1435     name = RtlAllocateHeap(GetProcessHeap(),0,strlen(host)+strlen(share)+5);
1436     if(!name)
1437         return FALSE;
1438
1439     sprintf(name,"\\\\%s\\%s",host,share);
1440     if(!SMB_TreeConnect(fd,*user_id,name,tree_id))
1441     {
1442         RtlFreeHeap(GetProcessHeap(),0,name);
1443         return FALSE;
1444     }
1445
1446     return TRUE;
1447 }
1448
1449 static HANDLE SMB_RegisterFile( int fd, USHORT tree_id, USHORT user_id, USHORT dialect, USHORT file_id)
1450 {
1451     int r;
1452     HANDLE ret;
1453
1454     wine_server_send_fd( fd );
1455
1456     SERVER_START_REQ( create_smb )
1457     {
1458         req->tree_id = tree_id;
1459         req->user_id = user_id;
1460         req->file_id = file_id;
1461         req->dialect = 0;
1462         req->fd      = fd;
1463         SetLastError(0);
1464         r = wine_server_call_err( req );
1465         ret = reply->handle;
1466     }
1467     SERVER_END_REQ;
1468
1469     if(!r)
1470         TRACE("created wineserver smb object, handle = %p\n",ret);
1471     else
1472         SetLastError( ERROR_PATH_NOT_FOUND );
1473
1474     return ret;
1475 }
1476
1477 HANDLE WINAPI SMB_CreateFileW( LPCWSTR uncname, DWORD access, DWORD sharing,
1478                               LPSECURITY_ATTRIBUTES sa, DWORD creation,
1479                               DWORD attributes, HANDLE template )
1480 {
1481     int fd;
1482     USHORT tree_id=0, user_id=0, dialect=0, file_id=0;
1483     LPSTR name,host,share,file;
1484     HANDLE handle = INVALID_HANDLE_VALUE;
1485     INT len;
1486
1487     len = WideCharToMultiByte(CP_ACP, 0, uncname, -1, NULL, 0, NULL, NULL);
1488     name = RtlAllocateHeap(GetProcessHeap(), 0, len);
1489     if(!name)
1490         return handle;
1491
1492     WideCharToMultiByte(CP_ACP, 0, uncname, -1, name, len, NULL, NULL);
1493
1494     if( !UNC_SplitName(name, &host, &share, &file) )
1495     {
1496         RtlFreeHeap(GetProcessHeap(),0,name);
1497         return handle;
1498     }
1499
1500     TRACE("server is %s, share is %s, file is %s\n", host, share, file);
1501
1502     fd = SMB_GetSocket(host);
1503     if(fd < 0)
1504         goto done;
1505
1506     if(!SMB_LoginAndConnect(fd, host, share, &tree_id, &user_id, &dialect))
1507         goto done;
1508
1509 #if 0
1510     if(!SMB_NtCreateOpen(fd, tree_id, user_id, dialect, file,
1511                     access, sharing, sa, creation, attributes, template, &file_id ))
1512     {
1513         close(fd);
1514         ERR("CreateOpen failed\n");
1515         goto done;
1516     }
1517 #endif
1518     if(!SMB_Open(fd, tree_id, user_id, dialect, file,
1519                     access, sharing, creation, attributes, &file_id ))
1520     {
1521         close(fd);
1522         ERR("CreateOpen failed\n");
1523         goto done;
1524     }
1525
1526     handle = SMB_RegisterFile(fd, tree_id, user_id, dialect, file_id);
1527     if(!handle)
1528     {
1529         ERR("register failed\n");
1530         close(fd);
1531     }
1532
1533 done:
1534     RtlFreeHeap(GetProcessHeap(),0,name);
1535     return handle;
1536 }
1537
1538 static NTSTATUS SMB_GetSmbInfo(HANDLE hFile, USHORT *tree_id, USHORT *user_id, USHORT *dialect, USHORT *file_id, LPDWORD offset)
1539 {
1540     NTSTATUS status;
1541
1542     SERVER_START_REQ( get_smb_info )
1543     {
1544         req->handle  = hFile;
1545         req->flags   = 0;
1546         status = wine_server_call( req );
1547         if(tree_id)
1548             *tree_id = reply->tree_id;
1549         if(user_id)
1550             *user_id = reply->user_id;
1551         if(file_id)
1552             *file_id = reply->file_id;
1553         if(dialect)
1554             *dialect = reply->dialect;
1555         if(offset)
1556             *offset = reply->offset;
1557     }
1558     SERVER_END_REQ;
1559
1560     return status;
1561 }
1562
1563 static NTSTATUS SMB_SetOffset(HANDLE hFile, DWORD offset)
1564 {
1565     NTSTATUS status;
1566
1567     TRACE("offset = %08lx\n",offset);
1568
1569     SERVER_START_REQ( get_smb_info )
1570     {
1571         req->handle  = hFile;
1572         req->flags   = SMBINFO_SET_OFFSET;
1573         req->offset  = offset;
1574         status = wine_server_call( req );
1575         /* if(offset)
1576             *offset = reply->offset; */
1577     }
1578     SERVER_END_REQ;
1579
1580     return status;
1581 }
1582
1583 NTSTATUS WINAPI SMB_ReadFile(HANDLE hFile, int fd, LPVOID buffer, DWORD bytesToRead,
1584                              PIO_STATUS_BLOCK io_status)
1585 {
1586     DWORD count, offset;
1587     USHORT user_id, tree_id, dialect, file_id, read;
1588
1589     TRACE("%p %p %ld %p\n", hFile, buffer, bytesToRead, io_status);
1590
1591     io_status->Information = 0;
1592
1593     io_status->u.Status = SMB_GetSmbInfo(hFile, &tree_id, &user_id, &dialect, &file_id, &offset);
1594     if (io_status->u.Status) return io_status->u.Status;
1595
1596     while(1)
1597     {
1598         count = bytesToRead - io_status->Information;
1599         if(count>0x400)
1600             count = 0x400;
1601         if(count==0)
1602             break;
1603         read = 0;
1604         if (!SMB_Read(fd, tree_id, user_id, dialect, file_id, offset, buffer, count, &read))
1605             break;
1606         if(!read)
1607             break;
1608         io_status->Information += read;
1609         buffer = (char*)buffer + read;
1610         offset += read;
1611         if(io_status->Information >= bytesToRead)
1612             break;
1613     }
1614     return io_status->u.Status = SMB_SetOffset(hFile, offset);
1615 }
1616
1617 SMB_DIR* WINAPI SMB_FindFirst(LPCWSTR name)
1618 {
1619     int fd = -1;
1620     LPSTR host,share,file;
1621     USHORT tree_id=0, user_id=0, dialect=0;
1622     SMB_DIR *ret = NULL;
1623     LPSTR filename;
1624     DWORD len;
1625
1626     TRACE("Find %s\n",debugstr_w(name));
1627
1628     len = WideCharToMultiByte( CP_ACP, 0, name, -1, NULL, 0, NULL, NULL );
1629     filename = RtlAllocateHeap(GetProcessHeap(),0,len);
1630     if(!filename)
1631         return ret;
1632     WideCharToMultiByte( CP_ACP, 0, name, -1, filename, len, NULL, NULL );
1633
1634     if( !UNC_SplitName(filename, &host, &share, &file) )
1635         goto done;
1636
1637     fd = SMB_GetSocket(host);
1638     if(fd < 0)
1639         goto done;
1640
1641     if(!SMB_LoginAndConnect(fd, host, share, &tree_id, &user_id, &dialect))
1642         goto done;
1643
1644     TRACE("server is %s, share is %s, file is %s\n", host, share, file);
1645
1646     ret = SMB_Trans2FindFirst(fd, tree_id, user_id, dialect, file);
1647
1648 done:
1649     /* disconnect */
1650     if(fd != -1)
1651         close(fd);
1652
1653     if(filename)
1654         RtlFreeHeap(GetProcessHeap(),0,filename);
1655
1656     return ret;
1657 }
1658
1659
1660 BOOL WINAPI SMB_FindNext(SMB_DIR *dir, WIN32_FIND_DATAW *data )
1661 {
1662     unsigned char *ent;
1663     int len, fnlen;
1664
1665     TRACE("%d of %d\n",dir->current,dir->num_entries);
1666
1667     if(dir->current >= dir->num_entries)
1668         return FALSE;
1669
1670     memset(data, 0, sizeof(*data));
1671
1672     ent = dir->entries[dir->current];
1673     len = SMB_GETDWORD(&ent[0]);
1674     if(len<0x5e)
1675         return FALSE;
1676
1677     memcpy(&data->ftCreationTime, &ent[8], 8);
1678     memcpy(&data->ftLastAccessTime, &ent[0x10], 8);
1679     memcpy(&data->ftLastWriteTime, &ent[0x18], 8);
1680     data->nFileSizeHigh = SMB_GETDWORD(&ent[0x30]);
1681     data->nFileSizeLow = SMB_GETDWORD(&ent[0x34]);
1682     data->dwFileAttributes = SMB_GETDWORD(&ent[0x38]);
1683
1684     /* copy the long filename */
1685     fnlen = SMB_GETDWORD(&ent[0x3c]);
1686     if ( fnlen > (sizeof(data->cFileName)/sizeof(WCHAR)) )
1687         return FALSE;
1688     MultiByteToWideChar( CP_ACP, 0, &ent[0x5e], fnlen, data->cFileName,
1689                          sizeof(data->cFileName)/sizeof(WCHAR) );
1690
1691     /* copy the short filename */
1692     if ( ent[0x44] > (sizeof(data->cAlternateFileName)/sizeof(WCHAR)) )
1693         return FALSE;
1694     MultiByteToWideChar( CP_ACP, 0, &ent[0x5e + len], ent[0x44], data->cAlternateFileName,
1695                          sizeof(data->cAlternateFileName)/sizeof(WCHAR) );
1696
1697     dir->current++;
1698
1699     return TRUE;
1700 }
1701
1702 BOOL WINAPI SMB_CloseDir(SMB_DIR *dir)
1703 {
1704     RtlFreeHeap(GetProcessHeap(),0,dir->buffer);
1705     RtlFreeHeap(GetProcessHeap(),0,dir->entries);
1706     memset(dir,0,sizeof(*dir));
1707     RtlFreeHeap(GetProcessHeap(),0,dir);
1708     return TRUE;
1709 }