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