r12542: Move some more prototypes out to seperate headers
[jelmer/samba4-debian.git] / source / libcli / raw / clitransport.c
1 /* 
2    Unix SMB/CIFS implementation.
3    SMB client transport context management functions
4
5    Copyright (C) Andrew Tridgell 1994-2005
6    Copyright (C) James Myers 2003 <myersjj@samba.org>
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 "libcli/raw/libcliraw.h"
25 #include "lib/socket/socket.h"
26 #include "dlinklist.h"
27 #include "lib/events/events.h"
28 #include "lib/stream/packet.h"
29 #include "libcli/nbt/libnbt.h"
30
31
32 /*
33   an event has happened on the socket
34 */
35 static void smbcli_transport_event_handler(struct event_context *ev, 
36                                            struct fd_event *fde, 
37                                            uint16_t flags, void *private)
38 {
39         struct smbcli_transport *transport = talloc_get_type(private,
40                                                              struct smbcli_transport);
41         if (flags & EVENT_FD_READ) {
42                 packet_recv(transport->packet);
43                 return;
44         }
45         if (flags & EVENT_FD_WRITE) {
46                 packet_queue_run(transport->packet);
47         }
48 }
49
50 /*
51   destroy a transport
52  */
53 static int transport_destructor(void *ptr)
54 {
55         struct smbcli_transport *transport = ptr;
56
57         smbcli_transport_dead(transport);
58         return 0;
59 }
60
61
62 /*
63   handle receive errors
64 */
65 static void smbcli_transport_error(void *private, NTSTATUS status)
66 {
67         struct smbcli_transport *transport = talloc_get_type(private, struct smbcli_transport);
68         smbcli_transport_dead(transport);
69 }
70
71 static NTSTATUS smbcli_transport_finish_recv(void *private, DATA_BLOB blob);
72
73 /*
74   create a transport structure based on an established socket
75 */
76 struct smbcli_transport *smbcli_transport_init(struct smbcli_socket *sock,
77                                                TALLOC_CTX *parent_ctx, BOOL primary)
78 {
79         struct smbcli_transport *transport;
80
81         transport = talloc_zero(parent_ctx, struct smbcli_transport);
82         if (!transport) return NULL;
83
84         if (primary) {
85                 transport->socket = talloc_steal(transport, sock);
86         } else {
87                 transport->socket = talloc_reference(transport, sock);
88         }
89         transport->negotiate.protocol = PROTOCOL_NT1;
90         transport->options.use_spnego = lp_use_spnego() && lp_nt_status_support();
91         transport->options.max_xmit = lp_max_xmit();
92         transport->options.max_mux = lp_maxmux();
93         transport->options.request_timeout = SMB_REQUEST_TIMEOUT;
94
95         transport->negotiate.max_xmit = transport->options.max_xmit;
96
97         /* setup the stream -> packet parser */
98         transport->packet = packet_init(transport);
99         if (transport->packet == NULL) {
100                 talloc_free(transport);
101                 return NULL;
102         }
103         packet_set_private(transport->packet, transport);
104         packet_set_socket(transport->packet, transport->socket->sock);
105         packet_set_callback(transport->packet, smbcli_transport_finish_recv);
106         packet_set_full_request(transport->packet, packet_full_request_nbt);
107         packet_set_error_handler(transport->packet, smbcli_transport_error);
108         packet_set_event_context(transport->packet, transport->socket->event.ctx);
109         packet_set_nofree(transport->packet);
110
111         smbcli_init_signing(transport);
112
113         ZERO_STRUCT(transport->called);
114
115         /* take over event handling from the socket layer - it only
116            handles events up until we are connected */
117         talloc_free(transport->socket->event.fde);
118         transport->socket->event.fde = event_add_fd(transport->socket->event.ctx,
119                                                     transport->socket->sock,
120                                                     socket_get_fd(transport->socket->sock),
121                                                     EVENT_FD_READ,
122                                                     smbcli_transport_event_handler,
123                                                     transport);
124
125         packet_set_fde(transport->packet, transport->socket->event.fde);
126         packet_set_serialise(transport->packet);
127         talloc_set_destructor(transport, transport_destructor);
128
129         return transport;
130 }
131
132 /*
133   mark the transport as dead
134 */
135 void smbcli_transport_dead(struct smbcli_transport *transport)
136 {
137         smbcli_sock_dead(transport->socket);
138
139         /* kill all pending receives */
140         while (transport->pending_recv) {
141                 struct smbcli_request *req = transport->pending_recv;
142                 req->state = SMBCLI_REQUEST_ERROR;
143                 req->status = NT_STATUS_NET_WRITE_FAULT;
144                 DLIST_REMOVE(transport->pending_recv, req);
145                 if (req->async.fn) {
146                         req->async.fn(req);
147                 }
148         }
149 }
150
151
152 /*
153   send a session request
154 */
155 struct smbcli_request *smbcli_transport_connect_send(struct smbcli_transport *transport,
156                                                      struct nbt_name *calling, 
157                                                      struct nbt_name *called)
158 {
159         uint8_t *p;
160         struct smbcli_request *req;
161         DATA_BLOB calling_blob, called_blob;
162         TALLOC_CTX *tmp_ctx = talloc_new(transport);
163         NTSTATUS status;
164
165         status = nbt_name_dup(transport, called, &transport->called);
166         if (!NT_STATUS_IS_OK(status)) goto failed;
167         
168         status = nbt_name_to_blob(tmp_ctx, &calling_blob, calling);
169         if (!NT_STATUS_IS_OK(status)) goto failed;
170
171         status = nbt_name_to_blob(tmp_ctx, &called_blob, called);
172         if (!NT_STATUS_IS_OK(status)) goto failed;
173
174         /* allocate output buffer */
175         req = smbcli_request_setup_nonsmb(transport, 
176                                           NBT_HDR_SIZE + 
177                                           calling_blob.length + called_blob.length);
178         if (req == NULL) goto failed;
179
180         /* put in the destination name */
181         p = req->out.buffer + NBT_HDR_SIZE;
182         memcpy(p, called_blob.data, called_blob.length);
183         p += called_blob.length;
184
185         memcpy(p, calling_blob.data, calling_blob.length);
186         p += calling_blob.length;
187
188         _smb_setlen(req->out.buffer, PTR_DIFF(p, req->out.buffer)-4);
189         SCVAL(req->out.buffer,0,0x81);
190
191         if (!smbcli_request_send(req)) {
192                 smbcli_request_destroy(req);
193                 goto failed;
194         }
195
196         talloc_free(tmp_ctx);
197         return req;
198
199 failed:
200         talloc_free(tmp_ctx);
201         return NULL;
202 }
203
204 /*
205   map a session request error to a NTSTATUS
206  */
207 static NTSTATUS map_session_refused_error(uint8_t error)
208 {
209         switch (error) {
210         case 0x80:
211         case 0x81:
212                 return NT_STATUS_REMOTE_NOT_LISTENING;
213         case 0x82:
214                 return NT_STATUS_RESOURCE_NAME_NOT_FOUND;
215         case 0x83:
216                 return NT_STATUS_REMOTE_RESOURCES;
217         }
218         return NT_STATUS_UNEXPECTED_IO_ERROR;
219 }
220
221
222 /*
223   finish a smbcli_transport_connect()
224 */
225 NTSTATUS smbcli_transport_connect_recv(struct smbcli_request *req)
226 {
227         NTSTATUS status;
228
229         if (!smbcli_request_receive(req)) {
230                 smbcli_request_destroy(req);
231                 return NT_STATUS_UNEXPECTED_NETWORK_ERROR;
232         }
233
234         switch (CVAL(req->in.buffer,0)) {
235         case 0x82:
236                 status = NT_STATUS_OK;
237                 break;
238         case 0x83:
239                 status = map_session_refused_error(CVAL(req->in.buffer,4));
240                 break;
241         case 0x84:
242                 DEBUG(1,("Warning: session retarget not supported\n"));
243                 status = NT_STATUS_NOT_SUPPORTED;
244                 break;
245         default:
246                 status = NT_STATUS_UNEXPECTED_IO_ERROR;
247                 break;
248         }
249
250         smbcli_request_destroy(req);
251         return status;
252 }
253
254
255 /*
256   send a session request (if needed)
257 */
258 BOOL smbcli_transport_connect(struct smbcli_transport *transport,
259                               struct nbt_name *calling, 
260                               struct nbt_name *called)
261 {
262         struct smbcli_request *req;
263         NTSTATUS status;
264
265         if (transport->socket->port == 445) {
266                 return True;
267         }
268
269         req = smbcli_transport_connect_send(transport, 
270                                             calling, called);
271         status = smbcli_transport_connect_recv(req);
272         return NT_STATUS_IS_OK(status);
273 }
274
275 /****************************************************************************
276 get next mid in sequence
277 ****************************************************************************/
278 uint16_t smbcli_transport_next_mid(struct smbcli_transport *transport)
279 {
280         uint16_t mid;
281         struct smbcli_request *req;
282
283         mid = transport->next_mid;
284
285 again:
286         /* now check to see if this mid is being used by one of the 
287            pending requests. This is quite efficient because the list is
288            usually very short */
289
290         /* the zero mid is reserved for requests that don't have a mid */
291         if (mid == 0) mid = 1;
292
293         for (req=transport->pending_recv; req; req=req->next) {
294                 if (req->mid == mid) {
295                         mid++;
296                         goto again;
297                 }
298         }
299
300         transport->next_mid = mid+1;
301         return mid;
302 }
303
304 static void idle_handler(struct event_context *ev, 
305                          struct timed_event *te, struct timeval t, void *private)
306 {
307         struct smbcli_transport *transport = talloc_get_type(private,
308                                                              struct smbcli_transport);
309         struct timeval next = timeval_add(&t, 0, transport->idle.period);
310         transport->socket->event.te = event_add_timed(transport->socket->event.ctx, 
311                                                       transport,
312                                                       next,
313                                                       idle_handler, transport);
314         transport->idle.func(transport, transport->idle.private);
315 }
316
317 /*
318   setup the idle handler for a transport
319   the period is in microseconds
320 */
321 void smbcli_transport_idle_handler(struct smbcli_transport *transport, 
322                                    void (*idle_func)(struct smbcli_transport *, void *),
323                                    uint64_t period,
324                                    void *private)
325 {
326         transport->idle.func = idle_func;
327         transport->idle.private = private;
328         transport->idle.period = period;
329
330         if (transport->socket->event.te != NULL) {
331                 talloc_free(transport->socket->event.te);
332         }
333
334         transport->socket->event.te = event_add_timed(transport->socket->event.ctx, 
335                                                       transport,
336                                                       timeval_current_ofs(0, period),
337                                                       idle_handler, transport);
338 }
339
340 /*
341   we have a full request in our receive buffer - match it to a pending request
342   and process
343  */
344 static NTSTATUS smbcli_transport_finish_recv(void *private, DATA_BLOB blob)
345 {
346         struct smbcli_transport *transport = talloc_get_type(private, 
347                                                              struct smbcli_transport);
348         uint8_t *buffer, *hdr, *vwv;
349         int len;
350         uint16_t wct=0, mid = 0, op = 0;
351         struct smbcli_request *req = NULL;
352
353         buffer = blob.data;
354         len = blob.length;
355
356         hdr = buffer+NBT_HDR_SIZE;
357         vwv = hdr + HDR_VWV;
358
359         /* see if it could be an oplock break request */
360         if (smbcli_handle_oplock_break(transport, len, hdr, vwv)) {
361                 talloc_free(buffer);
362                 return NT_STATUS_OK;
363         }
364
365         /* at this point we need to check for a readbraw reply, as
366            these can be any length */
367         if (transport->readbraw_pending) {
368                 transport->readbraw_pending = 0;
369
370                 /* it must match the first entry in the pending queue
371                    as the client is not allowed to have outstanding
372                    readbraw requests */
373                 req = transport->pending_recv;
374                 if (!req) goto error;
375
376                 req->in.buffer = buffer;
377                 talloc_steal(req, buffer);
378                 req->in.size = len;
379                 req->in.allocated = req->in.size;
380                 goto async;
381         }
382
383         if (len >= MIN_SMB_SIZE) {
384                 /* extract the mid for matching to pending requests */
385                 mid = SVAL(hdr, HDR_MID);
386                 wct = CVAL(hdr, HDR_WCT);
387                 op  = CVAL(hdr, HDR_COM);
388         }
389
390         /* match the incoming request against the list of pending requests */
391         for (req=transport->pending_recv; req; req=req->next) {
392                 if (req->mid == mid) break;
393         }
394
395         /* see if it's a ntcancel reply for the current MID */
396         req = smbcli_handle_ntcancel_reply(req, len, hdr);
397
398         if (!req) {
399                 DEBUG(1,("Discarding unmatched reply with mid %d op %d\n", mid, op));
400                 goto error;
401         }
402
403         /* fill in the 'in' portion of the matching request */
404         req->in.buffer = buffer;
405         talloc_steal(req, buffer);
406         req->in.size = len;
407         req->in.allocated = req->in.size;
408
409         /* handle NBT session replies */
410         if (req->in.size >= 4 && req->in.buffer[0] != 0) {
411                 req->status = NT_STATUS_OK;
412                 goto async;
413         }
414
415         /* handle non-SMB replies */
416         if (req->in.size < NBT_HDR_SIZE + MIN_SMB_SIZE) {
417                 req->state = SMBCLI_REQUEST_ERROR;
418                 goto error;
419         }
420
421         if (req->in.size < NBT_HDR_SIZE + MIN_SMB_SIZE + VWV(wct)) {
422                 DEBUG(2,("bad reply size for mid %d\n", mid));
423                 req->status = NT_STATUS_UNSUCCESSFUL;
424                 req->state = SMBCLI_REQUEST_ERROR;
425                 goto error;
426         }
427
428         req->in.hdr = hdr;
429         req->in.vwv = vwv;
430         req->in.wct = wct;
431         if (req->in.size >= NBT_HDR_SIZE + MIN_SMB_SIZE + VWV(wct)) {
432                 req->in.data = req->in.vwv + VWV(wct) + 2;
433                 req->in.data_size = SVAL(req->in.vwv, VWV(wct));
434                 if (req->in.size < NBT_HDR_SIZE + MIN_SMB_SIZE + VWV(wct) + req->in.data_size) {
435                         DEBUG(3,("bad data size for mid %d\n", mid));
436                         /* blergh - w2k3 gives a bogus data size values in some
437                            openX replies */
438                         req->in.data_size = req->in.size - (NBT_HDR_SIZE + MIN_SMB_SIZE + VWV(wct));
439                 }
440         }
441         req->in.ptr = req->in.data;
442         req->flags2 = SVAL(req->in.hdr, HDR_FLG2);
443
444         if (!(req->flags2 & FLAGS2_32_BIT_ERROR_CODES)) {
445                 int class = CVAL(req->in.hdr,HDR_RCLS);
446                 int code = SVAL(req->in.hdr,HDR_ERR);
447                 if (class == 0 && code == 0) {
448                         transport->error.e.nt_status = NT_STATUS_OK;
449                 } else {
450                         transport->error.e.nt_status = NT_STATUS_DOS(class, code);
451                 }
452         } else {
453                 transport->error.e.nt_status = NT_STATUS(IVAL(req->in.hdr, HDR_RCLS));
454         }
455
456         req->status = transport->error.e.nt_status;
457         if (NT_STATUS_IS_OK(req->status)) {
458                 transport->error.etype = ETYPE_NONE;
459         } else {
460                 transport->error.etype = ETYPE_SMB;
461         }
462
463         if (!smbcli_request_check_sign_mac(req)) {
464                 transport->error.etype = ETYPE_SOCKET;
465                 transport->error.e.socket_error = SOCKET_READ_BAD_SIG;
466                 req->state = SMBCLI_REQUEST_ERROR;
467                 req->status = NT_STATUS_ACCESS_DENIED;
468                 goto error;
469         };
470
471 async:
472         /* if this request has an async handler then call that to
473            notify that the reply has been received. This might destroy
474            the request so it must happen last */
475         DLIST_REMOVE(transport->pending_recv, req);
476         req->state = SMBCLI_REQUEST_DONE;
477         if (req->async.fn) {
478                 req->async.fn(req);
479         }
480         return NT_STATUS_OK;
481
482 error:
483         if (req) {
484                 DLIST_REMOVE(transport->pending_recv, req);
485                 req->state = SMBCLI_REQUEST_ERROR;
486                 if (req->async.fn) {
487                         req->async.fn(req);
488                 }
489         } else {
490                 talloc_free(buffer);
491         }
492         return NT_STATUS_OK;
493 }
494
495 /*
496   process some read/write requests that are pending
497   return False if the socket is dead
498 */
499 BOOL smbcli_transport_process(struct smbcli_transport *transport)
500 {
501         NTSTATUS status;
502         size_t npending;
503
504         packet_queue_run(transport->packet);
505         if (transport->socket->sock == NULL) {
506                 return False;
507         }
508
509         status = socket_pending(transport->socket->sock, &npending);
510         if (NT_STATUS_IS_OK(status) && npending > 0) {
511                 packet_recv(transport->packet);
512         }
513         if (transport->socket->sock == NULL) {
514                 return False;
515         }
516         return True;
517 }
518
519 /*
520   handle timeouts of individual smb requests
521 */
522 static void smbcli_timeout_handler(struct event_context *ev, struct timed_event *te, 
523                                    struct timeval t, void *private)
524 {
525         struct smbcli_request *req = talloc_get_type(private, struct smbcli_request);
526
527         if (req->state == SMBCLI_REQUEST_RECV) {
528                 DLIST_REMOVE(req->transport->pending_recv, req);
529         }
530         req->status = NT_STATUS_IO_TIMEOUT;
531         req->state = SMBCLI_REQUEST_ERROR;
532         if (req->async.fn) {
533                 req->async.fn(req);
534         }
535 }
536
537
538 /*
539   destroy a request
540 */
541 static int smbcli_request_destructor(void *ptr)
542 {
543         struct smbcli_request *req = talloc_get_type(ptr, struct smbcli_request);
544         if (req->state == SMBCLI_REQUEST_RECV) {
545                 DLIST_REMOVE(req->transport->pending_recv, req);
546         }
547         return 0;
548 }
549
550
551 /*
552   put a request into the send queue
553 */
554 void smbcli_transport_send(struct smbcli_request *req)
555 {
556         DATA_BLOB blob;
557         NTSTATUS status;
558
559         /* check if the transport is dead */
560         if (req->transport->socket->sock == NULL) {
561                 req->state = SMBCLI_REQUEST_ERROR;
562                 req->status = NT_STATUS_NET_WRITE_FAULT;
563                 return;
564         }
565
566         blob = data_blob_const(req->out.buffer, req->out.size);
567         status = packet_send(req->transport->packet, blob);
568         if (!NT_STATUS_IS_OK(status)) {
569                 req->state = SMBCLI_REQUEST_ERROR;
570                 req->status = status;
571                 return;
572         }
573
574         if (req->one_way_request) {
575                 req->state = SMBCLI_REQUEST_DONE;
576                 smbcli_request_destroy(req);
577                 return;
578         }
579
580         req->state = SMBCLI_REQUEST_RECV;
581         DLIST_ADD(req->transport->pending_recv, req);
582
583         /* add a timeout */
584         if (req->transport->options.request_timeout) {
585                 event_add_timed(req->transport->socket->event.ctx, req, 
586                                 timeval_current_ofs(req->transport->options.request_timeout, 0), 
587                                 smbcli_timeout_handler, req);
588         }
589
590         talloc_set_destructor(req, smbcli_request_destructor);
591 }