VirtualBox

source: vbox/trunk/src/VBox/Devices/Storage/ISCSIHDDCore.cpp@ 23613

Last change on this file since 23613 was 23594, checked in by vboxsync, 15 years ago

Storage/iSCSI: add config value to define the threshold for write splitting.

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 128.3 KB
Line 
1/** @file
2 * iSCSI initiator driver, VD backend.
3 */
4
5/*
6 * Copyright (C) 2006-2009 Sun Microsystems, Inc.
7 *
8 * This file is part of VirtualBox Open Source Edition (OSE), as
9 * available from http://www.virtualbox.org. This file is free software;
10 * you can redistribute it and/or modify it under the terms of the GNU
11 * General Public License (GPL) as published by the Free Software
12 * Foundation, in version 2 as it comes in the "COPYING" file of the
13 * VirtualBox OSE distribution. VirtualBox OSE is distributed in the
14 * hope that it will be useful, but WITHOUT ANY WARRANTY of any kind.
15 *
16 * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa
17 * Clara, CA 95054 USA or visit http://www.sun.com if you need
18 * additional information or have any questions.
19 */
20
21
22/*******************************************************************************
23* Header Files *
24*******************************************************************************/
25#define LOG_GROUP LOG_GROUP_VD_ISCSI
26#include <VBox/VBoxHDD-Plugin.h>
27#define VBOX_VDICORE_VD /* Signal that the header is included from here. */
28#include "VDICore.h"
29#include <VBox/err.h>
30
31#include <VBox/log.h>
32#include <iprt/alloc.h>
33#include <iprt/assert.h>
34#include <iprt/uuid.h>
35#include <iprt/file.h>
36#include <iprt/string.h>
37#include <iprt/asm.h>
38#include <iprt/thread.h>
39#include <iprt/semaphore.h>
40#include <iprt/md5.h>
41#include <iprt/tcp.h>
42#include <iprt/time.h>
43#include <VBox/scsi.h>
44
45
46/*******************************************************************************
47* Defined Constants And Macros *
48*******************************************************************************/
49
50/** Default port number to use for iSCSI. */
51#define ISCSI_DEFAULT_PORT 3260
52
53
54/** Converts a number in the range of 0 - 15 into the corresponding hex char. */
55#define NUM_2_HEX(b) ('0' + (b) + (((b) > 9) ? 39 : 0))
56/** Converts a hex char into the corresponding number in the range 0-15. */
57#define HEX_2_NUM(c) (((c) <= '9') ? ((c) - '0') : (((c - 'A' + 10) & 0xf)))
58/* Converts a base64 char into the corresponding number in the range 0-63. */
59#define B64_2_NUM(c) ((c >= 'A' && c <= 'Z') ? (c - 'A') : (c >= 'a' && c <= 'z') ? (c - 'a' + 26) : (c >= '0' && c <= '9') ? (c - '0' + 52) : (c == '+') ? 62 : (c == '/') ? 63 : -1)
60
61
62/** Minumum CHAP_MD5 challenge length in bytes. */
63#define CHAP_MD5_CHALLENGE_MIN 16
64/** Maximum CHAP_MD5 challenge length in bytes. */
65#define CHAP_MD5_CHALLENGE_MAX 24
66
67
68/**
69 * SCSI peripheral device type. */
70typedef enum SCSIDEVTYPE
71{
72 /** direct-access device. */
73 SCSI_DEVTYPE_DISK = 0,
74 /** sequential-access device. */
75 SCSI_DEVTYPE_TAPE,
76 /** printer device. */
77 SCSI_DEVTYPE_PRINTER,
78 /** processor device. */
79 SCSI_DEVTYPE_PROCESSOR,
80 /** write-once device. */
81 SCSI_DEVTYPE_WORM,
82 /** CD/DVD device. */
83 SCSI_DEVTYPE_CDROM,
84 /** scanner device. */
85 SCSI_DEVTYPE_SCANNER,
86 /** optical memory device. */
87 SCSI_DEVTYPE_OPTICAL,
88 /** medium changer. */
89 SCSI_DEVTYPE_CHANGER,
90 /** communications device. */
91 SCSI_DEVTYPE_COMMUNICATION,
92 /** storage array controller device. */
93 SCSI_DEVTYPE_RAIDCTL = 0x0c,
94 /** enclosure services device. */
95 SCSI_DEVTYPE_ENCLOSURE,
96 /** simplified direct-access device. */
97 SCSI_DEVTYPE_SIMPLEDISK,
98 /** optical card reader/writer device. */
99 SCSI_DEVTYPE_OCRW,
100 /** bridge controller device. */
101 SCSI_DEVTYPE_BRIDGE,
102 /** object-based storage device. */
103 SCSI_DEVTYPE_OSD
104} SCSIDEVTYPE;
105
106/** Mask for extracting the SCSI device type out of the first byte of the INQUIRY response. */
107#define SCSI_DEVTYPE_MASK 0x1f
108
109
110/** Maximum PDU payload size we can handle in one piece. Greater or equal than
111 * s_iscsiConfigDefaultWriteSplit. */
112#define ISCSI_DATA_LENGTH_MAX _256K
113
114/** Maximum PDU size we can handle in one piece. */
115#define ISCSI_RECV_PDU_BUFFER_SIZE (ISCSI_DATA_LENGTH_MAX + ISCSI_BHS_SIZE)
116
117
118/** Version of the iSCSI standard which this initiator driver can handle. */
119#define ISCSI_MY_VERSION 0
120
121
122/** Length of ISCSI basic header segment. */
123#define ISCSI_BHS_SIZE 48
124
125
126/** Reserved task tag value. */
127#define ISCSI_TASK_TAG_RSVD 0xffffffff
128
129
130/**
131 * iSCSI opcodes. */
132typedef enum ISCSIOPCODE
133{
134 /** NOP-Out. */
135 ISCSIOP_NOP_OUT = 0x00000000,
136 /** SCSI command. */
137 ISCSIOP_SCSI_CMD = 0x01000000,
138 /** SCSI task management request. */
139 ISCSIOP_SCSI_TASKMGMT_REQ = 0x02000000,
140 /** Login request. */
141 ISCSIOP_LOGIN_REQ = 0x03000000,
142 /** Text request. */
143 ISCSIOP_TEXT_REQ = 0x04000000,
144 /** SCSI Data-Out. */
145 ISCSIOP_SCSI_DATA_OUT = 0x05000000,
146 /** Logout request. */
147 ISCSIOP_LOGOUT_REQ = 0x06000000,
148 /** SNACK request. */
149 ISCSIOP_SNACK_REQ = 0x10000000,
150
151 /** NOP-In. */
152 ISCSIOP_NOP_IN = 0x20000000,
153 /** SCSI response. */
154 ISCSIOP_SCSI_RES = 0x21000000,
155 /** SCSI Task Management response. */
156 ISCSIOP_SCSI_TASKMGMT_RES = 0x22000000,
157 /** Login response. */
158 ISCSIOP_LOGIN_RES = 0x23000000,
159 /** Text response. */
160 ISCSIOP_TEXT_RES = 0x24000000,
161 /** SCSI Data-In. */
162 ISCSIOP_SCSI_DATA_IN = 0x25000000,
163 /** Logout response. */
164 ISCSIOP_LOGOUT_RES = 0x26000000,
165 /** Ready To Transfer (R2T). */
166 ISCSIOP_R2T = 0x31000000,
167 /** Asynchronous message. */
168 ISCSIOP_ASYN_MSG = 0x32000000,
169 /** Reject. */
170 ISCSIOP_REJECT = 0x3f000000
171} ISCSIOPCODE;
172
173/** Mask for extracting the iSCSI opcode out of the first header word. */
174#define ISCSIOP_MASK 0x3f000000
175
176
177/** ISCSI BHS word 0: Request should be processed immediately. */
178#define ISCSI_IMMEDIATE_DELIVERY_BIT 0x40000000
179
180/** ISCSI BHS word 0: This is the final PDU for this request/response. */
181#define ISCSI_FINAL_BIT 0x00800000
182/** ISCSI BHS word 0: Mask for extracting the CSG. */
183#define ISCSI_CSG_MASK 0x000c0000
184/** ISCSI BHS word 0: Shift offset for extracting the CSG. */
185#define ISCSI_CSG_SHIFT 18
186/** ISCSI BHS word 0: Mask for extracting the NSG. */
187#define ISCSI_NSG_MASK 0x00030000
188/** ISCSI BHS word 0: Shift offset for extracting the NSG. */
189#define ISCSI_NSG_SHIFT 16
190
191/** ISCSI BHS word 0: task attribute untagged */
192#define ISCSI_TASK_ATTR_UNTAGGED 0x00000000
193/** ISCSI BHS word 0: task attribute simple */
194#define ISCSI_TASK_ATTR_SIMPLE 0x00010000
195/** ISCSI BHS word 0: task attribute ordered */
196#define ISCSI_TASK_ATTR_ORDERED 0x00020000
197/** ISCSI BHS word 0: task attribute head of queue */
198#define ISCSI_TASK_ATTR_HOQ 0x00030000
199/** ISCSI BHS word 0: task attribute ACA */
200#define ISCSI_TASK_ATTR_ACA 0x00040000
201
202/** ISCSI BHS word 0: transit to next login phase. */
203#define ISCSI_TRANSIT_BIT 0x00800000
204/** ISCSI BHS word 0: continue with login negotiation. */
205#define ISCSI_CONTINUE_BIT 0x00400000
206
207/** ISCSI BHS word 0: residual underflow. */
208#define ISCSI_RESIDUAL_UNFL_BIT 0x00020000
209/** ISCSI BHS word 0: residual overflow. */
210#define ISCSI_RESIDUAL_OVFL_BIT 0x00040000
211/** ISCSI BHS word 0: Bidirectional read residual underflow. */
212#define ISCSI_BI_READ_RESIDUAL_UNFL_BIT 0x00080000
213/** ISCSI BHS word 0: Bidirectional read residual overflow. */
214#define ISCSI_BI_READ_RESIDUAL_OVFL_BIT 0x00100000
215
216/** ISCSI BHS word 0: SCSI response mask. */
217#define ISCSI_SCSI_RESPONSE_MASK 0x0000ff00
218/** ISCSI BHS word 0: SCSI status mask. */
219#define ISCSI_SCSI_STATUS_MASK 0x000000ff
220
221/** ISCSI BHS word 0: response includes status. */
222#define ISCSI_STATUS_BIT 0x00010000
223
224
225/**
226 * iSCSI login status class. */
227typedef enum ISCSILOGINSTATUSCLASS
228{
229 /** Success. */
230 ISCSI_LOGIN_STATUS_CLASS_SUCCESS = 0,
231 /** Redirection. */
232 ISCSI_LOGIN_STATUS_CLASS_REDIRECTION,
233 /** Initiator error. */
234 ISCSI_LOGIN_STATUS_CLASS_INITIATOR_ERROR,
235 /** Target error. */
236 ISCSI_LOGIN_STATUS_CLASS_TARGET_ERROR
237} ISCSILOGINSTATUSCLASS;
238
239
240/**
241 * iSCSI connection state. */
242typedef enum ISCSISTATE
243{
244 /** Not having a connection/session at all. */
245 ISCSISTATE_FREE,
246 /** Currently trying to login. */
247 ISCSISTATE_IN_LOGIN,
248 /** Normal operation, corresponds roughly to the Full Feature Phase. */
249 ISCSISTATE_NORMAL,
250 /** Currently trying to logout. */
251 ISCSISTATE_IN_LOGOUT
252} ISCSISTATE;
253
254
255/*******************************************************************************
256* Structures and Typedefs *
257*******************************************************************************/
258/**
259 * Block driver instance data.
260 */
261typedef struct ISCSIIMAGE
262{
263 /** Pointer to the filename (location). Not really used. */
264 const char *pszFilename;
265 /** Pointer to the initiator name. */
266 char *pszInitiatorName;
267 /** Pointer to the target name. */
268 char *pszTargetName;
269 /** Pointer to the target address. */
270 char *pszTargetAddress;
271 /** Pointer to the user name for authenticating the Initiator. */
272 char *pszInitiatorUsername;
273 /** Pointer to the secret for authenticating the Initiator. */
274 uint8_t *pbInitiatorSecret;
275 /** Length of the secret for authenticating the Initiator. */
276 size_t cbInitiatorSecret;
277 /** Pointer to the user name for authenticating the Target. */
278 char *pszTargetUsername;
279 /** Pointer to the secret for authenticating the Initiator. */
280 uint8_t *pbTargetSecret;
281 /** Length of the secret for authenticating the Initiator. */
282 size_t cbTargetSecret;
283 /** Limit for iSCSI writes, essentially limiting the amount of data
284 * written in a single write. This is negotiated with the target, so
285 * the actual size might be smaller. */
286 uint32_t cbWriteSplit;
287 /** Initiator session identifier. */
288 uint64_t ISID;
289 /** SCSI Logical Unit Number. */
290 uint64_t LUN;
291 /** Pointer to the per-disk VD interface list. */
292 PVDINTERFACE pVDIfsDisk;
293 /** Error interface. */
294 PVDINTERFACE pInterfaceError;
295 /** Error interface callback table. */
296 PVDINTERFACEERROR pInterfaceErrorCallbacks;
297 /** TCP network stack interface. */
298 PVDINTERFACE pInterfaceNet;
299 /** TCP network stack interface callback table. */
300 PVDINTERFACETCPNET pInterfaceNetCallbacks;
301 /** Pointer to the per-image VD interface list. */
302 PVDINTERFACE pVDIfsImage;
303 /** Config interface. */
304 PVDINTERFACE pInterfaceConfig;
305 /** Config interface callback table. */
306 PVDINTERFACECONFIG pInterfaceConfigCallbacks;
307 /** Image open flags. */
308 unsigned uOpenFlags;
309 /** Number of re-login retries when a connection fails. */
310 uint32_t cISCSIRetries;
311 /** Size of volume in sectors. */
312 uint32_t cVolume;
313 /** Sector size on volume. */
314 uint32_t cbSector;
315 /** Total volume size in bytes. Easiert that multiplying the above values all the time. */
316 uint64_t cbSize;
317
318 /** Negotiated maximum data length when sending to target. */
319 uint32_t cbSendDataLength;
320 /** Negotiated maximum data length when receiving from target. */
321 uint32_t cbRecvDataLength;
322
323 /** Current state of the connection/session. */
324 ISCSISTATE state;
325 /** Flag whether the first Login Response PDU has been seen. */
326 bool FirstRecvPDU;
327 /** Initiator Task Tag of the last iSCSI request PDU. */
328 uint32_t ITT;
329 /** Sequence number of the last command. */
330 uint32_t CmdSN;
331 /** Sequence number of the next command expected by the target. */
332 uint32_t ExpCmdSN;
333 /** Maximum sequence number accepted by the target (determines size of window). */
334 uint32_t MaxCmdSN;
335 /** Expected sequence number of next status. */
336 uint32_t ExpStatSN;
337 /** Currently active request. */
338 PISCSIREQ paCurrReq;
339 /** Segment number of currently active request. */
340 uint32_t cnCurrReq;
341 /** Pointer to receive PDU buffer. (Freed by RT) */
342 void *pvRecvPDUBuf;
343 /** Length of receive PDU buffer. */
344 size_t cbRecvPDUBuf;
345 /** Mutex protecting against concurrent use from several threads. */
346 RTSEMMUTEX Mutex;
347
348 /** Pointer to the target hostname. */
349 char *pszHostname;
350 /** Pointer to the target hostname. */
351 uint32_t uPort;
352 /** Socket handle of the TCP connection. */
353 RTSOCKET Socket;
354 /** Timeout for read operations on the TCP connection (in milliseconds). */
355 uint32_t uReadTimeout;
356 /** Flag whether to use the host IP stack or DevINIP. */
357 bool fHostIP;
358} ISCSIIMAGE, *PISCSIIMAGE;
359
360
361/**
362 * SCSI transfer directions.
363 */
364typedef enum SCSIXFER
365{
366 SCSIXFER_NONE = 0,
367 SCSIXFER_TO_TARGET,
368 SCSIXFER_FROM_TARGET,
369 SCSIXFER_TO_FROM_TARGET
370} SCSIXFER, *PSCSIXFER;
371
372
373/**
374 * SCSI request structure.
375 */
376typedef struct SCSIREQ
377{
378 /** Transfer direction. */
379 SCSIXFER enmXfer;
380 /** Length of command block. */
381 size_t cbCmd;
382 /** Length of Initiator2Target data buffer. */
383 size_t cbI2TData;
384 /** Length of Target2Initiator data buffer. */
385 size_t cbT2IData;
386 /** Length of sense buffer. */
387 size_t cbSense;
388 /** Completion status of the command. */
389 uint8_t status;
390 /** Pointer to command block. */
391 void *pvCmd;
392 /** Pointer to Initiator2Target data buffer. */
393 const void *pcvI2TData;
394 /** Pointer to Target2Initiator data buffer. */
395 void *pvT2IData;
396 /** Pointer to sense buffer. */
397 void *pvSense;
398} SCSIREQ, *PSCSIREQ;
399
400
401/**
402 * iSCSI login negotiation parameter
403 */
404typedef struct ISCSIPARAMETER
405{
406 /** Name of the parameter. */
407 const char *pszParamName;
408 /** Value of the parameter. */
409 const char *pszParamValue;
410 /** Length of the binary parameter. 0=zero-terminated string. */
411 size_t cbParamValue;
412} ISCSIPARAMETER;
413
414
415/*******************************************************************************
416* Static Variables *
417*******************************************************************************/
418
419/** Counter for getting unique instance IDs. */
420static uint32_t s_u32iscsiID = 0;
421
422/** Default LUN. */
423static const char *s_iscsiConfigDefaultLUN = "0";
424
425/** Default initiator name. */
426static const char *s_iscsiConfigDefaultInitiatorName = "iqn.2009-08.com.sun.virtualbox.initiator";
427
428/** Default timeout, 10 seconds. */
429static const char *s_iscsiConfigDefaultTimeout = "10000";
430
431/** Default write split value, less or equal to ISCSI_DATA_LENGTH_MAX. */
432static const char *s_iscsiConfigDefaultWriteSplit = "262144";
433
434/** Default host IP stack. */
435static const char *s_iscsiConfigDefaultHostIPStack = "1";
436
437/** Description of all accepted config parameters. */
438static const VDCONFIGINFO s_iscsiConfigInfo[] =
439{
440 { "TargetName", NULL, VDCFGVALUETYPE_STRING, VD_CFGKEY_MANDATORY },
441 /* LUN is defined of string type to handle the "enc" prefix. */
442 { "LUN", s_iscsiConfigDefaultLUN, VDCFGVALUETYPE_STRING, VD_CFGKEY_MANDATORY },
443 { "TargetAddress", NULL, VDCFGVALUETYPE_STRING, VD_CFGKEY_MANDATORY },
444 { "InitiatorName", s_iscsiConfigDefaultInitiatorName, VDCFGVALUETYPE_STRING, 0 },
445 { "InitiatorUsername", NULL, VDCFGVALUETYPE_STRING, 0 },
446 { "InitiatorSecret", NULL, VDCFGVALUETYPE_BYTES, 0 },
447 { "TargetUsername", NULL, VDCFGVALUETYPE_STRING, VD_CFGKEY_EXPERT },
448 { "TargetSecret", NULL, VDCFGVALUETYPE_BYTES, VD_CFGKEY_EXPERT },
449 { "WriteSplit", s_iscsiConfigDefaultWriteSplit, VDCFGVALUETYPE_INTEGER, VD_CFGKEY_EXPERT },
450 { "Timeout", s_iscsiConfigDefaultTimeout, VDCFGVALUETYPE_INTEGER, VD_CFGKEY_EXPERT },
451 { "HostIPStack", s_iscsiConfigDefaultHostIPStack, VDCFGVALUETYPE_INTEGER, VD_CFGKEY_EXPERT },
452 { NULL, NULL, VDCFGVALUETYPE_INTEGER, 0 }
453};
454
455/*******************************************************************************
456* Internal Functions *
457*******************************************************************************/
458
459/* iSCSI low-level functions (only to be used from the iSCSI high-level functions). */
460static uint32_t iscsiNewITT(PISCSIIMAGE pImage);
461static int iscsiSendPDU(PISCSIIMAGE pImage, PISCSIREQ paReq, uint32_t cnReq);
462static int iscsiRecvPDU(PISCSIIMAGE pImage, uint32_t itt, PISCSIRES paRes, uint32_t cnRes);
463static int drvISCSIValidatePDU(PISCSIRES paRes, uint32_t cnRes);
464static int iscsiTextAddKeyValue(uint8_t *pbBuf, size_t cbBuf, size_t *pcbBufCurr, const char *pcszKey, const char *pcszValue, size_t cbValue);
465static int iscsiTextGetKeyValue(const uint8_t *pbBuf, size_t cbBuf, const char *pcszKey, const char **ppcszValue);
466static int iscsiStrToBinary(const char *pcszValue, uint8_t *pbValue, size_t *pcbValue);
467static int iscsiUpdateParameters(PISCSIIMAGE pImage, const uint8_t *pbBuf, size_t cbBuf);
468
469/* Serial number arithmetic comparison. */
470static bool serial_number_less(uint32_t sn1, uint32_t sn2);
471
472/* CHAP-MD5 functions. */
473#ifdef IMPLEMENT_TARGET_AUTH
474static void chap_md5_generate_challenge(uint8_t *pbChallenge, size_t *pcbChallenge);
475#endif
476static void chap_md5_compute_response(uint8_t *pbResponse, uint8_t id, const uint8_t *pbChallenge, size_t cbChallenge,
477 const uint8_t *pbSecret, size_t cbSecret);
478
479
480/**
481 * Internal: signal an error to the frontend.
482 */
483DECLINLINE(int) iscsiError(PISCSIIMAGE pImage, int rc, RT_SRC_POS_DECL,
484 const char *pszFormat, ...)
485{
486 va_list va;
487 va_start(va, pszFormat);
488 if (pImage->pInterfaceError)
489 pImage->pInterfaceErrorCallbacks->pfnError(pImage->pInterfaceError->pvUser, rc, RT_SRC_POS_ARGS,
490 pszFormat, va);
491 va_end(va);
492 return rc;
493}
494
495
496static int iscsiTransportRead(PISCSIIMAGE pImage, PISCSIRES paResponse, unsigned int cnResponse)
497{
498 int rc = VINF_SUCCESS;
499 unsigned int i = 0;
500 size_t cbToRead, cbActuallyRead, residual, cbSegActual = 0, cbAHSLength, cbDataLength;
501 char *pDst;
502
503 LogFlowFunc(("cnResponse=%d (%s:%d)\n", cnResponse, pImage->pszHostname, pImage->uPort));
504 if (pImage->Socket == NIL_RTSOCKET)
505 {
506 /* Attempt to reconnect if the connection was previously broken. */
507 if (pImage->pszHostname != NULL)
508 {
509 rc = pImage->pInterfaceNetCallbacks->pfnClientConnect(pImage->pszHostname, pImage->uPort, &pImage->Socket);
510 if (RT_UNLIKELY( RT_FAILURE(rc)
511 && ( rc == VERR_NET_CONNECTION_REFUSED
512 || rc == VERR_NET_CONNECTION_RESET
513 || rc == VERR_NET_UNREACHABLE
514 || rc == VERR_NET_HOST_UNREACHABLE
515 || rc == VERR_NET_CONNECTION_TIMED_OUT)))
516 {
517 /* Standardize return value for no connection. */
518 rc = VERR_NET_CONNECTION_REFUSED;
519 }
520 }
521 }
522
523 if (RT_SUCCESS(rc) && paResponse[0].cbSeg >= 48)
524 {
525 cbToRead = 0;
526 residual = 48; /* Do not read more than the BHS length before the true PDU length is known. */
527 cbSegActual = residual;
528 pDst = (char *)paResponse[i].pvSeg;
529 uint64_t u64Timeout = RTTimeMilliTS() + pImage->uReadTimeout;
530 do
531 {
532 int64_t cMilliesRemaining = u64Timeout - RTTimeMilliTS();
533 if (cMilliesRemaining <= 0)
534 {
535 rc = VERR_TIMEOUT;
536 break;
537 }
538 Assert(cMilliesRemaining < 1000000);
539 rc = pImage->pInterfaceNetCallbacks->pfnSelectOne(pImage->Socket,
540 cMilliesRemaining);
541 if (RT_FAILURE(rc))
542 break;
543 rc = pImage->pInterfaceNetCallbacks->pfnRead(pImage->Socket,
544 pDst, residual,
545 &cbActuallyRead);
546 if (RT_FAILURE(rc))
547 break;
548 if (cbActuallyRead == 0)
549 {
550 /* The other end has closed the connection. */
551 pImage->pInterfaceNetCallbacks->pfnClientClose(pImage->Socket);
552 pImage->Socket = NIL_RTSOCKET;
553 rc = VERR_NET_CONNECTION_RESET;
554 break;
555 }
556 if (cbToRead == 0)
557 {
558 /* Currently reading the BHS. */
559 residual -= cbActuallyRead;
560 pDst += cbActuallyRead;
561 if (residual <= 40)
562 {
563 /* Enough data read to figure out the actual PDU size. */
564 uint32_t word1 = RT_N2H_U32(((uint32_t *)(paResponse[0].pvSeg))[1]);
565 cbAHSLength = (word1 & 0xff000000) >> 24;
566 cbAHSLength = ((cbAHSLength - 1) | 3) + 1; /* Add padding. */
567 cbDataLength = word1 & 0x00ffffff;
568 cbDataLength = ((cbDataLength - 1) | 3) + 1; /* Add padding. */
569 cbToRead = residual + cbAHSLength + cbDataLength;
570 residual += paResponse[0].cbSeg - 48;
571 if (residual > cbToRead)
572 residual = cbToRead;
573 cbSegActual = 48 + cbAHSLength + cbDataLength;
574 /* Check whether we are already done with this PDU (no payload). */
575 if (cbToRead == 0)
576 break;
577 }
578 }
579 else
580 {
581 cbToRead -= cbActuallyRead;
582 if (cbToRead == 0)
583 break;
584 pDst += cbActuallyRead;
585 residual -= cbActuallyRead;
586 }
587 if (residual == 0)
588 {
589 i++;
590 if (i >= cnResponse)
591 {
592 /* No space left in receive buffers. */
593 rc = VERR_BUFFER_OVERFLOW;
594 break;
595 }
596 pDst = (char *)paResponse[i].pvSeg;
597 residual = paResponse[i].cbSeg;
598 if (residual > cbToRead)
599 residual = cbToRead;
600 cbSegActual = residual;
601 }
602 } while (true);
603 }
604 else
605 {
606 if (RT_SUCCESS(rc))
607 rc = VERR_BUFFER_OVERFLOW;
608 }
609 if (RT_SUCCESS(rc))
610 {
611 paResponse[i].cbSeg = cbSegActual;
612 for (i++; i < cnResponse; i++)
613 paResponse[i].cbSeg = 0;
614 }
615
616 if (RT_UNLIKELY( RT_FAILURE(rc)
617 && ( rc == VERR_NET_CONNECTION_RESET
618 || rc == VERR_NET_CONNECTION_ABORTED
619 || rc == VERR_NET_CONNECTION_RESET_BY_PEER
620 || rc == VERR_NET_CONNECTION_REFUSED
621 || rc == VERR_BROKEN_PIPE)))
622 {
623 /* Standardize return value for broken connection. */
624 rc = VERR_BROKEN_PIPE;
625 }
626
627 LogFlowFunc(("returns %Rrc\n", rc));
628 return rc;
629}
630
631
632static int iscsiTransportWrite(PISCSIIMAGE pImage, PISCSIREQ paRequest, unsigned int cnRequest)
633{
634 int rc = VINF_SUCCESS;
635 uint32_t pad = 0;
636 unsigned int i;
637
638 LogFlow(("drvISCSITransportTcpWrite: cnRequest=%d (%s:%d)\n", cnRequest, pImage->pszHostname, pImage->uPort));
639 if (pImage->Socket == NIL_RTSOCKET)
640 {
641 /* Attempt to reconnect if the connection was previously broken. */
642 if (pImage->pszHostname != NULL)
643 {
644 rc = pImage->pInterfaceNetCallbacks->pfnClientConnect(pImage->pszHostname, pImage->uPort, &pImage->Socket);
645 if (RT_UNLIKELY( RT_FAILURE(rc)
646 && ( rc == VERR_NET_CONNECTION_REFUSED
647 || rc == VERR_NET_CONNECTION_RESET
648 || rc == VERR_NET_UNREACHABLE
649 || rc == VERR_NET_HOST_UNREACHABLE
650 || rc == VERR_NET_CONNECTION_TIMED_OUT)))
651 {
652 /* Standardize return value for no connection. */
653 rc = VERR_NET_CONNECTION_REFUSED;
654 }
655 }
656 }
657
658 if (RT_SUCCESS(rc))
659 {
660 for (i = 0; i < cnRequest; i++)
661 {
662 /* Write one chunk of data. */
663 rc = pImage->pInterfaceNetCallbacks->pfnWrite(pImage->Socket,
664 paRequest[i].pcvSeg,
665 paRequest[i].cbSeg);
666 if (RT_FAILURE(rc))
667 break;
668 /* Insert proper padding before the next chunk us written. */
669 if (paRequest[i].cbSeg & 3)
670 {
671 rc = pImage->pInterfaceNetCallbacks->pfnWrite(pImage->Socket,
672 &pad,
673 4 - (paRequest[i].cbSeg & 3));
674 if (RT_FAILURE(rc))
675 break;
676 }
677 }
678 /* Send out the request as soon as possible, otherwise the target will
679 * answer after an unnecessary delay. */
680 pImage->pInterfaceNetCallbacks->pfnFlush(pImage->Socket);
681 }
682
683 if (RT_UNLIKELY( RT_FAILURE(rc)
684 && ( rc == VERR_NET_CONNECTION_RESET
685 || rc == VERR_NET_CONNECTION_ABORTED
686 || rc == VERR_NET_CONNECTION_RESET_BY_PEER
687 || rc == VERR_NET_CONNECTION_REFUSED
688 || rc == VERR_BROKEN_PIPE)))
689 {
690 /* Standardize return value for broken connection. */
691 rc = VERR_BROKEN_PIPE;
692 }
693
694 LogFlow(("drvISCSITransportTcpWrite: returns %Rrc\n", rc));
695 return rc;
696}
697
698
699static int iscsiTransportOpen(PISCSIIMAGE pImage)
700{
701 int rc = VINF_SUCCESS;
702 size_t cbHostname = 0; /* shut up gcc */
703 const char *pcszPort = NULL; /* shut up gcc */
704 char *pszPortEnd;
705 uint16_t uPort;
706
707 /* Clean up previous connection data. */
708 if (pImage->Socket != NIL_RTSOCKET)
709 {
710 pImage->pInterfaceNetCallbacks->pfnClientClose(pImage->Socket);
711 pImage->Socket = NIL_RTSOCKET;
712 }
713 if (pImage->pszHostname)
714 {
715 RTMemFree(pImage->pszHostname);
716 pImage->pszHostname = NULL;
717 pImage->uPort = 0;
718 }
719
720 /* Locate the port number via the colon separating the hostname from the port. */
721 if (*pImage->pszTargetAddress)
722 {
723 if (*pImage->pszTargetAddress != '[')
724 {
725 /* Normal hostname or IPv4 dotted decimal. */
726 pcszPort = strchr(pImage->pszTargetAddress, ':');
727 if (pcszPort != NULL)
728 {
729 cbHostname = pcszPort - pImage->pszTargetAddress;
730 pcszPort++;
731 }
732 else
733 cbHostname = strlen(pImage->pszTargetAddress);
734 }
735 else
736 {
737 /* IPv6 literal address. Contains colons, so skip to closing square bracket. */
738 pcszPort = strchr(pImage->pszTargetAddress, ']');
739 if (pcszPort != NULL)
740 {
741 pcszPort++;
742 cbHostname = pcszPort - pImage->pszTargetAddress;
743 if (*pcszPort == '\0')
744 pcszPort = NULL;
745 else if (*pcszPort != ':')
746 rc = VERR_PARSE_ERROR;
747 else
748 pcszPort++;
749 }
750 else
751 rc = VERR_PARSE_ERROR;
752 }
753 }
754 else
755 rc = VERR_PARSE_ERROR;
756
757 /* Now split address into hostname and port. */
758 if (RT_SUCCESS(rc))
759 {
760 pImage->pszHostname = (char *)RTMemAlloc(cbHostname + 1);
761 if (!pImage->pszHostname)
762 rc = VERR_NO_MEMORY;
763 else
764 {
765 memcpy(pImage->pszHostname, pImage->pszTargetAddress, cbHostname);
766 pImage->pszHostname[cbHostname] = '\0';
767 if (pcszPort != NULL)
768 {
769 rc = RTStrToUInt16Ex(pcszPort, &pszPortEnd, 0, &uPort);
770 /* Note that RT_SUCCESS() macro to check the rc value is not strict enough in this case. */
771 if (rc == VINF_SUCCESS && *pszPortEnd == '\0' && uPort != 0)
772 {
773 pImage->uPort = uPort;
774 }
775 else
776 {
777 rc = VERR_PARSE_ERROR;
778 }
779 }
780 else
781 pImage->uPort = ISCSI_DEFAULT_PORT;
782 }
783 }
784
785 if (RT_FAILURE(rc))
786 {
787 if (pImage->pszHostname)
788 {
789 RTMemFree(pImage->pszHostname);
790 pImage->pszHostname = NULL;
791 }
792 pImage->uPort = 0;
793 }
794
795 /* Note that in this implementation the actual connection establishment is
796 * delayed until a PDU is read or written. */
797 LogFlowFunc(("returns %Rrc\n", rc));
798 return rc;
799}
800
801
802static int iscsiTransportClose(PISCSIIMAGE pImage)
803{
804 int rc;
805
806 LogFlowFunc(("(%s:%d)\n", pImage->pszHostname, pImage->uPort));
807 if (pImage->Socket != NIL_RTSOCKET)
808 {
809 rc = pImage->pInterfaceNetCallbacks->pfnClientClose(pImage->Socket);
810 pImage->Socket = NIL_RTSOCKET;
811 }
812 else
813 rc = VINF_SUCCESS;
814 LogFlowFunc(("returns %Rrc\n", rc));
815 return rc;
816}
817
818
819/**
820 * Attach to an iSCSI target. Performs all operations necessary to enter
821 * Full Feature Phase.
822 *
823 * @returns VBox status.
824 * @param pImage The iSCSI connection state to be used.
825 */
826static int iscsiAttach(PISCSIIMAGE pImage)
827{
828 int rc;
829 uint32_t itt;
830 uint32_t csg, nsg, substate;
831 uint64_t isid_tsih;
832 uint8_t bBuf[4096]; /* Should be large enough even for large authentication values. */
833 size_t cbBuf;
834 bool transit;
835 uint8_t pbChallenge[1024]; /* RFC3720 specifies this as maximum. */
836 size_t cbChallenge = 0; /* shut up gcc */
837 uint8_t bChapIdx;
838 uint8_t aResponse[RTMD5HASHSIZE];
839 uint32_t cnISCSIReq;
840 ISCSIREQ aISCSIReq[4];
841 uint32_t aReqBHS[12];
842 uint32_t cnISCSIRes;
843 ISCSIRES aISCSIRes[2];
844 uint32_t aResBHS[12];
845 char *pszNext;
846
847 bool fParameterNeg = true;;
848 pImage->cbRecvDataLength = ISCSI_DATA_LENGTH_MAX;
849 pImage->cbSendDataLength = RT_MIN(ISCSI_DATA_LENGTH_MAX, pImage->cbWriteSplit);
850 char szMaxDataLength[16];
851 RTStrPrintf(szMaxDataLength, sizeof(szMaxDataLength), "%u", ISCSI_DATA_LENGTH_MAX);
852 ISCSIPARAMETER aParameterNeg[] =
853 {
854 { "HeaderDigest", "None", 0 },
855 { "DataDigest", "None", 0 },
856 { "MaxConnections", "1", 0 },
857 { "InitialR2T", "No", 0 },
858 { "ImmediateData", "Yes", 0 },
859 { "MaxRecvDataSegmentLength", szMaxDataLength, 0 },
860 { "MaxBurstLength", szMaxDataLength, 0 },
861 { "FirstBurstLength", szMaxDataLength, 0 },
862 { "DefaultTime2Wait", "0", 0 },
863 { "DefaultTime2Retain", "60", 0 },
864 { "DataPDUInOrder", "Yes", 0 },
865 { "DataSequenceInOrder", "Yes", 0 },
866 { "ErrorRecoveryLevel", "0", 0 },
867 { "MaxOutstandingR2T", "1", 0 }
868 };
869
870 LogFlowFunc(("entering\n"));
871
872 Assert(pImage->state == ISCSISTATE_FREE);
873
874 RTSemMutexRequest(pImage->Mutex, RT_INDEFINITE_WAIT);
875
876 /* Make 100% sure the connection isn't reused for a new login. */
877 iscsiTransportClose(pImage);
878
879restart:
880 pImage->state = ISCSISTATE_IN_LOGIN;
881 pImage->ITT = 1;
882 pImage->FirstRecvPDU = true;
883 pImage->CmdSN = 1;
884 pImage->ExpCmdSN = 0;
885 pImage->MaxCmdSN = 1;
886 pImage->ExpStatSN = 1;
887
888 /*
889 * Send login request to target.
890 */
891 itt = iscsiNewITT(pImage);
892 csg = 0;
893 nsg = 0;
894 substate = 0;
895 isid_tsih = pImage->ISID << 16; /* TSIH field currently always 0 */
896
897 do {
898 transit = false;
899 cbBuf = 0;
900 /* Handle all cases with a single switch statement. */
901 switch (csg << 8 | substate)
902 {
903 case 0x0000: /* security negotiation, step 0: propose authentication. */
904 rc = iscsiTextAddKeyValue(bBuf, sizeof(bBuf), &cbBuf, "SessionType", "Normal", 0);
905 if (RT_FAILURE(rc))
906 goto out;
907 rc = iscsiTextAddKeyValue(bBuf, sizeof(bBuf), &cbBuf, "InitiatorName", pImage->pszInitiatorName, 0);
908 if (RT_FAILURE(rc))
909 goto out;
910 rc = iscsiTextAddKeyValue(bBuf, sizeof(bBuf), &cbBuf, "TargetName", pImage->pszTargetName, 0);
911 if (RT_FAILURE(rc))
912 goto out;
913 if (pImage->pszInitiatorUsername == NULL)
914 {
915 /* No authentication. Immediately switch to next phase. */
916 rc = iscsiTextAddKeyValue(bBuf, sizeof(bBuf), &cbBuf, "AuthMethod", "None", 0);
917 if (RT_FAILURE(rc))
918 goto out;
919 nsg = 1;
920 transit = true;
921 }
922 else
923 {
924 rc = iscsiTextAddKeyValue(bBuf, sizeof(bBuf), &cbBuf, "AuthMethod", "CHAP,None", 0);
925 if (RT_FAILURE(rc))
926 goto out;
927 }
928 break;
929 case 0x0001: /* security negotiation, step 1: propose CHAP_MD5 variant. */
930 rc = iscsiTextAddKeyValue(bBuf, sizeof(bBuf), &cbBuf, "CHAP_A", "5", 0);
931 if (RT_FAILURE(rc))
932 goto out;
933 break;
934 case 0x0002: /* security negotiation, step 2: send authentication info. */
935 rc = iscsiTextAddKeyValue(bBuf, sizeof(bBuf), &cbBuf, "CHAP_N", pImage->pszInitiatorUsername, 0);
936 if (RT_FAILURE(rc))
937 goto out;
938 chap_md5_compute_response(aResponse, bChapIdx, pbChallenge, cbChallenge,
939 pImage->pbInitiatorSecret, pImage->cbInitiatorSecret);
940 rc = iscsiTextAddKeyValue(bBuf, sizeof(bBuf), &cbBuf, "CHAP_R", (const char *)aResponse, RTMD5HASHSIZE);
941 if (RT_FAILURE(rc))
942 goto out;
943 nsg = 1;
944 transit = true;
945 break;
946 case 0x0100: /* login operational negotiation, step 0: set parameters. */
947 if (fParameterNeg)
948 {
949 for (unsigned i = 0; i < RT_ELEMENTS(aParameterNeg); i++)
950 {
951 rc = iscsiTextAddKeyValue(bBuf, sizeof(bBuf), &cbBuf,
952 aParameterNeg[i].pszParamName,
953 aParameterNeg[i].pszParamValue,
954 aParameterNeg[i].cbParamValue);
955 if (RT_FAILURE(rc))
956 goto out;
957 }
958 fParameterNeg = false;
959 }
960
961 nsg = 3;
962 transit = true;
963 break;
964 case 0x0300: /* full feature phase. */
965 default:
966 /* Should never come here. */
967 AssertMsgFailed(("send: Undefined login state %d substate %d\n", csg, substate));
968 break;
969 }
970
971 aReqBHS[0] = RT_H2N_U32( ISCSI_IMMEDIATE_DELIVERY_BIT
972 | (csg << ISCSI_CSG_SHIFT)
973 | (transit ? (nsg << ISCSI_NSG_SHIFT | ISCSI_TRANSIT_BIT) : 0)
974 | ISCSI_MY_VERSION /* Minimum version. */
975 | (ISCSI_MY_VERSION << 8) /* Maximum version. */
976 | ISCSIOP_LOGIN_REQ); /* C=0 */
977 aReqBHS[1] = RT_H2N_U32((uint32_t)cbBuf); /* TotalAHSLength=0 */
978 aReqBHS[2] = RT_H2N_U32(isid_tsih >> 32);
979 aReqBHS[3] = RT_H2N_U32(isid_tsih & 0xffffffff);
980 aReqBHS[4] = itt;
981 aReqBHS[5] = RT_H2N_U32(1 << 16); /* CID=1,reserved */
982 aReqBHS[6] = RT_H2N_U32(pImage->CmdSN);
983 aReqBHS[7] = RT_H2N_U32(pImage->ExpStatSN);
984 aReqBHS[8] = 0; /* reserved */
985 aReqBHS[9] = 0; /* reserved */
986 aReqBHS[10] = 0; /* reserved */
987 aReqBHS[11] = 0; /* reserved */
988
989 cnISCSIReq = 0;
990 aISCSIReq[cnISCSIReq].pcvSeg = aReqBHS;
991 aISCSIReq[cnISCSIReq].cbSeg = sizeof(aReqBHS);
992 cnISCSIReq++;
993
994 aISCSIReq[cnISCSIReq].pcvSeg = bBuf;
995 aISCSIReq[cnISCSIReq].cbSeg = cbBuf;
996 cnISCSIReq++;
997
998 rc = iscsiSendPDU(pImage, aISCSIReq, cnISCSIReq);
999 if (RT_SUCCESS(rc))
1000 {
1001 ISCSIOPCODE cmd;
1002 ISCSILOGINSTATUSCLASS loginStatusClass;
1003
1004 cnISCSIRes = 0;
1005 aISCSIRes[cnISCSIRes].pvSeg = aResBHS;
1006 aISCSIRes[cnISCSIRes].cbSeg = sizeof(aResBHS);
1007 cnISCSIRes++;
1008 aISCSIRes[cnISCSIRes].pvSeg = bBuf;
1009 aISCSIRes[cnISCSIRes].cbSeg = sizeof(bBuf);
1010 cnISCSIRes++;
1011
1012 rc = iscsiRecvPDU(pImage, itt, aISCSIRes, cnISCSIRes);
1013 if (RT_FAILURE(rc))
1014 break;
1015 /** @todo collect partial login responses with Continue bit set. */
1016 Assert(aISCSIRes[0].pvSeg == aResBHS);
1017 Assert(aISCSIRes[0].cbSeg >= ISCSI_BHS_SIZE);
1018 Assert((RT_N2H_U32(aResBHS[0]) & ISCSI_CONTINUE_BIT) == 0);
1019
1020 cmd = (ISCSIOPCODE)(RT_N2H_U32(aResBHS[0]) & ISCSIOP_MASK);
1021 if (cmd == ISCSIOP_LOGIN_RES)
1022 {
1023 if ((RT_N2H_U32(aResBHS[0]) & 0xff) != ISCSI_MY_VERSION)
1024 {
1025 iscsiTransportClose(pImage);
1026 rc = VERR_PARSE_ERROR;
1027 break; /* Give up immediately, as a RFC violation in version fields is very serious. */
1028 }
1029
1030 loginStatusClass = (ISCSILOGINSTATUSCLASS)(RT_N2H_U32(aResBHS[9]) >> 24);
1031 switch (loginStatusClass)
1032 {
1033 case ISCSI_LOGIN_STATUS_CLASS_SUCCESS:
1034 uint32_t targetCSG;
1035 uint32_t targetNSG;
1036 bool targetTransit;
1037
1038 if (pImage->FirstRecvPDU)
1039 {
1040 pImage->FirstRecvPDU = false;
1041 pImage->ExpStatSN = RT_N2H_U32(aResBHS[6]) + 1;
1042 }
1043
1044 targetCSG = (RT_N2H_U32(aResBHS[0]) & ISCSI_CSG_MASK) >> ISCSI_CSG_SHIFT;
1045 targetNSG = (RT_N2H_U32(aResBHS[0]) & ISCSI_NSG_MASK) >> ISCSI_NSG_SHIFT;
1046 targetTransit = !!(RT_N2H_U32(aResBHS[0]) & ISCSI_TRANSIT_BIT);
1047
1048 /* Handle all cases with a single switch statement. */
1049 switch (csg << 8 | substate)
1050 {
1051 case 0x0000: /* security negotiation, step 0: receive final authentication. */
1052 rc = iscsiUpdateParameters(pImage, bBuf, aISCSIRes[1].cbSeg);
1053 if (RT_FAILURE(rc))
1054 break;
1055
1056 const char *pcszAuthMethod;
1057
1058 rc = iscsiTextGetKeyValue(bBuf, aISCSIRes[1].cbSeg, "AuthMethod", &pcszAuthMethod);
1059 if (RT_FAILURE(rc))
1060 {
1061 rc = VERR_PARSE_ERROR;
1062 break;
1063 }
1064 if (strcmp(pcszAuthMethod, "None") == 0)
1065 {
1066 /* Authentication offered, but none required. Skip to operational parameters. */
1067 csg = 1;
1068 nsg = 1;
1069 transit = true;
1070 substate = 0;
1071 break;
1072 }
1073 else if (strcmp(pcszAuthMethod, "CHAP") == 0 && targetNSG == 0 && !targetTransit)
1074 {
1075 /* CHAP authentication required, continue with next substate. */
1076 substate++;
1077 break;
1078 }
1079
1080 /* Unknown auth method or login response PDU headers incorrect. */
1081 rc = VERR_PARSE_ERROR;
1082 break;
1083 case 0x0001: /* security negotiation, step 1: receive final CHAP variant and challenge. */
1084 rc = iscsiUpdateParameters(pImage, bBuf, aISCSIRes[1].cbSeg);
1085 if (RT_FAILURE(rc))
1086 break;
1087
1088 const char *pcszChapAuthMethod;
1089 const char *pcszChapIdxTarget;
1090 const char *pcszChapChallengeStr;
1091
1092 rc = iscsiTextGetKeyValue(bBuf, aISCSIRes[1].cbSeg, "CHAP_A", &pcszChapAuthMethod);
1093 if (RT_FAILURE(rc))
1094 {
1095 rc = VERR_PARSE_ERROR;
1096 break;
1097 }
1098 if (strcmp(pcszChapAuthMethod, "5") != 0)
1099 {
1100 rc = VERR_PARSE_ERROR;
1101 break;
1102 }
1103 rc = iscsiTextGetKeyValue(bBuf, aISCSIRes[1].cbSeg, "CHAP_I", &pcszChapIdxTarget);
1104 if (RT_FAILURE(rc))
1105 {
1106 rc = VERR_PARSE_ERROR;
1107 break;
1108 }
1109 rc = RTStrToUInt8Ex(pcszChapIdxTarget, &pszNext, 0, &bChapIdx);
1110 if ((rc > VINF_SUCCESS) || *pszNext != '\0')
1111 {
1112 rc = VERR_PARSE_ERROR;
1113 break;
1114 }
1115 rc = iscsiTextGetKeyValue(bBuf, aISCSIRes[1].cbSeg, "CHAP_C", &pcszChapChallengeStr);
1116 if (RT_FAILURE(rc))
1117 {
1118 rc = VERR_PARSE_ERROR;
1119 break;
1120 }
1121 cbChallenge = sizeof(pbChallenge);
1122 rc = iscsiStrToBinary(pcszChapChallengeStr, pbChallenge, &cbChallenge);
1123 if (RT_FAILURE(rc))
1124 break;
1125 substate++;
1126 transit = true;
1127 break;
1128 case 0x0002: /* security negotiation, step 2: check authentication success. */
1129 rc = iscsiUpdateParameters(pImage, bBuf, aISCSIRes[1].cbSeg);
1130 if (RT_FAILURE(rc))
1131 break;
1132
1133 if (targetCSG == 0 && targetNSG == 1 && targetTransit)
1134 {
1135 /* Target wants to continue in login operational state, authentication success. */
1136 csg = 1;
1137 nsg = 3;
1138 substate = 0;
1139 break;
1140 }
1141 rc = VERR_PARSE_ERROR;
1142 break;
1143 case 0x0100: /* login operational negotiation, step 0: check results. */
1144 rc = iscsiUpdateParameters(pImage, bBuf, aISCSIRes[1].cbSeg);
1145 if (RT_FAILURE(rc))
1146 break;
1147
1148 if (targetCSG == 1 && targetNSG == 3 && targetTransit)
1149 {
1150 /* Target wants to continue in full feature phase, login finished. */
1151 csg = 3;
1152 nsg = 3;
1153 substate = 0;
1154 break;
1155 }
1156 else if (targetCSG == 1 && targetNSG == 1 && !targetTransit)
1157 {
1158 /* Target wants to negotiate certain parameters and
1159 * stay in login operational negotiation. */
1160 csg = 1;
1161 nsg = 3;
1162 substate = 0;
1163 }
1164 rc = VERR_PARSE_ERROR;
1165 break;
1166 case 0x0300: /* full feature phase. */
1167 default:
1168 AssertMsgFailed(("recv: Undefined login state %d substate %d\n", csg, substate));
1169 rc = VERR_PARSE_ERROR;
1170 break;
1171 }
1172 break;
1173 case ISCSI_LOGIN_STATUS_CLASS_REDIRECTION:
1174 const char *pcszTargetRedir;
1175
1176 /* Target has moved to some other location, as indicated in the TargetAddress key. */
1177 rc = iscsiTextGetKeyValue(bBuf, aISCSIRes[1].cbSeg, "TargetAddress", &pcszTargetRedir);
1178 if (RT_FAILURE(rc))
1179 {
1180 rc = VERR_PARSE_ERROR;
1181 break;
1182 }
1183 if (pImage->pszTargetAddress)
1184 RTMemFree(pImage->pszTargetAddress);
1185 {
1186 size_t cb = strlen(pcszTargetRedir) + 1;
1187 pImage->pszTargetAddress = (char *)RTMemAlloc(cb);
1188 if (!pImage->pszTargetAddress)
1189 {
1190 rc = VERR_NO_MEMORY;
1191 break;
1192 }
1193 memcpy(pImage->pszTargetAddress, pcszTargetRedir, cb);
1194 }
1195 rc = iscsiTransportOpen(pImage);
1196 goto restart;
1197 case ISCSI_LOGIN_STATUS_CLASS_INITIATOR_ERROR:
1198 iscsiTransportClose(pImage);
1199 rc = VERR_IO_GEN_FAILURE;
1200 goto out;
1201 case ISCSI_LOGIN_STATUS_CLASS_TARGET_ERROR:
1202 iscsiTransportClose(pImage);
1203 rc = VINF_EOF;
1204 break;
1205 default:
1206 rc = VERR_PARSE_ERROR;
1207 }
1208
1209 if (csg == 3)
1210 {
1211 /*
1212 * Finished login, continuing with Full Feature Phase.
1213 */
1214 rc = VINF_SUCCESS;
1215 break;
1216 }
1217 }
1218 else
1219 {
1220 AssertMsgFailed(("%s: ignoring unexpected PDU with first word = %#08x\n", __FUNCTION__, RT_N2H_U32(aResBHS[0])));
1221 }
1222 }
1223 else
1224 break;
1225 } while (true);
1226
1227out:
1228 if (RT_FAILURE(rc))
1229 {
1230 /*
1231 * Close connection to target.
1232 */
1233 iscsiTransportClose(pImage);
1234 pImage->state = ISCSISTATE_FREE;
1235 }
1236 else
1237 pImage->state = ISCSISTATE_NORMAL;
1238
1239 RTSemMutexRelease(pImage->Mutex);
1240
1241 LogFlowFunc(("returning %Rrc\n", rc));
1242 LogRel(("iSCSI: login to target %s %s\n", pImage->pszTargetName, RT_SUCCESS(rc) ? "successful" : "failed"));
1243 return rc;
1244}
1245
1246
1247/**
1248 * Detach from an iSCSI target.
1249 *
1250 * @returns VBox status.
1251 * @param pImage The iSCSI connection state to be used.
1252 */
1253static int iscsiDetach(PISCSIIMAGE pImage)
1254{
1255 int rc;
1256 uint32_t itt;
1257 uint32_t cnISCSIReq = 0;
1258 ISCSIREQ aISCSIReq[4];
1259 uint32_t aReqBHS[12];
1260 LogFlow(("iscsiDetach: entering\n"));
1261
1262 RTSemMutexRequest(pImage->Mutex, RT_INDEFINITE_WAIT);
1263
1264 if (pImage->state != ISCSISTATE_FREE && pImage->state != ISCSISTATE_IN_LOGOUT)
1265 {
1266 pImage->state = ISCSISTATE_IN_LOGOUT;
1267
1268 /*
1269 * Send logout request to target.
1270 */
1271 itt = iscsiNewITT(pImage);
1272 aReqBHS[0] = RT_H2N_U32(ISCSI_FINAL_BIT | ISCSIOP_LOGOUT_REQ); /* I=0,F=1,Reason=close session */
1273 aReqBHS[1] = RT_H2N_U32(0); /* TotalAHSLength=0,DataSementLength=0 */
1274 aReqBHS[2] = 0; /* reserved */
1275 aReqBHS[3] = 0; /* reserved */
1276 aReqBHS[4] = itt;
1277 aReqBHS[5] = 0; /* reserved */
1278 aReqBHS[6] = RT_H2N_U32(pImage->CmdSN);
1279 aReqBHS[7] = RT_H2N_U32(pImage->ExpStatSN);
1280 aReqBHS[8] = 0; /* reserved */
1281 aReqBHS[9] = 0; /* reserved */
1282 aReqBHS[10] = 0; /* reserved */
1283 aReqBHS[11] = 0; /* reserved */
1284 pImage->CmdSN++;
1285
1286 aISCSIReq[cnISCSIReq].pcvSeg = aReqBHS;
1287 aISCSIReq[cnISCSIReq].cbSeg = sizeof(aReqBHS);
1288 cnISCSIReq++;
1289
1290 rc = iscsiSendPDU(pImage, aISCSIReq, cnISCSIReq);
1291 if (RT_SUCCESS(rc))
1292 {
1293 /*
1294 * Read logout response from target.
1295 */
1296 ISCSIRES aISCSIRes;
1297 uint32_t aResBHS[12];
1298
1299 aISCSIRes.pvSeg = aResBHS;
1300 aISCSIRes.cbSeg = sizeof(aResBHS);
1301 rc = iscsiRecvPDU(pImage, itt, &aISCSIRes, 1);
1302 if (RT_SUCCESS(rc))
1303 {
1304 if (RT_N2H_U32(aResBHS[0]) != (ISCSI_FINAL_BIT | ISCSIOP_LOGOUT_RES))
1305 AssertMsgFailed(("iSCSI Logout response invalid\n"));
1306 }
1307 else
1308 AssertMsgFailed(("iSCSI Logout response error, rc=%Rrc\n", rc));
1309 }
1310 else
1311 AssertMsgFailed(("Could not send iSCSI Logout request, rc=%Rrc\n", rc));
1312 }
1313
1314 if (pImage->state != ISCSISTATE_FREE)
1315 {
1316 /*
1317 * Close connection to target.
1318 */
1319 rc = iscsiTransportClose(pImage);
1320 if (RT_FAILURE(rc))
1321 AssertMsgFailed(("Could not close connection to target, rc=%Rrc\n", rc));
1322 }
1323
1324 pImage->state = ISCSISTATE_FREE;
1325
1326 RTSemMutexRelease(pImage->Mutex);
1327
1328 LogFlow(("iscsiDetach: leaving\n"));
1329 LogRel(("iSCSI: logout to target %s\n", pImage->pszTargetName));
1330 return VINF_SUCCESS;
1331}
1332
1333
1334/**
1335 * Perform a command on an iSCSI target. Target must be already in
1336 * Full Feature Phase.
1337 *
1338 * @returns VBOX status.
1339 * @param pImage The iSCSI connection state to be used.
1340 * @param pRequest Command descriptor. Contains all information about
1341 * the command, its transfer directions and pointers
1342 * to the buffer(s) used for transferring data and
1343 * status information.
1344 */
1345static int iscsiCommand(PISCSIIMAGE pImage, PSCSIREQ pRequest)
1346{
1347 int rc;
1348 uint32_t itt;
1349 uint32_t cbData;
1350 uint32_t cnISCSIReq = 0;
1351 ISCSIREQ aISCSIReq[4];
1352 uint32_t aReqBHS[12];
1353
1354 uint32_t *pDst = NULL;
1355 size_t cbBufLength;
1356 uint32_t aStat[64];
1357 uint32_t ExpDataSN = 0;
1358 bool final = false;
1359
1360 LogFlow(("iscsiCommand: entering, CmdSN=%d\n", pImage->CmdSN));
1361
1362 Assert(pRequest->enmXfer != SCSIXFER_TO_FROM_TARGET); /**< @todo not yet supported, would require AHS. */
1363 Assert(pRequest->cbI2TData <= 0xffffff); /* larger transfers would require R2T support. */
1364 Assert(pRequest->cbCmd <= 16); /* would cause buffer overrun below. */
1365
1366 /* If not in normal state, then the transport connection was dropped. Try
1367 * to reestablish by logging in, the target might be responsive again. */
1368 if (pImage->state == ISCSISTATE_FREE)
1369 rc = iscsiAttach(pImage);
1370
1371 /* If still not in normal state, then the underlying transport connection
1372 * cannot be established. Get out before bad things happen (and make
1373 * sure the caller suspends the VM again). */
1374 if (pImage->state != ISCSISTATE_NORMAL)
1375 {
1376 rc = VERR_NET_CONNECTION_REFUSED;
1377 goto out;
1378 }
1379
1380 /*
1381 * Send SCSI command to target with all I2T data included.
1382 */
1383 cbData = 0;
1384 if (pRequest->enmXfer == SCSIXFER_FROM_TARGET)
1385 cbData = (uint32_t)pRequest->cbT2IData;
1386 else
1387 cbData = (uint32_t)pRequest->cbI2TData;
1388
1389 RTSemMutexRequest(pImage->Mutex, RT_INDEFINITE_WAIT);
1390
1391 itt = iscsiNewITT(pImage);
1392 memset(aReqBHS, 0, sizeof(aReqBHS));
1393 aReqBHS[0] = RT_H2N_U32( ISCSI_FINAL_BIT | ISCSI_TASK_ATTR_ORDERED | ISCSIOP_SCSI_CMD
1394 | (pRequest->enmXfer << 21)); /* I=0,F=1,Attr=Ordered */
1395 aReqBHS[1] = RT_H2N_U32(0x00000000 | ((uint32_t)pRequest->cbI2TData & 0xffffff)); /* TotalAHSLength=0 */
1396 aReqBHS[2] = RT_H2N_U32(pImage->LUN >> 32);
1397 aReqBHS[3] = RT_H2N_U32(pImage->LUN & 0xffffffff);
1398 aReqBHS[4] = itt;
1399 aReqBHS[5] = RT_H2N_U32(cbData);
1400 aReqBHS[6] = RT_H2N_U32(pImage->CmdSN);
1401 aReqBHS[7] = RT_H2N_U32(pImage->ExpStatSN);
1402 memcpy(aReqBHS + 8, pRequest->pvCmd, pRequest->cbCmd);
1403 pImage->CmdSN++;
1404
1405 aISCSIReq[cnISCSIReq].pcvSeg = aReqBHS;
1406 aISCSIReq[cnISCSIReq].cbSeg = sizeof(aReqBHS);
1407 cnISCSIReq++;
1408
1409 if ( pRequest->enmXfer == SCSIXFER_TO_TARGET
1410 || pRequest->enmXfer == SCSIXFER_TO_FROM_TARGET)
1411 {
1412 aISCSIReq[cnISCSIReq].pcvSeg = pRequest->pcvI2TData;
1413 aISCSIReq[cnISCSIReq].cbSeg = pRequest->cbI2TData; /* Padding done by transport. */
1414 cnISCSIReq++;
1415 }
1416
1417 rc = iscsiSendPDU(pImage, aISCSIReq, cnISCSIReq);
1418 if (RT_FAILURE(rc))
1419 goto out_release;
1420
1421 /* Place SCSI request in queue. */
1422 pImage->paCurrReq = aISCSIReq;
1423 pImage->cnCurrReq = cnISCSIReq;
1424
1425 /*
1426 * Read SCSI response/data in PDUs from target.
1427 */
1428 if ( pRequest->enmXfer == SCSIXFER_FROM_TARGET
1429 || pRequest->enmXfer == SCSIXFER_TO_FROM_TARGET)
1430 {
1431 pDst = (uint32_t *)pRequest->pvT2IData;
1432 cbBufLength = pRequest->cbT2IData;
1433 }
1434 else
1435 cbBufLength = 0;
1436
1437 do {
1438 uint32_t cnISCSIRes = 0;
1439 ISCSIRES aISCSIRes[4];
1440 uint32_t aResBHS[12];
1441
1442 aISCSIRes[cnISCSIRes].pvSeg = aResBHS;
1443 aISCSIRes[cnISCSIRes].cbSeg = sizeof(aResBHS);
1444 cnISCSIRes++;
1445 if (cbBufLength != 0 &&
1446 ( pRequest->enmXfer == SCSIXFER_FROM_TARGET
1447 || pRequest->enmXfer == SCSIXFER_TO_FROM_TARGET))
1448 {
1449 aISCSIRes[cnISCSIRes].pvSeg = pDst;
1450 aISCSIRes[cnISCSIRes].cbSeg = cbBufLength;
1451 cnISCSIRes++;
1452 }
1453 /* Always reserve space for the status - it's impossible to tell
1454 * beforehand whether this will be the final PDU or not. */
1455 aISCSIRes[cnISCSIRes].pvSeg = aStat;
1456 aISCSIRes[cnISCSIRes].cbSeg = sizeof(aStat);
1457 cnISCSIRes++;
1458
1459 rc = iscsiRecvPDU(pImage, itt, aISCSIRes, cnISCSIRes);
1460 if (RT_FAILURE(rc))
1461 break;
1462
1463 final = !!(RT_N2H_U32(aResBHS[0]) & ISCSI_FINAL_BIT);
1464 ISCSIOPCODE cmd = (ISCSIOPCODE)(RT_N2H_U32(aResBHS[0]) & ISCSIOP_MASK);
1465 if (cmd == ISCSIOP_SCSI_RES)
1466 {
1467 /* This is the final PDU which delivers the status (and may be omitted if
1468 * the last Data-In PDU included successful completion status). Note
1469 * that ExpStatSN has been bumped already in iscsiRecvPDU. */
1470 if (!final || ((RT_N2H_U32(aResBHS[0]) & 0x0000ff00) != 0) || (RT_N2H_U32(aResBHS[6]) != pImage->ExpStatSN - 1))
1471 {
1472 /* SCSI Response in the wrong place or with a (target) failure. */
1473 rc = VERR_PARSE_ERROR;
1474 break;
1475 }
1476 /* The following is a bit tricky, as in error situations we may
1477 * get the status only instead of the result data plus optional
1478 * status. Thus the status may have ended up partially in the
1479 * data area. */
1480 pRequest->status = RT_N2H_U32(aResBHS[0]) & 0x000000ff;
1481 uint32_t cbData = RT_N2H_U32(aResBHS[1]) & 0x00ffffff;
1482 if (cbData >= 2)
1483 {
1484 uint32_t cbStat = RT_N2H_U32(((uint32_t *)aISCSIRes[1].pvSeg)[0]) >> 16;
1485 if (cbStat + 2 > cbData || cbStat > pRequest->cbSense)
1486 {
1487 rc = VERR_BUFFER_OVERFLOW;
1488 break;
1489 }
1490 pRequest->cbSense = cbStat;
1491 memcpy(pRequest->pvSense, ((const uint8_t *)aISCSIRes[1].pvSeg) + 2, aISCSIRes[1].cbSeg - 2);
1492 if (cnISCSIRes > 2 && aISCSIRes[2].cbSeg && (ssize_t)cbStat - aISCSIRes[1].cbSeg - 2 > 0)
1493 memcpy((char *)pRequest->pvSense + aISCSIRes[1].cbSeg, aISCSIRes[2].pvSeg, cbStat - aISCSIRes[1].cbSeg - 2);
1494 }
1495 else if (cbData == 1)
1496 {
1497 rc = VERR_PARSE_ERROR;
1498 break;
1499 }
1500 else
1501 pRequest->cbSense = 0;
1502 break;
1503 }
1504 else if (cmd == ISCSIOP_SCSI_DATA_IN)
1505 {
1506 /* A Data-In PDU carries some data that needs to be added to the received
1507 * data in response to the command. There may be both partial and complete
1508 * Data-In PDUs, so collect data until the status is included or the status
1509 * is sent in a separate SCSI Result frame (see above). */
1510 if (final && aISCSIRes[2].cbSeg != 0)
1511 {
1512 /* The received PDU is partially stored in the buffer for status.
1513 * Must not happen under normal circumstances and is a target error. */
1514 rc = VERR_BUFFER_OVERFLOW;
1515 break;
1516 }
1517 uint32_t len = RT_N2H_U32(aResBHS[1]) & 0x00ffffff;
1518 pDst = (uint32_t *)((char *)pDst + len);
1519 cbBufLength -= len;
1520 ExpDataSN++;
1521 if (final && (RT_N2H_U32(aResBHS[0]) & ISCSI_STATUS_BIT) != 0)
1522 {
1523 pRequest->status = RT_N2H_U32(aResBHS[0]) & 0x000000ff;
1524 pRequest->cbSense = 0;
1525 break;
1526 }
1527 }
1528 else
1529 {
1530 rc = VERR_PARSE_ERROR;
1531 break;
1532 }
1533 } while (true);
1534
1535 /* Remove SCSI request from queue. */
1536 pImage->paCurrReq = NULL;
1537 pImage->cnCurrReq = 0;
1538
1539out_release:
1540 if (rc == VERR_TIMEOUT)
1541 {
1542 /* Drop connection in case the target plays dead. Much better than
1543 * delaying the next requests until the timed out command actually
1544 * finishes. Also keep in mind that command shouldn't take longer than
1545 * about 30-40 seconds, or the guest will lose its patience. */
1546 iscsiTransportClose(pImage);
1547 pImage->state = ISCSISTATE_FREE;
1548 }
1549 RTSemMutexRelease(pImage->Mutex);
1550
1551out:
1552 LogFlow(("iscsiCommand: returns %Rrc\n", rc));
1553 return rc;
1554}
1555
1556
1557/**
1558 * Generate a new Initiator Task Tag.
1559 *
1560 * @returns Initiator Task Tag.
1561 * @param pImage The iSCSI connection state to be used.
1562 */
1563static uint32_t iscsiNewITT(PISCSIIMAGE pImage)
1564{
1565 uint32_t next_itt;
1566
1567 next_itt = pImage->ITT++;
1568 if (pImage->ITT == ISCSI_TASK_TAG_RSVD)
1569 pImage->ITT = 0;
1570 return RT_H2N_U32(next_itt);
1571}
1572
1573
1574/**
1575 * Send an iSCSI request. The request can consist of several segments, which
1576 * are padded to 4 byte boundaries and concatenated.
1577 *
1578 * @returns VBOX status
1579 * @param pImage The iSCSI connection state to be used.
1580 * @param paReq Pointer to array of iSCSI request sections.
1581 * @param cnReq Number of valid iSCSI request sections in the array.
1582 */
1583static int iscsiSendPDU(PISCSIIMAGE pImage, PISCSIREQ paReq, uint32_t cnReq)
1584{
1585 int rc = VINF_SUCCESS;
1586 uint32_t i;
1587 /** @todo return VERR_VD_ISCSI_INVALID_STATE in the appropriate situations,
1588 * needs cleaning up of timeout/disconnect handling a bit, as otherwise
1589 * too many incorrect errors are signalled. */
1590 Assert(pImage->paCurrReq == NULL);
1591 Assert(cnReq >= 1);
1592 Assert(paReq[0].cbSeg >= ISCSI_BHS_SIZE);
1593
1594 for (i = 0; i < pImage->cISCSIRetries; i++)
1595 {
1596 rc = iscsiTransportWrite(pImage, paReq, cnReq);
1597 if (RT_SUCCESS(rc))
1598 break;
1599 if (rc != VERR_BROKEN_PIPE && rc != VERR_NET_CONNECTION_REFUSED)
1600 break;
1601 /* No point in reestablishing the connection for a logout */
1602 if (pImage->state == ISCSISTATE_IN_LOGOUT)
1603 break;
1604 RTThreadSleep(500);
1605 if (pImage->state != ISCSISTATE_IN_LOGIN)
1606 {
1607 /* Attempt to re-login when a connection fails, but only when not
1608 * currently logging in. */
1609 rc = iscsiAttach(pImage);
1610 if (RT_FAILURE(rc))
1611 break;
1612 }
1613 }
1614 return rc;
1615}
1616
1617
1618/**
1619 * Wait for an iSCSI response with a matching Initiator Target Tag. The response is
1620 * split into several segments, as requested by the caller-provided buffer specification.
1621 * Remember that the response can be split into several PDUs by the sender, so make
1622 * sure that all parts are collected and processed appropriately by the caller.
1623 *
1624 * @returns VBOX status
1625 * @param pImage The iSCSI connection state to be used.
1626 * @param paRes Pointer to array of iSCSI response sections.
1627 * @param cnRes Number of valid iSCSI response sections in the array.
1628 */
1629static int iscsiRecvPDU(PISCSIIMAGE pImage, uint32_t itt, PISCSIRES paRes, uint32_t cnRes)
1630{
1631 int rc = VINF_SUCCESS;
1632 uint32_t i;
1633 ISCSIRES aResBuf;
1634
1635 for (i = 0; i < pImage->cISCSIRetries; i++)
1636 {
1637 aResBuf.pvSeg = pImage->pvRecvPDUBuf;
1638 aResBuf.cbSeg = pImage->cbRecvPDUBuf;
1639 rc = iscsiTransportRead(pImage, &aResBuf, 1);
1640 if (RT_FAILURE(rc))
1641 {
1642 if (rc == VERR_BROKEN_PIPE || rc == VERR_NET_CONNECTION_REFUSED)
1643 {
1644 /* No point in reestablishing the connection for a logout */
1645 if (pImage->state == ISCSISTATE_IN_LOGOUT)
1646 break;
1647 /* Connection broken while waiting for a response - wait a while and
1648 * try to restart by re-sending the original request (if any).
1649 * This also handles the connection reestablishment (login etc.). */
1650 RTThreadSleep(500);
1651 if (pImage->state != ISCSISTATE_IN_LOGIN)
1652 {
1653 /* Attempt to re-login when a connection fails, but only when not
1654 * currently logging in. */
1655 rc = iscsiAttach(pImage);
1656 if (RT_FAILURE(rc))
1657 break;
1658 }
1659 if (pImage->paCurrReq != NULL)
1660 {
1661 rc = iscsiSendPDU(pImage, pImage->paCurrReq, pImage->cnCurrReq);
1662 if (RT_FAILURE(rc))
1663 break;
1664 }
1665 }
1666 else
1667 {
1668 /* Signal other errors (VERR_BUFFER_OVERFLOW etc.) to the caller. */
1669 break;
1670 }
1671 }
1672 else
1673 {
1674 ISCSIOPCODE cmd;
1675 const uint32_t *pcvResSeg = (const uint32_t *)aResBuf.pvSeg;
1676
1677 /* Check whether the received PDU is valid, and update the internal state of
1678 * the iSCSI connection/session. */
1679 rc = drvISCSIValidatePDU(&aResBuf, 1);
1680 if (RT_FAILURE(rc))
1681 continue;
1682 cmd = (ISCSIOPCODE)(RT_N2H_U32(pcvResSeg[0]) & ISCSIOP_MASK);
1683 switch (cmd)
1684 {
1685 case ISCSIOP_SCSI_RES:
1686 case ISCSIOP_SCSI_TASKMGMT_RES:
1687 case ISCSIOP_SCSI_DATA_IN:
1688 case ISCSIOP_R2T:
1689 case ISCSIOP_ASYN_MSG:
1690 case ISCSIOP_TEXT_RES:
1691 case ISCSIOP_LOGIN_RES:
1692 case ISCSIOP_LOGOUT_RES:
1693 case ISCSIOP_REJECT:
1694 case ISCSIOP_NOP_IN:
1695 if (serial_number_less(pImage->MaxCmdSN, RT_N2H_U32(pcvResSeg[8])))
1696 pImage->MaxCmdSN = RT_N2H_U32(pcvResSeg[8]);
1697 if (serial_number_less(pImage->ExpCmdSN, RT_N2H_U32(pcvResSeg[7])))
1698 pImage->ExpCmdSN = RT_N2H_U32(pcvResSeg[7]);
1699 break;
1700 default:
1701 rc = VERR_PARSE_ERROR;
1702 }
1703 if (RT_FAILURE(rc))
1704 continue;
1705 if ( !pImage->FirstRecvPDU
1706 && (cmd != ISCSIOP_SCSI_DATA_IN || (RT_N2H_U32(pcvResSeg[0]) & ISCSI_STATUS_BIT)))
1707 {
1708 if (pImage->ExpStatSN == RT_N2H_U32(pcvResSeg[6]))
1709 {
1710 /* StatSN counter is not advanced on R2T and on a target SN update NOP-In. */
1711 if ( (cmd != ISCSIOP_R2T)
1712 && ((cmd != ISCSIOP_NOP_IN) || (RT_N2H_U32(pcvResSeg[4]) != ISCSI_TASK_TAG_RSVD)))
1713 pImage->ExpStatSN++;
1714 }
1715 else
1716 {
1717 rc = VERR_PARSE_ERROR;
1718 continue;
1719 }
1720 }
1721 /* Finally check whether the received PDU matches what the caller wants. */
1722 if (itt == pcvResSeg[4])
1723 {
1724 /* Copy received PDU (one segment) to caller-provided buffers. */
1725 uint32_t i;
1726 size_t cbSeg;
1727 const uint8_t *pSrc;
1728
1729 pSrc = (const uint8_t *)aResBuf.pvSeg;
1730 cbSeg = aResBuf.cbSeg;
1731 for (i = 0; i < cnRes; i++)
1732 {
1733 if (cbSeg > paRes[i].cbSeg)
1734 {
1735 memcpy(paRes[i].pvSeg, pSrc, paRes[i].cbSeg);
1736 pSrc += paRes[i].cbSeg;
1737 cbSeg -= paRes[i].cbSeg;
1738 }
1739 else
1740 {
1741 memcpy(paRes[i].pvSeg, pSrc, cbSeg);
1742 paRes[i].cbSeg = cbSeg;
1743 cbSeg = 0;
1744 break;
1745 }
1746 }
1747 if (cbSeg != 0)
1748 {
1749 rc = VERR_BUFFER_OVERFLOW;
1750 break;
1751 }
1752 for (i++; i < cnRes; i++)
1753 paRes[i].cbSeg = 0;
1754 break;
1755 }
1756 else if ( cmd == ISCSIOP_NOP_IN
1757 && RT_N2H_U32(pcvResSeg[5]) != ISCSI_TASK_TAG_RSVD)
1758 {
1759 uint32_t cnISCSIReq;
1760 ISCSIREQ aISCSIReq[4];
1761 uint32_t aReqBHS[12];
1762
1763 aReqBHS[0] = RT_H2N_U32(ISCSI_IMMEDIATE_DELIVERY_BIT | ISCSI_FINAL_BIT | ISCSIOP_NOP_OUT);
1764 aReqBHS[1] = RT_H2N_U32(0); /* TotalAHSLength=0,DataSementLength=0 */
1765 aReqBHS[2] = pcvResSeg[2]; /* copy LUN from NOP-In */
1766 aReqBHS[3] = pcvResSeg[3]; /* copy LUN from NOP-In */
1767 aReqBHS[4] = RT_H2N_U32(ISCSI_TASK_TAG_RSVD); /* ITT, reply */
1768 aReqBHS[5] = pcvResSeg[5]; /* copy TTT from NOP-In */
1769 aReqBHS[6] = RT_H2N_U32(pImage->CmdSN);
1770 aReqBHS[7] = RT_H2N_U32(pImage->ExpStatSN);
1771 aReqBHS[8] = 0; /* reserved */
1772 aReqBHS[9] = 0; /* reserved */
1773 aReqBHS[10] = 0; /* reserved */
1774 aReqBHS[11] = 0; /* reserved */
1775
1776 cnISCSIReq = 0;
1777 aISCSIReq[cnISCSIReq].pcvSeg = aReqBHS;
1778 aISCSIReq[cnISCSIReq].cbSeg = sizeof(aReqBHS);
1779 cnISCSIReq++;
1780
1781 iscsiSendPDU(pImage, aISCSIReq, cnISCSIReq);
1782 }
1783 }
1784 }
1785 return rc;
1786}
1787
1788
1789/**
1790 * Check the static (not dependent on the connection/session state) validity of an iSCSI response PDU.
1791 *
1792 * @returns VBOX status
1793 * @param paRes Pointer to array of iSCSI response sections.
1794 * @param cnRes Number of valid iSCSI response sections in the array.
1795 */
1796static int drvISCSIValidatePDU(PISCSIRES paRes, uint32_t cnRes)
1797{
1798 const uint32_t *pcrgResBHS;
1799 uint32_t hw0;
1800 Assert(cnRes >= 1);
1801 Assert(paRes[0].cbSeg >= ISCSI_BHS_SIZE);
1802
1803 pcrgResBHS = (const uint32_t *)(paRes[0].pvSeg);
1804 hw0 = RT_N2H_U32(pcrgResBHS[0]);
1805 switch (hw0 & ISCSIOP_MASK)
1806 {
1807 case ISCSIOP_NOP_IN:
1808 /* NOP-In responses must not be split into several PDUs nor it may contain
1809 * ping data for target-initiated pings nor may both task tags be valid task tags. */
1810 if ( (hw0 & ISCSI_FINAL_BIT) == 0
1811 || ( RT_N2H_U32(pcrgResBHS[4]) == ISCSI_TASK_TAG_RSVD
1812 && RT_N2H_U32(pcrgResBHS[1]) != 0)
1813 || ( RT_N2H_U32(pcrgResBHS[4]) != ISCSI_TASK_TAG_RSVD
1814 && RT_N2H_U32(pcrgResBHS[5]) != ISCSI_TASK_TAG_RSVD))
1815 return VERR_PARSE_ERROR;
1816 break;
1817 case ISCSIOP_SCSI_RES:
1818 /* SCSI responses must not be split into several PDUs nor must the residual
1819 * bits be contradicting each other nor may the residual bits be set for PDUs
1820 * containing anything else but a completed command response. Underflow
1821 * is no reason for declaring a PDU as invalid, as the target may choose
1822 * to return less data than we assume to get. */
1823 if ( (hw0 & ISCSI_FINAL_BIT) == 0
1824 || ((hw0 & ISCSI_BI_READ_RESIDUAL_OVFL_BIT) && (hw0 & ISCSI_BI_READ_RESIDUAL_UNFL_BIT))
1825 || ((hw0 & ISCSI_RESIDUAL_OVFL_BIT) && (hw0 & ISCSI_RESIDUAL_UNFL_BIT))
1826 || ( ((hw0 & ISCSI_SCSI_RESPONSE_MASK) == 0)
1827 && ((hw0 & ISCSI_SCSI_STATUS_MASK) == SCSI_STATUS_OK)
1828 && (hw0 & ( ISCSI_BI_READ_RESIDUAL_OVFL_BIT | ISCSI_BI_READ_RESIDUAL_UNFL_BIT
1829 | ISCSI_RESIDUAL_OVFL_BIT))))
1830 return VERR_PARSE_ERROR;
1831 break;
1832 case ISCSIOP_LOGIN_RES:
1833 /* Login responses must not contain contradicting transit and continue bits. */
1834 if ((hw0 & ISCSI_CONTINUE_BIT) && ((hw0 & ISCSI_TRANSIT_BIT) != 0))
1835 return VERR_PARSE_ERROR;
1836 break;
1837 case ISCSIOP_TEXT_RES:
1838 /* Text responses must not contain contradicting final and continue bits nor
1839 * may the final bit be set for PDUs containing a target transfer tag other than
1840 * the reserved transfer tag (and vice versa). */
1841 if ( (((hw0 & ISCSI_CONTINUE_BIT) && (hw0 & ISCSI_FINAL_BIT) != 0))
1842 || (((hw0 & ISCSI_FINAL_BIT) && (RT_N2H_U32(pcrgResBHS[5]) != ISCSI_TASK_TAG_RSVD)))
1843 || (((hw0 & ISCSI_FINAL_BIT) == 0) && (RT_N2H_U32(pcrgResBHS[5]) == ISCSI_TASK_TAG_RSVD)))
1844 return VERR_PARSE_ERROR;
1845 break;
1846 case ISCSIOP_SCSI_DATA_IN:
1847 /* SCSI Data-in responses must not contain contradicting residual bits when
1848 * status bit is set. */
1849 if ((hw0 & ISCSI_STATUS_BIT) && (hw0 & ISCSI_RESIDUAL_OVFL_BIT) && (hw0 & ISCSI_RESIDUAL_UNFL_BIT))
1850 return VERR_PARSE_ERROR;
1851 break;
1852 case ISCSIOP_LOGOUT_RES:
1853 /* Logout responses must not have the final bit unset and may not contain any
1854 * data or additional header segments. */
1855 if ( ((hw0 & ISCSI_FINAL_BIT) == 0)
1856 || (RT_N2H_U32(pcrgResBHS[1]) != 0))
1857 return VERR_PARSE_ERROR;
1858 break;
1859 case ISCSIOP_ASYN_MSG:
1860 /* Asynchronous Messages must not have the final bit unser and may not contain
1861 * an initiator task tag. */
1862 if ( ((hw0 & ISCSI_FINAL_BIT) == 0)
1863 || (RT_N2H_U32(pcrgResBHS[4]) != ISCSI_TASK_TAG_RSVD))
1864 return VERR_PARSE_ERROR;
1865 break;
1866 case ISCSIOP_SCSI_TASKMGMT_RES:
1867 case ISCSIOP_R2T:
1868 case ISCSIOP_REJECT:
1869 default:
1870 /* Do some logging, ignore PDU. */
1871 LogFlow(("drvISCSIValidatePDU: ignore unhandled PDU, first word %#08x\n", RT_N2H_U32(pcrgResBHS[0])));
1872 return VERR_PARSE_ERROR;
1873 }
1874 /* A target must not send PDUs with MaxCmdSN less than ExpCmdSN-1. */
1875
1876 if (serial_number_less(RT_N2H_U32(pcrgResBHS[8]), RT_N2H_U32(pcrgResBHS[7])-1))
1877 return VERR_PARSE_ERROR;
1878
1879 return VINF_SUCCESS;
1880}
1881
1882
1883/**
1884 * Appends a key-value pair to the buffer. Normal ASCII strings (cbValue == 0) and large binary values
1885 * of a given length (cbValue > 0) are directly supported. Other value types must be converted to ASCII
1886 * by the caller. Strings must be in UTF-8 encoding.
1887 *
1888 * @returns VBOX status
1889 * @param pbBuf Pointer to the key-value buffer.
1890 * @param cbBuf Length of the key-value buffer.
1891 * @param pcbBufCurr Currently used portion of the key-value buffer.
1892 * @param pszKey Pointer to a string containing the key.
1893 * @param pszValue Pointer to either a string containing the value or to a large binary value.
1894 * @param cbValue Length of the binary value if applicable.
1895 */
1896static int iscsiTextAddKeyValue(uint8_t *pbBuf, size_t cbBuf, size_t *pcbBufCurr, const char *pcszKey,
1897 const char *pcszValue, size_t cbValue)
1898{
1899 size_t cbBufTmp = *pcbBufCurr;
1900 size_t cbKey = strlen(pcszKey);
1901 size_t cbValueEnc;
1902 uint8_t *pbCurr;
1903
1904 if (cbValue == 0)
1905 cbValueEnc = strlen(pcszValue);
1906 else
1907 cbValueEnc = cbValue * 2 + 2; /* 2 hex bytes per byte, 2 bytes prefix */
1908
1909 if (cbBuf < cbBufTmp + cbKey + 1 + cbValueEnc + 1)
1910 {
1911 /* Buffer would overflow, signal error. */
1912 return VERR_BUFFER_OVERFLOW;
1913 }
1914
1915 /*
1916 * Append a key=value pair (zero terminated string) to the end of the buffer.
1917 */
1918 pbCurr = pbBuf + cbBufTmp;
1919 memcpy(pbCurr, pcszKey, cbKey);
1920 pbCurr += cbKey;
1921 *pbCurr++ = '=';
1922 if (cbValue == 0)
1923 {
1924 memcpy(pbCurr, pcszValue, cbValueEnc);
1925 pbCurr += cbValueEnc;
1926 }
1927 else
1928 {
1929 *pbCurr++ = '0';
1930 *pbCurr++ = 'x';
1931 for (uint32_t i = 0; i < cbValue; i++)
1932 {
1933 uint8_t b;
1934 b = pcszValue[i];
1935 *pbCurr++ = NUM_2_HEX(b >> 4);
1936 *pbCurr++ = NUM_2_HEX(b & 0xf);
1937 }
1938 }
1939 *pbCurr = '\0';
1940 *pcbBufCurr = cbBufTmp + cbKey + 1 + cbValueEnc + 1;
1941
1942 return VINF_SUCCESS;
1943}
1944
1945
1946/**
1947 * Retrieve the value for a given key from the key=value buffer.
1948 *
1949 * @returns VBOX status.
1950 * @param pbBuf Buffer containing key=value pairs.
1951 * @param cbBuf Length of buffer with key=value pairs.
1952 * @param pszKey Pointer to key for which to retrieve the value.
1953 * @param ppszValue Pointer to value string pointer.
1954 */
1955static int iscsiTextGetKeyValue(const uint8_t *pbBuf, size_t cbBuf, const char *pcszKey, const char **ppcszValue)
1956{
1957 size_t cbKey = strlen(pcszKey);
1958
1959 while (cbBuf != 0)
1960 {
1961 size_t cbKeyValNull = strlen((const char *)pbBuf) + 1;
1962
1963 if (strncmp(pcszKey, (const char *)pbBuf, cbKey) == 0 && pbBuf[cbKey] == '=')
1964 {
1965 *ppcszValue = (const char *)(pbBuf + cbKey + 1);
1966 return VINF_SUCCESS;
1967 }
1968 pbBuf += cbKeyValNull;
1969 cbBuf -= cbKeyValNull;
1970 }
1971 return VERR_INVALID_NAME;
1972}
1973
1974
1975/**
1976 * Convert a long-binary value from a value string to the binary representation.
1977 *
1978 * @returns VBOX status
1979 * @param pszValue Pointer to a string containing the textual value representation.
1980 * @param pbValue Pointer to the value buffer for the binary value.
1981 * @param pcbValue In: length of value buffer, out: actual length of binary value.
1982 */
1983static int iscsiStrToBinary(const char *pcszValue, uint8_t *pbValue, size_t *pcbValue)
1984{
1985 size_t cbValue = *pcbValue;
1986 char c1, c2, c3, c4;
1987 Assert(cbValue >= 1);
1988
1989 if (strlen(pcszValue) < 3)
1990 return VERR_PARSE_ERROR;
1991 if (*pcszValue++ != '0')
1992 return VERR_PARSE_ERROR;
1993 switch (*pcszValue++)
1994 {
1995 case 'x':
1996 case 'X':
1997 if (strlen(pcszValue) & 1)
1998 {
1999 c1 = *pcszValue++;
2000 *pbValue++ = HEX_2_NUM(c1);
2001 cbValue--;
2002 }
2003 while (*pcszValue != '\0')
2004 {
2005 if (cbValue == 0)
2006 return VERR_BUFFER_OVERFLOW;
2007 c1 = *pcszValue++;
2008 if ((c1 < '0' || c1 > '9') && (c1 < 'a' || c1 > 'f') && (c1 < 'A' || c1 > 'F'))
2009 return VERR_PARSE_ERROR;
2010 c2 = *pcszValue++;
2011 if ((c2 < '0' || c2 > '9') && (c2 < 'a' || c2 > 'f') && (c2 < 'A' || c2 > 'F'))
2012 return VERR_PARSE_ERROR;
2013 *pbValue++ = (HEX_2_NUM(c1) << 4) | HEX_2_NUM(c2);
2014 cbValue--;
2015 }
2016 *pcbValue -= cbValue;
2017 break;
2018 case 'b':
2019 case 'B':
2020 if ((strlen(pcszValue) & 3) != 0)
2021 return VERR_PARSE_ERROR;
2022 while (*pcszValue != '\0')
2023 {
2024 uint32_t temp;
2025 if (cbValue == 0)
2026 return VERR_BUFFER_OVERFLOW;
2027 c1 = *pcszValue++;
2028 if ((c1 < 'A' || c1 > 'Z') && (c1 < 'a' || c1 >'z') && (c1 < '0' || c1 > '9') && (c1 != '+') && (c1 != '/'))
2029 return VERR_PARSE_ERROR;
2030 c2 = *pcszValue++;
2031 if ((c2 < 'A' || c2 > 'Z') && (c2 < 'a' || c2 >'z') && (c2 < '0' || c2 > '9') && (c2 != '+') && (c2 != '/'))
2032 return VERR_PARSE_ERROR;
2033 c3 = *pcszValue++;
2034 if ((c3 < 'A' || c3 > 'Z') && (c3 < 'a' || c3 >'z') && (c3 < '0' || c3 > '9') && (c3 != '+') && (c3 != '/') && (c3 != '='))
2035 return VERR_PARSE_ERROR;
2036 c4 = *pcszValue++;
2037 if ( (c3 == '=' && c4 != '=')
2038 || ((c4 < 'A' || c4 > 'Z') && (c4 < 'a' || c4 >'z') && (c4 < '0' || c4 > '9') && (c4 != '+') && (c4 != '/') && (c4 != '=')))
2039 return VERR_PARSE_ERROR;
2040 temp = (B64_2_NUM(c1) << 18) | (B64_2_NUM(c2) << 12);
2041 if (c3 == '=') {
2042 if (*pcszValue != '\0')
2043 return VERR_PARSE_ERROR;
2044 *pbValue++ = temp >> 16;
2045 cbValue--;
2046 } else {
2047 temp |= B64_2_NUM(c3) << 6;
2048 if (c4 == '=') {
2049 if (*pcszValue != '\0')
2050 return VERR_PARSE_ERROR;
2051 if (cbValue < 2)
2052 return VERR_BUFFER_OVERFLOW;
2053 *pbValue++ = temp >> 16;
2054 *pbValue++ = (temp >> 8) & 0xff;
2055 cbValue -= 2;
2056 }
2057 else
2058 {
2059 temp |= B64_2_NUM(c4);
2060 if (cbValue < 3)
2061 return VERR_BUFFER_OVERFLOW;
2062 *pbValue++ = temp >> 16;
2063 *pbValue++ = (temp >> 8) & 0xff;
2064 *pbValue++ = temp & 0xff;
2065 cbValue -= 3;
2066 }
2067 }
2068 }
2069 *pcbValue -= cbValue;
2070 break;
2071 default:
2072 return VERR_PARSE_ERROR;
2073 }
2074 return VINF_SUCCESS;
2075}
2076
2077
2078/**
2079 * Retrieve the relevant parameter values and update the initiator state.
2080 *
2081 * @returns VBOX status.
2082 * @param pImage Current iSCSI initiator state.
2083 * @param pbBuf Buffer containing key=value pairs.
2084 * @param cbBuf Length of buffer with key=value pairs.
2085 */
2086static int iscsiUpdateParameters(PISCSIIMAGE pImage, const uint8_t *pbBuf, size_t cbBuf)
2087{
2088 int rc;
2089 const char *pcszMaxRecvDataSegmentLength = NULL;
2090 const char *pcszMaxBurstLength = NULL;
2091 const char *pcszFirstBurstLength = NULL;
2092 rc = iscsiTextGetKeyValue(pbBuf, cbBuf, "MaxRecvDataSegmentLength", &pcszMaxRecvDataSegmentLength);
2093 if (rc == VERR_INVALID_NAME)
2094 rc = VINF_SUCCESS;
2095 if (RT_FAILURE(rc))
2096 return VERR_PARSE_ERROR;
2097 rc = iscsiTextGetKeyValue(pbBuf, cbBuf, "MaxBurstLength", &pcszMaxBurstLength);
2098 if (rc == VERR_INVALID_NAME)
2099 rc = VINF_SUCCESS;
2100 if (RT_FAILURE(rc))
2101 return VERR_PARSE_ERROR;
2102 rc = iscsiTextGetKeyValue(pbBuf, cbBuf, "FirstBurstLength", &pcszFirstBurstLength);
2103 if (rc == VERR_INVALID_NAME)
2104 rc = VINF_SUCCESS;
2105 if (RT_FAILURE(rc))
2106 return VERR_PARSE_ERROR;
2107 if (pcszMaxRecvDataSegmentLength)
2108 {
2109 uint32_t cb = pImage->cbSendDataLength;
2110 rc = RTStrToUInt32Full(pcszMaxRecvDataSegmentLength, 0, &cb);
2111 AssertRC(rc);
2112 pImage->cbSendDataLength = RT_MIN(pImage->cbSendDataLength, cb);
2113 }
2114 if (pcszMaxBurstLength)
2115 {
2116 uint32_t cb = pImage->cbSendDataLength;
2117 rc = RTStrToUInt32Full(pcszMaxBurstLength, 0, &cb);
2118 AssertRC(rc);
2119 pImage->cbSendDataLength = RT_MIN(pImage->cbSendDataLength, cb);
2120 }
2121 if (pcszFirstBurstLength)
2122 {
2123 uint32_t cb = pImage->cbSendDataLength;
2124 rc = RTStrToUInt32Full(pcszFirstBurstLength, 0, &cb);
2125 AssertRC(rc);
2126 pImage->cbSendDataLength = RT_MIN(pImage->cbSendDataLength, cb);
2127 }
2128 return VINF_SUCCESS;
2129}
2130
2131
2132static bool serial_number_less(uint32_t s1, uint32_t s2)
2133{
2134 return (s1 < s2 && s2 - s1 < 0x80000000) || (s1 > s2 && s1 - s2 > 0x80000000);
2135}
2136
2137
2138#ifdef IMPLEMENT_TARGET_AUTH
2139static void chap_md5_generate_challenge(uint8_t *pbChallenge, size_t *pcbChallenge)
2140{
2141 uint8_t cbChallenge;
2142
2143 cbChallenge = RTrand_U8(CHAP_MD5_CHALLENGE_MIN, CHAP_MD5_CHALLENGE_MAX);
2144 RTrand_bytes(pbChallenge, cbChallenge);
2145 *pcbChallenge = cbChallenge;
2146}
2147#endif
2148
2149
2150static void chap_md5_compute_response(uint8_t *pbResponse, uint8_t id, const uint8_t *pbChallenge, size_t cbChallenge,
2151 const uint8_t *pbSecret, size_t cbSecret)
2152{
2153 RTMD5CONTEXT ctx;
2154 uint8_t bId;
2155
2156 bId = id;
2157 RTMd5Init(&ctx);
2158 RTMd5Update(&ctx, &bId, 1);
2159 RTMd5Update(&ctx, pbSecret, cbSecret);
2160 RTMd5Update(&ctx, pbChallenge, cbChallenge);
2161 RTMd5Final(pbResponse, &ctx);
2162}
2163
2164/**
2165 * Internal. Free all allocated space for representing an image, and optionally
2166 * delete the image from disk.
2167 */
2168static void iscsiFreeImage(PISCSIIMAGE pImage, bool fDelete)
2169{
2170 Assert(pImage);
2171 Assert(!fDelete); /* This MUST be false, the flag isn't supported. */
2172
2173 if (pImage->Mutex != NIL_RTSEMMUTEX)
2174 {
2175 /* Detaching only makes sense when the mutex is there. Otherwise the
2176 * failure happened long before we could attach to the target. */
2177 iscsiDetach(pImage);
2178 RTSemMutexDestroy(pImage->Mutex);
2179 pImage->Mutex = NIL_RTSEMMUTEX;
2180 }
2181 if (pImage->pszTargetName)
2182 {
2183 RTMemFree(pImage->pszTargetName);
2184 pImage->pszTargetName = NULL;
2185 }
2186 if (pImage->pszInitiatorName)
2187 {
2188 RTMemFree(pImage->pszInitiatorName);
2189 pImage->pszInitiatorName = NULL;
2190 }
2191 if (pImage->pszInitiatorUsername)
2192 {
2193 RTMemFree(pImage->pszInitiatorUsername);
2194 pImage->pszInitiatorUsername = NULL;
2195 }
2196 if (pImage->pbInitiatorSecret)
2197 {
2198 RTMemFree(pImage->pbInitiatorSecret);
2199 pImage->pbInitiatorSecret = NULL;
2200 }
2201 if (pImage->pszTargetUsername)
2202 {
2203 RTMemFree(pImage->pszTargetUsername);
2204 pImage->pszTargetUsername = NULL;
2205 }
2206 if (pImage->pbTargetSecret)
2207 {
2208 RTMemFree(pImage->pbTargetSecret);
2209 pImage->pbTargetSecret = NULL;
2210 }
2211 if (pImage->pvRecvPDUBuf)
2212 {
2213 RTMemFree(pImage->pvRecvPDUBuf);
2214 pImage->pvRecvPDUBuf = NULL;
2215 }
2216}
2217
2218/**
2219 * Internal: Open an image, constructing all necessary data structures.
2220 */
2221static int iscsiOpenImage(PISCSIIMAGE pImage, unsigned uOpenFlags)
2222{
2223 int rc;
2224 char *pszLUN = NULL, *pszLUNInitial = NULL;
2225 bool fLunEncoded = false;
2226 uint32_t uWriteSplitDef = 0;
2227 uint32_t uTimeoutDef = 0;
2228 uint64_t uHostIPTmp = 0;
2229 bool fHostIPDef = 0;
2230 rc = RTStrToUInt32Full(s_iscsiConfigDefaultWriteSplit, 0, &uWriteSplitDef);
2231 AssertRC(rc);
2232 rc = RTStrToUInt32Full(s_iscsiConfigDefaultTimeout, 0, &uTimeoutDef);
2233 AssertRC(rc);
2234 rc = RTStrToUInt64Full(s_iscsiConfigDefaultHostIPStack, 0, &uHostIPTmp);
2235 AssertRC(rc);
2236 fHostIPDef = !!uHostIPTmp;
2237
2238 pImage->uOpenFlags = uOpenFlags;
2239
2240 /* Get error signalling interface. */
2241 pImage->pInterfaceError = VDInterfaceGet(pImage->pVDIfsDisk, VDINTERFACETYPE_ERROR);
2242 if (pImage->pInterfaceError)
2243 pImage->pInterfaceErrorCallbacks = VDGetInterfaceError(pImage->pInterfaceError);
2244
2245 /* Get TCP network stack interface. */
2246 pImage->pInterfaceNet = VDInterfaceGet(pImage->pVDIfsDisk, VDINTERFACETYPE_TCPNET);
2247 if (pImage->pInterfaceNet)
2248 pImage->pInterfaceNetCallbacks = VDGetInterfaceTcpNet(pImage->pInterfaceNet);
2249 else
2250 {
2251 rc = iscsiError(pImage, VERR_VD_ISCSI_UNKNOWN_INTERFACE,
2252 RT_SRC_POS, N_("iSCSI: TCP network stack interface missing"));
2253 goto out;
2254 }
2255
2256 /* Get configuration interface. */
2257 pImage->pInterfaceConfig = VDInterfaceGet(pImage->pVDIfsImage, VDINTERFACETYPE_CONFIG);
2258 if (pImage->pInterfaceConfig)
2259 pImage->pInterfaceConfigCallbacks = VDGetInterfaceConfig(pImage->pInterfaceConfig);
2260 else
2261 {
2262 rc = iscsiError(pImage, VERR_VD_ISCSI_UNKNOWN_INTERFACE,
2263 RT_SRC_POS, N_("iSCSI: configuration interface missing"));
2264 goto out;
2265 }
2266
2267 pImage->ISID = 0x800000000000ULL | 0x001234560000ULL | (0x00000000cba0ULL + ASMAtomicIncU32(&s_u32iscsiID));
2268 pImage->cISCSIRetries = 10;
2269 pImage->state = ISCSISTATE_FREE;
2270 pImage->pvRecvPDUBuf = RTMemAlloc(ISCSI_RECV_PDU_BUFFER_SIZE);
2271 pImage->cbRecvPDUBuf = ISCSI_RECV_PDU_BUFFER_SIZE;
2272 if (pImage->pvRecvPDUBuf == NULL)
2273 {
2274 rc = VERR_NO_MEMORY;
2275 goto out;
2276 }
2277 pImage->Mutex = NIL_RTSEMMUTEX;
2278 rc = RTSemMutexCreate(&pImage->Mutex);
2279 if (RT_FAILURE(rc))
2280 goto out;
2281
2282 /* Validate configuration, detect unknown keys. */
2283 if (!VDCFGAreKeysValid(pImage->pInterfaceConfigCallbacks,
2284 pImage->pInterfaceConfig->pvUser,
2285 "TargetName\0InitiatorName\0LUN\0TargetAddress\0InitiatorUsername\0InitiatorSecret\0TargetUsername\0TargetSecret\0WriteSplit\0Timeout\0HostIPStack\0"))
2286 {
2287 rc = iscsiError(pImage, VERR_VD_ISCSI_UNKNOWN_CFG_VALUES, RT_SRC_POS, N_("iSCSI: configuration error: unknown configuration keys present"));
2288 goto out;
2289 }
2290
2291 /* Query the iSCSI upper level configuration. */
2292 rc = VDCFGQueryStringAlloc(pImage->pInterfaceConfigCallbacks,
2293 pImage->pInterfaceConfig->pvUser,
2294 "TargetName", &pImage->pszTargetName);
2295 if (RT_FAILURE(rc))
2296 {
2297 rc = iscsiError(pImage, rc, RT_SRC_POS, N_("iSCSI: configuration error: failed to read TargetName as string"));
2298 goto out;
2299 }
2300 rc = VDCFGQueryStringAllocDef(pImage->pInterfaceConfigCallbacks,
2301 pImage->pInterfaceConfig->pvUser,
2302 "InitiatorName", &pImage->pszInitiatorName,
2303 s_iscsiConfigDefaultInitiatorName);
2304 if (RT_FAILURE(rc))
2305 {
2306 rc = iscsiError(pImage, rc, RT_SRC_POS, N_("iSCSI: configuration error: failed to read InitiatorName as string"));
2307 goto out;
2308 }
2309 rc = VDCFGQueryStringAllocDef(pImage->pInterfaceConfigCallbacks,
2310 pImage->pInterfaceConfig->pvUser,
2311 "LUN", &pszLUN, s_iscsiConfigDefaultLUN);
2312 if (RT_FAILURE(rc))
2313 {
2314 rc = iscsiError(pImage, rc, RT_SRC_POS, N_("iSCSI: configuration error: failed to read LUN as string"));
2315 goto out;
2316 }
2317 pszLUNInitial = pszLUN;
2318 if (!strncmp(pszLUN, "enc", 3))
2319 {
2320 fLunEncoded = true;
2321 pszLUN += 3;
2322 }
2323 rc = RTStrToUInt64Full(pszLUN, 0, &pImage->LUN);
2324 if (RT_FAILURE(rc))
2325 {
2326 rc = iscsiError(pImage, rc, RT_SRC_POS, N_("iSCSI: configuration error: failed to convert LUN to integer"));
2327 goto out;
2328 }
2329 if (!fLunEncoded)
2330 {
2331 if (pImage->LUN <= 255)
2332 {
2333 pImage->LUN = pImage->LUN << 48; /* uses peripheral device addressing method */
2334 }
2335 else if (pImage->LUN <= 16383)
2336 {
2337 pImage->LUN = (pImage->LUN << 48) | RT_BIT_64(62); /* uses flat space addressing method */
2338 }
2339 else
2340 {
2341 rc = VERR_OUT_OF_RANGE;
2342 rc = iscsiError(pImage, rc, RT_SRC_POS, N_("iSCSI: configuration error: LUN number out of range (0-16383)"));
2343 goto out;
2344 }
2345 }
2346 rc = VDCFGQueryStringAlloc(pImage->pInterfaceConfigCallbacks,
2347 pImage->pInterfaceConfig->pvUser,
2348 "TargetAddress", &pImage->pszTargetAddress);
2349 if (RT_FAILURE(rc))
2350 {
2351 rc = iscsiError(pImage, rc, RT_SRC_POS, N_("iSCSI: configuration error: failed to read TargetAddress as string"));
2352 goto out;
2353 }
2354 pImage->pszInitiatorUsername = NULL;
2355 rc = VDCFGQueryStringAlloc(pImage->pInterfaceConfigCallbacks,
2356 pImage->pInterfaceConfig->pvUser,
2357 "InitiatorUsername",
2358 &pImage->pszInitiatorUsername);
2359 if (rc == VERR_CFGM_VALUE_NOT_FOUND || rc == VERR_CFGM_NO_PARENT)
2360 rc = VINF_SUCCESS;
2361 if (RT_FAILURE(rc))
2362 {
2363 rc = iscsiError(pImage, rc, RT_SRC_POS, N_("iSCSI: configuration error: failed to read InitiatorUsername as string"));
2364 goto out;
2365 }
2366 pImage->pbInitiatorSecret = NULL;
2367 pImage->cbInitiatorSecret = 0;
2368 rc = VDCFGQueryBytesAlloc(pImage->pInterfaceConfigCallbacks,
2369 pImage->pInterfaceConfig->pvUser,
2370 "InitiatorSecret",
2371 (void **)&pImage->pbInitiatorSecret,
2372 &pImage->cbInitiatorSecret);
2373 if (rc == VERR_CFGM_VALUE_NOT_FOUND || rc == VERR_CFGM_NO_PARENT)
2374 rc = VINF_SUCCESS;
2375 if (RT_FAILURE(rc))
2376 {
2377 rc = iscsiError(pImage, rc, RT_SRC_POS, N_("iSCSI: configuration error: failed to read InitiatorSecret as byte string"));
2378 goto out;
2379 }
2380 pImage->pszTargetUsername = NULL;
2381 rc = VDCFGQueryStringAlloc(pImage->pInterfaceConfigCallbacks,
2382 pImage->pInterfaceConfig->pvUser,
2383 "TargetUsername",
2384 &pImage->pszTargetUsername);
2385 if (rc == VERR_CFGM_VALUE_NOT_FOUND || rc == VERR_CFGM_NO_PARENT)
2386 rc = VINF_SUCCESS;
2387 if (RT_FAILURE(rc))
2388 {
2389 rc = iscsiError(pImage, rc, RT_SRC_POS, N_("iSCSI: configuration error: failed to read TargetUsername as string"));
2390 goto out;
2391 }
2392 pImage->pbTargetSecret = NULL;
2393 pImage->cbTargetSecret = 0;
2394 rc = VDCFGQueryBytesAlloc(pImage->pInterfaceConfigCallbacks,
2395 pImage->pInterfaceConfig->pvUser,
2396 "TargetSecret", (void **)&pImage->pbTargetSecret,
2397 &pImage->cbTargetSecret);
2398 if (rc == VERR_CFGM_VALUE_NOT_FOUND || rc == VERR_CFGM_NO_PARENT)
2399 rc = VINF_SUCCESS;
2400 if (RT_FAILURE(rc))
2401 {
2402 rc = iscsiError(pImage, rc, RT_SRC_POS, N_("iSCSI: configuration error: failed to read TargetSecret as byte string"));
2403 goto out;
2404 }
2405 rc = VDCFGQueryU32Def(pImage->pInterfaceConfigCallbacks,
2406 pImage->pInterfaceConfig->pvUser,
2407 "WriteSplit", &pImage->cbWriteSplit,
2408 uWriteSplitDef);
2409 if (RT_FAILURE(rc))
2410 {
2411 rc = iscsiError(pImage, rc, RT_SRC_POS, N_("iSCSI: configuration error: failed to read WriteSplit as U32"));
2412 goto out;
2413 }
2414
2415 pImage->pszHostname = NULL;
2416 pImage->uPort = 0;
2417 pImage->Socket = NIL_RTSOCKET;
2418 /* Query the iSCSI lower level configuration. */
2419 rc = VDCFGQueryU32Def(pImage->pInterfaceConfigCallbacks,
2420 pImage->pInterfaceConfig->pvUser,
2421 "Timeout", &pImage->uReadTimeout,
2422 uTimeoutDef);
2423 if (RT_FAILURE(rc))
2424 {
2425 rc = iscsiError(pImage, rc, RT_SRC_POS, N_("iSCSI: configuration error: failed to read Timeout as U32"));
2426 goto out;
2427 }
2428 rc = VDCFGQueryBoolDef(pImage->pInterfaceConfigCallbacks,
2429 pImage->pInterfaceConfig->pvUser,
2430 "HostIPStack", &pImage->fHostIP,
2431 fHostIPDef);
2432 if (RT_FAILURE(rc))
2433 {
2434 rc = iscsiError(pImage, rc, RT_SRC_POS, N_("iSCSI: configuration error: failed to read HostIPStack as boolean"));
2435 goto out;
2436 }
2437
2438 /* Don't actually establish iSCSI transport connection if this is just an
2439 * open to query the image information and the host IP stack isn't used.
2440 * Even trying is rather useless, as in this context the InTnet IP stack
2441 * isn't present. Returning dummies is the best possible result anyway. */
2442 if ((uOpenFlags & VD_OPEN_FLAGS_INFO) && !pImage->fHostIP)
2443 {
2444 LogFunc(("Not opening the transport connection as IntNet IP stack is not available. Will return dummies\n"));
2445 goto out;
2446 }
2447
2448 /*
2449 * Establish the iSCSI transport connection.
2450 */
2451 rc = iscsiTransportOpen(pImage);
2452 if (RT_SUCCESS(rc))
2453 rc = iscsiAttach(pImage);
2454
2455 if (RT_FAILURE(rc))
2456 {
2457 LogRel(("iSCSI: could not open target %s, rc=%Rrc\n", pImage->pszTargetName, rc));
2458 goto out;
2459 }
2460 LogFlowFunc(("target '%s' opened successfully\n", pImage->pszTargetName));
2461
2462 SCSIREQ sr;
2463 uint8_t sense[32];
2464 uint8_t data8[8];
2465
2466 /*
2467 * Inquire available LUNs - purely dummy request.
2468 */
2469 uint8_t cdb_rlun[12];
2470 uint8_t rlundata[16];
2471 cdb_rlun[0] = SCSI_REPORT_LUNS;
2472 cdb_rlun[1] = 0; /* reserved */
2473 cdb_rlun[2] = 0; /* reserved */
2474 cdb_rlun[3] = 0; /* reserved */
2475 cdb_rlun[4] = 0; /* reserved */
2476 cdb_rlun[5] = 0; /* reserved */
2477 cdb_rlun[6] = sizeof(rlundata) >> 24;
2478 cdb_rlun[7] = (sizeof(rlundata) >> 16) & 0xff;
2479 cdb_rlun[8] = (sizeof(rlundata) >> 8) & 0xff;
2480 cdb_rlun[9] = sizeof(rlundata) & 0xff;
2481 cdb_rlun[10] = 0; /* reserved */
2482 cdb_rlun[11] = 0; /* control */
2483
2484 sr.enmXfer = SCSIXFER_FROM_TARGET;
2485 sr.cbCmd = sizeof(cdb_rlun);
2486 sr.pvCmd = cdb_rlun;
2487 sr.cbI2TData = 0;
2488 sr.pcvI2TData = NULL;
2489 sr.cbT2IData = sizeof(rlundata);
2490 sr.pvT2IData = rlundata;
2491 sr.cbSense = sizeof(sense);
2492 sr.pvSense = sense;
2493
2494 rc = iscsiCommand(pImage, &sr);
2495 if (RT_FAILURE(rc))
2496 {
2497 LogRel(("iSCSI: Could not get LUN info for target %s, rc=%Rrc\n", pImage->pszTargetName, rc));
2498 return rc;
2499 }
2500
2501 /*
2502 * Inquire device characteristics - no tapes, scanners etc., please.
2503 */
2504 uint8_t cdb_inq[6];
2505 cdb_inq[0] = SCSI_INQUIRY;
2506 cdb_inq[1] = 0; /* reserved */
2507 cdb_inq[2] = 0; /* reserved */
2508 cdb_inq[3] = 0; /* reserved */
2509 cdb_inq[4] = sizeof(data8);
2510 cdb_inq[5] = 0; /* control */
2511
2512 sr.enmXfer = SCSIXFER_FROM_TARGET;
2513 sr.cbCmd = sizeof(cdb_inq);
2514 sr.pvCmd = cdb_inq;
2515 sr.cbI2TData = 0;
2516 sr.pcvI2TData = NULL;
2517 sr.cbT2IData = sizeof(data8);
2518 sr.pvT2IData = data8;
2519 sr.cbSense = sizeof(sense);
2520 sr.pvSense = sense;
2521
2522 rc = iscsiCommand(pImage, &sr);
2523 if (RT_SUCCESS(rc))
2524 {
2525 if ((data8[0] & SCSI_DEVTYPE_MASK) != SCSI_DEVTYPE_DISK)
2526 {
2527 rc = iscsiError(pImage, VERR_VD_ISCSI_INVALID_TYPE,
2528 RT_SRC_POS, N_("iSCSI: target address %s, target name %s, SCSI LUN %lld reports device type=%u"),
2529 pImage->pszTargetAddress, pImage->pszTargetName,
2530 pImage->LUN, data8[0]);
2531 LogRel(("iSCSI: Unsupported SCSI peripheral device type %d for target %s\n", data8[0] & SCSI_DEVTYPE_MASK, pImage->pszTargetName));
2532 goto out;
2533 }
2534 }
2535 else
2536 {
2537 LogRel(("iSCSI: Could not get INQUIRY info for target %s, rc=%Rrc\n", pImage->pszTargetName, rc));
2538 goto out;
2539 }
2540
2541 /*
2542 * Query write disable bit in the device specific parameter entry in the
2543 * mode parameter header. Refuse read/write opening of read only disks.
2544 */
2545
2546 uint8_t cdb_ms[6];
2547 uint8_t data4[4];
2548 cdb_ms[0] = SCSI_MODE_SENSE_6;
2549 cdb_ms[1] = 0; /* dbd=0/reserved */
2550 cdb_ms[2] = 0x3f; /* pc=0/page code=0x3f, ask for all pages */
2551 cdb_ms[3] = 0; /* subpage code=0, return everything in page_0 format */
2552 cdb_ms[4] = sizeof(data4); /* allocation length=4 */
2553 cdb_ms[5] = 0; /* control */
2554
2555 sr.enmXfer = SCSIXFER_FROM_TARGET;
2556 sr.cbCmd = sizeof(cdb_ms);
2557 sr.pvCmd = cdb_ms;
2558 sr.cbI2TData = 0;
2559 sr.pcvI2TData = NULL;
2560 sr.cbT2IData = sizeof(data4);
2561 sr.pvT2IData = data4;
2562 sr.cbSense = sizeof(sense);
2563 sr.pvSense = sense;
2564
2565 for (unsigned i = 0; i < 10; i++)
2566 {
2567 rc = iscsiCommand(pImage, &sr);
2568 if ( (RT_SUCCESS(rc) && !sr.cbSense)
2569 || RT_FAILURE(rc))
2570 break;
2571 rc = VERR_INVALID_STATE;
2572 }
2573 if (RT_SUCCESS(rc))
2574 {
2575 if (!(uOpenFlags & VD_OPEN_FLAGS_READONLY) && data4[2] & 0x80)
2576 {
2577 rc = VERR_VD_IMAGE_READ_ONLY;
2578 goto out;
2579 }
2580 }
2581 else
2582 {
2583 LogRel(("iSCSI: Could not get MODE SENSE info for target %s, rc=%Rrc\n", pImage->pszTargetName, rc));
2584 goto out;
2585 }
2586
2587 /*
2588 * Determine sector size and capacity of the volume immediately.
2589 */
2590 uint8_t cdb_cap[10];
2591
2592 cdb_cap[0] = SCSI_READ_CAPACITY;
2593 cdb_cap[1] = 0; /* reserved */
2594 cdb_cap[2] = 0; /* reserved */
2595 cdb_cap[3] = 0; /* reserved */
2596 cdb_cap[4] = 0; /* reserved */
2597 cdb_cap[5] = 0; /* reserved */
2598 cdb_cap[6] = 0; /* reserved */
2599 cdb_cap[7] = 0; /* reserved */
2600 cdb_cap[8] = 0; /* reserved */
2601 cdb_cap[9] = 0; /* control */
2602
2603 sr.enmXfer = SCSIXFER_FROM_TARGET;
2604 sr.cbCmd = sizeof(cdb_cap);
2605 sr.pvCmd = cdb_cap;
2606 sr.cbI2TData = 0;
2607 sr.pcvI2TData = NULL;
2608 sr.cbT2IData = sizeof(data8);
2609 sr.pvT2IData = data8;
2610 sr.cbSense = sizeof(sense);
2611 sr.pvSense = sense;
2612
2613 rc = iscsiCommand(pImage, &sr);
2614 if (RT_SUCCESS(rc))
2615 {
2616 pImage->cVolume = (data8[0] << 24) | (data8[1] << 16) | (data8[2] << 8) | data8[3];
2617 pImage->cVolume++;
2618 pImage->cbSector = (data8[4] << 24) | (data8[5] << 16) | (data8[6] << 8) | data8[7];
2619 pImage->cbSize = (uint64_t)(pImage->cVolume) * pImage->cbSector;
2620 if (pImage->cVolume == 0 || pImage->cbSector == 0)
2621 {
2622 rc = iscsiError(pImage, VERR_VD_ISCSI_INVALID_TYPE,
2623 RT_SRC_POS, N_("iSCSI: target address %s, target name %s, SCSI LUN %lld reports media sector count=%lu sector size=%lu"),
2624 pImage->pszTargetAddress, pImage->pszTargetName,
2625 pImage->LUN, pImage->cVolume, pImage->cbSector);
2626 }
2627 }
2628 else
2629 {
2630 LogRel(("iSCSI: Could not determine capacity of target %s, rc=%Rrc\n", pImage->pszTargetName, rc));
2631 goto out;
2632 }
2633
2634 /*
2635 * Check the read and write cache bits.
2636 * Try to enable the cache if it is disabled.
2637 *
2638 * We already checked that this is a block access device. No need
2639 * to do it again.
2640 */
2641 uint8_t aCachingModePage[32];
2642 uint8_t aCDBModeSense6[6];
2643
2644 memset(aCachingModePage, '\0', sizeof(aCachingModePage));
2645 aCDBModeSense6[0] = SCSI_MODE_SENSE_6;
2646 aCDBModeSense6[1] = 0;
2647 aCDBModeSense6[2] = (0x00 << 6) | (0x08 & 0x3f); /* Current values and caching mode page */
2648 aCDBModeSense6[3] = 0; /* Sub page code. */
2649 aCDBModeSense6[4] = sizeof(aCachingModePage) & 0xff;
2650 aCDBModeSense6[5] = 0;
2651 sr.enmXfer = SCSIXFER_FROM_TARGET;
2652 sr.cbCmd = sizeof(aCDBModeSense6);
2653 sr.pvCmd = aCDBModeSense6;
2654 sr.cbI2TData = 0;
2655 sr.pcvI2TData = NULL;
2656 sr.cbT2IData = sizeof(aCachingModePage);
2657 sr.pvT2IData = aCachingModePage;
2658 sr.cbSense = sizeof(sense);
2659 sr.pvSense = sense;
2660 rc = iscsiCommand(pImage, &sr);
2661 if ( RT_SUCCESS(rc)
2662 && (sr.status == SCSI_STATUS_OK)
2663 && (aCachingModePage[0] >= 15)
2664 && (aCachingModePage[4 + aCachingModePage[3]] & 0x3f) == 0x08
2665 && (aCachingModePage[4 + aCachingModePage[3] + 1] > 3))
2666 {
2667 uint32_t Offset = 4 + aCachingModePage[3];
2668 /*
2669 * Check if the read and/or the write cache is disabled.
2670 * The write cache is disabled if bit 2 (WCE) is zero and
2671 * the read cache is disabled if bit 0 (RCD) is set.
2672 */
2673 if (!ASMBitTest(&aCachingModePage[Offset + 2], 2) || ASMBitTest(&aCachingModePage[Offset + 2], 0))
2674 {
2675 /*
2676 * Write Cache Enable (WCE) bit is zero or the Read Cache Disable (RCD) is one
2677 * So one of the caches is disabled. Enable both caches.
2678 * The rest is unchanged.
2679 */
2680 ASMBitSet(&aCachingModePage[Offset + 2], 2);
2681 ASMBitClear(&aCachingModePage[Offset + 2], 0);
2682
2683 uint8_t aCDBCaching[6];
2684 aCDBCaching[0] = SCSI_MODE_SELECT_6;
2685 aCDBCaching[1] = 0; /* Don't write the page into NV RAM. */
2686 aCDBCaching[2] = 0;
2687 aCDBCaching[3] = 0;
2688 aCDBCaching[4] = sizeof(aCachingModePage) & 0xff;
2689 aCDBCaching[5] = 0;
2690 sr.enmXfer = SCSIXFER_TO_TARGET;
2691 sr.cbCmd = sizeof(aCDBCaching);
2692 sr.pvCmd = aCDBCaching;
2693 sr.cbI2TData = sizeof(aCachingModePage);
2694 sr.pcvI2TData = aCachingModePage;
2695 sr.cbT2IData = 0;
2696 sr.pvT2IData = NULL;
2697 sr.cbSense = sizeof(sense);
2698 sr.pvSense = sense;
2699 sr.status = 0;
2700 rc = iscsiCommand(pImage, &sr);
2701 if ( RT_SUCCESS(rc)
2702 && (sr.status == SCSI_STATUS_OK))
2703 {
2704 LogRel(("iSCSI: Enabled read and write cache of target %s\n", pImage->pszTargetName));
2705 }
2706 else
2707 {
2708 /* Log failures but continue. */
2709 LogRel(("iSCSI: Could not enable read and write cache of target %s, rc=%Rrc status=%#x\n",
2710 pImage->pszTargetName, rc, sr.status));
2711 LogRel(("iSCSI: Sense:\n%.*Rhxd\n", sr.cbSense, sense));
2712 rc = VINF_SUCCESS;
2713 }
2714 }
2715 }
2716 else
2717 {
2718 /* Log errors but continue. */
2719 LogRel(("iSCSI: Could not check write cache of target %s, rc=%Rrc, got mode page %#x\n", pImage->pszTargetName, rc,aCachingModePage[0] & 0x3f));
2720 LogRel(("iSCSI: Sense:\n%.*Rhxd\n", sr.cbSense, sense));
2721 rc = VINF_SUCCESS;
2722 }
2723
2724
2725out:
2726 if (RT_FAILURE(rc))
2727 iscsiFreeImage(pImage, false);
2728 return rc;
2729}
2730
2731
2732/** @copydoc VBOXHDDBACKEND::pfnCheckIfValid */
2733static int iscsiCheckIfValid(const char *pszFilename, PVDINTERFACE pVDIfsDisk)
2734{
2735 LogFlowFunc(("pszFilename=\"%s\"\n", pszFilename));
2736
2737 /* iSCSI images can't be checked for validity this way, as the filename
2738 * just can't supply enough configuration information. */
2739 int rc = VERR_VD_ISCSI_INVALID_HEADER;
2740
2741 LogFlowFunc(("returns %Rrc\n", rc));
2742 return rc;
2743}
2744
2745
2746/** @copydoc VBOXHDDBACKEND::pfnOpen */
2747static int iscsiOpen(const char *pszFilename, unsigned uOpenFlags,
2748 PVDINTERFACE pVDIfsDisk, PVDINTERFACE pVDIfsImage,
2749 void **ppBackendData)
2750{
2751 LogFlowFunc(("pszFilename=\"%s\" uOpenFlags=%#x pVDIfsDisk=%#p pVDIfsImage=%#p ppBackendData=%#p\n", pszFilename, uOpenFlags, pVDIfsDisk, pVDIfsImage, ppBackendData));
2752 int rc;
2753 PISCSIIMAGE pImage;
2754
2755 /* Check open flags. All valid flags are supported. */
2756 if (uOpenFlags & ~VD_OPEN_FLAGS_MASK)
2757 {
2758 rc = VERR_INVALID_PARAMETER;
2759 goto out;
2760 }
2761
2762 /* Check remaining arguments. */
2763 if ( !VALID_PTR(pszFilename)
2764 || !*pszFilename
2765 || strchr(pszFilename, '"'))
2766 {
2767 rc = VERR_INVALID_PARAMETER;
2768 goto out;
2769 }
2770
2771 pImage = (PISCSIIMAGE)RTMemAllocZ(sizeof(ISCSIIMAGE));
2772 if (!pImage)
2773 {
2774 rc = VERR_NO_MEMORY;
2775 goto out;
2776 }
2777
2778 pImage->pszFilename = pszFilename;
2779 pImage->pszInitiatorName = NULL;
2780 pImage->pszTargetName = NULL;
2781 pImage->pszTargetAddress = NULL;
2782 pImage->pszInitiatorUsername = NULL;
2783 pImage->pbInitiatorSecret = NULL;
2784 pImage->pszTargetUsername = NULL;
2785 pImage->pbTargetSecret = NULL;
2786 pImage->paCurrReq = NULL;
2787 pImage->pvRecvPDUBuf = NULL;
2788 pImage->pszHostname = NULL;
2789 pImage->pVDIfsDisk = pVDIfsDisk;
2790 pImage->pVDIfsImage = pVDIfsImage;
2791
2792 rc = iscsiOpenImage(pImage, uOpenFlags);
2793 if (RT_SUCCESS(rc))
2794 *ppBackendData = pImage;
2795
2796out:
2797 if (RT_SUCCESS(rc))
2798 {
2799 LogFlowFunc(("target %s cVolume %d, cbSector %d\n", pImage->pszTargetName, pImage->cVolume, pImage->cbSector));
2800 LogRel(("iSCSI: target address %s, target name %s, SCSI LUN %lld\n", pImage->pszTargetAddress, pImage->pszTargetName, pImage->LUN));
2801 }
2802 LogFlowFunc(("returns %Rrc (pBackendData=%#p)\n", rc, *ppBackendData));
2803 return rc;
2804}
2805
2806
2807/** @copydoc VBOXHDDBACKEND::pfnCreate */
2808static int iscsiCreate(const char *pszFilename, uint64_t cbSize,
2809 unsigned uImageFlags, const char *pszComment,
2810 PCPDMMEDIAGEOMETRY pPCHSGeometry,
2811 PCPDMMEDIAGEOMETRY pLCHSGeometry, PCRTUUID pUuid,
2812 unsigned uOpenFlags, unsigned uPercentStart,
2813 unsigned uPercentSpan, PVDINTERFACE pVDIfsDisk,
2814 PVDINTERFACE pVDIfsImage, PVDINTERFACE pVDIfsOperation,
2815 void **ppBackendData)
2816{
2817 LogFlowFunc(("pszFilename=\"%s\" cbSize=%llu uImageFlags=%#x pszComment=\"%s\" pPCHSGeometry=%#p pLCHSGeometry=%#p Uuid=%RTuuid uOpenFlags=%#x uPercentStart=%u uPercentSpan=%u pVDIfsDisk=%#p pVDIfsImage=%#p pVDIfsOperation=%#p ppBackendData=%#p", pszFilename, cbSize, uImageFlags, pszComment, pPCHSGeometry, pLCHSGeometry, pUuid, uOpenFlags, uPercentStart, uPercentSpan, pVDIfsDisk, pVDIfsImage, pVDIfsOperation, ppBackendData));
2818 int rc = VERR_NOT_SUPPORTED;
2819
2820 LogFlowFunc(("returns %Rrc (pBackendData=%#p)\n", rc, *ppBackendData));
2821 return rc;
2822}
2823
2824
2825/** @copydoc VBOXHDDBACKEND::pfnRename */
2826static int iscsiRename(void *pBackendData, const char *pszFilename)
2827{
2828 LogFlowFunc(("pBackendData=%#p pszFilename=%#p\n", pBackendData, pszFilename));
2829 int rc = VERR_NOT_SUPPORTED;
2830
2831 LogFlowFunc(("returns %Rrc\n", rc));
2832 return rc;
2833}
2834
2835
2836/** @copydoc VBOXHDDBACKEND::pfnClose */
2837static int iscsiClose(void *pBackendData, bool fDelete)
2838{
2839 LogFlowFunc(("pBackendData=%#p fDelete=%d\n", pBackendData, fDelete));
2840 PISCSIIMAGE pImage = (PISCSIIMAGE)pBackendData;
2841 int rc = VINF_SUCCESS;
2842
2843 Assert(!fDelete); /* This flag is unsupported. */
2844
2845 /* Freeing a never allocated image (e.g. because the open failed) is
2846 * not signalled as an error. After all nothing bad happens. */
2847 if (pImage)
2848 iscsiFreeImage(pImage, fDelete);
2849
2850 LogFlowFunc(("returns %Rrc\n", rc));
2851 return rc;
2852}
2853
2854
2855/** @copydoc VBOXHDDBACKEND::pfnRead */
2856static int iscsiRead(void *pBackendData, uint64_t uOffset, void *pvBuf,
2857 size_t cbToRead, size_t *pcbActuallyRead)
2858{
2859 /** @todo reinstate logging of the target everywhere - dropped temporarily */
2860 LogFlowFunc(("pBackendData=%#p uOffset=%llu pvBuf=%#p cbToRead=%zu pcbActuallyRead=%#p\n", pBackendData, uOffset, pvBuf, cbToRead, pcbActuallyRead));
2861 PISCSIIMAGE pImage = (PISCSIIMAGE)pBackendData;
2862 uint64_t lba;
2863 uint16_t tls;
2864 int rc;
2865
2866 Assert(pImage);
2867 Assert(uOffset % 512 == 0);
2868 Assert(cbToRead % 512 == 0);
2869
2870 Assert(pImage->cbSector);
2871 AssertPtr(pvBuf);
2872
2873 if ( uOffset + cbToRead > pImage->cbSize
2874 || cbToRead == 0)
2875 {
2876 rc = VERR_INVALID_PARAMETER;
2877 goto out;
2878 }
2879
2880 /*
2881 * Clip read size to a value which is supported by the target.
2882 */
2883 cbToRead = RT_MIN(cbToRead, pImage->cbRecvDataLength);
2884
2885 lba = uOffset / pImage->cbSector;
2886 tls = (uint16_t)(cbToRead / pImage->cbSector);
2887 SCSIREQ sr;
2888 uint8_t cdb[10];
2889 uint8_t sense[32];
2890
2891 cdb[0] = SCSI_READ_10;
2892 cdb[1] = 0; /* reserved */
2893 cdb[2] = (lba >> 24) & 0xff;
2894 cdb[3] = (lba >> 16) & 0xff;
2895 cdb[4] = (lba >> 8) & 0xff;
2896 cdb[5] = lba & 0xff;
2897 cdb[6] = 0; /* reserved */
2898 cdb[7] = (tls >> 8) & 0xff;
2899 cdb[8] = tls & 0xff;
2900 cdb[9] = 0; /* control */
2901
2902 sr.enmXfer = SCSIXFER_FROM_TARGET;
2903 sr.cbCmd = sizeof(cdb);
2904 sr.pvCmd = cdb;
2905 sr.cbI2TData = 0;
2906 sr.pcvI2TData = NULL;
2907 sr.cbT2IData = cbToRead;
2908 sr.pvT2IData = pvBuf;
2909 sr.cbSense = sizeof(sense);
2910 sr.pvSense = sense;
2911
2912 for (unsigned i = 0; i < 10; i++)
2913 {
2914 rc = iscsiCommand(pImage, &sr);
2915 if ( (RT_SUCCESS(rc) && !sr.cbSense)
2916 || RT_FAILURE(rc))
2917 break;
2918 rc = VERR_READ_ERROR;
2919 }
2920 if (RT_FAILURE(rc))
2921 {
2922 AssertMsgFailed(("iscsiCommand(%s, %#llx) -> %Rrc\n", pImage->pszTargetName, uOffset, rc));
2923 *pcbActuallyRead = 0;
2924 }
2925 else
2926 *pcbActuallyRead = sr.cbT2IData;
2927
2928out:
2929 LogFlowFunc(("returns %Rrc\n", rc));
2930 return rc;
2931}
2932
2933
2934/** @copydoc VBOXHDDBACKEND::pfnWrite */
2935static int iscsiWrite(void *pBackendData, uint64_t uOffset, const void *pvBuf,
2936 size_t cbToWrite, size_t *pcbWriteProcess,
2937 size_t *pcbPreRead, size_t *pcbPostRead, unsigned fWrite)
2938{
2939 LogFlowFunc(("pBackendData=%#p uOffset=%llu pvBuf=%#p cbToWrite=%zu pcbWriteProcess=%#p pcbPreRead=%#p pcbPostRead=%#p\n", pBackendData, uOffset, pvBuf, cbToWrite, pcbWriteProcess, pcbPreRead, pcbPostRead));
2940 PISCSIIMAGE pImage = (PISCSIIMAGE)pBackendData;
2941 uint64_t lba;
2942 uint16_t tls;
2943 int rc;
2944
2945 Assert(pImage);
2946 Assert(uOffset % 512 == 0);
2947 Assert(cbToWrite % 512 == 0);
2948
2949 Assert(pImage->cbSector);
2950 Assert(pvBuf);
2951
2952 if (pImage->uOpenFlags & VD_OPEN_FLAGS_READONLY)
2953 {
2954 rc = VERR_VD_IMAGE_READ_ONLY;
2955 goto out;
2956 }
2957
2958 *pcbPreRead = 0;
2959 *pcbPostRead = 0;
2960
2961 /*
2962 * Clip write size to a value which is supported by the target.
2963 */
2964 cbToWrite = RT_MIN(cbToWrite, pImage->cbSendDataLength);
2965
2966 lba = uOffset / pImage->cbSector;
2967 tls = (uint16_t)(cbToWrite / pImage->cbSector);
2968 SCSIREQ sr;
2969 uint8_t cdb[10];
2970 uint8_t sense[32];
2971
2972 cdb[0] = SCSI_WRITE_10;
2973 cdb[1] = 0; /* reserved */
2974 cdb[2] = (lba >> 24) & 0xff;
2975 cdb[3] = (lba >> 16) & 0xff;
2976 cdb[4] = (lba >> 8) & 0xff;
2977 cdb[5] = lba & 0xff;
2978 cdb[6] = 0; /* reserved */
2979 cdb[7] = (tls >> 8) & 0xff;
2980 cdb[8] = tls & 0xff;
2981 cdb[9] = 0; /* control */
2982
2983 sr.enmXfer = SCSIXFER_TO_TARGET;
2984 sr.cbCmd = sizeof(cdb);
2985 sr.pvCmd = cdb;
2986 sr.cbI2TData = cbToWrite;
2987 sr.pcvI2TData = pvBuf;
2988 sr.cbT2IData = 0;
2989 sr.pvT2IData = NULL;
2990 sr.cbSense = sizeof(sense);
2991 sr.pvSense = sense;
2992
2993 for (unsigned i = 0; i < 10; i++)
2994 {
2995 rc = iscsiCommand(pImage, &sr);
2996 if ( (RT_SUCCESS(rc) && !sr.cbSense)
2997 || RT_FAILURE(rc))
2998 break;
2999 rc = VERR_WRITE_ERROR;
3000 }
3001 if (RT_FAILURE(rc))
3002 {
3003 AssertMsgFailed(("iscsiCommand(%s, %#llx) -> %Rrc\n", pImage->pszTargetName, uOffset, rc));
3004 *pcbWriteProcess = 0;
3005 }
3006 else
3007 *pcbWriteProcess = cbToWrite;
3008
3009out:
3010 LogFlowFunc(("returns %Rrc\n", rc));
3011 return rc;
3012}
3013
3014
3015/** @copydoc VBOXHDDBACKEND::pfnFlush */
3016static int iscsiFlush(void *pBackendData)
3017{
3018 LogFlowFunc(("pBackendData=%#p\n", pBackendData));
3019 PISCSIIMAGE pImage = (PISCSIIMAGE)pBackendData;
3020 int rc;
3021
3022 Assert(pImage);
3023
3024 SCSIREQ sr;
3025 uint8_t cdb[10];
3026 uint8_t sense[32];
3027
3028 cdb[0] = SCSI_SYNCHRONIZE_CACHE;
3029 cdb[1] = 0; /* reserved */
3030 cdb[2] = 0; /* LBA 0 */
3031 cdb[3] = 0; /* LBA 0 */
3032 cdb[4] = 0; /* LBA 0 */
3033 cdb[5] = 0; /* LBA 0 */
3034 cdb[6] = 0; /* reserved */
3035 cdb[7] = 0; /* transfer everything to disk */
3036 cdb[8] = 0; /* transfer everything to disk */
3037 cdb[9] = 0; /* control */
3038
3039 sr.enmXfer = SCSIXFER_TO_TARGET;
3040 sr.cbCmd = sizeof(cdb);
3041 sr.pvCmd = cdb;
3042 sr.cbI2TData = 0;
3043 sr.pcvI2TData = NULL;
3044 sr.cbT2IData = 0;
3045 sr.pvT2IData = NULL;
3046 sr.cbSense = sizeof(sense);
3047 sr.pvSense = sense;
3048
3049 rc = iscsiCommand(pImage, &sr);
3050 if (RT_FAILURE(rc))
3051 AssertMsgFailed(("iscsiCommand(%s) -> %Rrc\n", pImage->pszTargetName, rc));
3052 LogFlowFunc(("returns %Rrc\n", rc));
3053 return rc;
3054}
3055
3056
3057/** @copydoc VBOXHDDBACKEND::pfnGetVersion */
3058static unsigned iscsiGetVersion(void *pBackendData)
3059{
3060 LogFlowFunc(("pBackendData=%#p\n", pBackendData));
3061 PISCSIIMAGE pImage = (PISCSIIMAGE)pBackendData;
3062
3063 Assert(pImage);
3064 NOREF(pImage);
3065
3066 return 0;
3067}
3068
3069
3070/** @copydoc VBOXHDDBACKEND::pfnGetSize */
3071static uint64_t iscsiGetSize(void *pBackendData)
3072{
3073 LogFlowFunc(("pBackendData=%#p\n", pBackendData));
3074 PISCSIIMAGE pImage = (PISCSIIMAGE)pBackendData;
3075
3076 Assert(pImage);
3077
3078 if (pImage)
3079 return pImage->cbSize;
3080 else
3081 return 0;
3082}
3083
3084
3085/** @copydoc VBOXHDDBACKEND::pfnGetFileSize */
3086static uint64_t iscsiGetFileSize(void *pBackendData)
3087{
3088 LogFlowFunc(("pBackendData=%#p\n", pBackendData));
3089 PISCSIIMAGE pImage = (PISCSIIMAGE)pBackendData;
3090
3091 Assert(pImage);
3092 NOREF(pImage);
3093
3094 if (pImage)
3095 return pImage->cbSize;
3096 else
3097 return 0;
3098}
3099
3100
3101/** @copydoc VBOXHDDBACKEND::pfnGetPCHSGeometry */
3102static int iscsiGetPCHSGeometry(void *pBackendData,
3103 PPDMMEDIAGEOMETRY pPCHSGeometry)
3104{
3105 LogFlowFunc(("pBackendData=%#p pPCHSGeometry=%#p\n", pBackendData, pPCHSGeometry));
3106 PISCSIIMAGE pImage = (PISCSIIMAGE)pBackendData;
3107 int rc;
3108
3109 Assert(pImage);
3110
3111 if (pImage)
3112 rc = VERR_VD_GEOMETRY_NOT_SET;
3113 else
3114 rc = VERR_VD_NOT_OPENED;
3115
3116 LogFlowFunc(("returns %Rrc (PCHS=%u/%u/%u)\n", rc, pPCHSGeometry->cCylinders, pPCHSGeometry->cHeads, pPCHSGeometry->cSectors));
3117 return rc;
3118}
3119
3120
3121/** @copydoc VBOXHDDBACKEND::pfnSetPCHSGeometry */
3122static int iscsiSetPCHSGeometry(void *pBackendData,
3123 PCPDMMEDIAGEOMETRY pPCHSGeometry)
3124{
3125 LogFlowFunc(("pBackendData=%#p pPCHSGeometry=%#p PCHS=%u/%u/%u\n", pBackendData, pPCHSGeometry, pPCHSGeometry->cCylinders, pPCHSGeometry->cHeads, pPCHSGeometry->cSectors));
3126 PISCSIIMAGE pImage = (PISCSIIMAGE)pBackendData;
3127 int rc;
3128
3129 Assert(pImage);
3130
3131 if (pImage)
3132 {
3133 if (pImage->uOpenFlags & VD_OPEN_FLAGS_READONLY)
3134 {
3135 rc = VERR_VD_IMAGE_READ_ONLY;
3136 goto out;
3137 }
3138 rc = VERR_VD_GEOMETRY_NOT_SET;
3139 }
3140 else
3141 rc = VERR_VD_NOT_OPENED;
3142
3143out:
3144 LogFlowFunc(("returns %Rrc\n", rc));
3145 return rc;
3146}
3147
3148
3149/** @copydoc VBOXHDDBACKEND::pfnGetLCHSGeometry */
3150static int iscsiGetLCHSGeometry(void *pBackendData,
3151 PPDMMEDIAGEOMETRY pLCHSGeometry)
3152{
3153 LogFlowFunc(("pBackendData=%#p pLCHSGeometry=%#p\n", pBackendData, pLCHSGeometry));
3154 PISCSIIMAGE pImage = (PISCSIIMAGE)pBackendData;
3155 int rc;
3156
3157 Assert(pImage);
3158
3159 if (pImage)
3160 rc = VERR_VD_GEOMETRY_NOT_SET;
3161 else
3162 rc = VERR_VD_NOT_OPENED;
3163
3164 LogFlowFunc(("returns %Rrc (LCHS=%u/%u/%u)\n", rc, pLCHSGeometry->cCylinders, pLCHSGeometry->cHeads, pLCHSGeometry->cSectors));
3165 return rc;
3166}
3167
3168
3169/** @copydoc VBOXHDDBACKEND::pfnGetImageFlags */
3170static unsigned iscsiGetImageFlags(void *pBackendData)
3171{
3172 LogFlowFunc(("pBackendData=%#p\n", pBackendData));
3173 PISCSIIMAGE pImage = (PISCSIIMAGE)pBackendData;
3174 unsigned uImageFlags;
3175
3176 Assert(pImage);
3177 NOREF(pImage);
3178
3179 uImageFlags = VD_IMAGE_FLAGS_FIXED;
3180
3181 LogFlowFunc(("returns %#x\n", uImageFlags));
3182 return uImageFlags;
3183}
3184
3185
3186/** @copydoc VBOXHDDBACKEND::pfnGetOpenFlags */
3187static unsigned iscsiGetOpenFlags(void *pBackendData)
3188{
3189 LogFlowFunc(("pBackendData=%#p\n", pBackendData));
3190 PISCSIIMAGE pImage = (PISCSIIMAGE)pBackendData;
3191 unsigned uOpenFlags;
3192
3193 Assert(pImage);
3194
3195 if (pImage)
3196 uOpenFlags = pImage->uOpenFlags;
3197 else
3198 uOpenFlags = 0;
3199
3200 LogFlowFunc(("returns %#x\n", uOpenFlags));
3201 return uOpenFlags;
3202}
3203
3204
3205/** @copydoc VBOXHDDBACKEND::pfnSetOpenFlags */
3206static int iscsiSetOpenFlags(void *pBackendData, unsigned uOpenFlags)
3207{
3208 LogFlowFunc(("pBackendData=%#p\n uOpenFlags=%#x", pBackendData, uOpenFlags));
3209 PISCSIIMAGE pImage = (PISCSIIMAGE)pBackendData;
3210 int rc;
3211
3212 /* Image must be opened and the new flags must be valid. Just readonly and
3213 * info flags are supported. */
3214 if (!pImage || (uOpenFlags & ~(VD_OPEN_FLAGS_READONLY | VD_OPEN_FLAGS_INFO)))
3215 {
3216 rc = VERR_INVALID_PARAMETER;
3217 goto out;
3218 }
3219
3220 /* Implement this operation via reopening the image. */
3221 iscsiFreeImage(pImage, false);
3222 rc = iscsiOpenImage(pImage, uOpenFlags);
3223
3224out:
3225 LogFlowFunc(("returns %Rrc\n", rc));
3226 return rc;
3227}
3228
3229
3230/** @copydoc VBOXHDDBACKEND::pfnSetLCHSGeometry */
3231static int iscsiSetLCHSGeometry(void *pBackendData,
3232 PCPDMMEDIAGEOMETRY pLCHSGeometry)
3233{
3234 LogFlowFunc(("pBackendData=%#p pLCHSGeometry=%#p LCHS=%u/%u/%u\n", pBackendData, pLCHSGeometry, pLCHSGeometry->cCylinders, pLCHSGeometry->cHeads, pLCHSGeometry->cSectors));
3235 PISCSIIMAGE pImage = (PISCSIIMAGE)pBackendData;
3236 int rc;
3237
3238 Assert(pImage);
3239
3240 if (pImage)
3241 {
3242 if (pImage->uOpenFlags & VD_OPEN_FLAGS_READONLY)
3243 {
3244 rc = VERR_VD_IMAGE_READ_ONLY;
3245 goto out;
3246 }
3247 rc = VERR_VD_GEOMETRY_NOT_SET;
3248 }
3249 else
3250 rc = VERR_VD_NOT_OPENED;
3251
3252out:
3253 LogFlowFunc(("returns %Rrc\n", rc));
3254 return rc;
3255}
3256
3257
3258/** @copydoc VBOXHDDBACKEND::pfnGetComment */
3259static int iscsiGetComment(void *pBackendData, char *pszComment,
3260 size_t cbComment)
3261{
3262 LogFlowFunc(("pBackendData=%#p pszComment=%#p cbComment=%zu\n", pBackendData, pszComment, cbComment));
3263 PISCSIIMAGE pImage = (PISCSIIMAGE)pBackendData;
3264 int rc;
3265
3266 Assert(pImage);
3267
3268 if (pImage)
3269 rc = VERR_NOT_SUPPORTED;
3270 else
3271 rc = VERR_VD_NOT_OPENED;
3272
3273 LogFlowFunc(("returns %Rrc comment='%s'\n", rc, pszComment));
3274 return rc;
3275}
3276
3277
3278/** @copydoc VBOXHDDBACKEND::pfnSetComment */
3279static int iscsiSetComment(void *pBackendData, const char *pszComment)
3280{
3281 LogFlowFunc(("pBackendData=%#p pszComment=\"%s\"\n", pBackendData, pszComment));
3282 PISCSIIMAGE pImage = (PISCSIIMAGE)pBackendData;
3283 int rc;
3284
3285 Assert(pImage);
3286
3287 if (pImage)
3288 {
3289 if (!(pImage->uOpenFlags & VD_OPEN_FLAGS_READONLY))
3290 rc = VERR_NOT_SUPPORTED;
3291 else
3292 rc = VERR_VD_IMAGE_READ_ONLY;
3293 }
3294 else
3295 rc = VERR_VD_NOT_OPENED;
3296
3297 LogFlowFunc(("returns %Rrc\n", rc));
3298 return rc;
3299}
3300
3301
3302/** @copydoc VBOXHDDBACKEND::pfnGetUuid */
3303static int iscsiGetUuid(void *pBackendData, PRTUUID pUuid)
3304{
3305 LogFlowFunc(("pBackendData=%#p pUuid=%#p\n", pBackendData, pUuid));
3306 PISCSIIMAGE pImage = (PISCSIIMAGE)pBackendData;
3307 int rc;
3308
3309 Assert(pImage);
3310
3311 if (pImage)
3312 rc = VERR_NOT_SUPPORTED;
3313 else
3314 rc = VERR_VD_NOT_OPENED;
3315
3316 LogFlowFunc(("returns %Rrc (%RTuuid)\n", rc, pUuid));
3317 return rc;
3318}
3319
3320
3321/** @copydoc VBOXHDDBACKEND::pfnSetUuid */
3322static int iscsiSetUuid(void *pBackendData, PCRTUUID pUuid)
3323{
3324 LogFlowFunc(("pBackendData=%#p Uuid=%RTuuid\n", pBackendData, pUuid));
3325 PISCSIIMAGE pImage = (PISCSIIMAGE)pBackendData;
3326 int rc;
3327
3328 LogFlowFunc(("%RTuuid\n", pUuid));
3329 Assert(pImage);
3330
3331 if (pImage)
3332 {
3333 if (!(pImage->uOpenFlags & VD_OPEN_FLAGS_READONLY))
3334 rc = VERR_NOT_SUPPORTED;
3335 else
3336 rc = VERR_VD_IMAGE_READ_ONLY;
3337 }
3338 else
3339 rc = VERR_VD_NOT_OPENED;
3340
3341 LogFlowFunc(("returns %Rrc\n", rc));
3342 return rc;
3343}
3344
3345
3346/** @copydoc VBOXHDDBACKEND::pfnGetModificationUuid */
3347static int iscsiGetModificationUuid(void *pBackendData, PRTUUID pUuid)
3348{
3349 LogFlowFunc(("pBackendData=%#p pUuid=%#p\n", pBackendData, pUuid));
3350 PISCSIIMAGE pImage = (PISCSIIMAGE)pBackendData;
3351 int rc;
3352
3353 Assert(pImage);
3354
3355 if (pImage)
3356 rc = VERR_NOT_SUPPORTED;
3357 else
3358 rc = VERR_VD_NOT_OPENED;
3359
3360 LogFlowFunc(("returns %Rrc (%RTuuid)\n", rc, pUuid));
3361 return rc;
3362}
3363
3364
3365/** @copydoc VBOXHDDBACKEND::pfnSetModificationUuid */
3366static int iscsiSetModificationUuid(void *pBackendData, PCRTUUID pUuid)
3367{
3368 LogFlowFunc(("pBackendData=%#p Uuid=%RTuuid\n", pBackendData, pUuid));
3369 PISCSIIMAGE pImage = (PISCSIIMAGE)pBackendData;
3370 int rc;
3371
3372 LogFlowFunc(("%RTuuid\n", pUuid));
3373 Assert(pImage);
3374
3375 if (pImage)
3376 {
3377 if (!(pImage->uOpenFlags & VD_OPEN_FLAGS_READONLY))
3378 rc = VERR_NOT_SUPPORTED;
3379 else
3380 rc = VERR_VD_IMAGE_READ_ONLY;
3381 }
3382 else
3383 rc = VERR_VD_NOT_OPENED;
3384
3385 LogFlowFunc(("returns %Rrc\n", rc));
3386 return rc;
3387}
3388
3389
3390/** @copydoc VBOXHDDBACKEND::pfnGetParentUuid */
3391static int iscsiGetParentUuid(void *pBackendData, PRTUUID pUuid)
3392{
3393 LogFlowFunc(("pBackendData=%#p pUuid=%#p\n", pBackendData, pUuid));
3394 PISCSIIMAGE pImage = (PISCSIIMAGE)pBackendData;
3395 int rc;
3396
3397 Assert(pImage);
3398
3399 if (pImage)
3400 rc = VERR_NOT_SUPPORTED;
3401 else
3402 rc = VERR_VD_NOT_OPENED;
3403
3404 LogFlowFunc(("returns %Rrc (%RTuuid)\n", rc, pUuid));
3405 return rc;
3406}
3407
3408
3409/** @copydoc VBOXHDDBACKEND::pfnSetParentUuid */
3410static int iscsiSetParentUuid(void *pBackendData, PCRTUUID pUuid)
3411{
3412 LogFlowFunc(("pBackendData=%#p Uuid=%RTuuid\n", pBackendData, pUuid));
3413 PISCSIIMAGE pImage = (PISCSIIMAGE)pBackendData;
3414 int rc;
3415
3416 LogFlowFunc(("%RTuuid\n", pUuid));
3417 Assert(pImage);
3418
3419 if (pImage)
3420 {
3421 if (!(pImage->uOpenFlags & VD_OPEN_FLAGS_READONLY))
3422 rc = VERR_NOT_SUPPORTED;
3423 else
3424 rc = VERR_VD_IMAGE_READ_ONLY;
3425 }
3426 else
3427 rc = VERR_VD_NOT_OPENED;
3428
3429 LogFlowFunc(("returns %Rrc\n", rc));
3430 return rc;
3431}
3432
3433
3434/** @copydoc VBOXHDDBACKEND::pfnGetParentModificationUuid */
3435static int iscsiGetParentModificationUuid(void *pBackendData, PRTUUID pUuid)
3436{
3437 LogFlowFunc(("pBackendData=%#p pUuid=%#p\n", pBackendData, pUuid));
3438 PISCSIIMAGE pImage = (PISCSIIMAGE)pBackendData;
3439 int rc;
3440
3441 Assert(pImage);
3442
3443 if (pImage)
3444 rc = VERR_NOT_SUPPORTED;
3445 else
3446 rc = VERR_VD_NOT_OPENED;
3447
3448 LogFlowFunc(("returns %Rrc (%RTuuid)\n", rc, pUuid));
3449 return rc;
3450}
3451
3452
3453/** @copydoc VBOXHDDBACKEND::pfnSetParentModificationUuid */
3454static int iscsiSetParentModificationUuid(void *pBackendData, PCRTUUID pUuid)
3455{
3456 LogFlowFunc(("pBackendData=%#p Uuid=%RTuuid\n", pBackendData, pUuid));
3457 PISCSIIMAGE pImage = (PISCSIIMAGE)pBackendData;
3458 int rc;
3459
3460 LogFlowFunc(("%RTuuid\n", pUuid));
3461 Assert(pImage);
3462
3463 if (pImage)
3464 {
3465 if (!(pImage->uOpenFlags & VD_OPEN_FLAGS_READONLY))
3466 rc = VERR_NOT_SUPPORTED;
3467 else
3468 rc = VERR_VD_IMAGE_READ_ONLY;
3469 }
3470 else
3471 rc = VERR_VD_NOT_OPENED;
3472
3473 LogFlowFunc(("returns %Rrc\n", rc));
3474 return rc;
3475}
3476
3477
3478/** @copydoc VBOXHDDBACKEND::pfnDump */
3479static void iscsiDump(void *pBackendData)
3480{
3481 PISCSIIMAGE pImage = (PISCSIIMAGE)pBackendData;
3482
3483 Assert(pImage);
3484 if (pImage)
3485 {
3486 /** @todo put something useful here */
3487 pImage->pInterfaceErrorCallbacks->pfnMessage(pImage->pInterfaceError->pvUser, "Header: cVolume=%u\n", pImage->cVolume);
3488 }
3489}
3490
3491
3492/** @copydoc VBOXHDDBACKEND::pfnGetTimeStamp */
3493static int iscsiGetTimeStamp(void *pBackendData, PRTTIMESPEC pTimeStamp)
3494{
3495 LogFlowFunc(("pBackendData=%#p pTimeStamp=%#p\n", pBackendData, pTimeStamp));
3496 PISCSIIMAGE pImage = (PISCSIIMAGE)pBackendData;
3497 int rc = VERR_NOT_SUPPORTED;
3498
3499 Assert(pImage);
3500 NOREF(pImage);
3501
3502 LogFlowFunc(("returns %Rrc\n", rc));
3503 return rc;
3504}
3505
3506
3507/** @copydoc VBOXHDDBACKEND::pfnGetParentTimeStamp */
3508static int iscsiGetParentTimeStamp(void *pBackendData, PRTTIMESPEC pTimeStamp)
3509{
3510 LogFlowFunc(("pBackendData=%#p pTimeStamp=%#p\n", pBackendData, pTimeStamp));
3511 PISCSIIMAGE pImage = (PISCSIIMAGE)pBackendData;
3512 int rc = VERR_NOT_SUPPORTED;
3513
3514 Assert(pImage);
3515 NOREF(pImage);
3516
3517 LogFlowFunc(("returns %Rrc\n", rc));
3518 return rc;
3519}
3520
3521
3522/** @copydoc VBOXHDDBACKEND::pfnSetParentTimeStamp */
3523static int iscsiSetParentTimeStamp(void *pBackendData, PCRTTIMESPEC pTimeStamp)
3524{
3525 LogFlowFunc(("pBackendData=%#p pTimeStamp=%#p\n", pBackendData, pTimeStamp));
3526 PISCSIIMAGE pImage = (PISCSIIMAGE)pBackendData;
3527 int rc = VERR_NOT_SUPPORTED;
3528
3529 Assert(pImage);
3530 NOREF(pImage);
3531
3532 LogFlowFunc(("returns %Rrc\n", rc));
3533 return rc;
3534}
3535
3536
3537/** @copydoc VBOXHDDBACKEND::pfnGetParentFilename */
3538static int iscsiGetParentFilename(void *pBackendData, char **ppszParentFilename)
3539{
3540 LogFlowFunc(("pBackendData=%#p ppszParentFilename=%#p\n", pBackendData, ppszParentFilename));
3541 PISCSIIMAGE pImage = (PISCSIIMAGE)pBackendData;
3542 int rc = VERR_NOT_SUPPORTED;
3543
3544 Assert(pImage);
3545 NOREF(pImage);
3546
3547 LogFlowFunc(("returns %Rrc\n", rc));
3548 return rc;
3549}
3550
3551
3552/** @copydoc VBOXHDDBACKEND::pfnSetParentFilename */
3553static int iscsiSetParentFilename(void *pBackendData, const char *pszParentFilename)
3554{
3555 LogFlowFunc(("pBackendData=%#p pszParentFilename=%s\n", pBackendData, pszParentFilename));
3556 PISCSIIMAGE pImage = (PISCSIIMAGE)pBackendData;
3557 int rc = VERR_NOT_SUPPORTED;
3558
3559 Assert(pImage);
3560 NOREF(pImage);
3561
3562 LogFlowFunc(("returns %Rrc\n", rc));
3563 return rc;
3564}
3565
3566/** @copydoc VBOXHDDBACKEND::pfnComposeLocation */
3567static int iscsiComposeLocation(PVDINTERFACE pConfig, char **pszLocation)
3568{
3569 char *pszTarget = NULL;
3570 char *pszLUN = NULL;
3571 char *pszAddress = NULL;
3572 int rc = VDCFGQueryStringAlloc(VDGetInterfaceConfig(pConfig), pConfig->pvUser, "TargetName", &pszTarget);
3573 if (RT_SUCCESS(rc))
3574 {
3575 rc = VDCFGQueryStringAlloc(VDGetInterfaceConfig(pConfig), pConfig->pvUser, "LUN", &pszLUN);
3576 if (RT_SUCCESS(rc))
3577 {
3578 rc = VDCFGQueryStringAlloc(VDGetInterfaceConfig(pConfig), pConfig->pvUser, "TargetAddress", &pszAddress);
3579 if (RT_SUCCESS(rc))
3580 {
3581 if (RTStrAPrintf(pszLocation, "iscsi://%s/%s/%s",
3582 pszAddress, pszTarget, pszLUN) < 0)
3583 rc = VERR_NO_MEMORY;
3584 }
3585 }
3586 }
3587 RTMemFree(pszTarget);
3588 RTMemFree(pszLUN);
3589 RTMemFree(pszAddress);
3590 return rc;
3591}
3592
3593/** @copydoc VBOXHDDBACKEND::pfnComposeName */
3594static int iscsiComposeName(PVDINTERFACE pConfig, char **pszName)
3595{
3596 char *pszTarget = NULL;
3597 char *pszLUN = NULL;
3598 char *pszAddress = NULL;
3599 int rc = VDCFGQueryStringAlloc(VDGetInterfaceConfig(pConfig), pConfig->pvUser, "TargetName", &pszTarget);
3600 if (RT_SUCCESS(rc))
3601 {
3602 rc = VDCFGQueryStringAlloc(VDGetInterfaceConfig(pConfig), pConfig->pvUser, "LUN", &pszLUN);
3603 if (RT_SUCCESS(rc))
3604 {
3605 rc = VDCFGQueryStringAlloc(VDGetInterfaceConfig(pConfig), pConfig->pvUser, "TargetAddress", &pszAddress);
3606 if (RT_SUCCESS(rc))
3607 {
3608 /** @todo think about a nicer looking location scheme for iSCSI */
3609 if (RTStrAPrintf(pszName, "%s/%s/%s",
3610 pszAddress, pszTarget, pszLUN) < 0)
3611 rc = VERR_NO_MEMORY;
3612 }
3613 }
3614 }
3615 RTMemFree(pszTarget);
3616 RTMemFree(pszLUN);
3617 RTMemFree(pszAddress);
3618
3619 return rc;
3620}
3621
3622
3623VBOXHDDBACKEND g_ISCSIBackend =
3624{
3625 /* pszBackendName */
3626 "iSCSI",
3627 /* cbSize */
3628 sizeof(VBOXHDDBACKEND),
3629 /* uBackendCaps */
3630 VD_CAP_CONFIG | VD_CAP_TCPNET,
3631 /* papszFileExtensions */
3632 NULL,
3633 /* paConfigInfo */
3634 s_iscsiConfigInfo,
3635 /* hPlugin */
3636 NIL_RTLDRMOD,
3637 /* pfnCheckIfValid */
3638 iscsiCheckIfValid,
3639 /* pfnOpen */
3640 iscsiOpen,
3641 /* pfnCreate */
3642 iscsiCreate,
3643 /* pfnRename */
3644 iscsiRename,
3645 /* pfnClose */
3646 iscsiClose,
3647 /* pfnRead */
3648 iscsiRead,
3649 /* pfnWrite */
3650 iscsiWrite,
3651 /* pfnFlush */
3652 iscsiFlush,
3653 /* pfnGetVersion */
3654 iscsiGetVersion,
3655 /* pfnGetSize */
3656 iscsiGetSize,
3657 /* pfnGetFileSize */
3658 iscsiGetFileSize,
3659 /* pfnGetPCHSGeometry */
3660 iscsiGetPCHSGeometry,
3661 /* pfnSetPCHSGeometry */
3662 iscsiSetPCHSGeometry,
3663 /* pfnGetLCHSGeometry */
3664 iscsiGetLCHSGeometry,
3665 /* pfnSetLCHSGeometry */
3666 iscsiSetLCHSGeometry,
3667 /* pfnGetImageFlags */
3668 iscsiGetImageFlags,
3669 /* pfnGetOpenFlags */
3670 iscsiGetOpenFlags,
3671 /* pfnSetOpenFlags */
3672 iscsiSetOpenFlags,
3673 /* pfnGetComment */
3674 iscsiGetComment,
3675 /* pfnSetComment */
3676 iscsiSetComment,
3677 /* pfnGetUuid */
3678 iscsiGetUuid,
3679 /* pfnSetUuid */
3680 iscsiSetUuid,
3681 /* pfnGetModificationUuid */
3682 iscsiGetModificationUuid,
3683 /* pfnSetModificationUuid */
3684 iscsiSetModificationUuid,
3685 /* pfnGetParentUuid */
3686 iscsiGetParentUuid,
3687 /* pfnSetParentUuid */
3688 iscsiSetParentUuid,
3689 /* pfnGetParentModificationUuid */
3690 iscsiGetParentModificationUuid,
3691 /* pfnSetParentModificationUuid */
3692 iscsiSetParentModificationUuid,
3693 /* pfnDump */
3694 iscsiDump,
3695 /* pfnGetTimeStamp */
3696 iscsiGetTimeStamp,
3697 /* pfnGetParentTimeStamp */
3698 iscsiGetParentTimeStamp,
3699 /* pfnSetParentTimeStamp */
3700 iscsiSetParentTimeStamp,
3701 /* pfnGetParentFilename */
3702 iscsiGetParentFilename,
3703 /* pfnSetParentFilename */
3704 iscsiSetParentFilename,
3705 /* pfnIsAsyncIOSupported */
3706 NULL,
3707 /* pfnAsyncRead */
3708 NULL,
3709 /* pfnAsyncWrite */
3710 NULL,
3711 /* pfnComposeLocation */
3712 iscsiComposeLocation,
3713 /* pfnComposeName */
3714 iscsiComposeName
3715};
Note: See TracBrowser for help on using the repository browser.

© 2024 Oracle Support Privacy / Do Not Sell My Info Terms of Use Trademark Policy Automated Access Etiquette