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