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