- define additional shell paths for CSIDL_... constants
[wine] / dlls / netapi32 / nbt.c
1 /* Copyright (c) 2003 Juan Lang
2  *
3  * This library is free software; you can redistribute it and/or
4  * modify it under the terms of the GNU Lesser General Public
5  * License as published by the Free Software Foundation; either
6  * version 2.1 of the License, or (at your option) any later version.
7  *
8  * This library is distributed in the hope that it will be useful,
9  * but WITHOUT ANY WARRANTY; without even the implied warranty of
10  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
11  * Lesser General Public License for more details.
12  *
13  * You should have received a copy of the GNU Lesser General Public
14  * License along with this library; if not, write to the Free Software
15  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
16  *
17  * I am heavily indebted to Chris Hertel's excellent Implementing CIFS,
18  * http://ubiqx.org/cifs/ , for whatever understanding I have of NBT.
19  * I also stole from Mike McCormack's smb.c and netapi32.c, although little of
20  * that code remains.
21  * Lack of understanding and bugs are my fault.
22  *
23  * FIXME:
24  * - Of the NetBIOS session functions, only client functions are supported, and
25  *   it's likely they'll be the only functions supported.  NBT requires session
26  *   servers to listen on TCP/139.  This requires root privilege, and Samba is
27  *   likely to be listening here already.  This further restricts NetBIOS
28  *   applications, both explicit users and implicit ones:  CreateNamedPipe
29  *   won't actually create a listening pipe, for example, so applications can't
30  *   act as RPC servers using a named pipe protocol binding, DCOM won't be able
31  *   to support callbacks or servers over the named pipe protocol, etc.
32  *
33  * - Datagram support is omitted for the same reason.  To send a NetBIOS
34  *   datagram, you must include the NetBIOS name by which your application is
35  *   known.  This requires you to have registered the name previously, and be
36  *   able to act as a NetBIOS datagram server (listening on UDP/138).
37  *
38  * - Name registration functions are omitted for the same reason--registering a
39  *   name requires you to be able to defend it, and this means listening on
40  *   UDP/137.
41  *   Win98 requires you either use your computer's NetBIOS name (with the NULL
42  *   suffix byte) as the calling name when creating a session, or to register
43  *   a new name before creating one:  it disallows '*' as the calling name.
44  *   Win2K initially starts with an empty name table, and doesn't allow you to
45  *   use the machine's NetBIOS name (with the NULL suffix byte) as the calling
46  *   name.  Although it allows sessions to be created with '*' as the calling
47  *   name, doing so results in timeouts for all receives, because the
48  *   application never gets them.
49  *   So, a well-behaved Netbios application will typically want to register a
50  *   name.  I should probably support a do-nothing name list that allows
51  *   NCBADDNAME to add to it, but doesn't actually register the name, or does
52  *   attempt to register it without being able to defend it.
53  *
54  * - Name lookups may not behave quite as you'd expect/like if you have
55  *   multiple LANAs.  If a name is resolvable through DNS, or if you're using
56  *   WINS, it'll resolve on _any_ LANA.  So, a Call will succeed on any LANA as
57  *   well.
58  *   I'm not sure how Windows behaves in this case.  I could try to force
59  *   lookups to the correct adapter by using one of the GetPreferred*
60  *   functions, but with the possibility of multiple adapters in the same
61  *   same subnet, there's no guarantee that what IpHlpApi thinks is the
62  *   preferred adapter will actually be a LANA.  (It's highly probable because
63  *   this is an unusual configuration, but not guaranteed.)
64  *
65  * See also other FIXMEs in the code.
66  */
67
68 #include "config.h"
69 #include <stdarg.h>
70
71 #include "windef.h"
72 #include "winbase.h"
73 #include "winsock2.h"
74 #include "wine/debug.h"
75 #include "winreg.h"
76 #include "iphlpapi.h"
77
78 #include "netbios.h"
79 #include "nbnamecache.h"
80
81 WINE_DEFAULT_DEBUG_CHANNEL(netbios);
82
83 #define PORT_NBNS 137
84 #define PORT_NBDG 138
85 #define PORT_NBSS 139
86
87 #ifndef INADDR_NONE
88 #define INADDR_NONE ~0UL
89 #endif
90
91 #define NBR_ADDWORD(p,word) (*(WORD *)(p)) = htons(word)
92 #define NBR_GETWORD(p) ntohs(*(WORD *)(p))
93
94 #define MIN_QUERIES         1
95 #define MAX_QUERIES         0xffff
96 #define MIN_QUERY_TIMEOUT   100
97 #define MAX_QUERY_TIMEOUT   0xffffffff
98 #define BCAST_QUERIES       3
99 #define BCAST_QUERY_TIMEOUT 750
100 #define WINS_QUERIES        3
101 #define WINS_QUERY_TIMEOUT  750
102 #define MAX_WINS_SERVERS    2
103 #define MIN_CACHE_TIMEOUT   60000
104 #define CACHE_TIMEOUT       360000
105
106 #define MAX_NBT_NAME_SZ (NCBNAMSZ * 2 + MAX_DOMAIN_NAME_LEN + 2)
107 #define SIMPLE_NAME_QUERY_PKT_SIZE 26 + MAX_NBT_NAME_SZ
108
109 #define DEFAULT_NBT_SESSIONS 16
110
111 #define NBNS_TYPE_NB             0x0020
112 #define NBNS_TYPE_NBSTAT         0x0021
113 #define NBNS_CLASS_INTERNET      0x00001
114 #define NBNS_HEADER_SIZE         (sizeof(WORD) * 6)
115 #define NBNS_RESPONSE_AND_OPCODE 0xf800
116 #define NBNS_RESPONSE_AND_QUERY  0x8000
117 #define NBNS_REPLYCODE           0x0f
118
119 #define NBSS_HDRSIZE 4
120
121 #define NBSS_MSG       0x00
122 #define NBSS_REQ       0x81
123 #define NBSS_ACK       0x82
124 #define NBSS_NACK      0x83
125 #define NBSS_RETARGET  0x84
126 #define NBSS_KEEPALIVE 0x85
127
128 #define NBSS_ERR_NOT_LISTENING_ON_NAME    0x80
129 #define NBSS_ERR_NOT_LISTENING_FOR_CALLER 0x81
130 #define NBSS_ERR_BAD_NAME                 0x82
131 #define NBSS_ERR_INSUFFICIENT_RESOURCES   0x83
132
133 #define NBSS_EXTENSION 0x01
134
135 typedef struct _NetBTSession
136 {
137     CRITICAL_SECTION cs;
138     SOCKET           fd;
139     DWORD            bytesPending;
140 } NetBTSession;
141
142 typedef struct _NetBTAdapter
143 {
144     MIB_IPADDRROW       ipr;
145     WORD                nameQueryXID;
146     struct NBNameCache *nameCache;
147     DWORD               xmit_success;
148     DWORD               recv_success;
149 } NetBTAdapter;
150
151 static ULONG gTransportID;
152 static BOOL  gEnableDNS;
153 static DWORD gBCastQueries;
154 static DWORD gBCastQueryTimeout;
155 static DWORD gWINSQueries;
156 static DWORD gWINSQueryTimeout;
157 static DWORD gWINSServers[MAX_WINS_SERVERS];
158 static int   gNumWINSServers;
159 static char  gScopeID[MAX_DOMAIN_NAME_LEN];
160 static DWORD gCacheTimeout;
161 static struct NBNameCache *gNameCache;
162
163 /* Converts from a NetBIOS name into a Second Level Encoding-formatted name.
164  * Assumes p is not NULL and is either NULL terminated or has at most NCBNAMSZ
165  * bytes, and buffer has at least MAX_NBT_NAME_SZ bytes.  Pads with space bytes
166  * if p is NULL-terminated.  Returns the number of bytes stored in buffer.
167  */
168 static int NetBTNameEncode(const UCHAR *p, UCHAR *buffer)
169 {
170     int i,len=0;
171
172     if (!p) return 0;
173     if (!buffer) return 0;
174
175     buffer[len++] = NCBNAMSZ * 2;
176     for (i = 0; p[i] && i < NCBNAMSZ; i++)
177     {
178         buffer[len++] = ((p[i] & 0xf0) >> 4) + 'A';
179         buffer[len++] =  (p[i] & 0x0f) + 'A';
180     }
181     while (len < NCBNAMSZ * 2)
182     {
183         buffer[len++] = 'C';
184         buffer[len++] = 'A';
185     }
186     if (*gScopeID)
187     {
188         int scopeIDLen = strlen(gScopeID);
189
190         memcpy(buffer + len, gScopeID, scopeIDLen);
191         len += scopeIDLen;
192     }
193     buffer[len++] = 0;     /* add second terminator */
194     return len;
195 }
196
197 /* Creates a NBT name request packet for name in buffer.  If broadcast is true,
198  * creates a broadcast request, otherwise creates a unicast request.
199  * Returns the number of bytes stored in buffer.
200  */
201 static DWORD NetBTNameReq(const UCHAR name[NCBNAMSZ], WORD xid, WORD qtype,
202  BOOL broadcast, UCHAR *buffer, int len)
203 {
204     int i = 0;
205
206     if (len < SIMPLE_NAME_QUERY_PKT_SIZE) return 0;
207
208     NBR_ADDWORD(&buffer[i],xid);    i+=2; /* transaction */
209     if (broadcast)
210     {
211         NBR_ADDWORD(&buffer[i],0x0110); /* flags: r=req,op=query,rd=1,b=1 */
212         i+=2;
213     }
214     else
215     {
216         NBR_ADDWORD(&buffer[i],0x0100); /* flags: r=req,op=query,rd=1,b=0 */
217         i+=2;
218     }
219     NBR_ADDWORD(&buffer[i],0x0001); i+=2; /* one name query */
220     NBR_ADDWORD(&buffer[i],0x0000); i+=2; /* zero answers */
221     NBR_ADDWORD(&buffer[i],0x0000); i+=2; /* zero authorities */
222     NBR_ADDWORD(&buffer[i],0x0000); i+=2; /* zero additional */
223
224     i += NetBTNameEncode(name, &buffer[i]);
225
226     NBR_ADDWORD(&buffer[i],qtype); i+=2;
227     NBR_ADDWORD(&buffer[i],NBNS_CLASS_INTERNET); i+=2;
228
229     return i;
230 }
231
232 /* Sends a name query request for name on fd to destAddr.  Sets SO_BROADCAST on
233  * fd if broadcast is TRUE.  Assumes fd is not INVALID_SOCKET, and name is not
234  * NULL.
235  * Returns 0 on success, -1 on failure.
236  */
237 static int NetBTSendNameQuery(SOCKET fd, const UCHAR name[NCBNAMSZ], WORD xid,
238  WORD qtype, DWORD destAddr, BOOL broadcast)
239 {
240     int ret = 0, on = 1;
241     struct in_addr addr;
242
243     addr.s_addr = destAddr;
244     TRACE("name %s, dest addr %s\n", name, inet_ntoa(addr));
245
246     if (broadcast)
247         ret = setsockopt(fd, SOL_SOCKET, SO_BROADCAST, (PUCHAR)&on, sizeof(on));
248     if(ret == 0)
249     {
250         WSABUF wsaBuf;
251         UCHAR buf[SIMPLE_NAME_QUERY_PKT_SIZE];
252         struct sockaddr_in sin;
253
254         memset(&sin, 0, sizeof(sin));
255         sin.sin_addr.s_addr = destAddr;
256         sin.sin_family      = AF_INET;
257         sin.sin_port        = htons(PORT_NBNS);
258
259         wsaBuf.buf = buf;
260         wsaBuf.len = NetBTNameReq(name, xid, qtype, broadcast, buf,
261          sizeof(buf));
262         if (wsaBuf.len > 0)
263         {
264             DWORD bytesSent;
265
266             ret = WSASendTo(fd, &wsaBuf, 1, &bytesSent, 0,
267              (struct sockaddr*)&sin, sizeof(sin), NULL, NULL);
268             if (ret < 0 || bytesSent < wsaBuf.len)
269                 ret = -1;
270             else
271                 ret = 0;
272         }
273         else
274             ret = -1;
275     }
276     return ret;
277 }
278
279 typedef BOOL (*NetBTAnswerCallback)(void *data, WORD answerCount,
280  WORD answerIndex, PUCHAR rData, WORD rdLength);
281
282 /* Waits on fd until GetTickCount() returns a value greater than or equal to
283  * waitUntil for a name service response.  If a name response matching xid
284  * is received, calls answerCallback once for each answer resource record in
285  * the response.  (The callback's answerCount will be the total number of
286  * answers to expect, and answerIndex will be the 0-based index that's being
287  * sent this time.)  Quits parsing if answerCallback returns FALSE.
288  * Returns NRC_GOODRET on timeout or a valid response received, something else
289  * on error.
290  */
291 static UCHAR NetBTWaitForNameResponse(NetBTAdapter *adapter, SOCKET fd,
292  DWORD waitUntil, NetBTAnswerCallback answerCallback, void *data)
293 {
294     BOOL found = FALSE;
295     DWORD now;
296     UCHAR ret = NRC_GOODRET;
297
298     if (!adapter) return NRC_BADDR;
299     if (fd == INVALID_SOCKET) return NRC_BADDR;
300     if (!answerCallback) return NRC_BADDR;
301
302     while (!found && ret == NRC_GOODRET && (now = GetTickCount()) < waitUntil)
303     {
304         DWORD msToWait = waitUntil - now;
305         struct fd_set fds;
306         struct timeval timeout = { msToWait / 1000, msToWait % 1000 };
307         int r;
308
309         FD_ZERO(&fds);
310         FD_SET(fd, &fds);
311         r = select(fd + 1, &fds, NULL, NULL, &timeout);
312         if (r < 0)
313             ret = NRC_SYSTEM;
314         else if (r == 1)
315         {
316             /* FIXME: magic #, is this always enough? */
317             UCHAR buffer[256];
318             int fromsize;
319             struct sockaddr_in fromaddr;
320             WORD respXID, flags, queryCount, answerCount;
321             WSABUF wsaBuf = { sizeof(buffer), buffer };
322             DWORD bytesReceived, recvFlags = 0;
323
324             fromsize = sizeof(fromaddr);
325             r = WSARecvFrom(fd, &wsaBuf, 1, &bytesReceived, &recvFlags,
326              (struct sockaddr*)&fromaddr, &fromsize, NULL, NULL);
327             if(r < 0)
328             {
329                 ret = NRC_SYSTEM;
330                 break;
331             }
332
333             if (bytesReceived < NBNS_HEADER_SIZE)
334                 continue;
335
336             respXID = NBR_GETWORD(buffer);
337             if (adapter->nameQueryXID != respXID)
338                 continue;
339
340             flags = NBR_GETWORD(buffer + 2);
341             queryCount = NBR_GETWORD(buffer + 4);
342             answerCount = NBR_GETWORD(buffer + 6);
343
344             /* a reply shouldn't contain a query, ignore bad packet */
345             if (queryCount > 0)
346                 continue;
347
348             if ((flags & NBNS_RESPONSE_AND_OPCODE) == NBNS_RESPONSE_AND_QUERY)
349             {
350                 if ((flags & NBNS_REPLYCODE) != 0)
351                     ret = NRC_NAMERR;
352                 else if ((flags & NBNS_REPLYCODE) == 0 && answerCount > 0)
353                 {
354                     PUCHAR ptr = buffer + NBNS_HEADER_SIZE;
355                     BOOL shouldContinue = TRUE;
356                     WORD answerIndex = 0;
357
358                     found = TRUE;
359                     /* decode one answer at a time */
360                     while (ret == NRC_GOODRET && answerIndex < answerCount &&
361                      ptr - buffer < bytesReceived && shouldContinue)
362                     {
363                         WORD rLen;
364
365                         /* scan past name */
366                         for (; ptr[0] && ptr - buffer < bytesReceived; )
367                             ptr += ptr[0] + 1;
368                         ptr++;
369                         ptr += 2; /* scan past type */
370                         if (ptr - buffer < bytesReceived && ret == NRC_GOODRET
371                          && NBR_GETWORD(ptr) == NBNS_CLASS_INTERNET)
372                             ptr += sizeof(WORD);
373                         else
374                             ret = NRC_SYSTEM; /* parse error */
375                         ptr += sizeof(DWORD); /* TTL */
376                         rLen = NBR_GETWORD(ptr);
377                         rLen = min(rLen, bytesReceived - (ptr - buffer));
378                         ptr += sizeof(WORD);
379                         shouldContinue = answerCallback(data, answerCount,
380                          answerIndex, ptr, rLen);
381                         ptr += rLen;
382                         answerIndex++;
383                     }
384                 }
385             }
386         }
387     }
388     TRACE("returning 0x%02x\n", ret);
389     return ret;
390 }
391
392 typedef struct _NetBTNameQueryData {
393     NBNameCacheEntry *cacheEntry;
394     UCHAR ret;
395 } NetBTNameQueryData;
396
397 /* Name query callback function for NetBTWaitForNameResponse, creates a cache
398  * entry on the first answer, adds each address as it's called again (as long
399  * as there's space).  If there's an error that should be propagated as the
400  * NetBIOS error, modifies queryData's ret member to the proper return code.
401  */
402 static BOOL NetBTFindNameAnswerCallback(void *pVoid, WORD answerCount,
403  WORD answerIndex, PUCHAR rData, WORD rLen)
404 {
405     NetBTNameQueryData *queryData = (NetBTNameQueryData *)pVoid;
406     BOOL ret;
407
408     if (queryData)
409     {
410         if (queryData->cacheEntry == NULL)
411         {
412             queryData->cacheEntry = (NBNameCacheEntry *)HeapAlloc(
413              GetProcessHeap(), 0, sizeof(NBNameCacheEntry) +
414              (answerCount - 1) * sizeof(DWORD));
415             if (queryData->cacheEntry)
416                 queryData->cacheEntry->numAddresses = 0;
417             else
418             {
419                 ret = FALSE;
420                 queryData->ret = NRC_OSRESNOTAV;
421             }
422         }
423         if (rLen == 6 && queryData->cacheEntry &&
424          queryData->cacheEntry->numAddresses < answerCount)
425         {
426             queryData->cacheEntry->addresses[queryData->cacheEntry->
427              numAddresses++] = *(PDWORD)(rData + 2);
428             ret = queryData->cacheEntry->numAddresses < answerCount;
429         }
430         else
431             ret = FALSE;
432     }
433     else
434         ret = FALSE;
435     return ret;
436 }
437
438 /* Workhorse NetBT name lookup function.  Sends a name lookup query for
439  * ncb->ncb_callname to sendTo, as a broadcast if broadcast is TRUE, using
440  * adapter->nameQueryXID as the transaction ID.  Waits up to timeout
441  * milliseconds, and retries up to maxQueries times, waiting for a reply.
442  * If a valid response is received, stores the looked up addresses as a
443  * NBNameCacheEntry in *cacheEntry.
444  * Returns NRC_GOODRET on success, though this may not mean the name was
445  * resolved--check whether *cacheEntry is NULL.
446  */
447 static UCHAR NetBTNameWaitLoop(NetBTAdapter *adapter, SOCKET fd, PNCB ncb,
448  DWORD sendTo, BOOL broadcast, DWORD timeout, DWORD maxQueries,
449  NBNameCacheEntry **cacheEntry)
450 {
451     int queries;
452     NetBTNameQueryData queryData;
453
454     if (!adapter) return NRC_BADDR;
455     if (fd == INVALID_SOCKET) return NRC_BADDR;
456     if (!ncb) return NRC_BADDR;
457     if (!cacheEntry) return NRC_BADDR;
458
459     queryData.cacheEntry = NULL;
460     queryData.ret = NRC_GOODRET;
461     for (queries = 0; queryData.cacheEntry == NULL && queries < maxQueries;
462      queries++)
463     {
464         if (!NCB_CANCELLED(ncb))
465         {
466             int r = NetBTSendNameQuery(fd, ncb->ncb_callname,
467              adapter->nameQueryXID, NBNS_TYPE_NB, sendTo, broadcast);
468
469             if (r == 0)
470                 queryData.ret = NetBTWaitForNameResponse(adapter, fd,
471                  GetTickCount() + timeout, NetBTFindNameAnswerCallback,
472                  &queryData);
473             else
474                 queryData.ret = NRC_SYSTEM;
475         }
476         else
477             queryData.ret = NRC_CMDCAN;
478     }
479     if (queryData.cacheEntry)
480     {
481         memcpy(queryData.cacheEntry->name, ncb->ncb_callname, NCBNAMSZ);
482         memcpy(queryData.cacheEntry->nbname, ncb->ncb_callname, NCBNAMSZ);
483     }
484     *cacheEntry = queryData.cacheEntry;
485     return queryData.ret;
486 }
487
488 /* Attempts to add cacheEntry to the name cache in *nameCache; if *nameCache
489  * has not yet been created, creates it, using gCacheTimeout as the cache
490  * entry timeout.  If memory allocation fails, or if NBNameCacheAddEntry fails,
491  * frees cacheEntry.
492  * Returns NRC_GOODRET on success, and something else on failure.
493  */
494 static UCHAR NetBTStoreCacheEntry(struct NBNameCache **nameCache,
495  NBNameCacheEntry *cacheEntry)
496 {
497     UCHAR ret;
498
499     if (!nameCache) return NRC_BADDR;
500     if (!cacheEntry) return NRC_BADDR;
501
502     if (!*nameCache)
503         *nameCache = NBNameCacheCreate(GetProcessHeap(), gCacheTimeout);
504     if (*nameCache)
505         ret = NBNameCacheAddEntry(*nameCache, cacheEntry)
506          ?  NRC_GOODRET : NRC_OSRESNOTAV;
507     else
508     {
509         HeapFree(GetProcessHeap(), 0, cacheEntry);
510         ret = NRC_OSRESNOTAV;
511     }
512     return ret;
513 }
514
515 /* Attempts to resolve name using inet_addr(), then gethostbyname() if
516  * gEnableDNS is TRUE, if the suffix byte is either <00> or <20>.  If the name
517  * can be looked up, returns 0 and stores the looked up addresses as a
518  * NBNameCacheEntry in *cacheEntry.
519  * Returns NRC_GOODRET on success, though this may not mean the name was
520  * resolved--check whether *cacheEntry is NULL.  Returns something else on
521  * error.
522  */
523 static UCHAR NetBTinetResolve(const UCHAR name[NCBNAMSZ],
524  NBNameCacheEntry **cacheEntry)
525 {
526     UCHAR ret = NRC_GOODRET;
527
528     TRACE("name %s, cacheEntry %p\n", name, cacheEntry);
529
530     if (!name) return NRC_BADDR;
531     if (!cacheEntry) return NRC_BADDR;
532
533     if (isalnum(name[0]) && (name[NCBNAMSZ - 1] == 0 ||
534      name[NCBNAMSZ - 1] == 0x20))
535     {
536         UCHAR toLookup[NCBNAMSZ];
537         int i;
538
539         for (i = 0; i < NCBNAMSZ - 1 && name[i] && name[i] != ' '; i++)
540             toLookup[i] = name[i];
541         toLookup[i] = '\0';
542
543         if (isdigit(toLookup[0]))
544         {
545             unsigned long addr = inet_addr(toLookup);
546
547             if (addr != INADDR_NONE)
548             {
549                 *cacheEntry = (NBNameCacheEntry *)HeapAlloc(GetProcessHeap(),
550                  0, sizeof(NBNameCacheEntry));
551                 if (*cacheEntry)
552                 {
553                     memcpy((*cacheEntry)->name, name, NCBNAMSZ);
554                     memset((*cacheEntry)->nbname, 0, NCBNAMSZ);
555                     (*cacheEntry)->nbname[0] = '*';
556                     (*cacheEntry)->numAddresses = 1;
557                     (*cacheEntry)->addresses[0] = addr;
558                 }
559                 else
560                     ret = NRC_OSRESNOTAV;
561             }
562         }
563         if (gEnableDNS && ret == NRC_GOODRET && !*cacheEntry)
564         {
565             struct hostent *host;
566
567             if ((host = gethostbyname(toLookup)) != NULL)
568             {
569                 for (i = 0; ret == NRC_GOODRET && host->h_addr_list &&
570                  host->h_addr_list[i]; i++)
571                     ;
572                 if (host->h_addr_list && host->h_addr_list[0])
573                 {
574                     *cacheEntry = (NBNameCacheEntry *)HeapAlloc(
575                      GetProcessHeap(), 0, sizeof(NBNameCacheEntry) +
576                      (i - 1) * sizeof(DWORD));
577                     if (*cacheEntry)
578                     {
579                         memcpy((*cacheEntry)->name, name, NCBNAMSZ);
580                         memset((*cacheEntry)->nbname, 0, NCBNAMSZ);
581                         (*cacheEntry)->nbname[0] = '*';
582                         (*cacheEntry)->numAddresses = i;
583                         for (i = 0; i < (*cacheEntry)->numAddresses; i++)
584                             (*cacheEntry)->addresses[i] =
585                              (DWORD)host->h_addr_list[i];
586                     }
587                     else
588                         ret = NRC_OSRESNOTAV;
589                 }
590             }
591         }
592     }
593
594     TRACE("returning 0x%02x\n", ret);
595     return ret;
596 }
597
598 /* Looks up the name in ncb->ncb_callname, first in the name caches (global
599  * and this adapter's), then using gethostbyname(), next by WINS if configured,
600  * and finally using broadcast NetBT name resolution.  In NBT parlance, this
601  * makes this an "H-node".  Stores an entry in the appropriate name cache for a
602  * found node, and returns it as *cacheEntry.
603  * Assumes data, ncb, and cacheEntry are not NULL.
604  * Returns NRC_GOODRET on success--which doesn't mean the name was resolved,
605  * just that all name lookup operations completed successfully--and something
606  * else on failure.  *cacheEntry will be NULL if the name was not found.
607  */
608 static UCHAR NetBTInternalFindName(NetBTAdapter *adapter, PNCB ncb,
609  const NBNameCacheEntry **cacheEntry)
610 {
611     UCHAR ret = NRC_GOODRET;
612
613     TRACE("adapter %p, ncb %p, cacheEntry %p\n", adapter, ncb, cacheEntry);
614
615     if (!cacheEntry) return NRC_BADDR;
616     *cacheEntry = NULL;
617
618     if (!adapter) return NRC_BADDR;
619     if (!ncb) return NRC_BADDR;
620
621     if (ncb->ncb_callname[0] == '*')
622         ret = NRC_NOWILD;
623     else
624     {
625         *cacheEntry = NBNameCacheFindEntry(gNameCache, ncb->ncb_callname);
626         if (!*cacheEntry)
627             *cacheEntry = NBNameCacheFindEntry(adapter->nameCache,
628              ncb->ncb_callname);
629         if (!*cacheEntry)
630         {
631             NBNameCacheEntry *newEntry = NULL;
632
633             ret = NetBTinetResolve(ncb->ncb_callname, &newEntry);
634             if (ret == NRC_GOODRET && newEntry)
635             {
636                 ret = NetBTStoreCacheEntry(&gNameCache, newEntry);
637                 if (ret != NRC_GOODRET)
638                     newEntry = NULL;
639             }
640             else
641             {
642                 SOCKET fd = WSASocketA(PF_INET, SOCK_DGRAM, IPPROTO_UDP, NULL,
643                  0, WSA_FLAG_OVERLAPPED);
644
645                 if(fd == INVALID_SOCKET)
646                     ret = NRC_OSRESNOTAV;
647                 else
648                 {
649                     int winsNdx;
650
651                     adapter->nameQueryXID++;
652                     for (winsNdx = 0; ret == NRC_GOODRET && *cacheEntry == NULL
653                      && winsNdx < gNumWINSServers; winsNdx++)
654                         ret = NetBTNameWaitLoop(adapter, fd, ncb,
655                          gWINSServers[winsNdx], FALSE, gWINSQueryTimeout,
656                          gWINSQueries, &newEntry);
657                     if (ret == NRC_GOODRET && newEntry)
658                     {
659                         ret = NetBTStoreCacheEntry(&gNameCache, newEntry);
660                         if (ret != NRC_GOODRET)
661                             newEntry = NULL;
662                     }
663                     if (ret == NRC_GOODRET && *cacheEntry == NULL)
664                     {
665                         ret = NetBTNameWaitLoop(adapter, fd, ncb,
666                          adapter->ipr.dwBCastAddr, TRUE, gBCastQueryTimeout,
667                          gBCastQueries, &newEntry);
668                         if (ret == NRC_GOODRET && newEntry)
669                         {
670                             ret = NetBTStoreCacheEntry(&adapter->nameCache,
671                              newEntry);
672                             if (ret != NRC_GOODRET)
673                                 newEntry = NULL;
674                         }
675                     }
676                     closesocket(fd);
677                 }
678             }
679             *cacheEntry = newEntry;
680         }
681     }
682     TRACE("returning 0x%02x\n", ret);
683     return ret;
684 }
685
686 typedef struct _NetBTNodeQueryData
687 {
688     BOOL gotResponse;
689     PADAPTER_STATUS astat;
690     WORD astatLen;
691 } NetBTNodeQueryData;
692
693 /* Callback function for NetBTAstatRemote, parses the rData for the node
694  * status and name list of the remote node.  Always returns FALSE, since
695  * there's never more than one answer we care about in a node status response.
696  */
697 static BOOL NetBTNodeStatusAnswerCallback(void *pVoid, WORD answerCount,
698  WORD answerIndex, PUCHAR rData, WORD rLen)
699 {
700     NetBTNodeQueryData *data = (NetBTNodeQueryData *)pVoid;
701
702     if (data && !data->gotResponse && rData && rLen >= 1)
703     {
704         /* num names is first byte; each name is NCBNAMSZ + 2 bytes */
705         if (rLen >= rData[0] * (NCBNAMSZ + 2))
706         {
707             WORD i;
708             PUCHAR src;
709             PNAME_BUFFER dst;
710
711             data->gotResponse = TRUE;
712             data->astat->name_count = rData[0];
713             for (i = 0, src = rData + 1,
714              dst = (PNAME_BUFFER)((PUCHAR)data->astat +
715               sizeof(ADAPTER_STATUS));
716              i < data->astat->name_count && src - rData < rLen &&
717              (PUCHAR)dst - (PUCHAR)data->astat < data->astatLen;
718              i++, dst++, src += NCBNAMSZ + 2)
719             {
720                 UCHAR flags = *(src + NCBNAMSZ);
721
722                 memcpy(dst->name, src, NCBNAMSZ);
723                 /* we won't actually see a registering name in the returned
724                  * response.  It's useful to see if no other flags are set; if
725                  * none are, then the name is registered. */
726                 dst->name_flags = REGISTERING;
727                 if (flags & 0x80)
728                     dst->name_flags |= GROUP_NAME;
729                 if (flags & 0x10)
730                     dst->name_flags |= DEREGISTERED;
731                 if (flags & 0x08)
732                     dst->name_flags |= DUPLICATE;
733                 if (dst->name_flags == REGISTERING)
734                     dst->name_flags = REGISTERED;
735             }
736             /* arbitrarily set HW type to Ethernet */
737             data->astat->adapter_type = 0xfe;
738             if (src - rData < rLen)
739                 memcpy(data->astat->adapter_address, src,
740                  min(rLen - (src - rData), 6));
741         }
742     }
743     return FALSE;
744 }
745
746 /* This uses the WINS timeout and query values, as they're the
747  * UCAST_REQ_RETRY_TIMEOUT and UCAST_REQ_RETRY_COUNT according to the RFCs.
748  */
749 static UCHAR NetBTAstatRemote(NetBTAdapter *adapter, PNCB ncb)
750 {
751     UCHAR ret = NRC_GOODRET;
752     const NBNameCacheEntry *cacheEntry = NULL;
753
754     TRACE("adapter %p, NCB %p\n", adapter, ncb);
755
756     if (!adapter) return NRC_BADDR;
757     if (!ncb) return NRC_INVADDRESS;
758
759     ret = NetBTInternalFindName(adapter, ncb, &cacheEntry);
760     if (ret == NRC_GOODRET && cacheEntry)
761     {
762         if (cacheEntry->numAddresses > 0)
763         {
764             SOCKET fd = WSASocketA(PF_INET, SOCK_DGRAM, IPPROTO_UDP, NULL, 0,
765              WSA_FLAG_OVERLAPPED);
766
767             if(fd == INVALID_SOCKET)
768                 ret = NRC_OSRESNOTAV;
769             else
770             {
771                 NetBTNodeQueryData queryData;
772                 DWORD queries;
773                 PADAPTER_STATUS astat = (PADAPTER_STATUS)ncb->ncb_buffer;
774
775                 adapter->nameQueryXID++;
776                 astat->name_count = 0;
777                 queryData.gotResponse = FALSE;
778                 queryData.astat = astat;
779                 queryData.astatLen = ncb->ncb_length;
780                 for (queries = 0; !queryData.gotResponse &&
781                  queries < gWINSQueries; queries++)
782                 {
783                     if (!NCB_CANCELLED(ncb))
784                     {
785                         int r = NetBTSendNameQuery(fd, ncb->ncb_callname,
786                          adapter->nameQueryXID, NBNS_TYPE_NBSTAT,
787                          cacheEntry->addresses[0], FALSE);
788
789                         if (r == 0)
790                             ret = NetBTWaitForNameResponse(adapter, fd,
791                              GetTickCount() + gWINSQueryTimeout,
792                              NetBTNodeStatusAnswerCallback, &queryData);
793                         else
794                             ret = NRC_SYSTEM;
795                     }
796                     else
797                         ret = NRC_CMDCAN;
798                 }
799                 closesocket(fd);
800             }
801         }
802         else
803             ret = NRC_CMDTMO;
804     }
805     else if (ret == NRC_CMDCAN)
806         ; /* do nothing, we were cancelled */
807     else
808         ret = NRC_CMDTMO;
809     TRACE("returning 0x%02x\n", ret);
810     return ret;
811 }
812
813 static UCHAR NetBTAstat(void *adapt, PNCB ncb)
814 {
815     NetBTAdapter *adapter = (NetBTAdapter *)adapt;
816     UCHAR ret;
817
818     TRACE("adapt %p, NCB %p\n", adapt, ncb);
819
820     if (!adapter) return NRC_ENVNOTDEF;
821     if (!ncb) return NRC_INVADDRESS;
822     if (!ncb->ncb_buffer) return NRC_BADDR;
823     if (ncb->ncb_length < sizeof(ADAPTER_STATUS)) return NRC_BUFLEN;
824
825     if (ncb->ncb_callname[0] == '*')
826     {
827         DWORD physAddrLen;
828         MIB_IFROW ifRow;
829         PADAPTER_STATUS astat = (PADAPTER_STATUS)ncb->ncb_buffer;
830   
831         memset(astat, 0, sizeof(ADAPTER_STATUS));
832         astat->rev_major = 3;
833         ifRow.dwIndex = adapter->ipr.dwIndex;
834         if (GetIfEntry(&ifRow) != NO_ERROR)
835             ret = NRC_BRIDGE;
836         else
837         {
838             physAddrLen = min(ifRow.dwPhysAddrLen, 6);
839             if (physAddrLen > 0)
840                 memcpy(astat->adapter_address, ifRow.bPhysAddr, physAddrLen);
841             /* doubt anyone cares, but why not.. */
842             if (ifRow.dwType == MIB_IF_TYPE_TOKENRING)
843                 astat->adapter_type = 0xff;
844             else
845                 astat->adapter_type = 0xfe; /* for Ethernet */
846             astat->max_sess_pkt_size = 0xffff;
847             astat->xmit_success = adapter->xmit_success;
848             astat->recv_success = adapter->recv_success;
849         }
850         ret = NRC_GOODRET;
851     }
852     else
853         ret = NetBTAstatRemote(adapter, ncb);
854     TRACE("returning 0x%02x\n", ret);
855     return ret;
856 }
857
858 static UCHAR NetBTFindName(void *adapt, PNCB ncb)
859 {
860     NetBTAdapter *adapter = (NetBTAdapter *)adapt;
861     UCHAR ret;
862     const NBNameCacheEntry *cacheEntry = NULL;
863     PFIND_NAME_HEADER foundName;
864
865     TRACE("adapt %p, NCB %p\n", adapt, ncb);
866
867     if (!adapter) return NRC_ENVNOTDEF;
868     if (!ncb) return NRC_INVADDRESS;
869     if (!ncb->ncb_buffer) return NRC_BADDR;
870     if (ncb->ncb_length < sizeof(FIND_NAME_HEADER)) return NRC_BUFLEN;
871
872     foundName = (PFIND_NAME_HEADER)ncb->ncb_buffer;
873     memset(foundName, 0, sizeof(FIND_NAME_HEADER));
874
875     ret = NetBTInternalFindName(adapter, ncb, &cacheEntry);
876     if (ret == NRC_GOODRET)
877     {
878         if (cacheEntry)
879         {
880             DWORD spaceFor = min((ncb->ncb_length - sizeof(FIND_NAME_HEADER)) /
881              sizeof(FIND_NAME_BUFFER), cacheEntry->numAddresses);
882             DWORD ndx;
883
884             for (ndx = 0; ndx < spaceFor; ndx++)
885             {
886                 PFIND_NAME_BUFFER findNameBuffer;
887
888                 findNameBuffer =
889                  (PFIND_NAME_BUFFER)((PUCHAR)foundName +
890                  sizeof(FIND_NAME_HEADER) + foundName->node_count *
891                  sizeof(FIND_NAME_BUFFER));
892                 memset(findNameBuffer->destination_addr, 0, 2);
893                 memcpy(findNameBuffer->destination_addr + 2,
894                  &adapter->ipr.dwAddr, sizeof(DWORD));
895                 memset(findNameBuffer->source_addr, 0, 2);
896                 memcpy(findNameBuffer->source_addr + 2,
897                  &cacheEntry->addresses[ndx], sizeof(DWORD));
898                 foundName->node_count++;
899             }
900             if (spaceFor < cacheEntry->numAddresses)
901                 ret = NRC_BUFLEN;
902         }
903         else
904             ret = NRC_CMDTMO;
905     }
906     TRACE("returning 0x%02x\n", ret);
907     return ret;
908 }
909
910 static UCHAR NetBTSessionReq(SOCKET fd, const UCHAR *calledName,
911  const UCHAR *callingName)
912 {
913     UCHAR buffer[NBSS_HDRSIZE + MAX_DOMAIN_NAME_LEN * 2], ret;
914     int len = 0, r;
915     DWORD bytesSent, bytesReceived, recvFlags = 0;
916     WSABUF wsaBuf;
917
918     buffer[0] = NBSS_REQ;
919     buffer[1] = 0;
920
921     len += NetBTNameEncode(calledName, &buffer[NBSS_HDRSIZE]);
922     len += NetBTNameEncode(callingName, &buffer[NBSS_HDRSIZE + len]);
923
924     NBR_ADDWORD(&buffer[2], len);
925
926     wsaBuf.len = len + NBSS_HDRSIZE;
927     wsaBuf.buf = buffer;
928
929     r = WSASend(fd, &wsaBuf, 1, &bytesSent, 0, NULL, NULL);
930     if(r < 0 || bytesSent < len + NBSS_HDRSIZE)
931     {
932         ERR("send failed\n");
933         return NRC_SABORT;
934     }
935
936     /* I've already set the recv timeout on this socket (if it supports it), so
937      * just block.  Hopefully we'll always receive the session acknowledgement
938      * within one timeout.
939      */
940     wsaBuf.len = NBSS_HDRSIZE + 1;
941     r = WSARecv(fd, &wsaBuf, 1, &bytesReceived, &recvFlags, NULL, NULL);
942     if (r < 0 || bytesReceived < NBSS_HDRSIZE)
943         ret = NRC_SABORT;
944     else if (buffer[0] == NBSS_NACK)
945     {
946         if (r == NBSS_HDRSIZE + 1)
947         {
948             switch (buffer[NBSS_HDRSIZE])
949             {
950                 case NBSS_ERR_INSUFFICIENT_RESOURCES:
951                     ret = NRC_REMTFUL;
952                     break;
953                 default:
954                     ret = NRC_NOCALL;
955             }
956         }
957         else
958             ret = NRC_NOCALL;
959     }
960     else if (buffer[0] == NBSS_RETARGET)
961     {
962         FIXME("Got a session retarget, can't deal\n");
963         ret = NRC_NOCALL;
964     }
965     else if (buffer[0] == NBSS_ACK)
966         ret = NRC_GOODRET;
967     else
968         ret = NRC_SYSTEM;
969
970     TRACE("returning 0x%02x\n", ret);
971     return ret;
972 }
973
974 static UCHAR NetBTCall(void *adapt, PNCB ncb, void **sess)
975 {
976     NetBTAdapter *adapter = (NetBTAdapter *)adapt;
977     UCHAR ret;
978     const NBNameCacheEntry *cacheEntry = NULL;
979
980     TRACE("adapt %p, ncb %p", adapt, ncb);
981
982     if (!adapter) return NRC_ENVNOTDEF;
983     if (!ncb) return NRC_INVADDRESS;
984     if (!sess) return NRC_BADDR;
985
986     ret = NetBTInternalFindName(adapter, ncb, &cacheEntry);
987     if (ret == NRC_GOODRET)
988     {
989         if (cacheEntry && cacheEntry->numAddresses > 0)
990         {
991             SOCKET fd;
992
993             fd = WSASocketA(PF_INET, SOCK_STREAM, IPPROTO_TCP, NULL, 0,
994              WSA_FLAG_OVERLAPPED);
995             if (fd != INVALID_SOCKET)
996             {
997                 DWORD timeout;
998                 struct sockaddr_in sin;
999
1000                 if (ncb->ncb_rto > 0)
1001                 {
1002                     timeout = ncb->ncb_rto * 500;
1003                     setsockopt(fd, SOL_SOCKET, SO_RCVTIMEO, (PUCHAR)&timeout,
1004                      sizeof(timeout));
1005                 }
1006                 if (ncb->ncb_rto > 0)
1007                 {
1008                     timeout = ncb->ncb_sto * 500;
1009                     setsockopt(fd, SOL_SOCKET, SO_SNDTIMEO, (PUCHAR)&timeout,
1010                      sizeof(timeout));
1011                 }
1012
1013                 memset(&sin, 0, sizeof(sin));
1014                 memcpy(&sin.sin_addr, &cacheEntry->addresses[0],
1015                  sizeof(sin.sin_addr));
1016                 sin.sin_family = AF_INET;
1017                 sin.sin_port   = htons(PORT_NBSS);
1018                 /* FIXME: use nonblocking mode for the socket, check the
1019                  * cancel flag periodically
1020                  */
1021                 if (connect(fd, (struct sockaddr *)&sin, sizeof(sin))
1022                  == SOCKET_ERROR)
1023                     ret = NRC_CMDTMO;
1024                 else
1025                 {
1026                     static UCHAR fakedCalledName[] = "*SMBSERVER";
1027                     const UCHAR *calledParty = cacheEntry->nbname[0] == '*'
1028                      ? fakedCalledName : cacheEntry->nbname;
1029
1030                     ret = NetBTSessionReq(fd, calledParty, ncb->ncb_name);
1031                     if (ret != NRC_GOODRET && calledParty[0] == '*')
1032                     {
1033                         FIXME("NBT session to \"*SMBSERVER\" refused,\n");
1034                         FIXME("should try finding name using ASTAT\n");
1035                     }
1036                 }
1037                 if (ret != NRC_GOODRET)
1038                     closesocket(fd);
1039                 else
1040                 {
1041                     NetBTSession *session = (NetBTSession *)HeapAlloc(
1042                      GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(NetBTSession));
1043
1044                     if (session)
1045                     {
1046                         session->fd = fd;
1047                         InitializeCriticalSection(&session->cs);
1048                         *sess = session;
1049                     }
1050                     else
1051                     {
1052                         ret = NRC_OSRESNOTAV;
1053                         closesocket(fd);
1054                     }
1055                 }
1056             }
1057             else
1058                 ret = NRC_OSRESNOTAV;
1059         }
1060         else
1061             ret = NRC_NAMERR;
1062     }
1063     TRACE("returning 0x%02x\n", ret);
1064     return ret;
1065 }
1066
1067 /* Notice that I don't protect against multiple thread access to NetBTSend.
1068  * This is because I don't update any data in the adapter, and I only make a
1069  * single call to WSASend, which I assume to act atomically (not interleaving
1070  * data from other threads).
1071  * I don't lock, because I only depend on the fd being valid, and this won't be
1072  * true until a session setup is completed.
1073  */
1074 static UCHAR NetBTSend(void *adapt, void *sess, PNCB ncb)
1075 {
1076     NetBTAdapter *adapter = (NetBTAdapter *)adapt;
1077     NetBTSession *session = (NetBTSession *)sess;
1078     UCHAR buffer[NBSS_HDRSIZE], ret;
1079     int r;
1080     WSABUF wsaBufs[2];
1081     DWORD bytesSent;
1082
1083     TRACE("adapt %p, session %p, NCB %p\n", adapt, session, ncb);
1084
1085     if (!adapter) return NRC_ENVNOTDEF;
1086     if (!ncb) return NRC_INVADDRESS;
1087     if (!ncb->ncb_buffer) return NRC_BADDR;
1088     if (!session) return NRC_SNUMOUT;
1089     if (session->fd == INVALID_SOCKET) return NRC_SNUMOUT;
1090
1091     buffer[0] = NBSS_MSG;
1092     buffer[1] = 0;
1093     NBR_ADDWORD(&buffer[2], ncb->ncb_length);
1094
1095     wsaBufs[0].len = NBSS_HDRSIZE;
1096     wsaBufs[0].buf = buffer;
1097     wsaBufs[1].len = ncb->ncb_length;
1098     wsaBufs[1].buf = ncb->ncb_buffer;
1099
1100     r = WSASend(session->fd, wsaBufs, sizeof(wsaBufs) / sizeof(wsaBufs[0]),
1101      &bytesSent, 0, NULL, NULL);
1102     if (r == SOCKET_ERROR)
1103     {
1104         NetBIOSHangupSession(ncb);
1105         ret = NRC_SABORT;
1106     }
1107     else if (bytesSent < NBSS_HDRSIZE + ncb->ncb_length)
1108     {
1109         FIXME("Only sent %ld bytes (of %d), hanging up session\n", bytesSent,
1110          NBSS_HDRSIZE + ncb->ncb_length);
1111         NetBIOSHangupSession(ncb);
1112         ret = NRC_SABORT;
1113     }
1114     else
1115     {
1116         ret = NRC_GOODRET;
1117         adapter->xmit_success++;
1118     }
1119     TRACE("returning 0x%02x\n", ret);
1120     return ret;
1121 }
1122
1123 static UCHAR NetBTRecv(void *adapt, void *sess, PNCB ncb)
1124 {
1125     NetBTAdapter *adapter = (NetBTAdapter *)adapt;
1126     NetBTSession *session = (NetBTSession *)sess;
1127     UCHAR buffer[NBSS_HDRSIZE], ret;
1128     int r;
1129     WSABUF wsaBufs[2];
1130     DWORD bufferCount, bytesReceived, flags;
1131
1132     TRACE("adapt %p, session %p, NCB %p\n", adapt, session, ncb);
1133
1134     if (!adapter) return NRC_ENVNOTDEF;
1135     if (!ncb) return NRC_BADDR;
1136     if (!ncb->ncb_buffer) return NRC_BADDR;
1137     if (!session) return NRC_SNUMOUT;
1138     if (session->fd == INVALID_SOCKET) return NRC_SNUMOUT;
1139
1140     EnterCriticalSection(&session->cs);
1141     bufferCount = 0;
1142     if (session->bytesPending == 0)
1143     {
1144         bufferCount++;
1145         wsaBufs[0].len = NBSS_HDRSIZE;
1146         wsaBufs[0].buf = buffer;
1147     }
1148     wsaBufs[bufferCount].len = ncb->ncb_length;
1149     wsaBufs[bufferCount].buf = ncb->ncb_buffer;
1150     bufferCount++;
1151
1152     flags = 0;
1153     /* FIXME: should poll a bit so I can check the cancel flag */
1154     r = WSARecv(session->fd, wsaBufs, bufferCount, &bytesReceived, &flags,
1155      NULL, NULL);
1156     if (r == SOCKET_ERROR && WSAGetLastError() != WSAEWOULDBLOCK)
1157     {
1158         LeaveCriticalSection(&session->cs);
1159         ERR("Receive error, WSAGetLastError() returns %d\n", WSAGetLastError());
1160         NetBIOSHangupSession(ncb);
1161         ret = NRC_SABORT;
1162     }
1163     else if (NCB_CANCELLED(ncb))
1164     {
1165         LeaveCriticalSection(&session->cs);
1166         ret = NRC_CMDCAN;
1167     }
1168     else
1169     {
1170         if (bufferCount == 2)
1171         {
1172             if (buffer[0] == NBSS_KEEPALIVE)
1173             {
1174                 LeaveCriticalSection(&session->cs);
1175                 FIXME("Oops, received a session keepalive and lost my place\n");
1176                 /* need to read another session header until we get a session
1177                  * message header. */
1178                 NetBIOSHangupSession(ncb);
1179                 ret = NRC_SABORT;
1180             }
1181             else if (buffer[0] != NBSS_MSG)
1182             {
1183                 LeaveCriticalSection(&session->cs);
1184                 FIXME("Received unexpected session msg type %d\n", buffer[0]);
1185                 NetBIOSHangupSession(ncb);
1186                 ret = NRC_SABORT;
1187             }
1188             else
1189             {
1190                 if (buffer[1] & NBSS_EXTENSION)
1191                 {
1192                     LeaveCriticalSection(&session->cs);
1193                     FIXME("Received a message that's too long for my taste\n");
1194                     NetBIOSHangupSession(ncb);
1195                     ret = NRC_SABORT;
1196                 }
1197                 else
1198                 {
1199                     session->bytesPending = NBSS_HDRSIZE
1200                      + NBR_GETWORD(&buffer[2]) - bytesReceived;
1201                     ncb->ncb_length = bytesReceived - NBSS_HDRSIZE;
1202                     LeaveCriticalSection(&session->cs);
1203                 }
1204             }
1205         }
1206         else
1207         {
1208             if (bytesReceived < session->bytesPending)
1209                 session->bytesPending -= bytesReceived;
1210             else
1211                 session->bytesPending = 0;
1212             LeaveCriticalSection(&session->cs);
1213             ncb->ncb_length = bytesReceived;
1214         }
1215         if (session->bytesPending > 0)
1216             ret = NRC_INCOMP;
1217         else
1218         {
1219             ret = NRC_GOODRET;
1220             adapter->recv_success++;
1221         }
1222     }
1223     TRACE("returning 0x%02x\n", ret);
1224     return ret;
1225 }
1226
1227 static UCHAR NetBTHangup(void *adapt, void *sess)
1228 {
1229     NetBTSession *session = (NetBTSession *)sess;
1230
1231     TRACE("adapt %p, session %p\n", adapt, session);
1232
1233     if (!session) return NRC_SNUMOUT;
1234
1235     /* I don't lock the session, because NetBTRecv knows not to decrement
1236      * past 0, so if a receive completes after this it should still deal.
1237      */
1238     closesocket(session->fd);
1239     session->fd = INVALID_SOCKET;
1240     session->bytesPending = 0;
1241     DeleteCriticalSection(&session->cs);
1242     HeapFree(GetProcessHeap(), 0, session);
1243
1244     return NRC_GOODRET;
1245 }
1246
1247 static void NetBTCleanupAdapter(void *adapt)
1248 {
1249     TRACE("adapt %p\n", adapt);
1250     if (adapt)
1251     {
1252         NetBTAdapter *adapter = (NetBTAdapter *)adapt;
1253
1254         if (adapter->nameCache)
1255             NBNameCacheDestroy(adapter->nameCache);
1256         HeapFree(GetProcessHeap(), 0, adapt);
1257     }
1258 }
1259
1260 static void NetBTCleanup(void)
1261 {
1262     TRACE("\n");
1263     if (gNameCache)
1264     {
1265         NBNameCacheDestroy(gNameCache);
1266         gNameCache = NULL;
1267     }
1268 }
1269
1270 static UCHAR NetBTRegisterAdapter(PMIB_IPADDRROW ipRow)
1271 {
1272     UCHAR ret;
1273     NetBTAdapter *adapter;
1274     
1275     if (!ipRow) return NRC_BADDR;
1276
1277     adapter = (NetBTAdapter *)HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY,
1278      sizeof(NetBTAdapter));
1279     if (adapter)
1280     {
1281         memcpy(&adapter->ipr, ipRow, sizeof(MIB_IPADDRROW));
1282         if (!NetBIOSRegisterAdapter(gTransportID, ipRow->dwIndex, adapter))
1283         {
1284             NetBTCleanupAdapter(adapter);
1285             ret = NRC_SYSTEM;
1286         }
1287         else
1288             ret = NRC_GOODRET;
1289     }
1290     else
1291         ret = NRC_OSRESNOTAV;
1292     return ret;
1293 }
1294
1295 /* Callback for NetBIOS adapter enumeration.  Assumes closure is a pointer to
1296  * a MIB_IPADDRTABLE containing all the IP adapters needed to be added to the
1297  * NetBIOS adapter table.  For each callback, checks if the passed-in adapt
1298  * has an entry in the table; if so, this adapter was enumerated previously,
1299  * and it's enabled.  As a flag, the table's dwAddr entry is changed to
1300  * INADDR_LOOPBACK, since this is an invalid address for a NetBT adapter.
1301  * The NetBTEnum function will add any remaining adapters from the
1302  * MIB_IPADDRTABLE to the NetBIOS adapter table.
1303  */
1304 static BOOL NetBTEnumCallback(UCHAR totalLANAs, UCHAR lanaIndex,
1305  ULONG transport, const NetBIOSAdapterImpl *data, void *closure)
1306 {
1307     BOOL ret;
1308     PMIB_IPADDRTABLE table = (PMIB_IPADDRTABLE)closure;
1309
1310     if (table && data)
1311     {
1312         DWORD ndx;
1313
1314         ret = FALSE;
1315         for (ndx = 0; !ret && ndx < table->dwNumEntries; ndx++)
1316         {
1317             const NetBTAdapter *adapter = (const NetBTAdapter *)data->data;
1318
1319             if (table->table[ndx].dwIndex == adapter->ipr.dwIndex)
1320             {
1321                 NetBIOSEnableAdapter(data->lana);
1322                 table->table[ndx].dwAddr = INADDR_LOOPBACK;
1323                 ret = TRUE;
1324             }
1325         }
1326     }
1327     else
1328         ret = FALSE;
1329     return ret;
1330 }
1331
1332 /* Enumerates adapters by:
1333  * - retrieving the IP address table for the local machine
1334  * - eliminating loopback addresses from the table
1335  * - eliminating redundant addresses, that is, multiple addresses on the same
1336  *   subnet
1337  * Calls NetBIOSEnumAdapters, passing the resulting table as the callback
1338  * data.  The callback reenables each adapter that's already in the NetBIOS
1339  * table.  After NetBIOSEnumAdapters returns, this function adds any remaining
1340  * adapters to the NetBIOS table.
1341  */
1342 static UCHAR NetBTEnum(void)
1343 {
1344     UCHAR ret;
1345     DWORD size = 0;
1346
1347     TRACE("\n");
1348
1349     if (GetIpAddrTable(NULL, &size, FALSE) == ERROR_INSUFFICIENT_BUFFER)
1350     {
1351         PMIB_IPADDRTABLE ipAddrs, coalesceTable = NULL;
1352         DWORD numIPAddrs = (size - sizeof(MIB_IPADDRTABLE)) /
1353          sizeof(MIB_IPADDRROW) + 1;
1354
1355         ipAddrs = (PMIB_IPADDRTABLE)HeapAlloc(GetProcessHeap(),
1356          HEAP_ZERO_MEMORY, size);
1357         if (ipAddrs)
1358             coalesceTable = (PMIB_IPADDRTABLE)HeapAlloc(GetProcessHeap(),
1359              HEAP_ZERO_MEMORY, sizeof(MIB_IPADDRTABLE) +
1360              (min(numIPAddrs, MAX_LANA + 1) - 1) * sizeof(MIB_IPADDRROW));
1361         if (ipAddrs && coalesceTable)
1362         {
1363             if (GetIpAddrTable(ipAddrs, &size, FALSE) == ERROR_SUCCESS)
1364             {
1365                 DWORD ndx;
1366
1367                 for (ndx = 0; ndx < ipAddrs->dwNumEntries; ndx++)
1368                 {
1369                     if ((ipAddrs->table[ndx].dwAddr &
1370                      ipAddrs->table[ndx].dwMask) !=
1371                      htonl((INADDR_LOOPBACK & IN_CLASSA_NET)))
1372                     {
1373                         BOOL newNetwork = TRUE;
1374                         DWORD innerIndex;
1375
1376                         /* make sure we don't have more than one entry
1377                          * for a subnet */
1378                         for (innerIndex = 0; newNetwork &&
1379                          innerIndex < coalesceTable->dwNumEntries; innerIndex++)
1380                             if ((ipAddrs->table[ndx].dwAddr &
1381                              ipAddrs->table[ndx].dwMask) ==
1382                              (coalesceTable->table[innerIndex].dwAddr
1383                              & coalesceTable->table[innerIndex].dwMask))
1384                                 newNetwork = FALSE;
1385
1386                         if (newNetwork)
1387                             memcpy(&coalesceTable->table[
1388                              coalesceTable->dwNumEntries++],
1389                              &ipAddrs->table[ndx], sizeof(MIB_IPADDRROW));
1390                     }
1391                 }
1392
1393                 NetBIOSEnumAdapters(gTransportID, NetBTEnumCallback,
1394                  coalesceTable);
1395                 ret = NRC_GOODRET;
1396                 for (ndx = 0; ret == NRC_GOODRET &&
1397                  ndx < coalesceTable->dwNumEntries; ndx++)
1398                     if (coalesceTable->table[ndx].dwAddr != INADDR_LOOPBACK)
1399                         ret = NetBTRegisterAdapter(&coalesceTable->table[ndx]);
1400             }
1401             else
1402                 ret = NRC_SYSTEM;
1403             HeapFree(GetProcessHeap(), 0, ipAddrs);
1404             HeapFree(GetProcessHeap(), 0, coalesceTable);
1405         }
1406         else
1407             ret = NRC_OSRESNOTAV;
1408     }
1409     else
1410         ret = NRC_SYSTEM;
1411     TRACE("returning 0x%02x\n", ret);
1412     return ret;
1413 }
1414
1415 /* Initializes global variables and registers the NetBT transport */
1416 void NetBTInit(void)
1417 {
1418     HKEY hKey;
1419     NetBIOSTransport transport;
1420     LONG ret;
1421
1422     TRACE("\n");
1423
1424     gEnableDNS = TRUE;
1425     gBCastQueries = BCAST_QUERIES;
1426     gBCastQueryTimeout = BCAST_QUERY_TIMEOUT;
1427     gWINSQueries = WINS_QUERIES;
1428     gWINSQueryTimeout = WINS_QUERY_TIMEOUT;
1429     gNumWINSServers = 0;
1430     memset(gWINSServers, 0, sizeof(gWINSServers));
1431     gScopeID[0] = '\0';
1432     gCacheTimeout = CACHE_TIMEOUT;
1433
1434     /* Try to open the Win9x NetBT configuration key */
1435     ret = RegOpenKeyExA(HKEY_LOCAL_MACHINE,
1436      "\\SYSTEM\\CurrentControlSet\\Services\\VxD\\MSTCP", 0, KEY_READ, &hKey);
1437     /* If that fails, try the WinNT NetBT configuration key */
1438     if (ret != ERROR_SUCCESS)
1439         ret = RegOpenKeyExA(HKEY_LOCAL_MACHINE,
1440          "\\SYSTEM\\CurrentControlSet\\Services\\NetBT\\Parameters", 0,
1441          KEY_READ, &hKey);
1442     if (ret == ERROR_SUCCESS)
1443     {
1444         DWORD dword, size;
1445
1446         size = sizeof(dword);
1447         if (RegQueryValueExA(hKey, "EnableDNS", NULL, NULL,
1448          (LPBYTE)&dword, &size) == ERROR_SUCCESS)
1449             gEnableDNS = dword;
1450         size = sizeof(dword);
1451         if (RegQueryValueExA(hKey, "BcastNameQueryCount", NULL, NULL,
1452          (LPBYTE)&dword, &size) == ERROR_SUCCESS && dword >= MIN_QUERIES
1453          && dword <= MAX_QUERIES)
1454             gBCastQueries = dword;
1455         size = sizeof(dword);
1456         if (RegQueryValueExA(hKey, "BcastNameQueryTimeout", NULL, NULL,
1457          (LPBYTE)&dword, &size) == ERROR_SUCCESS && dword >= MIN_QUERY_TIMEOUT
1458          && dword <= MAX_QUERY_TIMEOUT)
1459             gBCastQueryTimeout = dword;
1460         size = sizeof(dword);
1461         if (RegQueryValueExA(hKey, "NameSrvQueryCount", NULL, NULL,
1462          (LPBYTE)&dword, &size) == ERROR_SUCCESS && dword >= MIN_QUERIES
1463          && dword <= MAX_QUERIES)
1464             gWINSQueries = dword;
1465         size = sizeof(dword);
1466         if (RegQueryValueExA(hKey, "NameSrvQueryTimeout", NULL, NULL,
1467          (LPBYTE)&dword, &size) == ERROR_SUCCESS && dword >= MIN_QUERY_TIMEOUT
1468          && dword <= MAX_QUERY_TIMEOUT)
1469             gWINSQueryTimeout = dword;
1470         size = MAX_DOMAIN_NAME_LEN - 1;
1471         if (RegQueryValueExA(hKey, "ScopeID", NULL, NULL, gScopeID + 1, &size)
1472          == ERROR_SUCCESS)
1473         {
1474             /* convert into L2-encoded version, suitable for use by
1475                NetBTNameEncode */
1476             char *ptr, *lenPtr;
1477
1478             for (ptr = gScopeID + 1; *ptr &&
1479              ptr - gScopeID < MAX_DOMAIN_NAME_LEN; )
1480             {
1481                 for (lenPtr = ptr - 1, *lenPtr = 0; *ptr && *ptr != '.' &&
1482                  ptr - gScopeID < MAX_DOMAIN_NAME_LEN; ptr++)
1483                     *lenPtr += 1;
1484                 ptr++;
1485             }
1486         }
1487         if (RegQueryValueExA(hKey, "CacheTimeout", NULL, NULL,
1488          (LPBYTE)&dword, &size) == ERROR_SUCCESS && dword >= MIN_CACHE_TIMEOUT)
1489             gCacheTimeout = dword;
1490         RegCloseKey(hKey);
1491     }
1492     /* WINE-specific NetBT registry settings.  Because our adapter naming is
1493      * different than MS', we can't do per-adapter WINS configuration in the
1494      * same place.  Just do a global WINS configuration instead.
1495      */
1496     if (RegOpenKeyExA(HKEY_LOCAL_MACHINE,
1497      "\\Software\\Wine\\Wine\\Config\\Network", 0, KEY_READ, &hKey)
1498      == ERROR_SUCCESS)
1499     {
1500         static const char *nsValueNames[] = { "WinsServer", "BackupWinsServer" };
1501         char nsString[16];
1502         DWORD size, ndx;
1503
1504         for (ndx = 0; ndx < sizeof(nsValueNames) / sizeof(nsValueNames[0]);
1505          ndx++)
1506         {
1507             size = sizeof(nsString) / sizeof(char);
1508             if (RegQueryValueExA(hKey, nsValueNames[ndx], NULL, NULL,
1509              (LPBYTE)nsString, &size) == ERROR_SUCCESS)
1510             {
1511                 unsigned long addr = inet_addr(nsString);
1512
1513                 if (addr != INADDR_NONE && gNumWINSServers < MAX_WINS_SERVERS)
1514                     gWINSServers[gNumWINSServers++] = addr;
1515             }
1516         }
1517         RegCloseKey(hKey);
1518     }
1519
1520     transport.enumerate      = NetBTEnum;
1521     transport.astat          = NetBTAstat;
1522     transport.findName       = NetBTFindName;
1523     transport.call           = NetBTCall;
1524     transport.send           = NetBTSend;
1525     transport.recv           = NetBTRecv;
1526     transport.hangup         = NetBTHangup;
1527     transport.cleanupAdapter = NetBTCleanupAdapter;
1528     transport.cleanup        = NetBTCleanup;
1529     memcpy(&gTransportID, TRANSPORT_NBT, sizeof(ULONG));
1530     NetBIOSRegisterTransport(gTransportID, &transport);
1531 }