Delegates messages directly to the edit control window proc instead of
[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 "winreg.h"
112 #include "winternl.h"
113 #include "lmerr.h"
114 #include "smb.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     sin.sin_family = AF_INET;
310     sin.sin_port    = htons(137);
311     sin.sin_addr.s_addr = 0xffffffff;
312
313     len = NB_NameReq(host,buffer,sizeof(buffer));
314     if(len<=0)
315         goto err;
316
317     r = sendto(fd, buffer, len, 0, (struct sockaddr*)&sin, sizeof(sin));
318     if(r<0)
319     {
320         FIXME("Error sending packet\n");
321         goto err;
322     }
323
324     fds.fd = fd;
325     fds.events = POLLIN;
326     fds.revents = 0;
327
328     /* FIXME: this is simple and easily fooled logic
329      *  we should loop until we receive the correct packet or timeout
330      */
331     r = poll(&fds,1,NB_TIMEOUT);
332     if(r!=1)
333         goto err;
334
335     TRACE("Got response!\n");
336
337     fromsize = sizeof (fromaddr);
338     r = recvfrom(fd, buffer, sizeof(buffer), 0, (struct sockaddr*)&fromaddr, &fromsize);
339     if(r<0)
340         goto err;
341
342     TRACE("%d bytes received\n",r);
343
344     if(r!=62)
345         goto err;
346
347     for(i=0; i<r; i++)
348         DPRINTF("%02X%c",buffer[i],(((i+1)!=r)&&((i+1)%16))?' ':'\n');
349     DPRINTF("\n");
350
351     if(0x0f & buffer[3])
352         goto err;
353
354     TRACE("packet is OK\n");
355
356     memcpy(&addr->sin_addr, &buffer[58], sizeof(addr->sin_addr));
357
358     close(fd);
359     return TRUE;
360
361 err:
362     close(fd);
363     return FALSE;
364 }
365
366 #define NB_FIRST 0x40
367
368 #define NB_HDRSIZE 4
369
370 #define NB_SESSION_MSG 0x00
371 #define NB_SESSION_REQ 0x81
372
373 /* RFC 1002, section 4.3.2 */
374 static BOOL NB_SessionReq(int fd, const char *called, const char *calling)
375 {
376     unsigned char buffer[0x100];
377     int len = 0,r;
378     struct pollfd fds;
379
380     TRACE("called %s, calling %s\n",called,calling);
381
382     buffer[0] = NB_SESSION_REQ;
383     buffer[1] = NB_FIRST;
384
385     netbios_name(called, &buffer[NB_HDRSIZE]);
386     len += 34;
387     netbios_name(calling, &buffer[NB_HDRSIZE+len]);
388     len += 34;
389
390     NBR_ADDWORD(&buffer[2],len);
391
392     /* for(i=0; i<(len+NB_HDRSIZE); i++)
393         DPRINTF("%02X%c",buffer[i],(((i+1)!=(len+4))&&((i+1)%16))?' ':'\n'); */
394
395     r = write(fd,buffer,len+4);
396     if(r<0)
397     {
398         ERR("Write failed\n");
399         return FALSE;
400     }
401
402     fds.fd = fd;
403     fds.events = POLLIN;
404     fds.revents = 0;
405
406     r = poll(&fds,1,NB_TIMEOUT);
407     if(r!=1)
408     {
409         ERR("Poll failed\n");
410         return FALSE;
411     }
412
413     r = read(fd, buffer, NB_HDRSIZE);
414     if((r!=NB_HDRSIZE) || (buffer[0]!=0x82))
415     {
416         TRACE("Received %d bytes\n",r);
417         TRACE("%02x %02x %02x %02x\n", buffer[0],buffer[1],buffer[2],buffer[3]);
418         return FALSE;
419     }
420
421     return TRUE;
422 }
423
424 static BOOL NB_SendData(int fd, struct NB_Buffer *out)
425 {
426     unsigned char buffer[NB_HDRSIZE];
427     int r;
428
429     /* CHECK: is it always OK to do this in two writes?   */
430     /*        perhaps use scatter gather sendmsg instead? */
431
432     buffer[0] = NB_SESSION_MSG;
433     buffer[1] = NB_FIRST;
434     NBR_ADDWORD(&buffer[2],out->len);
435
436     r = write(fd, buffer, NB_HDRSIZE);
437     if(r!=NB_HDRSIZE)
438         return FALSE;
439
440     r = write(fd, out->buffer, out->len);
441     if(r!=out->len)
442     {
443         ERR("write failed\n");
444         return FALSE;
445     }
446
447     return TRUE;
448 }
449
450 static BOOL NB_RecvData(int fd, struct NB_Buffer *rx)
451 {
452     int r;
453     unsigned char buffer[NB_HDRSIZE];
454
455     r = read(fd, buffer, NB_HDRSIZE);
456     if((r!=NB_HDRSIZE) || (buffer[0]!=NB_SESSION_MSG))
457     {
458         ERR("Received %d bytes\n",r);
459         return FALSE;
460     }
461
462     rx->len = NBR_GETWORD(&buffer[2]);
463
464     rx->buffer = RtlAllocateHeap(GetProcessHeap(), 0, rx->len);
465     if(!rx->buffer)
466         return FALSE;
467
468     r = read(fd, rx->buffer, rx->len);
469     if(rx->len!=r)
470     {
471         TRACE("Received %d bytes\n",r);
472         RtlFreeHeap(GetProcessHeap(), 0, rx->buffer);
473         rx->buffer = 0;
474         rx->len = 0;
475         return FALSE;
476     }
477
478     return TRUE;
479 }
480
481 static BOOL NB_Transaction(int fd, struct NB_Buffer *in, struct NB_Buffer *out)
482 {
483     int r;
484     struct pollfd fds;
485
486     if(TRACE_ON(file))
487     {
488         int i;
489     DPRINTF("Sending request:\n");
490         for(i=0; i<in->len; i++)
491             DPRINTF("%02X%c",in->buffer[i],(((i+1)!=in->len)&&((i+1)%16))?' ':'\n');
492     }
493
494     if(!NB_SendData(fd,in))
495         return FALSE;
496
497     fds.fd = fd;
498     fds.events = POLLIN;
499     fds.revents = 0;
500
501     r = poll(&fds,1,NB_TIMEOUT);
502     if(r!=1)
503     {
504         ERR("Poll failed\n");
505         return FALSE;
506     }
507
508     if(!NB_RecvData(fd, out))
509         return FALSE;
510
511     if(TRACE_ON(file))
512     {
513         int i;
514     DPRINTF("Got response:\n");
515         for(i=0; i<out->len; i++)
516             DPRINTF("%02X%c",out->buffer[i],(((i+1)!=out->len)&&((i+1)%16))?' ':'\n');
517     }
518
519     return TRUE;
520 }
521
522 #define SMB_ADDHEADER(b,l) { b[(l)++]=0xff; b[(l)++]='S'; b[(l)++]='M'; b[(l)++]='B'; }
523 #define SMB_ADDERRINFO(b,l) { b[(l)++]=0; b[(l)++]=0; b[(l)++]=0; b[(l)++]=0; }
524 #define SMB_ADDPADSIG(b,l) { memset(&b[l],0,12); l+=12; }
525
526 #define SMB_ERRCLASS 5
527 #define SMB_ERRCODE  7
528 #define SMB_TREEID  24
529 #define SMB_PROCID  26
530 #define SMB_USERID  28
531 #define SMB_PLEXID  30
532 #define SMB_PCOUNT  32
533 #define SMB_HDRSIZE 33
534
535 static DWORD NetSrvErrorToDOSError(USHORT code)
536 {
537     DWORD ret;
538
539     switch (code)
540     {
541     case 1:
542         ret = ERROR_INTERNAL_ERROR;
543         break;
544     case 2:
545         ret = ERROR_INVALID_PASSWORD;
546         break;
547     case 3:
548         ret = ERROR_BAD_NETPATH;
549         break;
550     case 4:
551         ret = ERROR_ACCESS_DENIED;
552         break;
553     /* unmapped: case 5: invalid transaction ID? */
554     case 6:
555         ret = ERROR_INVALID_NETNAME;
556         break;
557     case 7:
558         ret = ERROR_BAD_DEV_TYPE;
559         break;
560     case 49:
561         ret = ERROR_PRINTQ_FULL;
562         break;
563     case 50:
564         ret = ERROR_NO_SPOOL_SPACE;
565         break;
566     case 65:
567         ret = ERROR_INTERNAL_ERROR;
568         break;
569     case 69:
570         ret = ERROR_ACCESS_DENIED;
571         break;
572     case 81:
573         ret = NERR_PausedRemote;
574         break;
575     case 82:
576         ret = NERR_BadReceive;
577         break;
578     case 83:
579         ret = NERR_RemoteFull;
580         break;
581     case 87:
582         ret = NERR_TooManyNames;
583         break;
584     case 88:
585         ret = ERROR_TIMEOUT;
586         break;
587     case 89:
588         ret = ERROR_NO_SYSTEM_RESOURCES;
589         break;
590     case 91:
591         ret = ERROR_BAD_USERNAME;
592         break;
593     case 0xffff:
594         ret = ERROR_NOT_SUPPORTED;
595         break;
596     default:
597         ret = ERROR_INVALID_PARAMETER;
598     }
599     return ret;
600 }
601
602 DWORD SMBErrorToDOSError(UCHAR errorClass, USHORT code)
603 {
604     DWORD ret;
605
606     switch (errorClass)
607     {
608     case 0:
609         ret = NO_ERROR;
610         break;
611     case 1:
612         /* the DOS class corresponds exactly to DOS error codes */
613         ret = code;
614         break;
615     case 2:
616         ret = NetSrvErrorToDOSError(code);
617         break;
618     case 3:
619         /* the hardware error values are the same as the DOS error codes */
620         ret = code;
621         break;
622     default:
623         ret = ERROR_INVALID_PARAMETER;
624     }
625     return ret;
626 }
627
628 static DWORD SMB_GetError(unsigned char *buffer)
629 {
630     /* FIXME: should check to see whether the error was a DOS error or an
631      * NT status
632      */
633     return SMBErrorToDOSError(buffer[SMB_ERRCLASS],
634      *(PSHORT)(buffer + SMB_ERRCODE));
635 }
636
637 static int SMB_Header(unsigned char *buffer, unsigned char command, USHORT tree_id, USHORT user_id)
638 {
639     int len = 0;
640     DWORD id;
641
642     /* 0 */
643     SMB_ADDHEADER(buffer,len);
644
645     /* 4 */
646     buffer[len++] = command;
647
648     /* 5 */
649     SMB_ADDERRINFO(buffer,len)
650
651     /* 9 */
652     buffer[len++] = 0x00; /* flags */
653     SMB_ADDWORD(&buffer[len],1); len += 2; /* flags2 */
654
655     /* 12 */
656     SMB_ADDPADSIG(buffer,len)
657
658     /* 24 */
659     SMB_ADDWORD(&buffer[len],tree_id); len += 2; /* treeid */
660     id = GetCurrentThreadId();
661     SMB_ADDWORD(&buffer[len],id); len += 2; /* process id */
662     SMB_ADDWORD(&buffer[len],user_id); len += 2; /* user id */
663     SMB_ADDWORD(&buffer[len],SMB_MultiplexId); len += 2; /* multiplex id */
664     SMB_MultiplexId++;
665
666     return len;
667 }
668
669 static const char *SMB_ProtocolDialect = "NT LM 0.12";
670 /* = "Windows for Workgroups 3.1a"; */
671
672 /* FIXME: support multiple SMB dialects */
673 static BOOL SMB_NegotiateProtocol(int fd, USHORT *dialect)
674 {
675     unsigned char buf[0x100];
676     int buflen = 0;
677     struct NB_Buffer tx, rx;
678
679     TRACE("\n");
680
681     memset(buf,0,sizeof(buf));
682
683     tx.buffer = buf;
684     tx.len = SMB_Header(tx.buffer, SMB_COM_NEGOTIATE, 0, 0);
685
686     /* parameters */
687     tx.buffer[tx.len++] = 0; /* no parameters */
688
689     /* command buffer */
690     buflen = strlen(SMB_ProtocolDialect)+2;  /* include type and nul byte */
691     SMB_ADDWORD(&tx.buffer[tx.len],buflen); tx.len += 2;
692
693     tx.buffer[tx.len] = 0x02;
694     strcpy(&tx.buffer[tx.len+1],SMB_ProtocolDialect);
695     tx.len += buflen;
696
697     rx.buffer = NULL;
698     rx.len = 0;
699     if(!NB_Transaction(fd, &tx, &rx))
700     {
701         ERR("Failed\n");
702         return FALSE;
703     }
704
705     if(!rx.buffer)
706         return FALSE;
707
708     /* FIXME: check response */
709     if(SMB_GetError(rx.buffer))
710     {
711         ERR("returned error\n");
712         RtlFreeHeap(GetProcessHeap(),0,rx.buffer);
713         return FALSE;
714     }
715
716     RtlFreeHeap(GetProcessHeap(),0,rx.buffer);
717
718     *dialect = 0;
719
720     return TRUE;
721 }
722
723 #define SMB_PARAM_COUNT(buffer) ((buffer)[SMB_PCOUNT])
724 #define SMB_PARAM(buffer,n) SMB_GETWORD(&(buffer)[SMB_HDRSIZE+2*(n)])
725 #define SMB_BUFFER_COUNT(buffer)  SMB_GETWORD(buffer+SMB_HDRSIZE+2*SMB_PARAM_COUNT(buffer))
726 #define SMB_BUFFER(buffer,n) ((buffer)[SMB_HDRSIZE + 2*SMB_PARAM_COUNT(buffer) + 2 + (n) ])
727
728 static BOOL SMB_SessionSetup(int fd, USHORT *userid)
729 {
730     unsigned char buf[0x100];
731     int pcount,bcount;
732     struct NB_Buffer rx, tx;
733
734     memset(buf,0,sizeof(buf));
735     tx.buffer = buf;
736
737     tx.len = SMB_Header(tx.buffer, SMB_COM_SESSION_SETUP_ANDX, 0, 0);
738
739     tx.buffer[tx.len++] = 0;    /* no parameters? */
740
741     tx.buffer[tx.len++] = 0xff; /* AndXCommand: secondary request */
742     tx.buffer[tx.len++] = 0x00; /* AndXReserved */
743     SMB_ADDWORD(&tx.buffer[tx.len],0);     /* AndXOffset */
744     tx.len += 2;
745     SMB_ADDWORD(&tx.buffer[tx.len],0x400); /* MaxBufferSize */
746     tx.len += 2;
747     SMB_ADDWORD(&tx.buffer[tx.len],1);     /* MaxMpxCount */
748     tx.len += 2;
749     SMB_ADDWORD(&tx.buffer[tx.len],0);     /* VcNumber */
750     tx.len += 2;
751     SMB_ADDWORD(&tx.buffer[tx.len],0);     /* SessionKey */
752     tx.len += 2;
753     SMB_ADDWORD(&tx.buffer[tx.len],0);     /* SessionKey */
754     tx.len += 2;
755     SMB_ADDWORD(&tx.buffer[tx.len],0);     /* Password length */
756     tx.len += 2;
757     SMB_ADDWORD(&tx.buffer[tx.len],0);     /* Reserved */
758     tx.len += 2;
759     SMB_ADDWORD(&tx.buffer[tx.len],0);     /* Reserved */
760     tx.len += 2;
761
762     /* FIXME: add name and password here */
763     tx.buffer[tx.len++] = 0; /* number of bytes in password */
764
765     rx.buffer = NULL;
766     rx.len = 0;
767     if(!NB_Transaction(fd, &tx, &rx))
768         return FALSE;
769
770     if(!rx.buffer)
771         return FALSE;
772
773     if(SMB_GetError(rx.buffer))
774         goto done;
775
776     pcount = SMB_PARAM_COUNT(rx.buffer);
777
778     if( (SMB_HDRSIZE+pcount*2) > rx.len )
779     {
780         ERR("Bad parameter count %d\n",pcount);
781         goto done;
782     }
783
784     if(TRACE_ON(file))
785     {
786         int i;
787     DPRINTF("SMB_COM_SESSION_SETUP response, %d args: ",pcount);
788     for(i=0; i<pcount; i++)
789             DPRINTF("%04x ",SMB_PARAM(rx.buffer,i));
790     DPRINTF("\n");
791     }
792
793     bcount = SMB_BUFFER_COUNT(rx.buffer);
794     if( (SMB_HDRSIZE+pcount*2+2+bcount) > rx.len )
795     {
796         ERR("parameter count %x, buffer count %x, len %x\n",pcount,bcount,rx.len);
797         goto done;
798     }
799
800     if(TRACE_ON(file))
801     {
802         int i;
803     DPRINTF("response buffer %d bytes: ",bcount);
804     for(i=0; i<bcount; i++)
805     {
806             unsigned char ch = SMB_BUFFER(rx.buffer,i);
807         DPRINTF("%c", isprint(ch)?ch:' ');
808     }
809     DPRINTF("\n");
810     }
811
812     *userid = SMB_GETWORD(&rx.buffer[SMB_USERID]);
813
814     RtlFreeHeap(GetProcessHeap(),0,rx.buffer);
815     return TRUE;
816
817 done:
818     RtlFreeHeap(GetProcessHeap(),0,rx.buffer);
819     return FALSE;
820 }
821
822
823 static BOOL SMB_TreeConnect(int fd, USHORT user_id, LPCSTR share_name, USHORT *treeid)
824 {
825     unsigned char buf[0x100];
826     int slen;
827     struct NB_Buffer rx,tx;
828
829     TRACE("%s\n",share_name);
830
831     memset(buf,0,sizeof(buf));
832     tx.buffer = buf;
833
834     tx.len = SMB_Header(tx.buffer, SMB_COM_TREE_CONNECT, 0, user_id);
835
836     tx.buffer[tx.len++] = 4; /* parameters */
837
838     tx.buffer[tx.len++] = 0xff; /* AndXCommand: secondary request */
839     tx.buffer[tx.len++] = 0x00; /* AndXReserved */
840     SMB_ADDWORD(&tx.buffer[tx.len],0); /* AndXOffset */
841     tx.len += 2;
842     SMB_ADDWORD(&tx.buffer[tx.len],0); /* Flags */
843     tx.len += 2;
844     SMB_ADDWORD(&tx.buffer[tx.len],1); /* Password length */
845     tx.len += 2;
846
847     /* SMB command buffer */
848     SMB_ADDWORD(&tx.buffer[tx.len],3); /* command buffer len */
849     tx.len += 2;
850     tx.buffer[tx.len++] = 0; /* null terminated password */
851
852     slen = strlen(share_name);
853     if(slen<(sizeof(buf)-tx.len))
854         strcpy(&tx.buffer[tx.len], share_name);
855     else
856         return FALSE;
857     tx.len += slen+1;
858
859     /* name of the service */
860     tx.buffer[tx.len++] = 0;
861
862     rx.buffer = NULL;
863     rx.len = 0;
864     if(!NB_Transaction(fd, &tx, &rx))
865         return FALSE;
866
867     if(!rx.buffer)
868         return FALSE;
869
870     if(SMB_GetError(rx.buffer))
871     {
872         RtlFreeHeap(GetProcessHeap(),0,rx.buffer);
873         return FALSE;
874     }
875
876     *treeid = SMB_GETWORD(&rx.buffer[SMB_TREEID]);
877
878     RtlFreeHeap(GetProcessHeap(),0,rx.buffer);
879     TRACE("OK, treeid = %04x\n", *treeid);
880
881     return TRUE;
882 }
883
884 #if 0  /* not yet */
885 static BOOL SMB_NtCreateOpen(int fd, USHORT tree_id, USHORT user_id, USHORT dialect,
886                               LPCSTR filename, DWORD access, DWORD sharing,
887                               LPSECURITY_ATTRIBUTES sa, DWORD creation,
888                               DWORD attributes, HANDLE template, USHORT *file_id )
889 {
890     unsigned char buffer[0x100];
891     int len = 0,slen;
892
893     TRACE("%s\n",filename);
894
895     memset(buffer,0,sizeof(buffer));
896
897     len = SMB_Header(buffer, SMB_COM_NT_CREATE_ANDX, tree_id, user_id);
898
899     /* 0 */
900     buffer[len++] = 24; /* parameters */
901
902     buffer[len++] = 0xff; /* AndXCommand: secondary request */
903     buffer[len++] = 0x00; /* AndXReserved */
904     SMB_ADDWORD(&buffer[len],0); len += 2; /* AndXOffset */
905
906     buffer[len++] = 0;                     /* reserved */
907     slen = strlen(filename);
908     SMB_ADDWORD(&buffer[len],slen);    len += 2; /* name length */
909
910     /* 0x08 */
911     SMB_ADDDWORD(&buffer[len],0);      len += 4; /* flags */
912     SMB_ADDDWORD(&buffer[len],0);      len += 4; /* root directory fid */
913     /* 0x10 */
914     SMB_ADDDWORD(&buffer[len],access); len += 4; /* access */
915     SMB_ADDDWORD(&buffer[len],0);      len += 4; /* allocation size */
916     /* 0x18 */
917     SMB_ADDDWORD(&buffer[len],0);      len += 4; /* root directory fid */
918
919     /* 0x1c */
920     SMB_ADDDWORD(&buffer[len],0);      len += 4; /* initial allocation */
921     SMB_ADDDWORD(&buffer[len],0);      len += 4;
922
923     /* 0x24 */
924     SMB_ADDDWORD(&buffer[len],attributes);      len += 4; /* ExtFileAttributes*/
925
926     /* 0x28 */
927     SMB_ADDDWORD(&buffer[len],sharing);      len += 4; /* ShareAccess */
928
929     /* 0x2c */
930     TRACE("creation = %08lx\n",creation);
931     SMB_ADDDWORD(&buffer[len],creation);      len += 4; /* CreateDisposition */
932
933     /* 0x30 */
934     SMB_ADDDWORD(&buffer[len],creation);      len += 4; /* CreateOptions */
935
936     /* 0x34 */
937     SMB_ADDDWORD(&buffer[len],0);      len += 4; /* Impersonation */
938
939     /* 0x38 */
940     buffer[len++] = 0;                     /* security flags */
941
942     /* 0x39 */
943     SMB_ADDWORD(&buffer[len],slen); len += 2; /* size of buffer */
944
945     if(slen<(sizeof(buffer)-len))
946         strcpy(&buffer[len], filename);
947     else
948         return FALSE;
949     len += slen+1;
950
951     /* name of the file */
952     buffer[len++] = 0;
953
954     if(!NB_Transaction(fd, buffer, len, &len))
955         return FALSE;
956
957     if(SMB_GetError(buffer))
958         return FALSE;
959
960     TRACE("OK\n");
961
962     /* FIXME */
963     /* *file_id = SMB_GETWORD(&buffer[xxx]); */
964     *file_id = 0;
965     return FALSE;
966
967     return TRUE;
968 }
969 #endif
970
971 static USHORT SMB_GetMode(DWORD access, DWORD sharing)
972 {
973     USHORT mode=0;
974
975     switch(access&(GENERIC_READ|GENERIC_WRITE))
976     {
977     case GENERIC_READ:
978         mode |= OF_READ;
979         break;
980     case GENERIC_WRITE:
981         mode |= OF_WRITE;
982         break;
983     case (GENERIC_READ|GENERIC_WRITE):
984         mode |= OF_READWRITE;
985         break;
986     }
987
988     switch(sharing&(FILE_SHARE_READ|FILE_SHARE_WRITE))
989     {
990     case (FILE_SHARE_READ|FILE_SHARE_WRITE):
991         mode |= OF_SHARE_DENY_NONE;
992         break;
993     case FILE_SHARE_READ:
994         mode |= OF_SHARE_DENY_WRITE;
995         break;
996     case FILE_SHARE_WRITE:
997         mode |= OF_SHARE_DENY_READ;
998         break;
999     default:
1000         mode |= OF_SHARE_EXCLUSIVE;
1001         break;
1002     }
1003
1004     return mode;
1005 }
1006
1007 #if 0  /* not yet */
1008 /* inverse of FILE_ConvertOFMode */
1009 static BOOL SMB_OpenAndX(int fd, USHORT tree_id, USHORT user_id, USHORT dialect,
1010                               LPCSTR filename, DWORD access, DWORD sharing,
1011                               DWORD creation, DWORD attributes, USHORT *file_id )
1012 {
1013     unsigned char buffer[0x100];
1014     int len = 0;
1015     USHORT mode;
1016
1017     TRACE("%s\n",filename);
1018
1019     mode = SMB_GetMode(access,sharing);
1020
1021     memset(buffer,0,sizeof(buffer));
1022
1023     len = SMB_Header(buffer, SMB_COM_OPEN_ANDX, tree_id, user_id);
1024
1025     /* 0 */
1026     buffer[len++] = 15; /* parameters */
1027     buffer[len++] = 0xff; /* AndXCommand: secondary request */
1028     buffer[len++] = 0x00; /* AndXReserved */
1029     SMB_ADDWORD(buffer+len,0); len+=2; /* AndXOffset */
1030     SMB_ADDWORD(buffer+len,0); len+=2; /* Flags */
1031     SMB_ADDWORD(buffer+len,mode); len+=2; /* desired access */
1032     SMB_ADDWORD(buffer+len,0); len+=2; /* search attributes */
1033     SMB_ADDWORD(buffer+len,0); len+=2;
1034
1035     /*FIXME: complete */
1036     return FALSE;
1037 }
1038 #endif
1039
1040
1041 static BOOL SMB_Open(int fd, USHORT tree_id, USHORT user_id, USHORT dialect,
1042                               LPCSTR filename, DWORD access, DWORD sharing,
1043                               DWORD creation, DWORD attributes, USHORT *file_id )
1044 {
1045     unsigned char buf[0x100];
1046     int slen,pcount,i;
1047     USHORT mode = SMB_GetMode(access,sharing);
1048     struct NB_Buffer rx,tx;
1049
1050     TRACE("%s\n",filename);
1051
1052     memset(buf,0,sizeof(buf));
1053
1054     tx.buffer = buf;
1055     tx.len = SMB_Header(tx.buffer, SMB_COM_OPEN, tree_id, user_id);
1056
1057     /* 0 */
1058     tx.buffer[tx.len++] = 2; /* parameters */
1059     SMB_ADDWORD(tx.buffer+tx.len,mode); tx.len+=2;
1060     SMB_ADDWORD(tx.buffer+tx.len,0);    tx.len+=2; /* search attributes */
1061
1062     slen = strlen(filename)+2;   /* inc. nul and BufferFormat */
1063     SMB_ADDWORD(tx.buffer+tx.len,slen); tx.len+=2;
1064
1065     tx.buffer[tx.len] = 0x04;  /* BufferFormat */
1066     strcpy(&tx.buffer[tx.len+1],filename);
1067     tx.len += slen;
1068
1069     rx.buffer = NULL;
1070     rx.len = 0;
1071     if(!NB_Transaction(fd, &tx, &rx))
1072         return FALSE;
1073
1074     if(!rx.buffer)
1075         return FALSE;
1076
1077     if(SMB_GetError(rx.buffer))
1078         return FALSE;
1079
1080     pcount = SMB_PARAM_COUNT(rx.buffer);
1081
1082     if( (SMB_HDRSIZE+pcount*2) > rx.len )
1083     {
1084         ERR("Bad parameter count %d\n",pcount);
1085         return FALSE;
1086     }
1087
1088     TRACE("response, %d args: ",pcount);
1089     for(i=0; i<pcount; i++)
1090         TRACE("%04x ",SMB_PARAM(rx.buffer,i));
1091     TRACE("\n");
1092
1093     *file_id = SMB_PARAM(rx.buffer,0);
1094
1095     TRACE("file_id = %04x\n",*file_id);
1096
1097     return TRUE;
1098 }
1099
1100
1101 static BOOL SMB_Read(int fd, USHORT tree_id, USHORT user_id, USHORT dialect,
1102        USHORT file_id, DWORD offset, LPVOID out, USHORT count, USHORT* read)
1103 {
1104     int buf_size,n,i;
1105     struct NB_Buffer rx,tx;
1106
1107     TRACE("user %04x tree %04x file %04x count %04x offset %08lx\n",
1108         user_id, tree_id, file_id, count, offset);
1109
1110     buf_size = count+0x100;
1111     tx.buffer = (unsigned char *) RtlAllocateHeap(GetProcessHeap(),0,buf_size);
1112
1113     memset(tx.buffer,0,buf_size);
1114
1115     tx.len = SMB_Header(tx.buffer, SMB_COM_READ, tree_id, user_id);
1116
1117     tx.buffer[tx.len++] = 5;
1118     SMB_ADDWORD(&tx.buffer[tx.len],file_id); tx.len += 2;
1119     SMB_ADDWORD(&tx.buffer[tx.len],count);   tx.len += 2;
1120     SMB_ADDDWORD(&tx.buffer[tx.len],offset); tx.len += 4;
1121     SMB_ADDWORD(&tx.buffer[tx.len],0);       tx.len += 2; /* how many more bytes will be read */
1122
1123     tx.buffer[tx.len++] = 0;
1124
1125     rx.buffer = NULL;
1126     rx.len = 0;
1127     if(!NB_Transaction(fd, &tx, &rx))
1128     {
1129         RtlFreeHeap(GetProcessHeap(),0,tx.buffer);
1130         return FALSE;
1131     }
1132
1133     if(SMB_GetError(rx.buffer))
1134     {
1135         RtlFreeHeap(GetProcessHeap(),0,rx.buffer);
1136         RtlFreeHeap(GetProcessHeap(),0,tx.buffer);
1137         return FALSE;
1138     }
1139
1140     n = SMB_PARAM_COUNT(rx.buffer);
1141
1142     if( (SMB_HDRSIZE+n*2) > rx.len )
1143     {
1144         RtlFreeHeap(GetProcessHeap(),0,rx.buffer);
1145         RtlFreeHeap(GetProcessHeap(),0,tx.buffer);
1146         ERR("Bad parameter count %d\n",n);
1147         return FALSE;
1148     }
1149
1150     TRACE("response, %d args: ",n);
1151     for(i=0; i<n; i++)
1152         TRACE("%04x ",SMB_PARAM(rx.buffer,i));
1153     TRACE("\n");
1154
1155     n = SMB_PARAM(rx.buffer,5) - 3;
1156     if(n>count)
1157         n=count;
1158
1159     memcpy( out, &SMB_BUFFER(rx.buffer,3), n);
1160
1161     TRACE("Read %d bytes\n",n);
1162     *read = n;
1163
1164     RtlFreeHeap(GetProcessHeap(),0,tx.buffer);
1165     RtlFreeHeap(GetProcessHeap(),0,rx.buffer);
1166
1167     return TRUE;
1168 }
1169
1170
1171 /*
1172  * setup_count : number of USHORTs in the setup string
1173  */
1174 struct SMB_Trans2Info
1175 {
1176     struct NB_Buffer buf;
1177     unsigned char *setup;
1178     int setup_count;
1179     unsigned char *params;
1180     int param_count;
1181     unsigned char *data;
1182     int data_count;
1183 };
1184
1185 /*
1186  * Do an SMB transaction
1187  *
1188  * This function allocates memory in the recv structure. It is
1189  * the caller's responsibility to free the memory if it finds
1190  * that recv->buf.buffer is nonzero.
1191  */
1192 static BOOL SMB_Transaction2(int fd, int tree_id, int user_id,
1193                  struct SMB_Trans2Info *send,
1194                  struct SMB_Trans2Info *recv)
1195 {
1196     int buf_size;
1197     const int retmaxparams = 0xf000;
1198     const int retmaxdata = 1024;
1199     const int retmaxsetup = 0; /* FIXME */
1200     const int flags = 0;
1201     const int timeout = 0;
1202     int param_ofs, data_ofs;
1203     struct NB_Buffer tx;
1204     BOOL ret = FALSE;
1205
1206     buf_size = 0x100 + send->setup_count*2 + send->param_count + send->data_count ;
1207     tx.buffer = (unsigned char *) RtlAllocateHeap(GetProcessHeap(),0,buf_size);
1208
1209     tx.len = SMB_Header(tx.buffer, SMB_COM_TRANSACTION2, tree_id, user_id);
1210
1211     tx.buffer[tx.len++] = 14 + send->setup_count;
1212     SMB_ADDWORD(&tx.buffer[tx.len],send->param_count); /* total param bytes sent */
1213     tx.len += 2;
1214     SMB_ADDWORD(&tx.buffer[tx.len],send->data_count);  /* total data bytes sent */
1215     tx.len += 2;
1216     SMB_ADDWORD(&tx.buffer[tx.len],retmaxparams); /*max parameter bytes to return */
1217     tx.len += 2;
1218     SMB_ADDWORD(&tx.buffer[tx.len],retmaxdata);  /* max data bytes to return */
1219     tx.len += 2;
1220     tx.buffer[tx.len++] = retmaxsetup;
1221     tx.buffer[tx.len++] = 0;                     /* reserved1 */
1222
1223     SMB_ADDWORD(&tx.buffer[tx.len],flags);       /* flags */
1224     tx.len += 2;
1225     SMB_ADDDWORD(&tx.buffer[tx.len],timeout);    /* timeout */
1226     tx.len += 4;
1227     SMB_ADDWORD(&tx.buffer[tx.len],0);           /* reserved2 */
1228     tx.len += 2;
1229     SMB_ADDWORD(&tx.buffer[tx.len],send->param_count); /* parameter count - this buffer */
1230     tx.len += 2;
1231
1232     param_ofs = tx.len;                          /* parameter offset */
1233     tx.len += 2;
1234     SMB_ADDWORD(&tx.buffer[tx.len],send->data_count);  /* data count */
1235     tx.len += 2;
1236
1237     data_ofs = tx.len;                           /* data offset */
1238     tx.len += 2;
1239     tx.buffer[tx.len++] = send->setup_count;     /* setup count */
1240     tx.buffer[tx.len++] = 0;                     /* reserved3 */
1241
1242     memcpy(&tx.buffer[tx.len], send->setup, send->setup_count*2); /* setup */
1243     tx.len += send->setup_count*2;
1244
1245     /* add string here when implementing SMB_COM_TRANS */
1246
1247     SMB_ADDWORD(&tx.buffer[param_ofs], tx.len);
1248     memcpy(&tx.buffer[tx.len], send->params, send->param_count); /* parameters */
1249     tx.len += send->param_count;
1250     if(tx.len%2)
1251         tx.len ++;                                      /* pad2 */
1252
1253     SMB_ADDWORD(&tx.buffer[data_ofs], tx.len);
1254     if(send->data_count && send->data)
1255     {
1256         memcpy(&tx.buffer[tx.len], send->data, send->data_count); /* data */
1257         tx.len += send->data_count;
1258     }
1259
1260     recv->buf.buffer = NULL;
1261     recv->buf.len = 0;
1262     if(!NB_Transaction(fd, &tx, &recv->buf))
1263         goto done;
1264
1265     if(!recv->buf.buffer)
1266         goto done;
1267
1268     if(SMB_GetError(recv->buf.buffer))
1269         goto done;
1270
1271     /* reuse these two offsets to check the received message */
1272     param_ofs = SMB_PARAM(recv->buf.buffer,4);
1273     data_ofs = SMB_PARAM(recv->buf.buffer,7);
1274
1275     if( (recv->param_count + param_ofs) > recv->buf.len )
1276         goto done;
1277
1278     if( (recv->data_count + data_ofs) > recv->buf.len )
1279         goto done;
1280
1281     TRACE("Success\n");
1282
1283     recv->setup = NULL;
1284     recv->setup_count = 0;
1285
1286     recv->param_count = SMB_PARAM(recv->buf.buffer,0);
1287     recv->params = &recv->buf.buffer[param_ofs];
1288
1289     recv->data_count = SMB_PARAM(recv->buf.buffer,6);
1290     recv->data = &recv->buf.buffer[data_ofs];
1291
1292    /*
1293     TRACE("%d words\n",SMB_PARAM_COUNT(recv->buf.buffer));
1294     TRACE("total parameters = %d\n",SMB_PARAM(recv->buf.buffer,0));
1295     TRACE("total data       = %d\n",SMB_PARAM(recv->buf.buffer,1));
1296     TRACE("parameters       = %d\n",SMB_PARAM(recv->buf.buffer,3));
1297     TRACE("parameter offset = %d\n",SMB_PARAM(recv->buf.buffer,4));
1298     TRACE("param displace   = %d\n",SMB_PARAM(recv->buf.buffer,5));
1299
1300     TRACE("data count       = %d\n",SMB_PARAM(recv->buf.buffer,6));
1301     TRACE("data offset      = %d\n",SMB_PARAM(recv->buf.buffer,7));
1302     TRACE("data displace    = %d\n",SMB_PARAM(recv->buf.buffer,8));
1303    */
1304
1305     ret = TRUE;
1306
1307 done:
1308     if(tx.buffer)
1309         RtlFreeHeap(GetProcessHeap(),0,tx.buffer);
1310
1311     return ret;
1312 }
1313
1314 static BOOL SMB_SetupFindFirst(struct SMB_Trans2Info *send, LPSTR filename)
1315 {
1316     int search_attribs = FILE_ATTRIBUTE_DIRECTORY | FILE_ATTRIBUTE_HIDDEN | FILE_ATTRIBUTE_SYSTEM;
1317     int search_count = 10;
1318     int flags = 0;
1319     int infolevel = 0x104; /* SMB_FILE_BOTH_DIRECTORY_INFO */
1320     int storagetype = 0;
1321     int len, buf_size;
1322
1323     memset(send,0,sizeof(send));
1324
1325     send->setup_count = 1;
1326     send->setup = RtlAllocateHeap(GetProcessHeap(),0,send->setup_count*2);
1327     if(!send->setup)
1328         return FALSE;
1329
1330     buf_size = 0x10 + strlen(filename);
1331     send->params = RtlAllocateHeap(GetProcessHeap(),0,buf_size);
1332     if(!send->params)
1333     {
1334         RtlFreeHeap(GetProcessHeap(),0,send->setup);
1335         return FALSE;
1336     }
1337
1338     SMB_ADDWORD(send->setup,TRANS2_FIND_FIRST2);
1339
1340     len = 0;
1341     memset(send->params,0,buf_size);
1342     SMB_ADDWORD(&send->params[len],search_attribs); len += 2;
1343     SMB_ADDWORD(&send->params[len],search_count); len += 2;
1344     SMB_ADDWORD(&send->params[len],flags); len += 2;
1345     SMB_ADDWORD(&send->params[len],infolevel); len += 2;
1346     SMB_ADDDWORD(&send->params[len],storagetype); len += 4;
1347
1348     strcpy(&send->params[len],filename);
1349     len += strlen(filename)+1;
1350
1351     send->param_count = len;
1352     send->data = NULL;
1353     send->data_count = 0;
1354
1355     return TRUE;
1356 }
1357
1358 static SMB_DIR *SMB_Trans2FindFirst(int fd, USHORT tree_id,
1359                     USHORT user_id, USHORT dialect, LPSTR filename )
1360 {
1361     int num;
1362     BOOL ret;
1363     /* char *filename = "\\*"; */
1364     struct SMB_Trans2Info send, recv;
1365     SMB_DIR *smbdir = NULL;
1366
1367     TRACE("pattern = %s\n",filename);
1368
1369     if(!SMB_SetupFindFirst(&send, filename))
1370         return FALSE;
1371
1372     memset(&recv,0,sizeof(recv));
1373
1374     ret = SMB_Transaction2(fd, tree_id, user_id, &send, &recv);
1375     RtlFreeHeap(GetProcessHeap(),0,send.params);
1376     RtlFreeHeap(GetProcessHeap(),0,send.setup);
1377
1378     if(!ret)
1379         goto done;
1380
1381     if(recv.setup_count)
1382         goto done;
1383
1384     if(recv.param_count != 10)
1385         goto done;
1386
1387     num = SMB_GETWORD(&recv.params[2]);
1388     TRACE("Success, search id: %d\n",num);
1389
1390     if(SMB_GETWORD(&recv.params[4]))
1391         FIXME("need to read more!\n");
1392
1393     smbdir = RtlAllocateHeap(GetProcessHeap(),0,sizeof(*smbdir));
1394     if(smbdir)
1395     {
1396         int i, ofs=0;
1397
1398         smbdir->current = 0;
1399         smbdir->num_entries = num;
1400         smbdir->entries = RtlAllocateHeap(GetProcessHeap(), 0, sizeof(unsigned char*)*num);
1401         if(!smbdir->entries)
1402             goto done;
1403         smbdir->buffer = recv.buf.buffer; /* save to free later */
1404
1405         for(i=0; i<num; i++)
1406         {
1407             int size = SMB_GETDWORD(&recv.data[ofs]);
1408
1409             smbdir->entries[i] = &recv.data[ofs];
1410
1411             if(TRACE_ON(file))
1412             {
1413                 int j;
1414                 for(j=0; j<size; j++)
1415                     DPRINTF("%02x%c",recv.data[ofs+j],((j+1)%16)?' ':'\n');
1416             }
1417             TRACE("file %d : %s\n", i, &recv.data[ofs+0x5e]);
1418             ofs += size;
1419             if(ofs>recv.data_count)
1420                 goto done;
1421         }
1422
1423         ret = TRUE;
1424     }
1425
1426 done:
1427     if(!ret)
1428     {
1429         if( recv.buf.buffer )
1430             RtlFreeHeap(GetProcessHeap(),0,recv.buf.buffer);
1431         if( smbdir )
1432         {
1433             if( smbdir->entries )
1434                 RtlFreeHeap(GetProcessHeap(),0,smbdir->entries);
1435             RtlFreeHeap(GetProcessHeap(),0,smbdir);
1436         }
1437         smbdir = NULL;
1438     }
1439
1440     return smbdir;
1441 }
1442
1443 static int SMB_GetSocket(LPCSTR host)
1444 {
1445     int fd=-1,r;
1446     struct sockaddr_in sin;
1447     struct hostent *he;
1448
1449     TRACE("host %s\n",host);
1450
1451     he = gethostbyname(host);
1452     if(he)
1453     {
1454         memcpy(&sin.sin_addr,he->h_addr, sizeof (sin.sin_addr));
1455         goto connect;
1456     }
1457
1458     if(NB_Lookup(host,&sin))
1459         goto connect;
1460
1461     /* FIXME: resolve by WINS too */
1462
1463     ERR("couldn't resolve SMB host %s\n", host);
1464
1465     return -1;
1466
1467 connect:
1468     sin.sin_family = AF_INET;
1469     sin.sin_port   = htons(139);  /* netbios session */
1470
1471     fd = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);
1472     if(fd<0)
1473         return fd;
1474
1475     {
1476         unsigned char *x = (unsigned char *)&sin.sin_addr;
1477         TRACE("Connecting to %d.%d.%d.%d ...\n", x[0],x[1],x[2],x[3]);
1478     }
1479     r = connect(fd, (struct sockaddr*)&sin, sizeof(sin));
1480
1481     if(!NB_SessionReq(fd, "*SMBSERVER", "WINE"))
1482     {
1483         close(fd);
1484         return -1;
1485     }
1486
1487     return fd;
1488 }
1489
1490 static BOOL SMB_LoginAndConnect(int fd, LPCSTR host, LPCSTR share, USHORT *tree_id, USHORT *user_id, USHORT *dialect)
1491 {
1492     LPSTR name=NULL;
1493
1494     TRACE("host %s share %s\n",host,share);
1495
1496     if(!SMB_NegotiateProtocol(fd, dialect))
1497         return FALSE;
1498
1499     if(!SMB_SessionSetup(fd, user_id))
1500         return FALSE;
1501
1502     name = RtlAllocateHeap(GetProcessHeap(),0,strlen(host)+strlen(share)+5);
1503     if(!name)
1504         return FALSE;
1505
1506     sprintf(name,"\\\\%s\\%s",host,share);
1507     if(!SMB_TreeConnect(fd,*user_id,name,tree_id))
1508     {
1509         RtlFreeHeap(GetProcessHeap(),0,name);
1510         return FALSE;
1511     }
1512
1513     return TRUE;
1514 }
1515
1516 static HANDLE SMB_RegisterFile( int fd, USHORT tree_id, USHORT user_id, USHORT dialect, USHORT file_id)
1517 {
1518     int r;
1519     HANDLE ret;
1520
1521     wine_server_send_fd( fd );
1522
1523     SERVER_START_REQ( create_smb )
1524     {
1525         req->tree_id = tree_id;
1526         req->user_id = user_id;
1527         req->file_id = file_id;
1528         req->dialect = 0;
1529         req->fd      = fd;
1530         SetLastError(0);
1531         r = wine_server_call_err( req );
1532         ret = reply->handle;
1533     }
1534     SERVER_END_REQ;
1535
1536     if(!r)
1537         TRACE("created wineserver smb object, handle = %p\n",ret);
1538     else
1539         SetLastError( ERROR_PATH_NOT_FOUND );
1540
1541     return ret;
1542 }
1543
1544 HANDLE WINAPI SMB_CreateFileW( LPCWSTR uncname, DWORD access, DWORD sharing,
1545                               LPSECURITY_ATTRIBUTES sa, DWORD creation,
1546                               DWORD attributes, HANDLE template )
1547 {
1548     int fd;
1549     USHORT tree_id=0, user_id=0, dialect=0, file_id=0;
1550     LPSTR name,host,share,file;
1551     HANDLE handle = INVALID_HANDLE_VALUE;
1552     INT len;
1553
1554     len = WideCharToMultiByte(CP_ACP, 0, uncname, -1, NULL, 0, NULL, NULL);
1555     name = RtlAllocateHeap(GetProcessHeap(), 0, len);
1556     if(!name)
1557         return handle;
1558
1559     WideCharToMultiByte(CP_ACP, 0, uncname, -1, name, len, NULL, NULL);
1560
1561     if( !UNC_SplitName(name, &host, &share, &file) )
1562     {
1563         RtlFreeHeap(GetProcessHeap(),0,name);
1564         return handle;
1565     }
1566
1567     TRACE("server is %s, share is %s, file is %s\n", host, share, file);
1568
1569     fd = SMB_GetSocket(host);
1570     if(fd < 0)
1571         goto done;
1572
1573     if(!SMB_LoginAndConnect(fd, host, share, &tree_id, &user_id, &dialect))
1574         goto done;
1575
1576 #if 0
1577     if(!SMB_NtCreateOpen(fd, tree_id, user_id, dialect, file,
1578                     access, sharing, sa, creation, attributes, template, &file_id ))
1579     {
1580         close(fd);
1581         ERR("CreateOpen failed\n");
1582         goto done;
1583     }
1584 #endif
1585     if(!SMB_Open(fd, tree_id, user_id, dialect, file,
1586                     access, sharing, creation, attributes, &file_id ))
1587     {
1588         close(fd);
1589         ERR("CreateOpen failed\n");
1590         goto done;
1591     }
1592
1593     handle = SMB_RegisterFile(fd, tree_id, user_id, dialect, file_id);
1594     if(!handle)
1595     {
1596         ERR("register failed\n");
1597         close(fd);
1598     }
1599
1600 done:
1601     RtlFreeHeap(GetProcessHeap(),0,name);
1602     return handle;
1603 }
1604
1605 static NTSTATUS SMB_GetSmbInfo(HANDLE hFile, USHORT *tree_id, USHORT *user_id, USHORT *dialect, USHORT *file_id, LPDWORD offset)
1606 {
1607     NTSTATUS status;
1608
1609     SERVER_START_REQ( get_smb_info )
1610     {
1611         req->handle  = hFile;
1612         req->flags   = 0;
1613         status = wine_server_call( req );
1614         if(tree_id)
1615             *tree_id = reply->tree_id;
1616         if(user_id)
1617             *user_id = reply->user_id;
1618         if(file_id)
1619             *file_id = reply->file_id;
1620         if(dialect)
1621             *dialect = reply->dialect;
1622         if(offset)
1623             *offset = reply->offset;
1624     }
1625     SERVER_END_REQ;
1626
1627     return status;
1628 }
1629
1630 static NTSTATUS SMB_SetOffset(HANDLE hFile, DWORD offset)
1631 {
1632     NTSTATUS status;
1633
1634     TRACE("offset = %08lx\n",offset);
1635
1636     SERVER_START_REQ( get_smb_info )
1637     {
1638         req->handle  = hFile;
1639         req->flags   = SMBINFO_SET_OFFSET;
1640         req->offset  = offset;
1641         status = wine_server_call( req );
1642         /* if(offset)
1643             *offset = reply->offset; */
1644     }
1645     SERVER_END_REQ;
1646
1647     return status;
1648 }
1649
1650 NTSTATUS WINAPI SMB_ReadFile(HANDLE hFile, int fd, LPVOID buffer, DWORD bytesToRead,
1651                              PIO_STATUS_BLOCK io_status)
1652 {
1653     DWORD count, offset;
1654     USHORT user_id, tree_id, dialect, file_id, read;
1655
1656     TRACE("%p %p %ld %p\n", hFile, buffer, bytesToRead, io_status);
1657
1658     io_status->Information = 0;
1659
1660     io_status->u.Status = SMB_GetSmbInfo(hFile, &tree_id, &user_id, &dialect, &file_id, &offset);
1661     if (io_status->u.Status) return io_status->u.Status;
1662
1663     while(1)
1664     {
1665         count = bytesToRead - io_status->Information;
1666         if(count>0x400)
1667             count = 0x400;
1668         if(count==0)
1669             break;
1670         read = 0;
1671         if (!SMB_Read(fd, tree_id, user_id, dialect, file_id, offset, buffer, count, &read))
1672             break;
1673         if(!read)
1674             break;
1675         io_status->Information += read;
1676         buffer = (char*)buffer + read;
1677         offset += read;
1678         if(io_status->Information >= bytesToRead)
1679             break;
1680     }
1681     return io_status->u.Status = SMB_SetOffset(hFile, offset);
1682 }
1683
1684 SMB_DIR* WINAPI SMB_FindFirst(LPCWSTR name)
1685 {
1686     int fd = -1;
1687     LPSTR host,share,file;
1688     USHORT tree_id=0, user_id=0, dialect=0;
1689     SMB_DIR *ret = NULL;
1690     LPSTR filename;
1691     DWORD len;
1692
1693     TRACE("Find %s\n",debugstr_w(name));
1694
1695     len = WideCharToMultiByte( CP_ACP, 0, name, -1, NULL, 0, NULL, NULL );
1696     filename = RtlAllocateHeap(GetProcessHeap(),0,len);
1697     if(!filename)
1698         return ret;
1699     WideCharToMultiByte( CP_ACP, 0, name, -1, filename, len, NULL, NULL );
1700
1701     if( !UNC_SplitName(filename, &host, &share, &file) )
1702         goto done;
1703
1704     fd = SMB_GetSocket(host);
1705     if(fd < 0)
1706         goto done;
1707
1708     if(!SMB_LoginAndConnect(fd, host, share, &tree_id, &user_id, &dialect))
1709         goto done;
1710
1711     TRACE("server is %s, share is %s, file is %s\n", host, share, file);
1712
1713     ret = SMB_Trans2FindFirst(fd, tree_id, user_id, dialect, file);
1714
1715 done:
1716     /* disconnect */
1717     if(fd != -1)
1718         close(fd);
1719
1720     if(filename)
1721         RtlFreeHeap(GetProcessHeap(),0,filename);
1722
1723     return ret;
1724 }
1725
1726
1727 BOOL WINAPI SMB_FindNext(SMB_DIR *dir, WIN32_FIND_DATAW *data )
1728 {
1729     unsigned char *ent;
1730     int len, fnlen;
1731
1732     TRACE("%d of %d\n",dir->current,dir->num_entries);
1733
1734     if(dir->current >= dir->num_entries)
1735         return FALSE;
1736
1737     memset(data, 0, sizeof(*data));
1738
1739     ent = dir->entries[dir->current];
1740     len = SMB_GETDWORD(&ent[0]);
1741     if(len<0x5e)
1742         return FALSE;
1743
1744     memcpy(&data->ftCreationTime, &ent[8], 8);
1745     memcpy(&data->ftLastAccessTime, &ent[0x10], 8);
1746     memcpy(&data->ftLastWriteTime, &ent[0x18], 8);
1747     data->nFileSizeHigh = SMB_GETDWORD(&ent[0x30]);
1748     data->nFileSizeLow = SMB_GETDWORD(&ent[0x34]);
1749     data->dwFileAttributes = SMB_GETDWORD(&ent[0x38]);
1750
1751     /* copy the long filename */
1752     fnlen = SMB_GETDWORD(&ent[0x3c]);
1753     if ( fnlen > (sizeof(data->cFileName)/sizeof(WCHAR)) )
1754         return FALSE;
1755     MultiByteToWideChar( CP_ACP, 0, &ent[0x5e], fnlen, data->cFileName,
1756                          sizeof(data->cFileName)/sizeof(WCHAR) );
1757
1758     /* copy the short filename */
1759     if ( ent[0x44] > (sizeof(data->cAlternateFileName)/sizeof(WCHAR)) )
1760         return FALSE;
1761     MultiByteToWideChar( CP_ACP, 0, &ent[0x5e + len], ent[0x44], data->cAlternateFileName,
1762                          sizeof(data->cAlternateFileName)/sizeof(WCHAR) );
1763
1764     dir->current++;
1765
1766     return TRUE;
1767 }
1768
1769 BOOL WINAPI SMB_CloseDir(SMB_DIR *dir)
1770 {
1771     RtlFreeHeap(GetProcessHeap(),0,dir->buffer);
1772     RtlFreeHeap(GetProcessHeap(),0,dir->entries);
1773     memset(dir,0,sizeof(*dir));
1774     RtlFreeHeap(GetProcessHeap(),0,dir);
1775     return TRUE;
1776 }