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