msvcirt: Add implementation of streambuf::sputbackc.
[wine.git] / dlls / netapi32 / nbt.c
blob0f593d516edeb812b3bd9794e05b994274f7a3ea
1 /* Copyright (c) 2003 Juan Lang
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.
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.
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., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
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.
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.
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).
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.
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.)
65 * See also other FIXMEs in the code.
68 #include "config.h"
69 #include <stdarg.h>
71 #include "winsock2.h"
72 #include "windef.h"
73 #include "winbase.h"
74 #include "wine/debug.h"
75 #include "winreg.h"
76 #include "iphlpapi.h"
78 #include "netbios.h"
79 #include "nbnamecache.h"
81 WINE_DEFAULT_DEBUG_CHANNEL(netbios);
83 #define PORT_NBNS 137
84 #define PORT_NBDG 138
85 #define PORT_NBSS 139
87 #ifndef INADDR_NONE
88 #define INADDR_NONE ~0UL
89 #endif
91 #define NBR_ADDWORD(p,word) (*(WORD *)(p)) = htons(word)
92 #define NBR_GETWORD(p) ntohs(*(WORD *)(p))
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
106 #define MAX_NBT_NAME_SZ 255
107 #define SIMPLE_NAME_QUERY_PKT_SIZE 16 + MAX_NBT_NAME_SZ
109 #define NBNS_TYPE_NB 0x0020
110 #define NBNS_TYPE_NBSTAT 0x0021
111 #define NBNS_CLASS_INTERNET 0x00001
112 #define NBNS_HEADER_SIZE (sizeof(WORD) * 6)
113 #define NBNS_RESPONSE_AND_OPCODE 0xf800
114 #define NBNS_RESPONSE_AND_QUERY 0x8000
115 #define NBNS_REPLYCODE 0x0f
117 #define NBSS_HDRSIZE 4
119 #define NBSS_MSG 0x00
120 #define NBSS_REQ 0x81
121 #define NBSS_ACK 0x82
122 #define NBSS_NACK 0x83
123 #define NBSS_RETARGET 0x84
124 #define NBSS_KEEPALIVE 0x85
126 #define NBSS_ERR_NOT_LISTENING_ON_NAME 0x80
127 #define NBSS_ERR_NOT_LISTENING_FOR_CALLER 0x81
128 #define NBSS_ERR_BAD_NAME 0x82
129 #define NBSS_ERR_INSUFFICIENT_RESOURCES 0x83
131 #define NBSS_EXTENSION 0x01
133 typedef struct _NetBTSession
135 CRITICAL_SECTION cs;
136 SOCKET fd;
137 DWORD bytesPending;
138 } NetBTSession;
140 typedef struct _NetBTAdapter
142 MIB_IPADDRROW ipr;
143 WORD nameQueryXID;
144 struct NBNameCache *nameCache;
145 DWORD xmit_success;
146 DWORD recv_success;
147 } NetBTAdapter;
149 static ULONG gTransportID;
150 static BOOL gEnableDNS;
151 static DWORD gBCastQueries;
152 static DWORD gBCastQueryTimeout;
153 static DWORD gWINSQueries;
154 static DWORD gWINSQueryTimeout;
155 static DWORD gWINSServers[MAX_WINS_SERVERS];
156 static int gNumWINSServers;
157 static char gScopeID[MAX_SCOPE_ID_LEN];
158 static DWORD gCacheTimeout;
159 static struct NBNameCache *gNameCache;
161 /* Converts from a NetBIOS name into a Second Level Encoding-formatted name.
162 * Assumes p is not NULL and is either NULL terminated or has at most NCBNAMSZ
163 * bytes, and buffer has at least MAX_NBT_NAME_SZ bytes. Pads with space bytes
164 * if p is NULL-terminated. Returns the number of bytes stored in buffer.
166 static int NetBTNameEncode(const UCHAR *p, UCHAR *buffer)
168 int i,len=0;
170 if (!p) return 0;
171 if (!buffer) return 0;
173 buffer[len++] = NCBNAMSZ * 2;
174 for (i = 0; p[i] && i < NCBNAMSZ; i++)
176 buffer[len++] = ((p[i] & 0xf0) >> 4) + 'A';
177 buffer[len++] = (p[i] & 0x0f) + 'A';
179 while (len < NCBNAMSZ * 2)
181 buffer[len++] = 'C';
182 buffer[len++] = 'A';
184 if (*gScopeID)
186 int scopeIDLen = strlen(gScopeID);
188 memcpy(buffer + len, gScopeID, scopeIDLen);
189 len += scopeIDLen;
191 buffer[len++] = 0; /* add second terminator */
192 return len;
195 /* Creates a NBT name request packet for name in buffer. If broadcast is true,
196 * creates a broadcast request, otherwise creates a unicast request.
197 * Returns the number of bytes stored in buffer.
199 static DWORD NetBTNameReq(const UCHAR name[NCBNAMSZ], WORD xid, WORD qtype,
200 BOOL broadcast, UCHAR *buffer, int len)
202 int i = 0;
204 if (len < SIMPLE_NAME_QUERY_PKT_SIZE) return 0;
206 NBR_ADDWORD(&buffer[i],xid); i+=2; /* transaction */
207 if (broadcast)
209 NBR_ADDWORD(&buffer[i],0x0110); /* flags: r=req,op=query,rd=1,b=1 */
210 i+=2;
212 else
214 NBR_ADDWORD(&buffer[i],0x0100); /* flags: r=req,op=query,rd=1,b=0 */
215 i+=2;
217 NBR_ADDWORD(&buffer[i],0x0001); i+=2; /* one name query */
218 NBR_ADDWORD(&buffer[i],0x0000); i+=2; /* zero answers */
219 NBR_ADDWORD(&buffer[i],0x0000); i+=2; /* zero authorities */
220 NBR_ADDWORD(&buffer[i],0x0000); i+=2; /* zero additional */
222 i += NetBTNameEncode(name, &buffer[i]);
224 NBR_ADDWORD(&buffer[i],qtype); i+=2;
225 NBR_ADDWORD(&buffer[i],NBNS_CLASS_INTERNET); i+=2;
227 return i;
230 /* Sends a name query request for name on fd to destAddr. Sets SO_BROADCAST on
231 * fd if broadcast is TRUE. Assumes fd is not INVALID_SOCKET, and name is not
232 * NULL.
233 * Returns 0 on success, -1 on failure.
235 static int NetBTSendNameQuery(SOCKET fd, const UCHAR name[NCBNAMSZ], WORD xid,
236 WORD qtype, DWORD destAddr, BOOL broadcast)
238 int ret = 0, on = 1;
239 struct in_addr addr;
241 addr.s_addr = destAddr;
242 TRACE("name %s, dest addr %s\n", name, inet_ntoa(addr));
244 if (broadcast)
245 ret = setsockopt(fd, SOL_SOCKET, SO_BROADCAST, (const char*)&on, sizeof(on));
246 if(ret == 0)
248 WSABUF wsaBuf;
249 UCHAR buf[SIMPLE_NAME_QUERY_PKT_SIZE];
250 struct sockaddr_in sin;
252 memset(&sin, 0, sizeof(sin));
253 sin.sin_addr.s_addr = destAddr;
254 sin.sin_family = AF_INET;
255 sin.sin_port = htons(PORT_NBNS);
257 wsaBuf.buf = (CHAR*)buf;
258 wsaBuf.len = NetBTNameReq(name, xid, qtype, broadcast, buf,
259 sizeof(buf));
260 if (wsaBuf.len > 0)
262 DWORD bytesSent;
264 ret = WSASendTo(fd, &wsaBuf, 1, &bytesSent, 0,
265 (struct sockaddr*)&sin, sizeof(sin), NULL, NULL);
266 if (ret < 0 || bytesSent < wsaBuf.len)
267 ret = -1;
268 else
269 ret = 0;
271 else
272 ret = -1;
274 return ret;
277 typedef BOOL (*NetBTAnswerCallback)(void *data, WORD answerCount,
278 WORD answerIndex, PUCHAR rData, WORD rdLength);
280 /* Waits on fd until GetTickCount() returns a value greater than or equal to
281 * waitUntil for a name service response. If a name response matching xid
282 * is received, calls answerCallback once for each answer resource record in
283 * the response. (The callback's answerCount will be the total number of
284 * answers to expect, and answerIndex will be the 0-based index that's being
285 * sent this time.) Quits parsing if answerCallback returns FALSE.
286 * Returns NRC_GOODRET on timeout or a valid response received, something else
287 * on error.
289 static UCHAR NetBTWaitForNameResponse(const NetBTAdapter *adapter, SOCKET fd,
290 DWORD waitUntil, NetBTAnswerCallback answerCallback, void *data)
292 BOOL found = FALSE;
293 DWORD now;
294 UCHAR ret = NRC_GOODRET;
296 if (!adapter) return NRC_BADDR;
297 if (fd == INVALID_SOCKET) return NRC_BADDR;
298 if (!answerCallback) return NRC_BADDR;
300 while (!found && ret == NRC_GOODRET && (int)((now = GetTickCount()) - waitUntil) < 0)
302 DWORD msToWait = waitUntil - now;
303 struct fd_set fds;
304 struct timeval timeout = { msToWait / 1000, msToWait % 1000 };
305 int r;
307 FD_ZERO(&fds);
308 FD_SET(fd, &fds);
309 r = select(fd + 1, &fds, NULL, NULL, &timeout);
310 if (r < 0)
311 ret = NRC_SYSTEM;
312 else if (r == 1)
314 /* FIXME: magic #, is this always enough? */
315 UCHAR buffer[256];
316 int fromsize;
317 struct sockaddr_in fromaddr;
318 WORD respXID, flags, queryCount, answerCount;
319 WSABUF wsaBuf = { sizeof(buffer), (CHAR*)buffer };
320 DWORD bytesReceived, recvFlags = 0;
322 fromsize = sizeof(fromaddr);
323 r = WSARecvFrom(fd, &wsaBuf, 1, &bytesReceived, &recvFlags,
324 (struct sockaddr*)&fromaddr, &fromsize, NULL, NULL);
325 if(r < 0)
327 ret = NRC_SYSTEM;
328 break;
331 if (bytesReceived < NBNS_HEADER_SIZE)
332 continue;
334 respXID = NBR_GETWORD(buffer);
335 if (adapter->nameQueryXID != respXID)
336 continue;
338 flags = NBR_GETWORD(buffer + 2);
339 queryCount = NBR_GETWORD(buffer + 4);
340 answerCount = NBR_GETWORD(buffer + 6);
342 /* a reply shouldn't contain a query, ignore bad packet */
343 if (queryCount > 0)
344 continue;
346 if ((flags & NBNS_RESPONSE_AND_OPCODE) == NBNS_RESPONSE_AND_QUERY)
348 if ((flags & NBNS_REPLYCODE) != 0)
349 ret = NRC_NAMERR;
350 else if ((flags & NBNS_REPLYCODE) == 0 && answerCount > 0)
352 PUCHAR ptr = buffer + NBNS_HEADER_SIZE;
353 BOOL shouldContinue = TRUE;
354 WORD answerIndex = 0;
356 found = TRUE;
357 /* decode one answer at a time */
358 while (ret == NRC_GOODRET && answerIndex < answerCount &&
359 ptr - buffer < bytesReceived && shouldContinue)
361 WORD rLen;
363 /* scan past name */
364 for (; ptr[0] && ptr - buffer < bytesReceived; )
365 ptr += ptr[0] + 1;
366 ptr++;
367 ptr += 2; /* scan past type */
368 if (ptr - buffer < bytesReceived && ret == NRC_GOODRET
369 && NBR_GETWORD(ptr) == NBNS_CLASS_INTERNET)
370 ptr += sizeof(WORD);
371 else
372 ret = NRC_SYSTEM; /* parse error */
373 ptr += sizeof(DWORD); /* TTL */
374 rLen = NBR_GETWORD(ptr);
375 rLen = min(rLen, bytesReceived - (ptr - buffer));
376 ptr += sizeof(WORD);
377 shouldContinue = answerCallback(data, answerCount,
378 answerIndex, ptr, rLen);
379 ptr += rLen;
380 answerIndex++;
386 TRACE("returning 0x%02x\n", ret);
387 return ret;
390 typedef struct _NetBTNameQueryData {
391 NBNameCacheEntry *cacheEntry;
392 UCHAR ret;
393 } NetBTNameQueryData;
395 /* Name query callback function for NetBTWaitForNameResponse, creates a cache
396 * entry on the first answer, adds each address as it's called again (as long
397 * as there's space). If there's an error that should be propagated as the
398 * NetBIOS error, modifies queryData's ret member to the proper return code.
400 static BOOL NetBTFindNameAnswerCallback(void *pVoid, WORD answerCount,
401 WORD answerIndex, PUCHAR rData, WORD rLen)
403 NetBTNameQueryData *queryData = pVoid;
404 BOOL ret;
406 if (queryData)
408 if (queryData->cacheEntry == NULL)
410 queryData->cacheEntry = HeapAlloc(GetProcessHeap(), 0,
411 FIELD_OFFSET(NBNameCacheEntry, addresses[answerCount]));
412 if (queryData->cacheEntry)
413 queryData->cacheEntry->numAddresses = 0;
414 else
415 queryData->ret = NRC_OSRESNOTAV;
417 if (rLen == 6 && queryData->cacheEntry &&
418 queryData->cacheEntry->numAddresses < answerCount)
420 queryData->cacheEntry->addresses[queryData->cacheEntry->
421 numAddresses++] = *(const DWORD *)(rData + 2);
422 ret = queryData->cacheEntry->numAddresses < answerCount;
424 else
425 ret = FALSE;
427 else
428 ret = FALSE;
429 return ret;
432 /* Workhorse NetBT name lookup function. Sends a name lookup query for
433 * ncb->ncb_callname to sendTo, as a broadcast if broadcast is TRUE, using
434 * adapter->nameQueryXID as the transaction ID. Waits up to timeout
435 * milliseconds, and retries up to maxQueries times, waiting for a reply.
436 * If a valid response is received, stores the looked up addresses as a
437 * NBNameCacheEntry in *cacheEntry.
438 * Returns NRC_GOODRET on success, though this may not mean the name was
439 * resolved--check whether *cacheEntry is NULL.
441 static UCHAR NetBTNameWaitLoop(const NetBTAdapter *adapter, SOCKET fd, const NCB *ncb,
442 DWORD sendTo, BOOL broadcast, DWORD timeout, DWORD maxQueries,
443 NBNameCacheEntry **cacheEntry)
445 unsigned int queries;
446 NetBTNameQueryData queryData;
448 if (!adapter) return NRC_BADDR;
449 if (fd == INVALID_SOCKET) return NRC_BADDR;
450 if (!ncb) return NRC_BADDR;
451 if (!cacheEntry) return NRC_BADDR;
453 queryData.cacheEntry = NULL;
454 queryData.ret = NRC_GOODRET;
455 for (queries = 0; queryData.cacheEntry == NULL && queries < maxQueries;
456 queries++)
458 if (!NCB_CANCELLED(ncb))
460 int r = NetBTSendNameQuery(fd, ncb->ncb_callname,
461 adapter->nameQueryXID, NBNS_TYPE_NB, sendTo, broadcast);
463 if (r == 0)
464 queryData.ret = NetBTWaitForNameResponse(adapter, fd,
465 GetTickCount() + timeout, NetBTFindNameAnswerCallback,
466 &queryData);
467 else
468 queryData.ret = NRC_SYSTEM;
470 else
471 queryData.ret = NRC_CMDCAN;
473 if (queryData.cacheEntry)
475 memcpy(queryData.cacheEntry->name, ncb->ncb_callname, NCBNAMSZ);
476 memcpy(queryData.cacheEntry->nbname, ncb->ncb_callname, NCBNAMSZ);
478 *cacheEntry = queryData.cacheEntry;
479 return queryData.ret;
482 /* Attempts to add cacheEntry to the name cache in *nameCache; if *nameCache
483 * has not yet been created, creates it, using gCacheTimeout as the cache
484 * entry timeout. If memory allocation fails, or if NBNameCacheAddEntry fails,
485 * frees cacheEntry.
486 * Returns NRC_GOODRET on success, and something else on failure.
488 static UCHAR NetBTStoreCacheEntry(struct NBNameCache **nameCache,
489 NBNameCacheEntry *cacheEntry)
491 UCHAR ret;
493 if (!nameCache) return NRC_BADDR;
494 if (!cacheEntry) return NRC_BADDR;
496 if (!*nameCache)
497 *nameCache = NBNameCacheCreate(GetProcessHeap(), gCacheTimeout);
498 if (*nameCache)
499 ret = NBNameCacheAddEntry(*nameCache, cacheEntry)
500 ? NRC_GOODRET : NRC_OSRESNOTAV;
501 else
503 HeapFree(GetProcessHeap(), 0, cacheEntry);
504 ret = NRC_OSRESNOTAV;
506 return ret;
509 /* Attempts to resolve name using inet_addr(), then gethostbyname() if
510 * gEnableDNS is TRUE, if the suffix byte is either <00> or <20>. If the name
511 * can be looked up, returns 0 and stores the looked up addresses as a
512 * NBNameCacheEntry in *cacheEntry.
513 * Returns NRC_GOODRET on success, though this may not mean the name was
514 * resolved--check whether *cacheEntry is NULL. Returns something else on
515 * error.
517 static UCHAR NetBTinetResolve(const UCHAR name[NCBNAMSZ],
518 NBNameCacheEntry **cacheEntry)
520 UCHAR ret = NRC_GOODRET;
522 TRACE("name %s, cacheEntry %p\n", name, cacheEntry);
524 if (!name) return NRC_BADDR;
525 if (!cacheEntry) return NRC_BADDR;
527 if (isalnum(name[0]) && (name[NCBNAMSZ - 1] == 0 ||
528 name[NCBNAMSZ - 1] == 0x20))
530 CHAR toLookup[NCBNAMSZ];
531 unsigned int i;
533 for (i = 0; i < NCBNAMSZ - 1 && name[i] && name[i] != ' '; i++)
534 toLookup[i] = name[i];
535 toLookup[i] = '\0';
537 if (isdigit(toLookup[0]))
539 unsigned long addr = inet_addr(toLookup);
541 if (addr != INADDR_NONE)
543 *cacheEntry = HeapAlloc(GetProcessHeap(), 0,
544 FIELD_OFFSET(NBNameCacheEntry, addresses[1]));
545 if (*cacheEntry)
547 memcpy((*cacheEntry)->name, name, NCBNAMSZ);
548 memset((*cacheEntry)->nbname, 0, NCBNAMSZ);
549 (*cacheEntry)->nbname[0] = '*';
550 (*cacheEntry)->numAddresses = 1;
551 (*cacheEntry)->addresses[0] = addr;
553 else
554 ret = NRC_OSRESNOTAV;
557 if (gEnableDNS && ret == NRC_GOODRET && !*cacheEntry)
559 struct hostent *host;
561 if ((host = gethostbyname(toLookup)) != NULL)
563 for (i = 0; host->h_addr_list && host->h_addr_list[i]; i++)
565 if (host->h_addr_list && host->h_addr_list[0])
567 *cacheEntry = HeapAlloc(GetProcessHeap(), 0,
568 FIELD_OFFSET(NBNameCacheEntry, addresses[i]));
569 if (*cacheEntry)
571 memcpy((*cacheEntry)->name, name, NCBNAMSZ);
572 memset((*cacheEntry)->nbname, 0, NCBNAMSZ);
573 (*cacheEntry)->nbname[0] = '*';
574 (*cacheEntry)->numAddresses = i;
575 for (i = 0; i < (*cacheEntry)->numAddresses; i++)
576 (*cacheEntry)->addresses[i] =
577 *(DWORD*)host->h_addr_list[i];
579 else
580 ret = NRC_OSRESNOTAV;
586 TRACE("returning 0x%02x\n", ret);
587 return ret;
590 /* Looks up the name in ncb->ncb_callname, first in the name caches (global
591 * and this adapter's), then using gethostbyname(), next by WINS if configured,
592 * and finally using broadcast NetBT name resolution. In NBT parlance, this
593 * makes this an "H-node". Stores an entry in the appropriate name cache for a
594 * found node, and returns it as *cacheEntry.
595 * Assumes data, ncb, and cacheEntry are not NULL.
596 * Returns NRC_GOODRET on success--which doesn't mean the name was resolved,
597 * just that all name lookup operations completed successfully--and something
598 * else on failure. *cacheEntry will be NULL if the name was not found.
600 static UCHAR NetBTInternalFindName(NetBTAdapter *adapter, PNCB ncb,
601 const NBNameCacheEntry **cacheEntry)
603 UCHAR ret = NRC_GOODRET;
605 TRACE("adapter %p, ncb %p, cacheEntry %p\n", adapter, ncb, cacheEntry);
607 if (!cacheEntry) return NRC_BADDR;
608 *cacheEntry = NULL;
610 if (!adapter) return NRC_BADDR;
611 if (!ncb) return NRC_BADDR;
613 if (ncb->ncb_callname[0] == '*')
614 ret = NRC_NOWILD;
615 else
617 *cacheEntry = NBNameCacheFindEntry(gNameCache, ncb->ncb_callname);
618 if (!*cacheEntry)
619 *cacheEntry = NBNameCacheFindEntry(adapter->nameCache,
620 ncb->ncb_callname);
621 if (!*cacheEntry)
623 NBNameCacheEntry *newEntry = NULL;
625 ret = NetBTinetResolve(ncb->ncb_callname, &newEntry);
626 if (ret == NRC_GOODRET && newEntry)
628 ret = NetBTStoreCacheEntry(&gNameCache, newEntry);
629 if (ret != NRC_GOODRET)
630 newEntry = NULL;
632 else
634 SOCKET fd = WSASocketA(PF_INET, SOCK_DGRAM, IPPROTO_UDP, NULL,
635 0, WSA_FLAG_OVERLAPPED);
637 if(fd == INVALID_SOCKET)
638 ret = NRC_OSRESNOTAV;
639 else
641 int winsNdx;
643 adapter->nameQueryXID++;
644 for (winsNdx = 0; ret == NRC_GOODRET && *cacheEntry == NULL
645 && winsNdx < gNumWINSServers; winsNdx++)
646 ret = NetBTNameWaitLoop(adapter, fd, ncb,
647 gWINSServers[winsNdx], FALSE, gWINSQueryTimeout,
648 gWINSQueries, &newEntry);
649 if (ret == NRC_GOODRET && newEntry)
651 ret = NetBTStoreCacheEntry(&gNameCache, newEntry);
652 if (ret != NRC_GOODRET)
653 newEntry = NULL;
655 if (ret == NRC_GOODRET && *cacheEntry == NULL)
657 DWORD bcastAddr =
658 adapter->ipr.dwAddr & adapter->ipr.dwMask;
660 if (adapter->ipr.dwBCastAddr)
661 bcastAddr |= ~adapter->ipr.dwMask;
662 ret = NetBTNameWaitLoop(adapter, fd, ncb, bcastAddr,
663 TRUE, gBCastQueryTimeout, gBCastQueries, &newEntry);
664 if (ret == NRC_GOODRET && newEntry)
666 ret = NetBTStoreCacheEntry(&adapter->nameCache,
667 newEntry);
668 if (ret != NRC_GOODRET)
669 newEntry = NULL;
672 closesocket(fd);
675 *cacheEntry = newEntry;
678 TRACE("returning 0x%02x\n", ret);
679 return ret;
682 typedef struct _NetBTNodeQueryData
684 BOOL gotResponse;
685 PADAPTER_STATUS astat;
686 WORD astatLen;
687 } NetBTNodeQueryData;
689 /* Callback function for NetBTAstatRemote, parses the rData for the node
690 * status and name list of the remote node. Always returns FALSE, since
691 * there's never more than one answer we care about in a node status response.
693 static BOOL NetBTNodeStatusAnswerCallback(void *pVoid, WORD answerCount,
694 WORD answerIndex, PUCHAR rData, WORD rLen)
696 NetBTNodeQueryData *data = pVoid;
698 if (data && !data->gotResponse && rData && rLen >= 1)
700 /* num names is first byte; each name is NCBNAMSZ + 2 bytes */
701 if (rLen >= rData[0] * (NCBNAMSZ + 2))
703 WORD i;
704 PUCHAR src;
705 PNAME_BUFFER dst;
707 data->gotResponse = TRUE;
708 data->astat->name_count = rData[0];
709 for (i = 0, src = rData + 1,
710 dst = (PNAME_BUFFER)((PUCHAR)data->astat +
711 sizeof(ADAPTER_STATUS));
712 i < data->astat->name_count && src - rData < rLen &&
713 (PUCHAR)dst - (PUCHAR)data->astat < data->astatLen;
714 i++, dst++, src += NCBNAMSZ + 2)
716 UCHAR flags = *(src + NCBNAMSZ);
718 memcpy(dst->name, src, NCBNAMSZ);
719 /* we won't actually see a registering name in the returned
720 * response. It's useful to see if no other flags are set; if
721 * none are, then the name is registered. */
722 dst->name_flags = REGISTERING;
723 if (flags & 0x80)
724 dst->name_flags |= GROUP_NAME;
725 if (flags & 0x10)
726 dst->name_flags |= DEREGISTERED;
727 if (flags & 0x08)
728 dst->name_flags |= DUPLICATE;
729 if (dst->name_flags == REGISTERING)
730 dst->name_flags = REGISTERED;
732 /* arbitrarily set HW type to Ethernet */
733 data->astat->adapter_type = 0xfe;
734 if (src - rData < rLen)
735 memcpy(data->astat->adapter_address, src,
736 min(rLen - (src - rData), 6));
739 return FALSE;
742 /* This uses the WINS timeout and query values, as they're the
743 * UCAST_REQ_RETRY_TIMEOUT and UCAST_REQ_RETRY_COUNT according to the RFCs.
745 static UCHAR NetBTAstatRemote(NetBTAdapter *adapter, PNCB ncb)
747 UCHAR ret = NRC_GOODRET;
748 const NBNameCacheEntry *cacheEntry = NULL;
750 TRACE("adapter %p, NCB %p\n", adapter, ncb);
752 if (!adapter) return NRC_BADDR;
753 if (!ncb) return NRC_INVADDRESS;
755 ret = NetBTInternalFindName(adapter, ncb, &cacheEntry);
756 if (ret == NRC_GOODRET && cacheEntry)
758 if (cacheEntry->numAddresses > 0)
760 SOCKET fd = WSASocketA(PF_INET, SOCK_DGRAM, IPPROTO_UDP, NULL, 0,
761 WSA_FLAG_OVERLAPPED);
763 if(fd == INVALID_SOCKET)
764 ret = NRC_OSRESNOTAV;
765 else
767 NetBTNodeQueryData queryData;
768 DWORD queries;
769 PADAPTER_STATUS astat = (PADAPTER_STATUS)ncb->ncb_buffer;
771 adapter->nameQueryXID++;
772 astat->name_count = 0;
773 queryData.gotResponse = FALSE;
774 queryData.astat = astat;
775 queryData.astatLen = ncb->ncb_length;
776 for (queries = 0; !queryData.gotResponse &&
777 queries < gWINSQueries; queries++)
779 if (!NCB_CANCELLED(ncb))
781 int r = NetBTSendNameQuery(fd, ncb->ncb_callname,
782 adapter->nameQueryXID, NBNS_TYPE_NBSTAT,
783 cacheEntry->addresses[0], FALSE);
785 if (r == 0)
786 ret = NetBTWaitForNameResponse(adapter, fd,
787 GetTickCount() + gWINSQueryTimeout,
788 NetBTNodeStatusAnswerCallback, &queryData);
789 else
790 ret = NRC_SYSTEM;
792 else
793 ret = NRC_CMDCAN;
795 closesocket(fd);
798 else
799 ret = NRC_CMDTMO;
801 else if (ret == NRC_CMDCAN)
802 ; /* do nothing, we were cancelled */
803 else
804 ret = NRC_CMDTMO;
805 TRACE("returning 0x%02x\n", ret);
806 return ret;
809 static UCHAR NetBTAstat(void *adapt, PNCB ncb)
811 NetBTAdapter *adapter = adapt;
812 UCHAR ret;
814 TRACE("adapt %p, NCB %p\n", adapt, ncb);
816 if (!adapter) return NRC_ENVNOTDEF;
817 if (!ncb) return NRC_INVADDRESS;
818 if (!ncb->ncb_buffer) return NRC_BADDR;
819 if (ncb->ncb_length < sizeof(ADAPTER_STATUS)) return NRC_BUFLEN;
821 if (ncb->ncb_callname[0] == '*')
823 DWORD physAddrLen;
824 MIB_IFROW ifRow;
825 PADAPTER_STATUS astat = (PADAPTER_STATUS)ncb->ncb_buffer;
827 memset(astat, 0, sizeof(ADAPTER_STATUS));
828 astat->rev_major = 3;
829 ifRow.dwIndex = adapter->ipr.dwIndex;
830 if (GetIfEntry(&ifRow) != NO_ERROR)
831 ret = NRC_BRIDGE;
832 else
834 physAddrLen = min(ifRow.dwPhysAddrLen, 6);
835 if (physAddrLen > 0)
836 memcpy(astat->adapter_address, ifRow.bPhysAddr, physAddrLen);
837 /* doubt anyone cares, but why not.. */
838 if (ifRow.dwType == MIB_IF_TYPE_TOKENRING)
839 astat->adapter_type = 0xff;
840 else
841 astat->adapter_type = 0xfe; /* for Ethernet */
842 astat->max_sess_pkt_size = 0xffff;
843 astat->xmit_success = adapter->xmit_success;
844 astat->recv_success = adapter->recv_success;
845 ret = NRC_GOODRET;
848 else
849 ret = NetBTAstatRemote(adapter, ncb);
850 TRACE("returning 0x%02x\n", ret);
851 return ret;
854 static UCHAR NetBTFindName(void *adapt, PNCB ncb)
856 NetBTAdapter *adapter = adapt;
857 UCHAR ret;
858 const NBNameCacheEntry *cacheEntry = NULL;
859 PFIND_NAME_HEADER foundName;
861 TRACE("adapt %p, NCB %p\n", adapt, ncb);
863 if (!adapter) return NRC_ENVNOTDEF;
864 if (!ncb) return NRC_INVADDRESS;
865 if (!ncb->ncb_buffer) return NRC_BADDR;
866 if (ncb->ncb_length < sizeof(FIND_NAME_HEADER)) return NRC_BUFLEN;
868 foundName = (PFIND_NAME_HEADER)ncb->ncb_buffer;
869 memset(foundName, 0, sizeof(FIND_NAME_HEADER));
871 ret = NetBTInternalFindName(adapter, ncb, &cacheEntry);
872 if (ret == NRC_GOODRET)
874 if (cacheEntry)
876 DWORD spaceFor = min((ncb->ncb_length - sizeof(FIND_NAME_HEADER)) /
877 sizeof(FIND_NAME_BUFFER), cacheEntry->numAddresses);
878 DWORD ndx;
880 for (ndx = 0; ndx < spaceFor; ndx++)
882 PFIND_NAME_BUFFER findNameBuffer;
884 findNameBuffer =
885 (PFIND_NAME_BUFFER)((PUCHAR)foundName +
886 sizeof(FIND_NAME_HEADER) + foundName->node_count *
887 sizeof(FIND_NAME_BUFFER));
888 memset(findNameBuffer->destination_addr, 0, 2);
889 memcpy(findNameBuffer->destination_addr + 2,
890 &adapter->ipr.dwAddr, sizeof(DWORD));
891 memset(findNameBuffer->source_addr, 0, 2);
892 memcpy(findNameBuffer->source_addr + 2,
893 &cacheEntry->addresses[ndx], sizeof(DWORD));
894 foundName->node_count++;
896 if (spaceFor < cacheEntry->numAddresses)
897 ret = NRC_BUFLEN;
899 else
900 ret = NRC_CMDTMO;
902 TRACE("returning 0x%02x\n", ret);
903 return ret;
906 static UCHAR NetBTSessionReq(SOCKET fd, const UCHAR *calledName,
907 const UCHAR *callingName)
909 UCHAR buffer[NBSS_HDRSIZE + MAX_DOMAIN_NAME_LEN * 2], ret;
910 int r;
911 unsigned int len = 0;
912 DWORD bytesSent, bytesReceived, recvFlags = 0;
913 WSABUF wsaBuf;
915 buffer[0] = NBSS_REQ;
916 buffer[1] = 0;
918 len += NetBTNameEncode(calledName, &buffer[NBSS_HDRSIZE]);
919 len += NetBTNameEncode(callingName, &buffer[NBSS_HDRSIZE + len]);
921 NBR_ADDWORD(&buffer[2], len);
923 wsaBuf.len = len + NBSS_HDRSIZE;
924 wsaBuf.buf = (char*)buffer;
926 r = WSASend(fd, &wsaBuf, 1, &bytesSent, 0, NULL, NULL);
927 if(r < 0 || bytesSent < len + NBSS_HDRSIZE)
929 ERR("send failed\n");
930 return NRC_SABORT;
933 /* I've already set the recv timeout on this socket (if it supports it), so
934 * just block. Hopefully we'll always receive the session acknowledgement
935 * within one timeout.
937 wsaBuf.len = NBSS_HDRSIZE + 1;
938 r = WSARecv(fd, &wsaBuf, 1, &bytesReceived, &recvFlags, NULL, NULL);
939 if (r < 0 || bytesReceived < NBSS_HDRSIZE)
940 ret = NRC_SABORT;
941 else if (buffer[0] == NBSS_NACK)
943 if (r == NBSS_HDRSIZE + 1)
945 switch (buffer[NBSS_HDRSIZE])
947 case NBSS_ERR_INSUFFICIENT_RESOURCES:
948 ret = NRC_REMTFUL;
949 break;
950 default:
951 ret = NRC_NOCALL;
954 else
955 ret = NRC_NOCALL;
957 else if (buffer[0] == NBSS_RETARGET)
959 FIXME("Got a session retarget, can't deal\n");
960 ret = NRC_NOCALL;
962 else if (buffer[0] == NBSS_ACK)
963 ret = NRC_GOODRET;
964 else
965 ret = NRC_SYSTEM;
967 TRACE("returning 0x%02x\n", ret);
968 return ret;
971 static UCHAR NetBTCall(void *adapt, PNCB ncb, void **sess)
973 NetBTAdapter *adapter = adapt;
974 UCHAR ret;
975 const NBNameCacheEntry *cacheEntry = NULL;
977 TRACE("adapt %p, ncb %p\n", adapt, ncb);
979 if (!adapter) return NRC_ENVNOTDEF;
980 if (!ncb) return NRC_INVADDRESS;
981 if (!sess) return NRC_BADDR;
983 ret = NetBTInternalFindName(adapter, ncb, &cacheEntry);
984 if (ret == NRC_GOODRET)
986 if (cacheEntry && cacheEntry->numAddresses > 0)
988 SOCKET fd;
990 fd = WSASocketA(PF_INET, SOCK_STREAM, IPPROTO_TCP, NULL, 0,
991 WSA_FLAG_OVERLAPPED);
992 if (fd != INVALID_SOCKET)
994 DWORD timeout;
995 struct sockaddr_in sin;
997 if (ncb->ncb_rto > 0)
999 timeout = ncb->ncb_rto * 500;
1000 setsockopt(fd, SOL_SOCKET, SO_RCVTIMEO, (char*)&timeout,
1001 sizeof(timeout));
1003 if (ncb->ncb_sto > 0)
1005 timeout = ncb->ncb_sto * 500;
1006 setsockopt(fd, SOL_SOCKET, SO_SNDTIMEO, (char*)&timeout,
1007 sizeof(timeout));
1010 memset(&sin, 0, sizeof(sin));
1011 memcpy(&sin.sin_addr, &cacheEntry->addresses[0],
1012 sizeof(sin.sin_addr));
1013 sin.sin_family = AF_INET;
1014 sin.sin_port = htons(PORT_NBSS);
1015 /* FIXME: use nonblocking mode for the socket, check the
1016 * cancel flag periodically
1018 if (connect(fd, (struct sockaddr *)&sin, sizeof(sin))
1019 == SOCKET_ERROR)
1020 ret = NRC_CMDTMO;
1021 else
1023 static const UCHAR fakedCalledName[] = "*SMBSERVER";
1024 const UCHAR *calledParty = cacheEntry->nbname[0] == '*'
1025 ? fakedCalledName : cacheEntry->nbname;
1027 ret = NetBTSessionReq(fd, calledParty, ncb->ncb_name);
1028 if (ret != NRC_GOODRET && calledParty[0] == '*')
1030 FIXME("NBT session to \"*SMBSERVER\" refused,\n");
1031 FIXME("should try finding name using ASTAT\n");
1034 if (ret != NRC_GOODRET)
1035 closesocket(fd);
1036 else
1038 NetBTSession *session = HeapAlloc(
1039 GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(NetBTSession));
1041 if (session)
1043 session->fd = fd;
1044 InitializeCriticalSection(&session->cs);
1045 session->cs.DebugInfo->Spare[0] = (DWORD_PTR)(__FILE__ ": NetBTSession.cs");
1046 *sess = session;
1048 else
1050 ret = NRC_OSRESNOTAV;
1051 closesocket(fd);
1055 else
1056 ret = NRC_OSRESNOTAV;
1058 else
1059 ret = NRC_NAMERR;
1061 TRACE("returning 0x%02x\n", ret);
1062 return ret;
1065 /* Notice that I don't protect against multiple thread access to NetBTSend.
1066 * This is because I don't update any data in the adapter, and I only make a
1067 * single call to WSASend, which I assume to act atomically (not interleaving
1068 * data from other threads).
1069 * I don't lock, because I only depend on the fd being valid, and this won't be
1070 * true until a session setup is completed.
1072 static UCHAR NetBTSend(void *adapt, void *sess, PNCB ncb)
1074 NetBTAdapter *adapter = adapt;
1075 NetBTSession *session = sess;
1076 UCHAR buffer[NBSS_HDRSIZE], ret;
1077 int r;
1078 WSABUF wsaBufs[2];
1079 DWORD bytesSent;
1081 TRACE("adapt %p, session %p, NCB %p\n", adapt, session, ncb);
1083 if (!adapter) return NRC_ENVNOTDEF;
1084 if (!ncb) return NRC_INVADDRESS;
1085 if (!ncb->ncb_buffer) return NRC_BADDR;
1086 if (!session) return NRC_SNUMOUT;
1087 if (session->fd == INVALID_SOCKET) return NRC_SNUMOUT;
1089 buffer[0] = NBSS_MSG;
1090 buffer[1] = 0;
1091 NBR_ADDWORD(&buffer[2], ncb->ncb_length);
1093 wsaBufs[0].len = NBSS_HDRSIZE;
1094 wsaBufs[0].buf = (char*)buffer;
1095 wsaBufs[1].len = ncb->ncb_length;
1096 wsaBufs[1].buf = (char*)ncb->ncb_buffer;
1098 r = WSASend(session->fd, wsaBufs, sizeof(wsaBufs) / sizeof(wsaBufs[0]),
1099 &bytesSent, 0, NULL, NULL);
1100 if (r == SOCKET_ERROR)
1102 NetBIOSHangupSession(ncb);
1103 ret = NRC_SABORT;
1105 else if (bytesSent < NBSS_HDRSIZE + ncb->ncb_length)
1107 FIXME("Only sent %d bytes (of %d), hanging up session\n", bytesSent,
1108 NBSS_HDRSIZE + ncb->ncb_length);
1109 NetBIOSHangupSession(ncb);
1110 ret = NRC_SABORT;
1112 else
1114 ret = NRC_GOODRET;
1115 adapter->xmit_success++;
1117 TRACE("returning 0x%02x\n", ret);
1118 return ret;
1121 static UCHAR NetBTRecv(void *adapt, void *sess, PNCB ncb)
1123 NetBTAdapter *adapter = adapt;
1124 NetBTSession *session = sess;
1125 UCHAR buffer[NBSS_HDRSIZE], ret;
1126 int r;
1127 WSABUF wsaBufs[2];
1128 DWORD bufferCount, bytesReceived, flags;
1130 TRACE("adapt %p, session %p, NCB %p\n", adapt, session, ncb);
1132 if (!adapter) return NRC_ENVNOTDEF;
1133 if (!ncb) return NRC_BADDR;
1134 if (!ncb->ncb_buffer) return NRC_BADDR;
1135 if (!session) return NRC_SNUMOUT;
1136 if (session->fd == INVALID_SOCKET) return NRC_SNUMOUT;
1138 EnterCriticalSection(&session->cs);
1139 bufferCount = 0;
1140 if (session->bytesPending == 0)
1142 bufferCount++;
1143 wsaBufs[0].len = NBSS_HDRSIZE;
1144 wsaBufs[0].buf = (char*)buffer;
1146 wsaBufs[bufferCount].len = ncb->ncb_length;
1147 wsaBufs[bufferCount].buf = (char*)ncb->ncb_buffer;
1148 bufferCount++;
1150 flags = 0;
1151 /* FIXME: should poll a bit so I can check the cancel flag */
1152 r = WSARecv(session->fd, wsaBufs, bufferCount, &bytesReceived, &flags,
1153 NULL, NULL);
1154 if (r == SOCKET_ERROR && WSAGetLastError() != WSAEWOULDBLOCK)
1156 LeaveCriticalSection(&session->cs);
1157 ERR("Receive error, WSAGetLastError() returns %d\n", WSAGetLastError());
1158 NetBIOSHangupSession(ncb);
1159 ret = NRC_SABORT;
1161 else if (NCB_CANCELLED(ncb))
1163 LeaveCriticalSection(&session->cs);
1164 ret = NRC_CMDCAN;
1166 else
1168 if (bufferCount == 2)
1170 if (buffer[0] == NBSS_KEEPALIVE)
1172 LeaveCriticalSection(&session->cs);
1173 FIXME("Oops, received a session keepalive and lost my place\n");
1174 /* need to read another session header until we get a session
1175 * message header. */
1176 NetBIOSHangupSession(ncb);
1177 ret = NRC_SABORT;
1178 goto error;
1180 else if (buffer[0] != NBSS_MSG)
1182 LeaveCriticalSection(&session->cs);
1183 FIXME("Received unexpected session msg type %d\n", buffer[0]);
1184 NetBIOSHangupSession(ncb);
1185 ret = NRC_SABORT;
1186 goto error;
1188 else
1190 if (buffer[1] & NBSS_EXTENSION)
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 goto error;
1198 else
1200 session->bytesPending = NBSS_HDRSIZE
1201 + NBR_GETWORD(&buffer[2]) - bytesReceived;
1202 ncb->ncb_length = bytesReceived - NBSS_HDRSIZE;
1203 LeaveCriticalSection(&session->cs);
1207 else
1209 if (bytesReceived < session->bytesPending)
1210 session->bytesPending -= bytesReceived;
1211 else
1212 session->bytesPending = 0;
1213 LeaveCriticalSection(&session->cs);
1214 ncb->ncb_length = bytesReceived;
1216 if (session->bytesPending > 0)
1217 ret = NRC_INCOMP;
1218 else
1220 ret = NRC_GOODRET;
1221 adapter->recv_success++;
1224 error:
1225 TRACE("returning 0x%02x\n", ret);
1226 return ret;
1229 static UCHAR NetBTHangup(void *adapt, void *sess)
1231 NetBTSession *session = sess;
1233 TRACE("adapt %p, session %p\n", adapt, session);
1235 if (!session) return NRC_SNUMOUT;
1237 /* I don't lock the session, because NetBTRecv knows not to decrement
1238 * past 0, so if a receive completes after this it should still deal.
1240 closesocket(session->fd);
1241 session->fd = INVALID_SOCKET;
1242 session->bytesPending = 0;
1243 session->cs.DebugInfo->Spare[0] = 0;
1244 DeleteCriticalSection(&session->cs);
1245 HeapFree(GetProcessHeap(), 0, session);
1247 return NRC_GOODRET;
1250 static void NetBTCleanupAdapter(void *adapt)
1252 TRACE("adapt %p\n", adapt);
1253 if (adapt)
1255 NetBTAdapter *adapter = adapt;
1257 if (adapter->nameCache)
1258 NBNameCacheDestroy(adapter->nameCache);
1259 HeapFree(GetProcessHeap(), 0, adapt);
1263 static void NetBTCleanup(void)
1265 TRACE("\n");
1266 if (gNameCache)
1268 NBNameCacheDestroy(gNameCache);
1269 gNameCache = NULL;
1273 static UCHAR NetBTRegisterAdapter(const MIB_IPADDRROW *ipRow)
1275 UCHAR ret;
1276 NetBTAdapter *adapter;
1278 if (!ipRow) return NRC_BADDR;
1280 adapter = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(NetBTAdapter));
1281 if (adapter)
1283 adapter->ipr = *ipRow;
1284 if (!NetBIOSRegisterAdapter(gTransportID, ipRow->dwIndex, adapter))
1286 NetBTCleanupAdapter(adapter);
1287 ret = NRC_SYSTEM;
1289 else
1290 ret = NRC_GOODRET;
1292 else
1293 ret = NRC_OSRESNOTAV;
1294 return ret;
1297 /* Callback for NetBIOS adapter enumeration. Assumes closure is a pointer to
1298 * a MIB_IPADDRTABLE containing all the IP adapters needed to be added to the
1299 * NetBIOS adapter table. For each callback, checks if the passed-in adapt
1300 * has an entry in the table; if so, this adapter was enumerated previously,
1301 * and it's enabled. As a flag, the table's dwAddr entry is changed to
1302 * INADDR_LOOPBACK, since this is an invalid address for a NetBT adapter.
1303 * The NetBTEnum function will add any remaining adapters from the
1304 * MIB_IPADDRTABLE to the NetBIOS adapter table.
1306 static BOOL NetBTEnumCallback(UCHAR totalLANAs, UCHAR lanaIndex,
1307 ULONG transport, const NetBIOSAdapterImpl *data, void *closure)
1309 BOOL ret;
1310 PMIB_IPADDRTABLE table = closure;
1312 if (table && data)
1314 DWORD ndx;
1316 ret = FALSE;
1317 for (ndx = 0; !ret && ndx < table->dwNumEntries; ndx++)
1319 const NetBTAdapter *adapter = data->data;
1321 if (table->table[ndx].dwIndex == adapter->ipr.dwIndex)
1323 NetBIOSEnableAdapter(data->lana);
1324 table->table[ndx].dwAddr = INADDR_LOOPBACK;
1325 ret = TRUE;
1329 else
1330 ret = FALSE;
1331 return ret;
1334 /* Enumerates adapters by:
1335 * - retrieving the IP address table for the local machine
1336 * - eliminating loopback addresses from the table
1337 * - eliminating redundant addresses, that is, multiple addresses on the same
1338 * subnet
1339 * Calls NetBIOSEnumAdapters, passing the resulting table as the callback
1340 * data. The callback reenables each adapter that's already in the NetBIOS
1341 * table. After NetBIOSEnumAdapters returns, this function adds any remaining
1342 * adapters to the NetBIOS table.
1344 static UCHAR NetBTEnum(void)
1346 UCHAR ret;
1347 DWORD size = 0;
1349 TRACE("\n");
1351 if (GetIpAddrTable(NULL, &size, FALSE) == ERROR_INSUFFICIENT_BUFFER)
1353 PMIB_IPADDRTABLE ipAddrs, coalesceTable = NULL;
1354 DWORD numIPAddrs = (size - sizeof(MIB_IPADDRTABLE)) /
1355 sizeof(MIB_IPADDRROW) + 1;
1357 ipAddrs = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, size);
1358 if (ipAddrs)
1359 coalesceTable = HeapAlloc(GetProcessHeap(),
1360 HEAP_ZERO_MEMORY, sizeof(MIB_IPADDRTABLE) +
1361 (min(numIPAddrs, MAX_LANA + 1) - 1) * sizeof(MIB_IPADDRROW));
1362 if (ipAddrs && coalesceTable)
1364 if (GetIpAddrTable(ipAddrs, &size, FALSE) == ERROR_SUCCESS)
1366 DWORD ndx;
1368 for (ndx = 0; ndx < ipAddrs->dwNumEntries; ndx++)
1370 if ((ipAddrs->table[ndx].dwAddr &
1371 ipAddrs->table[ndx].dwMask) !=
1372 htonl((INADDR_LOOPBACK & IN_CLASSA_NET)))
1374 BOOL newNetwork = TRUE;
1375 DWORD innerIndex;
1377 /* make sure we don't have more than one entry
1378 * for a subnet */
1379 for (innerIndex = 0; newNetwork &&
1380 innerIndex < coalesceTable->dwNumEntries; innerIndex++)
1381 if ((ipAddrs->table[ndx].dwAddr &
1382 ipAddrs->table[ndx].dwMask) ==
1383 (coalesceTable->table[innerIndex].dwAddr
1384 & coalesceTable->table[innerIndex].dwMask))
1385 newNetwork = FALSE;
1387 if (newNetwork)
1388 memcpy(&coalesceTable->table[
1389 coalesceTable->dwNumEntries++],
1390 &ipAddrs->table[ndx], sizeof(MIB_IPADDRROW));
1394 NetBIOSEnumAdapters(gTransportID, NetBTEnumCallback,
1395 coalesceTable);
1396 ret = NRC_GOODRET;
1397 for (ndx = 0; ret == NRC_GOODRET &&
1398 ndx < coalesceTable->dwNumEntries; ndx++)
1399 if (coalesceTable->table[ndx].dwAddr != INADDR_LOOPBACK)
1400 ret = NetBTRegisterAdapter(&coalesceTable->table[ndx]);
1402 else
1403 ret = NRC_SYSTEM;
1404 HeapFree(GetProcessHeap(), 0, ipAddrs);
1405 HeapFree(GetProcessHeap(), 0, coalesceTable);
1407 else
1408 ret = NRC_OSRESNOTAV;
1410 else
1411 ret = NRC_SYSTEM;
1412 TRACE("returning 0x%02x\n", ret);
1413 return ret;
1416 static const WCHAR VxD_MSTCPW[] = { 'S','Y','S','T','E','M','\\','C','u','r',
1417 'r','e','n','t','C','o','n','t','r','o','l','S','e','t','\\','S','e','r','v',
1418 'i','c','e','s','\\','V','x','D','\\','M','S','T','C','P','\0' };
1419 static const WCHAR NetBT_ParametersW[] = { 'S','Y','S','T','E','M','\\','C','u',
1420 'r','r','e','n','t','C','o','n','t','r','o','l','S','e','t','\\','S','e','r',
1421 'v','i','c','e','s','\\','N','e','t','B','T','\\','P','a','r','a','m','e','t',
1422 'e','r','s','\0' };
1423 static const WCHAR EnableDNSW[] = { 'E','n','a','b','l','e','D','N','S','\0' };
1424 static const WCHAR BcastNameQueryCountW[] = { 'B','c','a','s','t','N','a','m',
1425 'e','Q','u','e','r','y','C','o','u','n','t','\0' };
1426 static const WCHAR BcastNameQueryTimeoutW[] = { 'B','c','a','s','t','N','a','m',
1427 'e','Q','u','e','r','y','T','i','m','e','o','u','t','\0' };
1428 static const WCHAR NameSrvQueryCountW[] = { 'N','a','m','e','S','r','v',
1429 'Q','u','e','r','y','C','o','u','n','t','\0' };
1430 static const WCHAR NameSrvQueryTimeoutW[] = { 'N','a','m','e','S','r','v',
1431 'Q','u','e','r','y','T','i','m','e','o','u','t','\0' };
1432 static const WCHAR ScopeIDW[] = { 'S','c','o','p','e','I','D','\0' };
1433 static const WCHAR CacheTimeoutW[] = { 'C','a','c','h','e','T','i','m','e','o',
1434 'u','t','\0' };
1435 static const WCHAR Config_NetworkW[] = { 'S','o','f','t','w','a','r','e','\\',
1436 'W','i','n','e','\\','N','e','t','w','o','r','k','\0' };
1438 /* Initializes global variables and registers the NetBT transport */
1439 void NetBTInit(void)
1441 HKEY hKey;
1442 NetBIOSTransport transport;
1443 LONG ret;
1445 TRACE("\n");
1447 gEnableDNS = TRUE;
1448 gBCastQueries = BCAST_QUERIES;
1449 gBCastQueryTimeout = BCAST_QUERY_TIMEOUT;
1450 gWINSQueries = WINS_QUERIES;
1451 gWINSQueryTimeout = WINS_QUERY_TIMEOUT;
1452 gNumWINSServers = 0;
1453 memset(gWINSServers, 0, sizeof(gWINSServers));
1454 gScopeID[0] = '\0';
1455 gCacheTimeout = CACHE_TIMEOUT;
1457 /* Try to open the Win9x NetBT configuration key */
1458 ret = RegOpenKeyExW(HKEY_LOCAL_MACHINE, VxD_MSTCPW, 0, KEY_READ, &hKey);
1459 /* If that fails, try the WinNT NetBT configuration key */
1460 if (ret != ERROR_SUCCESS)
1461 ret = RegOpenKeyExW(HKEY_LOCAL_MACHINE, NetBT_ParametersW, 0, KEY_READ,
1462 &hKey);
1463 if (ret == ERROR_SUCCESS)
1465 DWORD dword, size;
1467 size = sizeof(dword);
1468 if (RegQueryValueExW(hKey, EnableDNSW, NULL, NULL,
1469 (LPBYTE)&dword, &size) == ERROR_SUCCESS)
1470 gEnableDNS = dword;
1471 size = sizeof(dword);
1472 if (RegQueryValueExW(hKey, BcastNameQueryCountW, NULL, NULL,
1473 (LPBYTE)&dword, &size) == ERROR_SUCCESS && dword >= MIN_QUERIES
1474 && dword <= MAX_QUERIES)
1475 gBCastQueries = dword;
1476 size = sizeof(dword);
1477 if (RegQueryValueExW(hKey, BcastNameQueryTimeoutW, NULL, NULL,
1478 (LPBYTE)&dword, &size) == ERROR_SUCCESS && dword >= MIN_QUERY_TIMEOUT)
1479 gBCastQueryTimeout = dword;
1480 size = sizeof(dword);
1481 if (RegQueryValueExW(hKey, NameSrvQueryCountW, NULL, NULL,
1482 (LPBYTE)&dword, &size) == ERROR_SUCCESS && dword >= MIN_QUERIES
1483 && dword <= MAX_QUERIES)
1484 gWINSQueries = dword;
1485 size = sizeof(dword);
1486 if (RegQueryValueExW(hKey, NameSrvQueryTimeoutW, NULL, NULL,
1487 (LPBYTE)&dword, &size) == ERROR_SUCCESS && dword >= MIN_QUERY_TIMEOUT)
1488 gWINSQueryTimeout = dword;
1489 size = sizeof(gScopeID) - 1;
1490 if (RegQueryValueExW(hKey, ScopeIDW, NULL, NULL, (LPBYTE)gScopeID + 1, &size)
1491 == ERROR_SUCCESS)
1493 /* convert into L2-encoded version, suitable for use by
1494 NetBTNameEncode */
1495 char *ptr, *lenPtr;
1497 for (ptr = gScopeID + 1, lenPtr = gScopeID; ptr - gScopeID < sizeof(gScopeID) && *ptr; ++ptr)
1499 if (*ptr == '.')
1501 lenPtr = ptr;
1502 *lenPtr = 0;
1504 else
1506 ++*lenPtr;
1510 if (RegQueryValueExW(hKey, CacheTimeoutW, NULL, NULL,
1511 (LPBYTE)&dword, &size) == ERROR_SUCCESS && dword >= MIN_CACHE_TIMEOUT)
1512 gCacheTimeout = dword;
1513 RegCloseKey(hKey);
1515 /* WINE-specific NetBT registry settings. Because our adapter naming is
1516 * different than MS', we can't do per-adapter WINS configuration in the
1517 * same place. Just do a global WINS configuration instead.
1519 /* @@ Wine registry key: HKCU\Software\Wine\Network */
1520 if (RegOpenKeyW(HKEY_CURRENT_USER, Config_NetworkW, &hKey) == ERROR_SUCCESS)
1522 static const char *nsValueNames[] = { "WinsServer", "BackupWinsServer" };
1523 char nsString[16];
1524 DWORD size, ndx;
1526 for (ndx = 0; ndx < sizeof(nsValueNames) / sizeof(nsValueNames[0]);
1527 ndx++)
1529 size = sizeof(nsString) / sizeof(char);
1530 if (RegQueryValueExA(hKey, nsValueNames[ndx], NULL, NULL,
1531 (LPBYTE)nsString, &size) == ERROR_SUCCESS)
1533 unsigned long addr = inet_addr(nsString);
1535 if (addr != INADDR_NONE && gNumWINSServers < MAX_WINS_SERVERS)
1536 gWINSServers[gNumWINSServers++] = addr;
1539 RegCloseKey(hKey);
1542 transport.enumerate = NetBTEnum;
1543 transport.astat = NetBTAstat;
1544 transport.findName = NetBTFindName;
1545 transport.call = NetBTCall;
1546 transport.send = NetBTSend;
1547 transport.recv = NetBTRecv;
1548 transport.hangup = NetBTHangup;
1549 transport.cleanupAdapter = NetBTCleanupAdapter;
1550 transport.cleanup = NetBTCleanup;
1551 memcpy(&gTransportID, TRANSPORT_NBT, sizeof(ULONG));
1552 NetBIOSRegisterTransport(gTransportID, &transport);