r21316: if we got an unexpected nbt packet that most times mean
[bbaumbach/samba-autobuild/.git] / source4 / libcli / nbt / nbtsocket.c
1 /* 
2    Unix SMB/CIFS implementation.
3
4    low level socket handling for nbt requests
5
6    Copyright (C) Andrew Tridgell 2005
7    
8    This program is free software; you can redistribute it and/or modify
9    it under the terms of the GNU General Public License as published by
10    the Free Software Foundation; either version 2 of the License, or
11    (at your option) any later version.
12    
13    This program is distributed in the hope that it will be useful,
14    but WITHOUT ANY WARRANTY; without even the implied warranty of
15    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16    GNU General Public License for more details.
17    
18    You should have received a copy of the GNU General Public License
19    along with this program; if not, write to the Free Software
20    Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
21 */
22
23 #include "includes.h"
24 #include "lib/events/events.h"
25 #include "lib/util/dlinklist.h"
26 #include "libcli/nbt/libnbt.h"
27 #include "lib/socket/socket.h"
28 #include "librpc/gen_ndr/ndr_nbt.h"
29
30 #define NBT_MAX_REPLIES 1000
31
32 /*
33   destroy a pending request
34 */
35 static int nbt_name_request_destructor(struct nbt_name_request *req)
36 {       
37         if (req->state == NBT_REQUEST_SEND) {
38                 DLIST_REMOVE(req->nbtsock->send_queue, req);
39         }
40         if (req->state == NBT_REQUEST_WAIT) {
41                 req->nbtsock->num_pending--;
42         }
43         if (req->name_trn_id != 0 && !req->is_reply) {
44                 idr_remove(req->nbtsock->idr, req->name_trn_id);
45                 req->name_trn_id = 0;
46         }
47         if (req->te) {
48                 req->te = NULL;
49         }
50         if (req->nbtsock->send_queue == NULL) {
51                 EVENT_FD_NOT_WRITEABLE(req->nbtsock->fde);
52         }
53         if (req->nbtsock->num_pending == 0 && 
54             req->nbtsock->incoming.handler == NULL) {
55                 EVENT_FD_NOT_READABLE(req->nbtsock->fde);
56         }
57         return 0;
58 }
59
60
61 /*
62   handle send events on a nbt name socket
63 */
64 static void nbt_name_socket_send(struct nbt_name_socket *nbtsock)
65 {
66         struct nbt_name_request *req = nbtsock->send_queue;
67         TALLOC_CTX *tmp_ctx = talloc_new(nbtsock);
68         NTSTATUS status;
69
70         while ((req = nbtsock->send_queue)) {
71                 size_t len;
72                 
73                 len = req->encoded.length;
74                 status = socket_sendto(nbtsock->sock, &req->encoded, &len, 
75                                        req->dest);
76                 if (NT_STATUS_IS_ERR(status)) goto failed;              
77
78                 if (!NT_STATUS_IS_OK(status)) {
79                         talloc_free(tmp_ctx);
80                         return;
81                 }
82
83                 DLIST_REMOVE(nbtsock->send_queue, req);
84                 req->state = NBT_REQUEST_WAIT;
85                 if (req->is_reply) {
86                         talloc_free(req);
87                 } else {
88                         EVENT_FD_READABLE(nbtsock->fde);
89                         nbtsock->num_pending++;
90                 }
91         }
92
93         EVENT_FD_NOT_WRITEABLE(nbtsock->fde);
94         talloc_free(tmp_ctx);
95         return;
96
97 failed:
98         DLIST_REMOVE(nbtsock->send_queue, req);
99         nbt_name_request_destructor(req);
100         req->status = status;
101         req->state = NBT_REQUEST_ERROR;
102         talloc_free(tmp_ctx);
103         if (req->async.fn) {
104                 req->async.fn(req);
105         }
106         return;
107 }
108
109
110 /*
111   handle a request timeout
112 */
113 static void nbt_name_socket_timeout(struct event_context *ev, struct timed_event *te,
114                                     struct timeval t, void *private)
115 {
116         struct nbt_name_request *req = talloc_get_type(private, 
117                                                        struct nbt_name_request);
118
119         if (req->num_retries != 0) {
120                 req->num_retries--;
121                 req->te = event_add_timed(req->nbtsock->event_ctx, req, 
122                                           timeval_add(&t, req->timeout, 0),
123                                           nbt_name_socket_timeout, req);
124                 if (req->state != NBT_REQUEST_SEND) {
125                         req->state = NBT_REQUEST_SEND;
126                         DLIST_ADD_END(req->nbtsock->send_queue, req, 
127                                       struct nbt_name_request *);
128                 }
129                 EVENT_FD_WRITEABLE(req->nbtsock->fde);
130                 return;
131         }
132
133         nbt_name_request_destructor(req);
134         if (req->num_replies == 0) {
135                 req->state = NBT_REQUEST_TIMEOUT;
136                 req->status = NT_STATUS_IO_TIMEOUT;
137         } else {
138                 req->state = NBT_REQUEST_DONE;
139                 req->status = NT_STATUS_OK;
140         }
141         if (req->async.fn) {
142                 req->async.fn(req);
143         }
144 }
145
146
147
148 /*
149   handle recv events on a nbt name socket
150 */
151 static void nbt_name_socket_recv(struct nbt_name_socket *nbtsock)
152 {
153         TALLOC_CTX *tmp_ctx = talloc_new(nbtsock);
154         NTSTATUS status;
155         struct socket_address *src;
156         DATA_BLOB blob;
157         size_t nread, dsize;
158         struct nbt_name_packet *packet;
159         struct nbt_name_request *req;
160
161         status = socket_pending(nbtsock->sock, &dsize);
162         if (!NT_STATUS_IS_OK(status)) {
163                 talloc_free(tmp_ctx);
164                 return;
165         }
166
167         blob = data_blob_talloc(tmp_ctx, NULL, dsize);
168         if (blob.data == NULL) {
169                 talloc_free(tmp_ctx);
170                 return;
171         }
172
173         status = socket_recvfrom(nbtsock->sock, blob.data, blob.length, &nread,
174                                  tmp_ctx, &src);
175         if (!NT_STATUS_IS_OK(status)) {
176                 talloc_free(tmp_ctx);
177                 return;
178         }
179
180         packet = talloc(tmp_ctx, struct nbt_name_packet);
181         if (packet == NULL) {
182                 talloc_free(tmp_ctx);
183                 return;
184         }
185
186         /* parse the request */
187         status = ndr_pull_struct_blob(&blob, packet, packet, 
188                                       (ndr_pull_flags_fn_t)ndr_pull_nbt_name_packet);
189         if (!NT_STATUS_IS_OK(status)) {
190                 DEBUG(2,("Failed to parse incoming NBT name packet - %s\n",
191                          nt_errstr(status)));
192                 talloc_free(tmp_ctx);
193                 return;
194         }
195
196         if (DEBUGLVL(10)) {
197                 DEBUG(10,("Received nbt packet of length %d from %s:%d\n", 
198                           (int)blob.length, src->addr, src->port));
199                 NDR_PRINT_DEBUG(nbt_name_packet, packet);
200         }
201
202         /* if its not a reply then pass it off to the incoming request
203            handler, if any */
204         if (!(packet->operation & NBT_FLAG_REPLY)) {
205                 if (nbtsock->incoming.handler) {
206                         nbtsock->incoming.handler(nbtsock, packet, src);
207                 }
208                 talloc_free(tmp_ctx);
209                 return;
210         }
211
212         /* find the matching request */
213         req = idr_find(nbtsock->idr, packet->name_trn_id);
214         if (req == NULL) {
215                 if (nbtsock->unexpected.handler) {
216                         nbtsock->unexpected.handler(nbtsock, packet, src);
217                 } else {
218                         DEBUG(10,("Failed to match request for incoming name packet id 0x%04x on %p\n",
219                                  packet->name_trn_id, nbtsock));
220                 }
221                 talloc_free(tmp_ctx);
222                 return;
223         }
224
225         /* if this is a WACK response, this we need to go back to waiting,
226            but perhaps increase the timeout */
227         if ((packet->operation & NBT_OPCODE) == NBT_OPCODE_WACK) {
228                 if (req->received_wack || packet->ancount < 1) {
229                         nbt_name_request_destructor(req);
230                         req->status = NT_STATUS_INVALID_NETWORK_RESPONSE;
231                         req->state  = NBT_REQUEST_ERROR;
232                         goto done;
233                 }
234                 talloc_free(req->te);
235                 /* we know we won't need any more retries - the server
236                    has received our request */
237                 req->num_retries   = 0;
238                 req->received_wack = True;
239                 /* although there can be a timeout in the packet, w2k3 screws it up,
240                    so better to set it ourselves */                
241                 req->timeout = lp_parm_int(-1, "nbt", "wack_timeout", 30);
242                 req->te = event_add_timed(req->nbtsock->event_ctx, req, 
243                                           timeval_current_ofs(req->timeout, 0),
244                                           nbt_name_socket_timeout, req);
245                 talloc_free(tmp_ctx);
246                 return;
247         }
248         
249
250         req->replies = talloc_realloc(req, req->replies, struct nbt_name_reply, req->num_replies+1);
251         if (req->replies == NULL) {
252                 nbt_name_request_destructor(req);
253                 req->state  = NBT_REQUEST_ERROR;
254                 req->status = NT_STATUS_NO_MEMORY;
255                 goto done;
256         }
257
258         talloc_steal(req, src);
259         req->replies[req->num_replies].dest   = src;
260         talloc_steal(req, packet);
261         req->replies[req->num_replies].packet = packet;
262         req->num_replies++;
263
264         /* if we don't want multiple replies then we are done */
265         if (req->allow_multiple_replies &&
266             req->num_replies < NBT_MAX_REPLIES) {
267                 talloc_free(tmp_ctx);
268                 return;
269         }
270
271         nbt_name_request_destructor(req);
272         req->state  = NBT_REQUEST_DONE;
273         req->status = NT_STATUS_OK;
274
275 done:
276         talloc_free(tmp_ctx);
277         if (req->async.fn) {
278                 req->async.fn(req);
279         }
280 }
281
282 /*
283   handle fd events on a nbt_name_socket
284 */
285 static void nbt_name_socket_handler(struct event_context *ev, struct fd_event *fde,
286                                     uint16_t flags, void *private)
287 {
288         struct nbt_name_socket *nbtsock = talloc_get_type(private, 
289                                                           struct nbt_name_socket);
290         if (flags & EVENT_FD_WRITE) {
291                 nbt_name_socket_send(nbtsock);
292         } 
293         if (flags & EVENT_FD_READ) {
294                 nbt_name_socket_recv(nbtsock);
295         }
296 }
297
298
299 /*
300   initialise a nbt_name_socket. The event_ctx is optional, if provided
301   then operations will use that event context
302 */
303 _PUBLIC_ struct nbt_name_socket *nbt_name_socket_init(TALLOC_CTX *mem_ctx, 
304                                              struct event_context *event_ctx)
305 {
306         struct nbt_name_socket *nbtsock;
307         NTSTATUS status;
308
309         nbtsock = talloc(mem_ctx, struct nbt_name_socket);
310         if (nbtsock == NULL) goto failed;
311
312         if (event_ctx == NULL) {
313                 nbtsock->event_ctx = event_context_init(nbtsock);
314         } else {
315                 nbtsock->event_ctx = talloc_reference(nbtsock, event_ctx);
316         }
317         if (nbtsock->event_ctx == NULL) goto failed;
318
319         status = socket_create("ip", SOCKET_TYPE_DGRAM, &nbtsock->sock, 0);
320         if (!NT_STATUS_IS_OK(status)) goto failed;
321
322         socket_set_option(nbtsock->sock, "SO_BROADCAST", "1");
323
324         talloc_steal(nbtsock, nbtsock->sock);
325
326         nbtsock->idr = idr_init(nbtsock);
327         if (nbtsock->idr == NULL) goto failed;
328
329         nbtsock->send_queue = NULL;
330         nbtsock->num_pending = 0;
331         nbtsock->incoming.handler = NULL;
332         nbtsock->unexpected.handler = NULL;
333
334         nbtsock->fde = event_add_fd(nbtsock->event_ctx, nbtsock, 
335                                     socket_get_fd(nbtsock->sock), 0,
336                                     nbt_name_socket_handler, nbtsock);
337         
338         return nbtsock;
339
340 failed:
341         talloc_free(nbtsock);
342         return NULL;
343 }
344
345 /*
346   send off a nbt name request
347 */
348 struct nbt_name_request *nbt_name_request_send(struct nbt_name_socket *nbtsock, 
349                                                struct socket_address *dest,
350                                                struct nbt_name_packet *request,
351                                                int timeout, int retries,
352                                                BOOL allow_multiple_replies)
353 {
354         struct nbt_name_request *req;
355         int id;
356         NTSTATUS status;
357
358         req = talloc_zero(nbtsock, struct nbt_name_request);
359         if (req == NULL) goto failed;
360
361         req->nbtsock                = nbtsock;
362         req->allow_multiple_replies = allow_multiple_replies;
363         req->state                  = NBT_REQUEST_SEND;
364         req->is_reply               = False;
365         req->timeout                = timeout;
366         req->num_retries            = retries;
367         req->dest                   = dest;
368         if (talloc_reference(req, dest) == NULL) goto failed;
369
370         /* we select a random transaction id unless the user supplied one */
371         if (request->name_trn_id == 0) {
372                 id = idr_get_new_random(req->nbtsock->idr, req, UINT16_MAX);
373         } else {
374                 if (idr_find(req->nbtsock->idr, request->name_trn_id)) goto failed;
375                 id = idr_get_new_above(req->nbtsock->idr, req, request->name_trn_id, 
376                                        UINT16_MAX);
377         }
378         if (id == -1) goto failed;
379
380         request->name_trn_id = id;
381         req->name_trn_id     = id;
382
383         req->te = event_add_timed(nbtsock->event_ctx, req, 
384                                   timeval_current_ofs(req->timeout, 0),
385                                   nbt_name_socket_timeout, req);
386         
387         talloc_set_destructor(req, nbt_name_request_destructor);        
388
389         status = ndr_push_struct_blob(&req->encoded, req, request, 
390                                       (ndr_push_flags_fn_t)ndr_push_nbt_name_packet);
391         if (!NT_STATUS_IS_OK(status)) goto failed;
392
393         DLIST_ADD_END(nbtsock->send_queue, req, struct nbt_name_request *);
394
395         if (DEBUGLVL(10)) {
396                 DEBUG(10,("Queueing nbt packet to %s:%d\n", 
397                           req->dest->addr, req->dest->port));
398                 NDR_PRINT_DEBUG(nbt_name_packet, request);
399         }
400
401         EVENT_FD_WRITEABLE(nbtsock->fde);
402
403         return req;
404
405 failed:
406         talloc_free(req);
407         return NULL;
408 }
409
410
411 /*
412   send off a nbt name reply
413 */
414 NTSTATUS nbt_name_reply_send(struct nbt_name_socket *nbtsock, 
415                              struct socket_address *dest,
416                              struct nbt_name_packet *request)
417 {
418         struct nbt_name_request *req;
419         NTSTATUS status;
420
421         req = talloc_zero(nbtsock, struct nbt_name_request);
422         NT_STATUS_HAVE_NO_MEMORY(req);
423
424         req->nbtsock   = nbtsock;
425         req->dest = dest;
426         if (talloc_reference(req, dest) == NULL) goto failed;
427         req->state     = NBT_REQUEST_SEND;
428         req->is_reply = True;
429
430         talloc_set_destructor(req, nbt_name_request_destructor);        
431
432         if (DEBUGLVL(10)) {
433                 NDR_PRINT_DEBUG(nbt_name_packet, request);              
434         }
435
436         status = ndr_push_struct_blob(&req->encoded, req, request, 
437                                       (ndr_push_flags_fn_t)ndr_push_nbt_name_packet);
438         if (!NT_STATUS_IS_OK(status)) {
439                 talloc_free(req);
440                 return status;
441         }
442
443         DLIST_ADD_END(nbtsock->send_queue, req, struct nbt_name_request *);
444
445         EVENT_FD_WRITEABLE(nbtsock->fde);
446
447         return NT_STATUS_OK;
448
449 failed:
450         talloc_free(req);
451         return NT_STATUS_NO_MEMORY;
452 }
453
454 /*
455   wait for a nbt request to complete
456 */
457 NTSTATUS nbt_name_request_recv(struct nbt_name_request *req)
458 {
459         if (!req) return NT_STATUS_NO_MEMORY;
460
461         while (req->state < NBT_REQUEST_DONE) {
462                 if (event_loop_once(req->nbtsock->event_ctx) != 0) {
463                         req->state = NBT_REQUEST_ERROR;
464                         req->status = NT_STATUS_UNEXPECTED_NETWORK_ERROR;
465                         if (req->async.fn) {
466                                 req->async.fn(req);
467                         }
468                 }
469         }
470         return req->status;
471 }
472
473
474 /*
475   setup a handler for incoming requests
476 */
477 NTSTATUS nbt_set_incoming_handler(struct nbt_name_socket *nbtsock,
478                                   void (*handler)(struct nbt_name_socket *, struct nbt_name_packet *, 
479                                                   struct socket_address *),
480                                   void *private)
481 {
482         nbtsock->incoming.handler = handler;
483         nbtsock->incoming.private = private;
484         EVENT_FD_READABLE(nbtsock->fde);
485         return NT_STATUS_OK;
486 }
487
488
489 /*
490   turn a NBT rcode into a NTSTATUS
491 */
492 NTSTATUS nbt_rcode_to_ntstatus(uint8_t rcode)
493 {
494         int i;
495         struct {
496                 enum nbt_rcode rcode;
497                 NTSTATUS status;
498         } map[] = {
499                 { NBT_RCODE_FMT, NT_STATUS_INVALID_PARAMETER },
500                 { NBT_RCODE_SVR, NT_STATUS_SERVER_DISABLED },
501                 { NBT_RCODE_NAM, NT_STATUS_OBJECT_NAME_NOT_FOUND },
502                 { NBT_RCODE_IMP, NT_STATUS_NOT_SUPPORTED },
503                 { NBT_RCODE_RFS, NT_STATUS_ACCESS_DENIED },
504                 { NBT_RCODE_ACT, NT_STATUS_ADDRESS_ALREADY_EXISTS },
505                 { NBT_RCODE_CFT, NT_STATUS_CONFLICTING_ADDRESSES }
506         };
507         for (i=0;i<ARRAY_SIZE(map);i++) {
508                 if (map[i].rcode == rcode) {
509                         return map[i].status;
510                 }
511         }
512         return NT_STATUS_UNSUCCESSFUL;
513 }