Imported Upstream version 3.25.0
[platform/upstream/cmake.git] / Utilities / cmcurl / lib / smb.c
1 /***************************************************************************
2  *                                  _   _ ____  _
3  *  Project                     ___| | | |  _ \| |
4  *                             / __| | | | |_) | |
5  *                            | (__| |_| |  _ <| |___
6  *                             \___|\___/|_| \_\_____|
7  *
8  * Copyright (C) 2016 - 2022, Daniel Stenberg, <daniel@haxx.se>, et al.
9  * Copyright (C) 2014, Bill Nagel <wnagel@tycoint.com>, Exacq Technologies
10  *
11  * This software is licensed as described in the file COPYING, which
12  * you should have received as part of this distribution. The terms
13  * are also available at https://curl.se/docs/copyright.html.
14  *
15  * You may opt to use, copy, modify, merge, publish, distribute and/or sell
16  * copies of the Software, and permit persons to whom the Software is
17  * furnished to do so, under the terms of the COPYING file.
18  *
19  * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
20  * KIND, either express or implied.
21  *
22  * SPDX-License-Identifier: curl
23  *
24  ***************************************************************************/
25
26 #include "curl_setup.h"
27
28 #if !defined(CURL_DISABLE_SMB) && defined(USE_CURL_NTLM_CORE) &&  \
29   (SIZEOF_CURL_OFF_T > 4)
30
31 #define BUILDING_CURL_SMB_C
32
33 #ifdef HAVE_PROCESS_H
34 #include <process.h>
35 #ifdef CURL_WINDOWS_APP
36 #define getpid GetCurrentProcessId
37 #elif defined(WIN32)
38 #define getpid _getpid
39 #endif
40 #endif
41
42 #include "smb.h"
43 #include "urldata.h"
44 #include "sendf.h"
45 #include "multiif.h"
46 #include "connect.h"
47 #include "progress.h"
48 #include "transfer.h"
49 #include "vtls/vtls.h"
50 #include "curl_ntlm_core.h"
51 #include "escape.h"
52 #include "curl_endian.h"
53
54 /* The last #include files should be: */
55 #include "curl_memory.h"
56 #include "memdebug.h"
57
58 /* Local API functions */
59 static CURLcode smb_setup_connection(struct Curl_easy *data,
60                                      struct connectdata *conn);
61 static CURLcode smb_connect(struct Curl_easy *data, bool *done);
62 static CURLcode smb_connection_state(struct Curl_easy *data, bool *done);
63 static CURLcode smb_do(struct Curl_easy *data, bool *done);
64 static CURLcode smb_request_state(struct Curl_easy *data, bool *done);
65 static CURLcode smb_done(struct Curl_easy *data, CURLcode status,
66                          bool premature);
67 static CURLcode smb_disconnect(struct Curl_easy *data,
68                                struct connectdata *conn, bool dead);
69 static int smb_getsock(struct Curl_easy *data, struct connectdata *conn,
70                        curl_socket_t *socks);
71 static CURLcode smb_parse_url_path(struct Curl_easy *data,
72                                    struct connectdata *conn);
73
74 /*
75  * SMB handler interface
76  */
77 const struct Curl_handler Curl_handler_smb = {
78   "SMB",                                /* scheme */
79   smb_setup_connection,                 /* setup_connection */
80   smb_do,                               /* do_it */
81   smb_done,                             /* done */
82   ZERO_NULL,                            /* do_more */
83   smb_connect,                          /* connect_it */
84   smb_connection_state,                 /* connecting */
85   smb_request_state,                    /* doing */
86   smb_getsock,                          /* proto_getsock */
87   smb_getsock,                          /* doing_getsock */
88   ZERO_NULL,                            /* domore_getsock */
89   ZERO_NULL,                            /* perform_getsock */
90   smb_disconnect,                       /* disconnect */
91   ZERO_NULL,                            /* readwrite */
92   ZERO_NULL,                            /* connection_check */
93   ZERO_NULL,                            /* attach connection */
94   PORT_SMB,                             /* defport */
95   CURLPROTO_SMB,                        /* protocol */
96   CURLPROTO_SMB,                        /* family */
97   PROTOPT_NONE                          /* flags */
98 };
99
100 #ifdef USE_SSL
101 /*
102  * SMBS handler interface
103  */
104 const struct Curl_handler Curl_handler_smbs = {
105   "SMBS",                               /* scheme */
106   smb_setup_connection,                 /* setup_connection */
107   smb_do,                               /* do_it */
108   smb_done,                             /* done */
109   ZERO_NULL,                            /* do_more */
110   smb_connect,                          /* connect_it */
111   smb_connection_state,                 /* connecting */
112   smb_request_state,                    /* doing */
113   smb_getsock,                          /* proto_getsock */
114   smb_getsock,                          /* doing_getsock */
115   ZERO_NULL,                            /* domore_getsock */
116   ZERO_NULL,                            /* perform_getsock */
117   smb_disconnect,                       /* disconnect */
118   ZERO_NULL,                            /* readwrite */
119   ZERO_NULL,                            /* connection_check */
120   ZERO_NULL,                            /* attach connection */
121   PORT_SMBS,                            /* defport */
122   CURLPROTO_SMBS,                       /* protocol */
123   CURLPROTO_SMB,                        /* family */
124   PROTOPT_SSL                           /* flags */
125 };
126 #endif
127
128 #define MAX_PAYLOAD_SIZE  0x8000
129 #define MAX_MESSAGE_SIZE  (MAX_PAYLOAD_SIZE + 0x1000)
130 #define CLIENTNAME        "curl"
131 #define SERVICENAME       "?????"
132
133 /* Append a string to an SMB message */
134 #define MSGCAT(str)                             \
135   do {                                          \
136     strcpy(p, (str));                           \
137     p += strlen(str);                           \
138   } while(0)
139
140 /* Append a null-terminated string to an SMB message */
141 #define MSGCATNULL(str)                         \
142   do {                                          \
143     strcpy(p, (str));                           \
144     p += strlen(str) + 1;                       \
145   } while(0)
146
147 /* SMB is mostly little endian */
148 #if (defined(__BYTE_ORDER__) && __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__) || \
149   defined(__OS400__)
150 static unsigned short smb_swap16(unsigned short x)
151 {
152   return (unsigned short) ((x << 8) | ((x >> 8) & 0xff));
153 }
154
155 static unsigned int smb_swap32(unsigned int x)
156 {
157   return (x << 24) | ((x << 8) & 0xff0000) | ((x >> 8) & 0xff00) |
158     ((x >> 24) & 0xff);
159 }
160
161 static curl_off_t smb_swap64(curl_off_t x)
162 {
163   return ((curl_off_t) smb_swap32((unsigned int) x) << 32) |
164     smb_swap32((unsigned int) (x >> 32));
165 }
166
167 #else
168 #  define smb_swap16(x) (x)
169 #  define smb_swap32(x) (x)
170 #  define smb_swap64(x) (x)
171 #endif
172
173 /* SMB request state */
174 enum smb_req_state {
175   SMB_REQUESTING,
176   SMB_TREE_CONNECT,
177   SMB_OPEN,
178   SMB_DOWNLOAD,
179   SMB_UPLOAD,
180   SMB_CLOSE,
181   SMB_TREE_DISCONNECT,
182   SMB_DONE
183 };
184
185 /* SMB request data */
186 struct smb_request {
187   enum smb_req_state state;
188   char *path;
189   unsigned short tid; /* Even if we connect to the same tree as another */
190   unsigned short fid; /* request, the tid will be different */
191   CURLcode result;
192 };
193
194 static void conn_state(struct Curl_easy *data, enum smb_conn_state newstate)
195 {
196   struct smb_conn *smbc = &data->conn->proto.smbc;
197 #if defined(DEBUGBUILD) && !defined(CURL_DISABLE_VERBOSE_STRINGS)
198   /* For debug purposes */
199   static const char * const names[] = {
200     "SMB_NOT_CONNECTED",
201     "SMB_CONNECTING",
202     "SMB_NEGOTIATE",
203     "SMB_SETUP",
204     "SMB_CONNECTED",
205     /* LAST */
206   };
207
208   if(smbc->state != newstate)
209     infof(data, "SMB conn %p state change from %s to %s",
210           (void *)smbc, names[smbc->state], names[newstate]);
211 #endif
212
213   smbc->state = newstate;
214 }
215
216 static void request_state(struct Curl_easy *data,
217                           enum smb_req_state newstate)
218 {
219   struct smb_request *req = data->req.p.smb;
220 #if defined(DEBUGBUILD) && !defined(CURL_DISABLE_VERBOSE_STRINGS)
221   /* For debug purposes */
222   static const char * const names[] = {
223     "SMB_REQUESTING",
224     "SMB_TREE_CONNECT",
225     "SMB_OPEN",
226     "SMB_DOWNLOAD",
227     "SMB_UPLOAD",
228     "SMB_CLOSE",
229     "SMB_TREE_DISCONNECT",
230     "SMB_DONE",
231     /* LAST */
232   };
233
234   if(req->state != newstate)
235     infof(data, "SMB request %p state change from %s to %s",
236           (void *)req, names[req->state], names[newstate]);
237 #endif
238
239   req->state = newstate;
240 }
241
242 /* this should setup things in the connection, not in the easy
243    handle */
244 static CURLcode smb_setup_connection(struct Curl_easy *data,
245                                      struct connectdata *conn)
246 {
247   struct smb_request *req;
248
249   /* Initialize the request state */
250   data->req.p.smb = req = calloc(1, sizeof(struct smb_request));
251   if(!req)
252     return CURLE_OUT_OF_MEMORY;
253
254   /* Parse the URL path */
255   return smb_parse_url_path(data, conn);
256 }
257
258 static CURLcode smb_connect(struct Curl_easy *data, bool *done)
259 {
260   struct connectdata *conn = data->conn;
261   struct smb_conn *smbc = &conn->proto.smbc;
262   char *slash;
263
264   (void) done;
265
266   /* Check we have a username and password to authenticate with */
267   if(!data->state.aptr.user)
268     return CURLE_LOGIN_DENIED;
269
270   /* Initialize the connection state */
271   smbc->state = SMB_CONNECTING;
272   smbc->recv_buf = malloc(MAX_MESSAGE_SIZE);
273   if(!smbc->recv_buf)
274     return CURLE_OUT_OF_MEMORY;
275
276   /* Multiple requests are allowed with this connection */
277   connkeep(conn, "SMB default");
278
279   /* Parse the username, domain, and password */
280   slash = strchr(conn->user, '/');
281   if(!slash)
282     slash = strchr(conn->user, '\\');
283
284   if(slash) {
285     smbc->user = slash + 1;
286     smbc->domain = strdup(conn->user);
287     if(!smbc->domain)
288       return CURLE_OUT_OF_MEMORY;
289     smbc->domain[slash - conn->user] = 0;
290   }
291   else {
292     smbc->user = conn->user;
293     smbc->domain = strdup(conn->host.name);
294     if(!smbc->domain)
295       return CURLE_OUT_OF_MEMORY;
296   }
297
298   return CURLE_OK;
299 }
300
301 static CURLcode smb_recv_message(struct Curl_easy *data, void **msg)
302 {
303   struct connectdata *conn = data->conn;
304   curl_socket_t sockfd = conn->sock[FIRSTSOCKET];
305   struct smb_conn *smbc = &conn->proto.smbc;
306   char *buf = smbc->recv_buf;
307   ssize_t bytes_read;
308   size_t nbt_size;
309   size_t msg_size;
310   size_t len = MAX_MESSAGE_SIZE - smbc->got;
311   CURLcode result;
312
313   result = Curl_read(data, sockfd, buf + smbc->got, len, &bytes_read);
314   if(result)
315     return result;
316
317   if(!bytes_read)
318     return CURLE_OK;
319
320   smbc->got += bytes_read;
321
322   /* Check for a 32-bit nbt header */
323   if(smbc->got < sizeof(unsigned int))
324     return CURLE_OK;
325
326   nbt_size = Curl_read16_be((const unsigned char *)
327                             (buf + sizeof(unsigned short))) +
328     sizeof(unsigned int);
329   if(smbc->got < nbt_size)
330     return CURLE_OK;
331
332   msg_size = sizeof(struct smb_header);
333   if(nbt_size >= msg_size + 1) {
334     /* Add the word count */
335     msg_size += 1 + ((unsigned char) buf[msg_size]) * sizeof(unsigned short);
336     if(nbt_size >= msg_size + sizeof(unsigned short)) {
337       /* Add the byte count */
338       msg_size += sizeof(unsigned short) +
339         Curl_read16_le((const unsigned char *)&buf[msg_size]);
340       if(nbt_size < msg_size)
341         return CURLE_READ_ERROR;
342     }
343   }
344
345   *msg = buf;
346
347   return CURLE_OK;
348 }
349
350 static void smb_pop_message(struct connectdata *conn)
351 {
352   struct smb_conn *smbc = &conn->proto.smbc;
353
354   smbc->got = 0;
355 }
356
357 static void smb_format_message(struct Curl_easy *data, struct smb_header *h,
358                                unsigned char cmd, size_t len)
359 {
360   struct connectdata *conn = data->conn;
361   struct smb_conn *smbc = &conn->proto.smbc;
362   struct smb_request *req = data->req.p.smb;
363   unsigned int pid;
364
365   memset(h, 0, sizeof(*h));
366   h->nbt_length = htons((unsigned short) (sizeof(*h) - sizeof(unsigned int) +
367                                           len));
368   memcpy((char *)h->magic, "\xffSMB", 4);
369   h->command = cmd;
370   h->flags = SMB_FLAGS_CANONICAL_PATHNAMES | SMB_FLAGS_CASELESS_PATHNAMES;
371   h->flags2 = smb_swap16(SMB_FLAGS2_IS_LONG_NAME | SMB_FLAGS2_KNOWS_LONG_NAME);
372   h->uid = smb_swap16(smbc->uid);
373   h->tid = smb_swap16(req->tid);
374   pid = getpid();
375   h->pid_high = smb_swap16((unsigned short)(pid >> 16));
376   h->pid = smb_swap16((unsigned short) pid);
377 }
378
379 static CURLcode smb_send(struct Curl_easy *data, ssize_t len,
380                          size_t upload_size)
381 {
382   struct connectdata *conn = data->conn;
383   curl_socket_t sockfd = conn->sock[FIRSTSOCKET];
384   struct smb_conn *smbc = &conn->proto.smbc;
385   ssize_t bytes_written;
386   CURLcode result;
387
388   result = Curl_write(data, sockfd, data->state.ulbuf,
389                       len, &bytes_written);
390   if(result)
391     return result;
392
393   if(bytes_written != len) {
394     smbc->send_size = len;
395     smbc->sent = bytes_written;
396   }
397
398   smbc->upload_size = upload_size;
399
400   return CURLE_OK;
401 }
402
403 static CURLcode smb_flush(struct Curl_easy *data)
404 {
405   struct connectdata *conn = data->conn;
406   curl_socket_t sockfd = conn->sock[FIRSTSOCKET];
407   struct smb_conn *smbc = &conn->proto.smbc;
408   ssize_t bytes_written;
409   ssize_t len = smbc->send_size - smbc->sent;
410   CURLcode result;
411
412   if(!smbc->send_size)
413     return CURLE_OK;
414
415   result = Curl_write(data, sockfd,
416                       data->state.ulbuf + smbc->sent,
417                       len, &bytes_written);
418   if(result)
419     return result;
420
421   if(bytes_written != len)
422     smbc->sent += bytes_written;
423   else
424     smbc->send_size = 0;
425
426   return CURLE_OK;
427 }
428
429 static CURLcode smb_send_message(struct Curl_easy *data, unsigned char cmd,
430                                  const void *msg, size_t msg_len)
431 {
432   CURLcode result = Curl_get_upload_buffer(data);
433   if(result)
434     return result;
435   smb_format_message(data, (struct smb_header *)data->state.ulbuf,
436                      cmd, msg_len);
437   memcpy(data->state.ulbuf + sizeof(struct smb_header),
438          msg, msg_len);
439
440   return smb_send(data, sizeof(struct smb_header) + msg_len, 0);
441 }
442
443 static CURLcode smb_send_negotiate(struct Curl_easy *data)
444 {
445   const char *msg = "\x00\x0c\x00\x02NT LM 0.12";
446
447   return smb_send_message(data, SMB_COM_NEGOTIATE, msg, 15);
448 }
449
450 static CURLcode smb_send_setup(struct Curl_easy *data)
451 {
452   struct connectdata *conn = data->conn;
453   struct smb_conn *smbc = &conn->proto.smbc;
454   struct smb_setup msg;
455   char *p = msg.bytes;
456   unsigned char lm_hash[21];
457   unsigned char lm[24];
458   unsigned char nt_hash[21];
459   unsigned char nt[24];
460
461   size_t byte_count = sizeof(lm) + sizeof(nt);
462   byte_count += strlen(smbc->user) + strlen(smbc->domain);
463   byte_count += strlen(OS) + strlen(CLIENTNAME) + 4; /* 4 null chars */
464   if(byte_count > sizeof(msg.bytes))
465     return CURLE_FILESIZE_EXCEEDED;
466
467   Curl_ntlm_core_mk_lm_hash(conn->passwd, lm_hash);
468   Curl_ntlm_core_lm_resp(lm_hash, smbc->challenge, lm);
469   Curl_ntlm_core_mk_nt_hash(conn->passwd, nt_hash);
470   Curl_ntlm_core_lm_resp(nt_hash, smbc->challenge, nt);
471
472   memset(&msg, 0, sizeof(msg));
473   msg.word_count = SMB_WC_SETUP_ANDX;
474   msg.andx.command = SMB_COM_NO_ANDX_COMMAND;
475   msg.max_buffer_size = smb_swap16(MAX_MESSAGE_SIZE);
476   msg.max_mpx_count = smb_swap16(1);
477   msg.vc_number = smb_swap16(1);
478   msg.session_key = smb_swap32(smbc->session_key);
479   msg.capabilities = smb_swap32(SMB_CAP_LARGE_FILES);
480   msg.lengths[0] = smb_swap16(sizeof(lm));
481   msg.lengths[1] = smb_swap16(sizeof(nt));
482   memcpy(p, lm, sizeof(lm));
483   p += sizeof(lm);
484   memcpy(p, nt, sizeof(nt));
485   p += sizeof(nt);
486   MSGCATNULL(smbc->user);
487   MSGCATNULL(smbc->domain);
488   MSGCATNULL(OS);
489   MSGCATNULL(CLIENTNAME);
490   byte_count = p - msg.bytes;
491   msg.byte_count = smb_swap16((unsigned short)byte_count);
492
493   return smb_send_message(data, SMB_COM_SETUP_ANDX, &msg,
494                           sizeof(msg) - sizeof(msg.bytes) + byte_count);
495 }
496
497 static CURLcode smb_send_tree_connect(struct Curl_easy *data)
498 {
499   struct smb_tree_connect msg;
500   struct connectdata *conn = data->conn;
501   struct smb_conn *smbc = &conn->proto.smbc;
502   char *p = msg.bytes;
503
504   size_t byte_count = strlen(conn->host.name) + strlen(smbc->share);
505   byte_count += strlen(SERVICENAME) + 5; /* 2 nulls and 3 backslashes */
506   if(byte_count > sizeof(msg.bytes))
507     return CURLE_FILESIZE_EXCEEDED;
508
509   memset(&msg, 0, sizeof(msg));
510   msg.word_count = SMB_WC_TREE_CONNECT_ANDX;
511   msg.andx.command = SMB_COM_NO_ANDX_COMMAND;
512   msg.pw_len = 0;
513   MSGCAT("\\\\");
514   MSGCAT(conn->host.name);
515   MSGCAT("\\");
516   MSGCATNULL(smbc->share);
517   MSGCATNULL(SERVICENAME); /* Match any type of service */
518   byte_count = p - msg.bytes;
519   msg.byte_count = smb_swap16((unsigned short)byte_count);
520
521   return smb_send_message(data, SMB_COM_TREE_CONNECT_ANDX, &msg,
522                           sizeof(msg) - sizeof(msg.bytes) + byte_count);
523 }
524
525 static CURLcode smb_send_open(struct Curl_easy *data)
526 {
527   struct smb_request *req = data->req.p.smb;
528   struct smb_nt_create msg;
529   size_t byte_count;
530
531   if((strlen(req->path) + 1) > sizeof(msg.bytes))
532     return CURLE_FILESIZE_EXCEEDED;
533
534   memset(&msg, 0, sizeof(msg));
535   msg.word_count = SMB_WC_NT_CREATE_ANDX;
536   msg.andx.command = SMB_COM_NO_ANDX_COMMAND;
537   byte_count = strlen(req->path);
538   msg.name_length = smb_swap16((unsigned short)byte_count);
539   msg.share_access = smb_swap32(SMB_FILE_SHARE_ALL);
540   if(data->set.upload) {
541     msg.access = smb_swap32(SMB_GENERIC_READ | SMB_GENERIC_WRITE);
542     msg.create_disposition = smb_swap32(SMB_FILE_OVERWRITE_IF);
543   }
544   else {
545     msg.access = smb_swap32(SMB_GENERIC_READ);
546     msg.create_disposition = smb_swap32(SMB_FILE_OPEN);
547   }
548   msg.byte_count = smb_swap16((unsigned short) ++byte_count);
549   strcpy(msg.bytes, req->path);
550
551   return smb_send_message(data, SMB_COM_NT_CREATE_ANDX, &msg,
552                           sizeof(msg) - sizeof(msg.bytes) + byte_count);
553 }
554
555 static CURLcode smb_send_close(struct Curl_easy *data)
556 {
557   struct smb_request *req = data->req.p.smb;
558   struct smb_close msg;
559
560   memset(&msg, 0, sizeof(msg));
561   msg.word_count = SMB_WC_CLOSE;
562   msg.fid = smb_swap16(req->fid);
563
564   return smb_send_message(data, SMB_COM_CLOSE, &msg, sizeof(msg));
565 }
566
567 static CURLcode smb_send_tree_disconnect(struct Curl_easy *data)
568 {
569   struct smb_tree_disconnect msg;
570
571   memset(&msg, 0, sizeof(msg));
572
573   return smb_send_message(data, SMB_COM_TREE_DISCONNECT, &msg, sizeof(msg));
574 }
575
576 static CURLcode smb_send_read(struct Curl_easy *data)
577 {
578   struct smb_request *req = data->req.p.smb;
579   curl_off_t offset = data->req.offset;
580   struct smb_read msg;
581
582   memset(&msg, 0, sizeof(msg));
583   msg.word_count = SMB_WC_READ_ANDX;
584   msg.andx.command = SMB_COM_NO_ANDX_COMMAND;
585   msg.fid = smb_swap16(req->fid);
586   msg.offset = smb_swap32((unsigned int) offset);
587   msg.offset_high = smb_swap32((unsigned int) (offset >> 32));
588   msg.min_bytes = smb_swap16(MAX_PAYLOAD_SIZE);
589   msg.max_bytes = smb_swap16(MAX_PAYLOAD_SIZE);
590
591   return smb_send_message(data, SMB_COM_READ_ANDX, &msg, sizeof(msg));
592 }
593
594 static CURLcode smb_send_write(struct Curl_easy *data)
595 {
596   struct smb_write *msg;
597   struct smb_request *req = data->req.p.smb;
598   curl_off_t offset = data->req.offset;
599   curl_off_t upload_size = data->req.size - data->req.bytecount;
600   CURLcode result = Curl_get_upload_buffer(data);
601   if(result)
602     return result;
603   msg = (struct smb_write *)data->state.ulbuf;
604
605   if(upload_size >= MAX_PAYLOAD_SIZE - 1) /* There is one byte of padding */
606     upload_size = MAX_PAYLOAD_SIZE - 1;
607
608   memset(msg, 0, sizeof(*msg));
609   msg->word_count = SMB_WC_WRITE_ANDX;
610   msg->andx.command = SMB_COM_NO_ANDX_COMMAND;
611   msg->fid = smb_swap16(req->fid);
612   msg->offset = smb_swap32((unsigned int) offset);
613   msg->offset_high = smb_swap32((unsigned int) (offset >> 32));
614   msg->data_length = smb_swap16((unsigned short) upload_size);
615   msg->data_offset = smb_swap16(sizeof(*msg) - sizeof(unsigned int));
616   msg->byte_count = smb_swap16((unsigned short) (upload_size + 1));
617
618   smb_format_message(data, &msg->h, SMB_COM_WRITE_ANDX,
619                      sizeof(*msg) - sizeof(msg->h) + (size_t) upload_size);
620
621   return smb_send(data, sizeof(*msg), (size_t) upload_size);
622 }
623
624 static CURLcode smb_send_and_recv(struct Curl_easy *data, void **msg)
625 {
626   struct connectdata *conn = data->conn;
627   struct smb_conn *smbc = &conn->proto.smbc;
628   CURLcode result;
629   *msg = NULL; /* if it returns early */
630
631   /* Check if there is data in the transfer buffer */
632   if(!smbc->send_size && smbc->upload_size) {
633     size_t nread = smbc->upload_size > (size_t)data->set.upload_buffer_size ?
634       (size_t)data->set.upload_buffer_size : smbc->upload_size;
635     data->req.upload_fromhere = data->state.ulbuf;
636     result = Curl_fillreadbuffer(data, nread, &nread);
637     if(result && result != CURLE_AGAIN)
638       return result;
639     if(!nread)
640       return CURLE_OK;
641
642     smbc->upload_size -= nread;
643     smbc->send_size = nread;
644     smbc->sent = 0;
645   }
646
647   /* Check if there is data to send */
648   if(smbc->send_size) {
649     result = smb_flush(data);
650     if(result)
651       return result;
652   }
653
654   /* Check if there is still data to be sent */
655   if(smbc->send_size || smbc->upload_size)
656     return CURLE_AGAIN;
657
658   return smb_recv_message(data, msg);
659 }
660
661 static CURLcode smb_connection_state(struct Curl_easy *data, bool *done)
662 {
663   struct connectdata *conn = data->conn;
664   struct smb_conn *smbc = &conn->proto.smbc;
665   struct smb_negotiate_response *nrsp;
666   struct smb_header *h;
667   CURLcode result;
668   void *msg = NULL;
669
670   if(smbc->state == SMB_CONNECTING) {
671 #ifdef USE_SSL
672     if((conn->handler->flags & PROTOPT_SSL)) {
673       bool ssl_done = FALSE;
674       result = Curl_ssl_connect_nonblocking(data, conn, FALSE,
675                                             FIRSTSOCKET, &ssl_done);
676       if(result && result != CURLE_AGAIN)
677         return result;
678       if(!ssl_done)
679         return CURLE_OK;
680     }
681 #endif
682
683     result = smb_send_negotiate(data);
684     if(result) {
685       connclose(conn, "SMB: failed to send negotiate message");
686       return result;
687     }
688
689     conn_state(data, SMB_NEGOTIATE);
690   }
691
692   /* Send the previous message and check for a response */
693   result = smb_send_and_recv(data, &msg);
694   if(result && result != CURLE_AGAIN) {
695     connclose(conn, "SMB: failed to communicate");
696     return result;
697   }
698
699   if(!msg)
700     return CURLE_OK;
701
702   h = msg;
703
704   switch(smbc->state) {
705   case SMB_NEGOTIATE:
706     if((smbc->got < sizeof(*nrsp) + sizeof(smbc->challenge) - 1) ||
707        h->status) {
708       connclose(conn, "SMB: negotiation failed");
709       return CURLE_COULDNT_CONNECT;
710     }
711     nrsp = msg;
712     memcpy(smbc->challenge, nrsp->bytes, sizeof(smbc->challenge));
713     smbc->session_key = smb_swap32(nrsp->session_key);
714     result = smb_send_setup(data);
715     if(result) {
716       connclose(conn, "SMB: failed to send setup message");
717       return result;
718     }
719     conn_state(data, SMB_SETUP);
720     break;
721
722   case SMB_SETUP:
723     if(h->status) {
724       connclose(conn, "SMB: authentication failed");
725       return CURLE_LOGIN_DENIED;
726     }
727     smbc->uid = smb_swap16(h->uid);
728     conn_state(data, SMB_CONNECTED);
729     *done = true;
730     break;
731
732   default:
733     smb_pop_message(conn);
734     return CURLE_OK; /* ignore */
735   }
736
737   smb_pop_message(conn);
738
739   return CURLE_OK;
740 }
741
742 /*
743  * Convert a timestamp from the Windows world (100 nsec units from 1 Jan 1601)
744  * to Posix time. Cap the output to fit within a time_t.
745  */
746 static void get_posix_time(time_t *out, curl_off_t timestamp)
747 {
748   timestamp -= 116444736000000000;
749   timestamp /= 10000000;
750 #if SIZEOF_TIME_T < SIZEOF_CURL_OFF_T
751   if(timestamp > TIME_T_MAX)
752     *out = TIME_T_MAX;
753   else if(timestamp < TIME_T_MIN)
754     *out = TIME_T_MIN;
755   else
756 #endif
757     *out = (time_t) timestamp;
758 }
759
760 static CURLcode smb_request_state(struct Curl_easy *data, bool *done)
761 {
762   struct connectdata *conn = data->conn;
763   struct smb_request *req = data->req.p.smb;
764   struct smb_header *h;
765   struct smb_conn *smbc = &conn->proto.smbc;
766   enum smb_req_state next_state = SMB_DONE;
767   unsigned short len;
768   unsigned short off;
769   CURLcode result;
770   void *msg = NULL;
771   const struct smb_nt_create_response *smb_m;
772
773   /* Start the request */
774   if(req->state == SMB_REQUESTING) {
775     result = smb_send_tree_connect(data);
776     if(result) {
777       connclose(conn, "SMB: failed to send tree connect message");
778       return result;
779     }
780
781     request_state(data, SMB_TREE_CONNECT);
782   }
783
784   /* Send the previous message and check for a response */
785   result = smb_send_and_recv(data, &msg);
786   if(result && result != CURLE_AGAIN) {
787     connclose(conn, "SMB: failed to communicate");
788     return result;
789   }
790
791   if(!msg)
792     return CURLE_OK;
793
794   h = msg;
795
796   switch(req->state) {
797   case SMB_TREE_CONNECT:
798     if(h->status) {
799       req->result = CURLE_REMOTE_FILE_NOT_FOUND;
800       if(h->status == smb_swap32(SMB_ERR_NOACCESS))
801         req->result = CURLE_REMOTE_ACCESS_DENIED;
802       break;
803     }
804     req->tid = smb_swap16(h->tid);
805     next_state = SMB_OPEN;
806     break;
807
808   case SMB_OPEN:
809     if(h->status || smbc->got < sizeof(struct smb_nt_create_response)) {
810       req->result = CURLE_REMOTE_FILE_NOT_FOUND;
811       if(h->status == smb_swap32(SMB_ERR_NOACCESS))
812         req->result = CURLE_REMOTE_ACCESS_DENIED;
813       next_state = SMB_TREE_DISCONNECT;
814       break;
815     }
816     smb_m = (const struct smb_nt_create_response*) msg;
817     req->fid = smb_swap16(smb_m->fid);
818     data->req.offset = 0;
819     if(data->set.upload) {
820       data->req.size = data->state.infilesize;
821       Curl_pgrsSetUploadSize(data, data->req.size);
822       next_state = SMB_UPLOAD;
823     }
824     else {
825       smb_m = (const struct smb_nt_create_response*) msg;
826       data->req.size = smb_swap64(smb_m->end_of_file);
827       if(data->req.size < 0) {
828         req->result = CURLE_WEIRD_SERVER_REPLY;
829         next_state = SMB_CLOSE;
830       }
831       else {
832         Curl_pgrsSetDownloadSize(data, data->req.size);
833         if(data->set.get_filetime)
834           get_posix_time(&data->info.filetime, smb_m->last_change_time);
835         next_state = SMB_DOWNLOAD;
836       }
837     }
838     break;
839
840   case SMB_DOWNLOAD:
841     if(h->status || smbc->got < sizeof(struct smb_header) + 14) {
842       req->result = CURLE_RECV_ERROR;
843       next_state = SMB_CLOSE;
844       break;
845     }
846     len = Curl_read16_le(((const unsigned char *) msg) +
847                          sizeof(struct smb_header) + 11);
848     off = Curl_read16_le(((const unsigned char *) msg) +
849                          sizeof(struct smb_header) + 13);
850     if(len > 0) {
851       if(off + sizeof(unsigned int) + len > smbc->got) {
852         failf(data, "Invalid input packet");
853         result = CURLE_RECV_ERROR;
854       }
855       else
856         result = Curl_client_write(data, CLIENTWRITE_BODY,
857                                    (char *)msg + off + sizeof(unsigned int),
858                                    len);
859       if(result) {
860         req->result = result;
861         next_state = SMB_CLOSE;
862         break;
863       }
864     }
865     data->req.bytecount += len;
866     data->req.offset += len;
867     Curl_pgrsSetDownloadCounter(data, data->req.bytecount);
868     next_state = (len < MAX_PAYLOAD_SIZE) ? SMB_CLOSE : SMB_DOWNLOAD;
869     break;
870
871   case SMB_UPLOAD:
872     if(h->status || smbc->got < sizeof(struct smb_header) + 6) {
873       req->result = CURLE_UPLOAD_FAILED;
874       next_state = SMB_CLOSE;
875       break;
876     }
877     len = Curl_read16_le(((const unsigned char *) msg) +
878                          sizeof(struct smb_header) + 5);
879     data->req.bytecount += len;
880     data->req.offset += len;
881     Curl_pgrsSetUploadCounter(data, data->req.bytecount);
882     if(data->req.bytecount >= data->req.size)
883       next_state = SMB_CLOSE;
884     else
885       next_state = SMB_UPLOAD;
886     break;
887
888   case SMB_CLOSE:
889     /* We don't care if the close failed, proceed to tree disconnect anyway */
890     next_state = SMB_TREE_DISCONNECT;
891     break;
892
893   case SMB_TREE_DISCONNECT:
894     next_state = SMB_DONE;
895     break;
896
897   default:
898     smb_pop_message(conn);
899     return CURLE_OK; /* ignore */
900   }
901
902   smb_pop_message(conn);
903
904   switch(next_state) {
905   case SMB_OPEN:
906     result = smb_send_open(data);
907     break;
908
909   case SMB_DOWNLOAD:
910     result = smb_send_read(data);
911     break;
912
913   case SMB_UPLOAD:
914     result = smb_send_write(data);
915     break;
916
917   case SMB_CLOSE:
918     result = smb_send_close(data);
919     break;
920
921   case SMB_TREE_DISCONNECT:
922     result = smb_send_tree_disconnect(data);
923     break;
924
925   case SMB_DONE:
926     result = req->result;
927     *done = true;
928     break;
929
930   default:
931     break;
932   }
933
934   if(result) {
935     connclose(conn, "SMB: failed to send message");
936     return result;
937   }
938
939   request_state(data, next_state);
940
941   return CURLE_OK;
942 }
943
944 static CURLcode smb_done(struct Curl_easy *data, CURLcode status,
945                          bool premature)
946 {
947   (void) premature;
948   Curl_safefree(data->req.p.smb);
949   return status;
950 }
951
952 static CURLcode smb_disconnect(struct Curl_easy *data,
953                                struct connectdata *conn, bool dead)
954 {
955   struct smb_conn *smbc = &conn->proto.smbc;
956   (void) dead;
957   (void) data;
958   Curl_safefree(smbc->share);
959   Curl_safefree(smbc->domain);
960   Curl_safefree(smbc->recv_buf);
961   return CURLE_OK;
962 }
963
964 static int smb_getsock(struct Curl_easy *data,
965                        struct connectdata *conn, curl_socket_t *socks)
966 {
967   (void)data;
968   socks[0] = conn->sock[FIRSTSOCKET];
969   return GETSOCK_READSOCK(0) | GETSOCK_WRITESOCK(0);
970 }
971
972 static CURLcode smb_do(struct Curl_easy *data, bool *done)
973 {
974   struct connectdata *conn = data->conn;
975   struct smb_conn *smbc = &conn->proto.smbc;
976
977   *done = FALSE;
978   if(smbc->share) {
979     return CURLE_OK;
980   }
981   return CURLE_URL_MALFORMAT;
982 }
983
984 static CURLcode smb_parse_url_path(struct Curl_easy *data,
985                                    struct connectdata *conn)
986 {
987   struct smb_request *req = data->req.p.smb;
988   struct smb_conn *smbc = &conn->proto.smbc;
989   char *path;
990   char *slash;
991
992   /* URL decode the path */
993   CURLcode result = Curl_urldecode(data->state.up.path, 0, &path, NULL,
994                                    REJECT_CTRL);
995   if(result)
996     return result;
997
998   /* Parse the path for the share */
999   smbc->share = strdup((*path == '/' || *path == '\\') ? path + 1 : path);
1000   free(path);
1001   if(!smbc->share)
1002     return CURLE_OUT_OF_MEMORY;
1003
1004   slash = strchr(smbc->share, '/');
1005   if(!slash)
1006     slash = strchr(smbc->share, '\\');
1007
1008   /* The share must be present */
1009   if(!slash) {
1010     Curl_safefree(smbc->share);
1011     return CURLE_URL_MALFORMAT;
1012   }
1013
1014   /* Parse the path for the file path converting any forward slashes into
1015      backslashes */
1016   *slash++ = 0;
1017   req->path = slash;
1018
1019   for(; *slash; slash++) {
1020     if(*slash == '/')
1021       *slash = '\\';
1022   }
1023   return CURLE_OK;
1024 }
1025
1026 #endif /* CURL_DISABLE_SMB && USE_CURL_NTLM_CORE &&
1027           SIZEOF_CURL_OFF_T > 4 */