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