docs: fix a typo in history file
[bbaumbach/samba-autobuild/.git] / 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 "../libcli/nbt/nbt_proto.h"
27 #include "lib/socket/socket.h"
28 #include "librpc/gen_ndr/ndr_nbt.h"
29 #include "param/param.h"
30 #include "lib/util/idtree_random.h"
31
32 #define NBT_MAX_REPLIES 1000
33
34 /*
35   destroy a pending request
36 */
37 static int nbt_name_request_destructor(struct nbt_name_request *req)
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         TALLOC_FREE(req->te);
50         if (req->nbtsock->send_queue == NULL) {
51                 TEVENT_FD_NOT_WRITEABLE(req->nbtsock->fde);
52         }
53         if (req->nbtsock->num_pending == 0 &&
54             req->nbtsock->incoming.handler == NULL) {
55                 TEVENT_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;
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                         TEVENT_FD_READABLE(nbtsock->fde);
89                         nbtsock->num_pending++;
90                 }
91         }
92
93         TEVENT_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         } else if (req->is_reply) {
106                 talloc_free(req);
107         }
108         return;
109 }
110
111
112 /*
113   handle a request timeout
114 */
115 static void nbt_name_socket_timeout(struct tevent_context *ev, struct tevent_timer *te,
116                                     struct timeval t, void *private_data)
117 {
118         struct nbt_name_request *req = talloc_get_type(private_data,
119                                                        struct nbt_name_request);
120
121         if (req->num_retries != 0) {
122                 req->num_retries--;
123                 req->te = tevent_add_timer(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                 }
130                 TEVENT_FD_WRITEABLE(req->nbtsock->fde);
131                 return;
132         }
133
134         nbt_name_request_destructor(req);
135         if (req->num_replies == 0) {
136                 req->state = NBT_REQUEST_TIMEOUT;
137                 req->status = NT_STATUS_IO_TIMEOUT;
138         } else {
139                 req->state = NBT_REQUEST_DONE;
140                 req->status = NT_STATUS_OK;
141         }
142         if (req->async.fn) {
143                 req->async.fn(req);
144         } else if (req->is_reply) {
145                 talloc_free(req);
146         }
147 }
148
149
150
151 /**
152   handle recv events on a nbt name socket
153 */
154 static void nbt_name_socket_recv(struct nbt_name_socket *nbtsock)
155 {
156         TALLOC_CTX *tmp_ctx = talloc_new(nbtsock);
157         NTSTATUS status;
158         enum ndr_err_code ndr_err;
159         struct socket_address *src;
160         DATA_BLOB blob;
161         size_t nread, dsize;
162         struct nbt_name_packet *packet;
163         struct nbt_name_request *req;
164
165         status = socket_pending(nbtsock->sock, &dsize);
166         if (!NT_STATUS_IS_OK(status)) {
167                 talloc_free(tmp_ctx);
168                 return;
169         }
170
171         /*
172          * Given a zero length, data_blob_talloc() returns the
173          * NULL blob {NULL, 0}.
174          *
175          * We only want to error return here on a real out of memory condition
176          * (i.e. dsize != 0, so the UDP packet has data, but the return of the
177          * allocation failed, so blob.data==NULL).
178          *
179          * Given an actual zero length UDP packet having blob.data == NULL
180          * isn't an out of memory error condition, that's the defined semantics
181          * of data_blob_talloc() when asked for zero bytes.
182          *
183          * We still need to continue to do the zero-length socket_recvfrom()
184          * read in order to clear the "read pending" condition on the socket.
185          */
186         blob = data_blob_talloc(tmp_ctx, NULL, dsize);
187         if (blob.data == NULL && dsize != 0) {
188                 talloc_free(tmp_ctx);
189                 return;
190         }
191
192         status = socket_recvfrom(nbtsock->sock, blob.data, blob.length, &nread,
193                                  tmp_ctx, &src);
194         if (!NT_STATUS_IS_OK(status)) {
195                 talloc_free(tmp_ctx);
196                 return;
197         }
198
199         packet = talloc(tmp_ctx, struct nbt_name_packet);
200         if (packet == NULL) {
201                 talloc_free(tmp_ctx);
202                 return;
203         }
204
205         /* parse the request */
206         ndr_err = ndr_pull_struct_blob(&blob, packet, packet,
207                                        (ndr_pull_flags_fn_t)ndr_pull_nbt_name_packet);
208         if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
209                 status = ndr_map_error2ntstatus(ndr_err);
210                 DEBUG(2,("Failed to parse incoming NBT name packet - %s\n",
211                          nt_errstr(status)));
212                 talloc_free(tmp_ctx);
213                 return;
214         }
215
216         if (DEBUGLVL(10)) {
217                 DEBUG(10,("Received nbt packet of length %d from %s:%d\n",
218                           (int)blob.length, src->addr, src->port));
219                 NDR_PRINT_DEBUG(nbt_name_packet, packet);
220         }
221
222         /* if its not a reply then pass it off to the incoming request
223            handler, if any */
224         if (!(packet->operation & NBT_FLAG_REPLY)) {
225                 if (nbtsock->incoming.handler) {
226                         nbtsock->incoming.handler(nbtsock, packet, src);
227                 }
228                 talloc_free(tmp_ctx);
229                 return;
230         }
231
232         /* find the matching request */
233         req = (struct nbt_name_request *)idr_find(nbtsock->idr,
234                                                   packet->name_trn_id);
235         if (req == NULL) {
236                 if (nbtsock->unexpected.handler) {
237                         nbtsock->unexpected.handler(nbtsock, packet, src);
238                 } else {
239                         DEBUG(10,("Failed to match request for incoming name packet id 0x%04x on %p\n",
240                                  packet->name_trn_id, nbtsock));
241                 }
242                 talloc_free(tmp_ctx);
243                 return;
244         }
245
246         talloc_steal(req, packet);
247         talloc_steal(req, src);
248         talloc_free(tmp_ctx);
249         nbt_name_socket_handle_response_packet(req, packet, src);
250 }
251
252 void nbt_name_socket_handle_response_packet(struct nbt_name_request *req,
253                                             struct nbt_name_packet *packet,
254                                             struct socket_address *src)
255 {
256         /* if this is a WACK response, this we need to go back to waiting,
257            but perhaps increase the timeout */
258         if ((packet->operation & NBT_OPCODE) == NBT_OPCODE_WACK) {
259                 uint32_t ttl;
260                 if (req->received_wack || packet->ancount < 1) {
261                         nbt_name_request_destructor(req);
262                         req->status = NT_STATUS_INVALID_NETWORK_RESPONSE;
263                         req->state  = NBT_REQUEST_ERROR;
264                         goto done;
265                 }
266                 talloc_free(req->te);
267                 /* we know we won't need any more retries - the server
268                    has received our request */
269                 req->num_retries   = 0;
270                 req->received_wack = true;
271                 /*
272                  * there is a timeout in the packet,
273                  * it is 5 + 4 * num_old_addresses
274                  *
275                  * although w2k3 screws it up
276                  * and uses num_old_addresses = 0
277                  *
278                  * so we better fallback to the maximum
279                  * of num_old_addresses = 25 if we got
280                  * a timeout of less than 9s (5 + 4*1)
281                  * or more than 105s (5 + 4*25).
282                  */
283                 ttl = packet->answers[0].ttl;
284                 if ((ttl < (5 + 4*1)) || (ttl > (5 + 4*25))) {
285                         ttl = 5 + 4*25;
286                 }
287                 req->timeout = ttl;
288                 req->te = tevent_add_timer(req->nbtsock->event_ctx, req,
289                                            timeval_current_ofs(req->timeout, 0),
290                                            nbt_name_socket_timeout, req);
291                 return;
292         }
293
294
295         req->replies = talloc_realloc(req, req->replies, struct nbt_name_reply, req->num_replies+1);
296         if (req->replies == NULL) {
297                 nbt_name_request_destructor(req);
298                 req->state  = NBT_REQUEST_ERROR;
299                 req->status = NT_STATUS_NO_MEMORY;
300                 goto done;
301         }
302
303         talloc_steal(req, src);
304         req->replies[req->num_replies].dest   = src;
305         talloc_steal(req, packet);
306         req->replies[req->num_replies].packet = packet;
307         req->num_replies++;
308
309         /* if we don't want multiple replies then we are done */
310         if (req->allow_multiple_replies &&
311             req->num_replies < NBT_MAX_REPLIES) {
312                 return;
313         }
314
315         nbt_name_request_destructor(req);
316         req->state  = NBT_REQUEST_DONE;
317         req->status = NT_STATUS_OK;
318
319 done:
320         if (req->async.fn) {
321                 req->async.fn(req);
322         }
323 }
324
325 /*
326   handle fd events on a nbt_name_socket
327 */
328 static void nbt_name_socket_handler(struct tevent_context *ev, struct tevent_fd *fde,
329                                     uint16_t flags, void *private_data)
330 {
331         struct nbt_name_socket *nbtsock = talloc_get_type(private_data,
332                                                           struct nbt_name_socket);
333         if (flags & TEVENT_FD_WRITE) {
334                 nbt_name_socket_send(nbtsock);
335         }
336         if (flags & TEVENT_FD_READ) {
337                 nbt_name_socket_recv(nbtsock);
338         }
339 }
340
341
342 /*
343   initialise a nbt_name_socket. The event_ctx is optional, if provided
344   then operations will use that event context
345 */
346 _PUBLIC_ struct nbt_name_socket *nbt_name_socket_init(TALLOC_CTX *mem_ctx,
347                                              struct tevent_context *event_ctx)
348 {
349         struct nbt_name_socket *nbtsock;
350         NTSTATUS status;
351
352         nbtsock = talloc(mem_ctx, struct nbt_name_socket);
353         if (nbtsock == NULL) goto failed;
354
355         nbtsock->event_ctx = event_ctx;
356         if (nbtsock->event_ctx == NULL) goto failed;
357
358         status = socket_create(nbtsock, "ip", SOCKET_TYPE_DGRAM,
359                                &nbtsock->sock, 0);
360         if (!NT_STATUS_IS_OK(status)) goto failed;
361
362         socket_set_option(nbtsock->sock, "SO_BROADCAST", "1");
363
364         nbtsock->idr = idr_init(nbtsock);
365         if (nbtsock->idr == NULL) goto failed;
366
367         nbtsock->send_queue = NULL;
368         nbtsock->num_pending = 0;
369         nbtsock->incoming.handler = NULL;
370         nbtsock->unexpected.handler = NULL;
371
372         nbtsock->fde = tevent_add_fd(nbtsock->event_ctx, nbtsock,
373                                      socket_get_fd(nbtsock->sock), 0,
374                                      nbt_name_socket_handler, nbtsock);
375
376         return nbtsock;
377
378 failed:
379         talloc_free(nbtsock);
380         return NULL;
381 }
382
383 /*
384   send off a nbt name request
385 */
386 struct nbt_name_request *nbt_name_request_send(TALLOC_CTX *mem_ctx,
387                                                struct nbt_name_socket *nbtsock,
388                                                struct socket_address *dest,
389                                                struct nbt_name_packet *request,
390                                                int timeout, int retries,
391                                                bool allow_multiple_replies)
392 {
393         struct nbt_name_request *req;
394         int id;
395         enum ndr_err_code ndr_err;
396
397         req = talloc_zero(mem_ctx, struct nbt_name_request);
398         if (req == NULL) goto failed;
399
400         req->nbtsock                = nbtsock;
401         req->allow_multiple_replies = allow_multiple_replies;
402         req->state                  = NBT_REQUEST_SEND;
403         req->is_reply               = false;
404         req->timeout                = timeout;
405         req->num_retries            = retries;
406         req->dest                   = socket_address_copy(req, dest);
407         if (req->dest == NULL) goto failed;
408
409         /* we select a random transaction id unless the user supplied one */
410         if (request->name_trn_id == 0) {
411                 id = idr_get_new_random(
412                         req->nbtsock->idr, req, 1, UINT16_MAX);
413         } else {
414                 if (idr_find(req->nbtsock->idr, request->name_trn_id)) goto failed;
415                 id = idr_get_new_above(req->nbtsock->idr, req, request->name_trn_id,
416                                        UINT16_MAX);
417         }
418         if (id == -1) goto failed;
419
420         request->name_trn_id = id;
421         req->name_trn_id     = id;
422
423         req->te = tevent_add_timer(nbtsock->event_ctx, req,
424                                    timeval_current_ofs(req->timeout, 0),
425                                    nbt_name_socket_timeout, req);
426
427         talloc_set_destructor(req, nbt_name_request_destructor);
428
429         ndr_err = ndr_push_struct_blob(&req->encoded, req,
430                                        request,
431                                        (ndr_push_flags_fn_t)ndr_push_nbt_name_packet);
432         if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) goto failed;
433
434         DLIST_ADD_END(nbtsock->send_queue, req);
435
436         if (DEBUGLVL(10)) {
437                 DEBUG(10,("Queueing nbt packet to %s:%d\n",
438                           req->dest->addr, req->dest->port));
439                 NDR_PRINT_DEBUG(nbt_name_packet, request);
440         }
441
442         TEVENT_FD_WRITEABLE(nbtsock->fde);
443
444         return req;
445
446 failed:
447         talloc_free(req);
448         return NULL;
449 }
450
451
452 /*
453   send off a nbt name reply
454 */
455 _PUBLIC_ NTSTATUS nbt_name_reply_send(struct nbt_name_socket *nbtsock,
456                              struct socket_address *dest,
457                              struct nbt_name_packet *request)
458 {
459         struct nbt_name_request *req;
460         enum ndr_err_code ndr_err;
461
462         req = talloc_zero(nbtsock, struct nbt_name_request);
463         NT_STATUS_HAVE_NO_MEMORY(req);
464
465         req->nbtsock   = nbtsock;
466         req->dest = socket_address_copy(req, dest);
467         if (req->dest == NULL) goto failed;
468         req->state     = NBT_REQUEST_SEND;
469         req->is_reply = true;
470
471         talloc_set_destructor(req, nbt_name_request_destructor);
472
473         if (DEBUGLVL(10)) {
474                 NDR_PRINT_DEBUG(nbt_name_packet, request);
475         }
476
477         ndr_err = ndr_push_struct_blob(&req->encoded, req,
478                                        request,
479                                        (ndr_push_flags_fn_t)ndr_push_nbt_name_packet);
480         if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
481                 talloc_free(req);
482                 return ndr_map_error2ntstatus(ndr_err);
483         }
484
485         DLIST_ADD_END(nbtsock->send_queue, req);
486
487         TEVENT_FD_WRITEABLE(nbtsock->fde);
488
489         return NT_STATUS_OK;
490
491 failed:
492         talloc_free(req);
493         return NT_STATUS_NO_MEMORY;
494 }
495
496 /*
497   wait for a nbt request to complete
498 */
499 NTSTATUS nbt_name_request_recv(struct nbt_name_request *req)
500 {
501         if (!req) return NT_STATUS_NO_MEMORY;
502
503         while (req->state < NBT_REQUEST_DONE) {
504                 if (tevent_loop_once(req->nbtsock->event_ctx) != 0) {
505                         req->state = NBT_REQUEST_ERROR;
506                         req->status = NT_STATUS_UNEXPECTED_NETWORK_ERROR;
507                         break;
508                 }
509         }
510         return req->status;
511 }
512
513
514 /*
515   setup a handler for incoming requests
516 */
517 _PUBLIC_ NTSTATUS nbt_set_incoming_handler(struct nbt_name_socket *nbtsock,
518                                   void (*handler)(struct nbt_name_socket *, struct nbt_name_packet *,
519                                                   struct socket_address *),
520                                   void *private_data)
521 {
522         nbtsock->incoming.handler = handler;
523         nbtsock->incoming.private_data = private_data;
524         TEVENT_FD_READABLE(nbtsock->fde);
525         return NT_STATUS_OK;
526 }
527
528 /*
529   setup a handler for unexpected requests
530 */
531 NTSTATUS nbt_set_unexpected_handler(struct nbt_name_socket *nbtsock,
532                                     void (*handler)(struct nbt_name_socket *, struct nbt_name_packet *,
533                                                     struct socket_address *),
534                                     void *private_data)
535 {
536         nbtsock->unexpected.handler = handler;
537         nbtsock->unexpected.private_data = private_data;
538         TEVENT_FD_READABLE(nbtsock->fde);
539         return NT_STATUS_OK;
540 }
541
542 /*
543   turn a NBT rcode into a NTSTATUS
544 */
545 _PUBLIC_ NTSTATUS nbt_rcode_to_ntstatus(uint8_t rcode)
546 {
547         size_t i;
548         struct {
549                 enum nbt_rcode rcode;
550                 NTSTATUS status;
551         } map[] = {
552                 { NBT_RCODE_FMT, NT_STATUS_INVALID_PARAMETER },
553                 { NBT_RCODE_SVR, NT_STATUS_SERVER_DISABLED },
554                 { NBT_RCODE_NAM, NT_STATUS_OBJECT_NAME_NOT_FOUND },
555                 { NBT_RCODE_IMP, NT_STATUS_NOT_SUPPORTED },
556                 { NBT_RCODE_RFS, NT_STATUS_ACCESS_DENIED },
557                 { NBT_RCODE_ACT, NT_STATUS_ADDRESS_ALREADY_EXISTS },
558                 { NBT_RCODE_CFT, NT_STATUS_CONFLICTING_ADDRESSES }
559         };
560         for (i=0;i<ARRAY_SIZE(map);i++) {
561                 if (map[i].rcode == rcode) {
562                         return map[i].status;
563                 }
564         }
565         return NT_STATUS_UNSUCCESSFUL;
566 }