VirtualBox

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

最後變更 在這個檔案從24144是 24144,由 vboxsync 提交於 15 年 前

Storage/iSCSI: try to get the capacity with a command that supports 64bit sector numbers, and fall back to the old one which does only 32bit if that fails

  • 屬性 svn:eol-style 設為 native
  • 屬性 svn:keywords 設為 Author Date Id Revision
檔案大小: 129.7 KB
 
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.alldomusa.eu.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 /** Sector size on volume. */
312 uint32_t cbSector;
313 /** Size of volume in sectors. */
314 uint64_t cVolume;
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 uint8_t data12[12];
2466
2467 /*
2468 * Inquire available LUNs - purely dummy request.
2469 */
2470 uint8_t cdb_rlun[12];
2471 uint8_t rlundata[16];
2472 cdb_rlun[0] = SCSI_REPORT_LUNS;
2473 cdb_rlun[1] = 0; /* reserved */
2474 cdb_rlun[2] = 0; /* reserved */
2475 cdb_rlun[3] = 0; /* reserved */
2476 cdb_rlun[4] = 0; /* reserved */
2477 cdb_rlun[5] = 0; /* reserved */
2478 cdb_rlun[6] = sizeof(rlundata) >> 24;
2479 cdb_rlun[7] = (sizeof(rlundata) >> 16) & 0xff;
2480 cdb_rlun[8] = (sizeof(rlundata) >> 8) & 0xff;
2481 cdb_rlun[9] = sizeof(rlundata) & 0xff;
2482 cdb_rlun[10] = 0; /* reserved */
2483 cdb_rlun[11] = 0; /* control */
2484
2485 sr.enmXfer = SCSIXFER_FROM_TARGET;
2486 sr.cbCmd = sizeof(cdb_rlun);
2487 sr.pvCmd = cdb_rlun;
2488 sr.cbI2TData = 0;
2489 sr.pcvI2TData = NULL;
2490 sr.cbT2IData = sizeof(rlundata);
2491 sr.pvT2IData = rlundata;
2492 sr.cbSense = sizeof(sense);
2493 sr.pvSense = sense;
2494
2495 rc = iscsiCommand(pImage, &sr);
2496 if (RT_FAILURE(rc))
2497 {
2498 LogRel(("iSCSI: Could not get LUN info for target %s, rc=%Rrc\n", pImage->pszTargetName, rc));
2499 return rc;
2500 }
2501
2502 /*
2503 * Inquire device characteristics - no tapes, scanners etc., please.
2504 */
2505 uint8_t cdb_inq[6];
2506 cdb_inq[0] = SCSI_INQUIRY;
2507 cdb_inq[1] = 0; /* reserved */
2508 cdb_inq[2] = 0; /* reserved */
2509 cdb_inq[3] = 0; /* reserved */
2510 cdb_inq[4] = sizeof(data8);
2511 cdb_inq[5] = 0; /* control */
2512
2513 sr.enmXfer = SCSIXFER_FROM_TARGET;
2514 sr.cbCmd = sizeof(cdb_inq);
2515 sr.pvCmd = cdb_inq;
2516 sr.cbI2TData = 0;
2517 sr.pcvI2TData = NULL;
2518 sr.cbT2IData = sizeof(data8);
2519 sr.pvT2IData = data8;
2520 sr.cbSense = sizeof(sense);
2521 sr.pvSense = sense;
2522
2523 rc = iscsiCommand(pImage, &sr);
2524 if (RT_SUCCESS(rc))
2525 {
2526 if ((data8[0] & SCSI_DEVTYPE_MASK) != SCSI_DEVTYPE_DISK)
2527 {
2528 rc = iscsiError(pImage, VERR_VD_ISCSI_INVALID_TYPE,
2529 RT_SRC_POS, N_("iSCSI: target address %s, target name %s, SCSI LUN %lld reports device type=%u"),
2530 pImage->pszTargetAddress, pImage->pszTargetName,
2531 pImage->LUN, data8[0]);
2532 LogRel(("iSCSI: Unsupported SCSI peripheral device type %d for target %s\n", data8[0] & SCSI_DEVTYPE_MASK, pImage->pszTargetName));
2533 goto out;
2534 }
2535 }
2536 else
2537 {
2538 LogRel(("iSCSI: Could not get INQUIRY info for target %s, rc=%Rrc\n", pImage->pszTargetName, rc));
2539 goto out;
2540 }
2541
2542 /*
2543 * Query write disable bit in the device specific parameter entry in the
2544 * mode parameter header. Refuse read/write opening of read only disks.
2545 */
2546
2547 uint8_t cdb_ms[6];
2548 uint8_t data4[4];
2549 cdb_ms[0] = SCSI_MODE_SENSE_6;
2550 cdb_ms[1] = 0; /* dbd=0/reserved */
2551 cdb_ms[2] = 0x3f; /* pc=0/page code=0x3f, ask for all pages */
2552 cdb_ms[3] = 0; /* subpage code=0, return everything in page_0 format */
2553 cdb_ms[4] = sizeof(data4); /* allocation length=4 */
2554 cdb_ms[5] = 0; /* control */
2555
2556 sr.enmXfer = SCSIXFER_FROM_TARGET;
2557 sr.cbCmd = sizeof(cdb_ms);
2558 sr.pvCmd = cdb_ms;
2559 sr.cbI2TData = 0;
2560 sr.pcvI2TData = NULL;
2561 sr.cbT2IData = sizeof(data4);
2562 sr.pvT2IData = data4;
2563 sr.cbSense = sizeof(sense);
2564 sr.pvSense = sense;
2565
2566 for (unsigned i = 0; i < 10; i++)
2567 {
2568 rc = iscsiCommand(pImage, &sr);
2569 if ( (RT_SUCCESS(rc) && !sr.cbSense)
2570 || RT_FAILURE(rc))
2571 break;
2572 rc = VERR_INVALID_STATE;
2573 }
2574 if (RT_SUCCESS(rc))
2575 {
2576 if (!(uOpenFlags & VD_OPEN_FLAGS_READONLY) && data4[2] & 0x80)
2577 {
2578 rc = VERR_VD_IMAGE_READ_ONLY;
2579 goto out;
2580 }
2581 }
2582 else
2583 {
2584 LogRel(("iSCSI: Could not get MODE SENSE info for target %s, rc=%Rrc\n", pImage->pszTargetName, rc));
2585 goto out;
2586 }
2587
2588 /*
2589 * Determine sector size and capacity of the volume immediately.
2590 */
2591 uint8_t cdb_cap[16];
2592
2593 memset(cdb_cap, '\0', sizeof(cdb_cap));
2594 cdb_cap[0] = SCSI_SERVICE_ACTION_IN_16;
2595 cdb_cap[1] = SCSI_SVC_ACTION_IN_READ_CAPACITY_16; /* subcommand */
2596
2597 sr.enmXfer = SCSIXFER_FROM_TARGET;
2598 sr.cbCmd = sizeof(cdb_cap);
2599 sr.pvCmd = cdb_cap;
2600 sr.cbI2TData = 0;
2601 sr.pcvI2TData = NULL;
2602 sr.cbT2IData = sizeof(data12);
2603 sr.pvT2IData = data12;
2604 sr.cbSense = sizeof(sense);
2605 sr.pvSense = sense;
2606
2607 rc = iscsiCommand(pImage, &sr);
2608 if (RT_SUCCESS(rc))
2609 {
2610 pImage->cVolume = RT_BE2H_U64(*(uint64_t *)&data12[0]);
2611 pImage->cVolume++;
2612 pImage->cbSector = RT_BE2H_U32(*(uint32_t *)&data12[8]);
2613 pImage->cbSize = pImage->cVolume * pImage->cbSector;
2614 if (pImage->cVolume == 0 || pImage->cbSector == 0)
2615 {
2616 rc = iscsiError(pImage, VERR_VD_ISCSI_INVALID_TYPE,
2617 RT_SRC_POS, N_("iSCSI: target address %s, target name %s, SCSI LUN %lld reports media sector count=%lu sector size=%lu"),
2618 pImage->pszTargetAddress, pImage->pszTargetName,
2619 pImage->LUN, pImage->cVolume, pImage->cbSector);
2620 }
2621 }
2622 else
2623 {
2624 uint8_t cdb_capfb[10];
2625
2626 cdb_capfb[0] = SCSI_READ_CAPACITY;
2627 cdb_capfb[1] = 0; /* reserved */
2628 cdb_capfb[2] = 0; /* reserved */
2629 cdb_capfb[3] = 0; /* reserved */
2630 cdb_capfb[4] = 0; /* reserved */
2631 cdb_capfb[5] = 0; /* reserved */
2632 cdb_capfb[6] = 0; /* reserved */
2633 cdb_capfb[7] = 0; /* reserved */
2634 cdb_capfb[8] = 0; /* reserved */
2635 cdb_capfb[9] = 0; /* control */
2636
2637 sr.enmXfer = SCSIXFER_FROM_TARGET;
2638 sr.cbCmd = sizeof(cdb_capfb);
2639 sr.pvCmd = cdb_capfb;
2640 sr.cbI2TData = 0;
2641 sr.pcvI2TData = NULL;
2642 sr.cbT2IData = sizeof(data8);
2643 sr.pvT2IData = data8;
2644 sr.cbSense = sizeof(sense);
2645 sr.pvSense = sense;
2646
2647 rc = iscsiCommand(pImage, &sr);
2648 if (RT_SUCCESS(rc))
2649 {
2650 pImage->cVolume = (data8[0] << 24) | (data8[1] << 16) | (data8[2] << 8) | data8[3];
2651 pImage->cVolume++;
2652 pImage->cbSector = (data8[4] << 24) | (data8[5] << 16) | (data8[6] << 8) | data8[7];
2653 pImage->cbSize = pImage->cVolume * pImage->cbSector;
2654 if (pImage->cVolume == 0 || pImage->cbSector == 0)
2655 {
2656 rc = iscsiError(pImage, VERR_VD_ISCSI_INVALID_TYPE,
2657 RT_SRC_POS, N_("iSCSI: fallback capacity detectio for target address %s, target name %s, SCSI LUN %lld reports media sector count=%lu sector size=%lu"),
2658 pImage->pszTargetAddress, pImage->pszTargetName,
2659 pImage->LUN, pImage->cVolume, pImage->cbSector);
2660 }
2661 }
2662 else
2663 {
2664 LogRel(("iSCSI: Could not determine capacity of target %s, rc=%Rrc\n", pImage->pszTargetName, rc));
2665 goto out;
2666 }
2667 }
2668
2669 /*
2670 * Check the read and write cache bits.
2671 * Try to enable the cache if it is disabled.
2672 *
2673 * We already checked that this is a block access device. No need
2674 * to do it again.
2675 */
2676 uint8_t aCachingModePage[32];
2677 uint8_t aCDBModeSense6[6];
2678
2679 memset(aCachingModePage, '\0', sizeof(aCachingModePage));
2680 aCDBModeSense6[0] = SCSI_MODE_SENSE_6;
2681 aCDBModeSense6[1] = 0;
2682 aCDBModeSense6[2] = (0x00 << 6) | (0x08 & 0x3f); /* Current values and caching mode page */
2683 aCDBModeSense6[3] = 0; /* Sub page code. */
2684 aCDBModeSense6[4] = sizeof(aCachingModePage) & 0xff;
2685 aCDBModeSense6[5] = 0;
2686 sr.enmXfer = SCSIXFER_FROM_TARGET;
2687 sr.cbCmd = sizeof(aCDBModeSense6);
2688 sr.pvCmd = aCDBModeSense6;
2689 sr.cbI2TData = 0;
2690 sr.pcvI2TData = NULL;
2691 sr.cbT2IData = sizeof(aCachingModePage);
2692 sr.pvT2IData = aCachingModePage;
2693 sr.cbSense = sizeof(sense);
2694 sr.pvSense = sense;
2695 rc = iscsiCommand(pImage, &sr);
2696 if ( RT_SUCCESS(rc)
2697 && (sr.status == SCSI_STATUS_OK)
2698 && (aCachingModePage[0] >= 15)
2699 && (aCachingModePage[4 + aCachingModePage[3]] & 0x3f) == 0x08
2700 && (aCachingModePage[4 + aCachingModePage[3] + 1] > 3))
2701 {
2702 uint32_t Offset = 4 + aCachingModePage[3];
2703 /*
2704 * Check if the read and/or the write cache is disabled.
2705 * The write cache is disabled if bit 2 (WCE) is zero and
2706 * the read cache is disabled if bit 0 (RCD) is set.
2707 */
2708 if (!ASMBitTest(&aCachingModePage[Offset + 2], 2) || ASMBitTest(&aCachingModePage[Offset + 2], 0))
2709 {
2710 /*
2711 * Write Cache Enable (WCE) bit is zero or the Read Cache Disable (RCD) is one
2712 * So one of the caches is disabled. Enable both caches.
2713 * The rest is unchanged.
2714 */
2715 ASMBitSet(&aCachingModePage[Offset + 2], 2);
2716 ASMBitClear(&aCachingModePage[Offset + 2], 0);
2717
2718 uint8_t aCDBCaching[6];
2719 aCDBCaching[0] = SCSI_MODE_SELECT_6;
2720 aCDBCaching[1] = 0; /* Don't write the page into NV RAM. */
2721 aCDBCaching[2] = 0;
2722 aCDBCaching[3] = 0;
2723 aCDBCaching[4] = sizeof(aCachingModePage) & 0xff;
2724 aCDBCaching[5] = 0;
2725 sr.enmXfer = SCSIXFER_TO_TARGET;
2726 sr.cbCmd = sizeof(aCDBCaching);
2727 sr.pvCmd = aCDBCaching;
2728 sr.cbI2TData = sizeof(aCachingModePage);
2729 sr.pcvI2TData = aCachingModePage;
2730 sr.cbT2IData = 0;
2731 sr.pvT2IData = NULL;
2732 sr.cbSense = sizeof(sense);
2733 sr.pvSense = sense;
2734 sr.status = 0;
2735 rc = iscsiCommand(pImage, &sr);
2736 if ( RT_SUCCESS(rc)
2737 && (sr.status == SCSI_STATUS_OK))
2738 {
2739 LogRel(("iSCSI: Enabled read and write cache of target %s\n", pImage->pszTargetName));
2740 }
2741 else
2742 {
2743 /* Log failures but continue. */
2744 LogRel(("iSCSI: Could not enable read and write cache of target %s, rc=%Rrc status=%#x\n",
2745 pImage->pszTargetName, rc, sr.status));
2746 LogRel(("iSCSI: Sense:\n%.*Rhxd\n", sr.cbSense, sense));
2747 rc = VINF_SUCCESS;
2748 }
2749 }
2750 }
2751 else
2752 {
2753 /* Log errors but continue. */
2754 LogRel(("iSCSI: Could not check write cache of target %s, rc=%Rrc, got mode page %#x\n", pImage->pszTargetName, rc,aCachingModePage[0] & 0x3f));
2755 LogRel(("iSCSI: Sense:\n%.*Rhxd\n", sr.cbSense, sense));
2756 rc = VINF_SUCCESS;
2757 }
2758
2759
2760out:
2761 if (RT_FAILURE(rc))
2762 iscsiFreeImage(pImage, false);
2763 return rc;
2764}
2765
2766
2767/** @copydoc VBOXHDDBACKEND::pfnCheckIfValid */
2768static int iscsiCheckIfValid(const char *pszFilename, PVDINTERFACE pVDIfsDisk)
2769{
2770 LogFlowFunc(("pszFilename=\"%s\"\n", pszFilename));
2771
2772 /* iSCSI images can't be checked for validity this way, as the filename
2773 * just can't supply enough configuration information. */
2774 int rc = VERR_VD_ISCSI_INVALID_HEADER;
2775
2776 LogFlowFunc(("returns %Rrc\n", rc));
2777 return rc;
2778}
2779
2780
2781/** @copydoc VBOXHDDBACKEND::pfnOpen */
2782static int iscsiOpen(const char *pszFilename, unsigned uOpenFlags,
2783 PVDINTERFACE pVDIfsDisk, PVDINTERFACE pVDIfsImage,
2784 void **ppBackendData)
2785{
2786 LogFlowFunc(("pszFilename=\"%s\" uOpenFlags=%#x pVDIfsDisk=%#p pVDIfsImage=%#p ppBackendData=%#p\n", pszFilename, uOpenFlags, pVDIfsDisk, pVDIfsImage, ppBackendData));
2787 int rc;
2788 PISCSIIMAGE pImage;
2789
2790 /* Check open flags. All valid flags are supported. */
2791 if (uOpenFlags & ~VD_OPEN_FLAGS_MASK)
2792 {
2793 rc = VERR_INVALID_PARAMETER;
2794 goto out;
2795 }
2796
2797 /* Check remaining arguments. */
2798 if ( !VALID_PTR(pszFilename)
2799 || !*pszFilename
2800 || strchr(pszFilename, '"'))
2801 {
2802 rc = VERR_INVALID_PARAMETER;
2803 goto out;
2804 }
2805
2806 pImage = (PISCSIIMAGE)RTMemAllocZ(sizeof(ISCSIIMAGE));
2807 if (!pImage)
2808 {
2809 rc = VERR_NO_MEMORY;
2810 goto out;
2811 }
2812
2813 pImage->pszFilename = pszFilename;
2814 pImage->pszInitiatorName = NULL;
2815 pImage->pszTargetName = NULL;
2816 pImage->pszTargetAddress = NULL;
2817 pImage->pszInitiatorUsername = NULL;
2818 pImage->pbInitiatorSecret = NULL;
2819 pImage->pszTargetUsername = NULL;
2820 pImage->pbTargetSecret = NULL;
2821 pImage->paCurrReq = NULL;
2822 pImage->pvRecvPDUBuf = NULL;
2823 pImage->pszHostname = NULL;
2824 pImage->pVDIfsDisk = pVDIfsDisk;
2825 pImage->pVDIfsImage = pVDIfsImage;
2826
2827 rc = iscsiOpenImage(pImage, uOpenFlags);
2828 if (RT_SUCCESS(rc))
2829 *ppBackendData = pImage;
2830
2831out:
2832 if (RT_SUCCESS(rc))
2833 {
2834 LogFlowFunc(("target %s cVolume %d, cbSector %d\n", pImage->pszTargetName, pImage->cVolume, pImage->cbSector));
2835 LogRel(("iSCSI: target address %s, target name %s, SCSI LUN %lld\n", pImage->pszTargetAddress, pImage->pszTargetName, pImage->LUN));
2836 }
2837 LogFlowFunc(("returns %Rrc (pBackendData=%#p)\n", rc, *ppBackendData));
2838 return rc;
2839}
2840
2841
2842/** @copydoc VBOXHDDBACKEND::pfnCreate */
2843static int iscsiCreate(const char *pszFilename, uint64_t cbSize,
2844 unsigned uImageFlags, const char *pszComment,
2845 PCPDMMEDIAGEOMETRY pPCHSGeometry,
2846 PCPDMMEDIAGEOMETRY pLCHSGeometry, PCRTUUID pUuid,
2847 unsigned uOpenFlags, unsigned uPercentStart,
2848 unsigned uPercentSpan, PVDINTERFACE pVDIfsDisk,
2849 PVDINTERFACE pVDIfsImage, PVDINTERFACE pVDIfsOperation,
2850 void **ppBackendData)
2851{
2852 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));
2853 int rc = VERR_NOT_SUPPORTED;
2854
2855 LogFlowFunc(("returns %Rrc (pBackendData=%#p)\n", rc, *ppBackendData));
2856 return rc;
2857}
2858
2859
2860/** @copydoc VBOXHDDBACKEND::pfnRename */
2861static int iscsiRename(void *pBackendData, const char *pszFilename)
2862{
2863 LogFlowFunc(("pBackendData=%#p pszFilename=%#p\n", pBackendData, pszFilename));
2864 int rc = VERR_NOT_SUPPORTED;
2865
2866 LogFlowFunc(("returns %Rrc\n", rc));
2867 return rc;
2868}
2869
2870
2871/** @copydoc VBOXHDDBACKEND::pfnClose */
2872static int iscsiClose(void *pBackendData, bool fDelete)
2873{
2874 LogFlowFunc(("pBackendData=%#p fDelete=%d\n", pBackendData, fDelete));
2875 PISCSIIMAGE pImage = (PISCSIIMAGE)pBackendData;
2876 int rc = VINF_SUCCESS;
2877
2878 Assert(!fDelete); /* This flag is unsupported. */
2879
2880 /* Freeing a never allocated image (e.g. because the open failed) is
2881 * not signalled as an error. After all nothing bad happens. */
2882 if (pImage)
2883 iscsiFreeImage(pImage, fDelete);
2884
2885 LogFlowFunc(("returns %Rrc\n", rc));
2886 return rc;
2887}
2888
2889
2890/** @copydoc VBOXHDDBACKEND::pfnRead */
2891static int iscsiRead(void *pBackendData, uint64_t uOffset, void *pvBuf,
2892 size_t cbToRead, size_t *pcbActuallyRead)
2893{
2894 /** @todo reinstate logging of the target everywhere - dropped temporarily */
2895 LogFlowFunc(("pBackendData=%#p uOffset=%llu pvBuf=%#p cbToRead=%zu pcbActuallyRead=%#p\n", pBackendData, uOffset, pvBuf, cbToRead, pcbActuallyRead));
2896 PISCSIIMAGE pImage = (PISCSIIMAGE)pBackendData;
2897 uint64_t lba;
2898 uint16_t tls;
2899 int rc;
2900
2901 Assert(pImage);
2902 Assert(uOffset % 512 == 0);
2903 Assert(cbToRead % 512 == 0);
2904
2905 Assert(pImage->cbSector);
2906 AssertPtr(pvBuf);
2907
2908 if ( uOffset + cbToRead > pImage->cbSize
2909 || cbToRead == 0)
2910 {
2911 rc = VERR_INVALID_PARAMETER;
2912 goto out;
2913 }
2914
2915 /*
2916 * Clip read size to a value which is supported by the target.
2917 */
2918 cbToRead = RT_MIN(cbToRead, pImage->cbRecvDataLength);
2919
2920 lba = uOffset / pImage->cbSector;
2921 tls = (uint16_t)(cbToRead / pImage->cbSector);
2922 SCSIREQ sr;
2923 uint8_t cdb[10];
2924 uint8_t sense[32];
2925
2926 cdb[0] = SCSI_READ_10;
2927 cdb[1] = 0; /* reserved */
2928 cdb[2] = (lba >> 24) & 0xff;
2929 cdb[3] = (lba >> 16) & 0xff;
2930 cdb[4] = (lba >> 8) & 0xff;
2931 cdb[5] = lba & 0xff;
2932 cdb[6] = 0; /* reserved */
2933 cdb[7] = (tls >> 8) & 0xff;
2934 cdb[8] = tls & 0xff;
2935 cdb[9] = 0; /* control */
2936
2937 sr.enmXfer = SCSIXFER_FROM_TARGET;
2938 sr.cbCmd = sizeof(cdb);
2939 sr.pvCmd = cdb;
2940 sr.cbI2TData = 0;
2941 sr.pcvI2TData = NULL;
2942 sr.cbT2IData = cbToRead;
2943 sr.pvT2IData = pvBuf;
2944 sr.cbSense = sizeof(sense);
2945 sr.pvSense = sense;
2946
2947 for (unsigned i = 0; i < 10; i++)
2948 {
2949 rc = iscsiCommand(pImage, &sr);
2950 if ( (RT_SUCCESS(rc) && !sr.cbSense)
2951 || RT_FAILURE(rc))
2952 break;
2953 rc = VERR_READ_ERROR;
2954 }
2955 if (RT_FAILURE(rc))
2956 {
2957 AssertMsgFailed(("iscsiCommand(%s, %#llx) -> %Rrc\n", pImage->pszTargetName, uOffset, rc));
2958 *pcbActuallyRead = 0;
2959 }
2960 else
2961 *pcbActuallyRead = sr.cbT2IData;
2962
2963out:
2964 LogFlowFunc(("returns %Rrc\n", rc));
2965 return rc;
2966}
2967
2968
2969/** @copydoc VBOXHDDBACKEND::pfnWrite */
2970static int iscsiWrite(void *pBackendData, uint64_t uOffset, const void *pvBuf,
2971 size_t cbToWrite, size_t *pcbWriteProcess,
2972 size_t *pcbPreRead, size_t *pcbPostRead, unsigned fWrite)
2973{
2974 LogFlowFunc(("pBackendData=%#p uOffset=%llu pvBuf=%#p cbToWrite=%zu pcbWriteProcess=%#p pcbPreRead=%#p pcbPostRead=%#p\n", pBackendData, uOffset, pvBuf, cbToWrite, pcbWriteProcess, pcbPreRead, pcbPostRead));
2975 PISCSIIMAGE pImage = (PISCSIIMAGE)pBackendData;
2976 uint64_t lba;
2977 uint16_t tls;
2978 int rc;
2979
2980 Assert(pImage);
2981 Assert(uOffset % 512 == 0);
2982 Assert(cbToWrite % 512 == 0);
2983
2984 Assert(pImage->cbSector);
2985 Assert(pvBuf);
2986
2987 if (pImage->uOpenFlags & VD_OPEN_FLAGS_READONLY)
2988 {
2989 rc = VERR_VD_IMAGE_READ_ONLY;
2990 goto out;
2991 }
2992
2993 *pcbPreRead = 0;
2994 *pcbPostRead = 0;
2995
2996 /*
2997 * Clip write size to a value which is supported by the target.
2998 */
2999 cbToWrite = RT_MIN(cbToWrite, pImage->cbSendDataLength);
3000
3001 lba = uOffset / pImage->cbSector;
3002 tls = (uint16_t)(cbToWrite / pImage->cbSector);
3003 SCSIREQ sr;
3004 uint8_t cdb[10];
3005 uint8_t sense[32];
3006
3007 cdb[0] = SCSI_WRITE_10;
3008 cdb[1] = 0; /* reserved */
3009 cdb[2] = (lba >> 24) & 0xff;
3010 cdb[3] = (lba >> 16) & 0xff;
3011 cdb[4] = (lba >> 8) & 0xff;
3012 cdb[5] = lba & 0xff;
3013 cdb[6] = 0; /* reserved */
3014 cdb[7] = (tls >> 8) & 0xff;
3015 cdb[8] = tls & 0xff;
3016 cdb[9] = 0; /* control */
3017
3018 sr.enmXfer = SCSIXFER_TO_TARGET;
3019 sr.cbCmd = sizeof(cdb);
3020 sr.pvCmd = cdb;
3021 sr.cbI2TData = cbToWrite;
3022 sr.pcvI2TData = pvBuf;
3023 sr.cbT2IData = 0;
3024 sr.pvT2IData = NULL;
3025 sr.cbSense = sizeof(sense);
3026 sr.pvSense = sense;
3027
3028 for (unsigned i = 0; i < 10; i++)
3029 {
3030 rc = iscsiCommand(pImage, &sr);
3031 if ( (RT_SUCCESS(rc) && !sr.cbSense)
3032 || RT_FAILURE(rc))
3033 break;
3034 rc = VERR_WRITE_ERROR;
3035 }
3036 if (RT_FAILURE(rc))
3037 {
3038 AssertMsgFailed(("iscsiCommand(%s, %#llx) -> %Rrc\n", pImage->pszTargetName, uOffset, rc));
3039 *pcbWriteProcess = 0;
3040 }
3041 else
3042 *pcbWriteProcess = cbToWrite;
3043
3044out:
3045 LogFlowFunc(("returns %Rrc\n", rc));
3046 return rc;
3047}
3048
3049
3050/** @copydoc VBOXHDDBACKEND::pfnFlush */
3051static int iscsiFlush(void *pBackendData)
3052{
3053 LogFlowFunc(("pBackendData=%#p\n", pBackendData));
3054 PISCSIIMAGE pImage = (PISCSIIMAGE)pBackendData;
3055 int rc;
3056
3057 Assert(pImage);
3058
3059 SCSIREQ sr;
3060 uint8_t cdb[10];
3061 uint8_t sense[32];
3062
3063 cdb[0] = SCSI_SYNCHRONIZE_CACHE;
3064 cdb[1] = 0; /* reserved */
3065 cdb[2] = 0; /* LBA 0 */
3066 cdb[3] = 0; /* LBA 0 */
3067 cdb[4] = 0; /* LBA 0 */
3068 cdb[5] = 0; /* LBA 0 */
3069 cdb[6] = 0; /* reserved */
3070 cdb[7] = 0; /* transfer everything to disk */
3071 cdb[8] = 0; /* transfer everything to disk */
3072 cdb[9] = 0; /* control */
3073
3074 sr.enmXfer = SCSIXFER_TO_TARGET;
3075 sr.cbCmd = sizeof(cdb);
3076 sr.pvCmd = cdb;
3077 sr.cbI2TData = 0;
3078 sr.pcvI2TData = NULL;
3079 sr.cbT2IData = 0;
3080 sr.pvT2IData = NULL;
3081 sr.cbSense = sizeof(sense);
3082 sr.pvSense = sense;
3083
3084 rc = iscsiCommand(pImage, &sr);
3085 if (RT_FAILURE(rc))
3086 AssertMsgFailed(("iscsiCommand(%s) -> %Rrc\n", pImage->pszTargetName, rc));
3087 LogFlowFunc(("returns %Rrc\n", rc));
3088 return rc;
3089}
3090
3091
3092/** @copydoc VBOXHDDBACKEND::pfnGetVersion */
3093static unsigned iscsiGetVersion(void *pBackendData)
3094{
3095 LogFlowFunc(("pBackendData=%#p\n", pBackendData));
3096 PISCSIIMAGE pImage = (PISCSIIMAGE)pBackendData;
3097
3098 Assert(pImage);
3099 NOREF(pImage);
3100
3101 return 0;
3102}
3103
3104
3105/** @copydoc VBOXHDDBACKEND::pfnGetSize */
3106static uint64_t iscsiGetSize(void *pBackendData)
3107{
3108 LogFlowFunc(("pBackendData=%#p\n", pBackendData));
3109 PISCSIIMAGE pImage = (PISCSIIMAGE)pBackendData;
3110
3111 Assert(pImage);
3112
3113 if (pImage)
3114 return pImage->cbSize;
3115 else
3116 return 0;
3117}
3118
3119
3120/** @copydoc VBOXHDDBACKEND::pfnGetFileSize */
3121static uint64_t iscsiGetFileSize(void *pBackendData)
3122{
3123 LogFlowFunc(("pBackendData=%#p\n", pBackendData));
3124 PISCSIIMAGE pImage = (PISCSIIMAGE)pBackendData;
3125
3126 Assert(pImage);
3127 NOREF(pImage);
3128
3129 if (pImage)
3130 return pImage->cbSize;
3131 else
3132 return 0;
3133}
3134
3135
3136/** @copydoc VBOXHDDBACKEND::pfnGetPCHSGeometry */
3137static int iscsiGetPCHSGeometry(void *pBackendData,
3138 PPDMMEDIAGEOMETRY pPCHSGeometry)
3139{
3140 LogFlowFunc(("pBackendData=%#p pPCHSGeometry=%#p\n", pBackendData, pPCHSGeometry));
3141 PISCSIIMAGE pImage = (PISCSIIMAGE)pBackendData;
3142 int rc;
3143
3144 Assert(pImage);
3145
3146 if (pImage)
3147 rc = VERR_VD_GEOMETRY_NOT_SET;
3148 else
3149 rc = VERR_VD_NOT_OPENED;
3150
3151 LogFlowFunc(("returns %Rrc (PCHS=%u/%u/%u)\n", rc, pPCHSGeometry->cCylinders, pPCHSGeometry->cHeads, pPCHSGeometry->cSectors));
3152 return rc;
3153}
3154
3155
3156/** @copydoc VBOXHDDBACKEND::pfnSetPCHSGeometry */
3157static int iscsiSetPCHSGeometry(void *pBackendData,
3158 PCPDMMEDIAGEOMETRY pPCHSGeometry)
3159{
3160 LogFlowFunc(("pBackendData=%#p pPCHSGeometry=%#p PCHS=%u/%u/%u\n", pBackendData, pPCHSGeometry, pPCHSGeometry->cCylinders, pPCHSGeometry->cHeads, pPCHSGeometry->cSectors));
3161 PISCSIIMAGE pImage = (PISCSIIMAGE)pBackendData;
3162 int rc;
3163
3164 Assert(pImage);
3165
3166 if (pImage)
3167 {
3168 if (pImage->uOpenFlags & VD_OPEN_FLAGS_READONLY)
3169 {
3170 rc = VERR_VD_IMAGE_READ_ONLY;
3171 goto out;
3172 }
3173 rc = VERR_VD_GEOMETRY_NOT_SET;
3174 }
3175 else
3176 rc = VERR_VD_NOT_OPENED;
3177
3178out:
3179 LogFlowFunc(("returns %Rrc\n", rc));
3180 return rc;
3181}
3182
3183
3184/** @copydoc VBOXHDDBACKEND::pfnGetLCHSGeometry */
3185static int iscsiGetLCHSGeometry(void *pBackendData,
3186 PPDMMEDIAGEOMETRY pLCHSGeometry)
3187{
3188 LogFlowFunc(("pBackendData=%#p pLCHSGeometry=%#p\n", pBackendData, pLCHSGeometry));
3189 PISCSIIMAGE pImage = (PISCSIIMAGE)pBackendData;
3190 int rc;
3191
3192 Assert(pImage);
3193
3194 if (pImage)
3195 rc = VERR_VD_GEOMETRY_NOT_SET;
3196 else
3197 rc = VERR_VD_NOT_OPENED;
3198
3199 LogFlowFunc(("returns %Rrc (LCHS=%u/%u/%u)\n", rc, pLCHSGeometry->cCylinders, pLCHSGeometry->cHeads, pLCHSGeometry->cSectors));
3200 return rc;
3201}
3202
3203
3204/** @copydoc VBOXHDDBACKEND::pfnGetImageFlags */
3205static unsigned iscsiGetImageFlags(void *pBackendData)
3206{
3207 LogFlowFunc(("pBackendData=%#p\n", pBackendData));
3208 PISCSIIMAGE pImage = (PISCSIIMAGE)pBackendData;
3209 unsigned uImageFlags;
3210
3211 Assert(pImage);
3212 NOREF(pImage);
3213
3214 uImageFlags = VD_IMAGE_FLAGS_FIXED;
3215
3216 LogFlowFunc(("returns %#x\n", uImageFlags));
3217 return uImageFlags;
3218}
3219
3220
3221/** @copydoc VBOXHDDBACKEND::pfnGetOpenFlags */
3222static unsigned iscsiGetOpenFlags(void *pBackendData)
3223{
3224 LogFlowFunc(("pBackendData=%#p\n", pBackendData));
3225 PISCSIIMAGE pImage = (PISCSIIMAGE)pBackendData;
3226 unsigned uOpenFlags;
3227
3228 Assert(pImage);
3229
3230 if (pImage)
3231 uOpenFlags = pImage->uOpenFlags;
3232 else
3233 uOpenFlags = 0;
3234
3235 LogFlowFunc(("returns %#x\n", uOpenFlags));
3236 return uOpenFlags;
3237}
3238
3239
3240/** @copydoc VBOXHDDBACKEND::pfnSetOpenFlags */
3241static int iscsiSetOpenFlags(void *pBackendData, unsigned uOpenFlags)
3242{
3243 LogFlowFunc(("pBackendData=%#p\n uOpenFlags=%#x", pBackendData, uOpenFlags));
3244 PISCSIIMAGE pImage = (PISCSIIMAGE)pBackendData;
3245 int rc;
3246
3247 /* Image must be opened and the new flags must be valid. Just readonly and
3248 * info flags are supported. */
3249 if (!pImage || (uOpenFlags & ~(VD_OPEN_FLAGS_READONLY | VD_OPEN_FLAGS_INFO)))
3250 {
3251 rc = VERR_INVALID_PARAMETER;
3252 goto out;
3253 }
3254
3255 /* Implement this operation via reopening the image. */
3256 iscsiFreeImage(pImage, false);
3257 rc = iscsiOpenImage(pImage, uOpenFlags);
3258
3259out:
3260 LogFlowFunc(("returns %Rrc\n", rc));
3261 return rc;
3262}
3263
3264
3265/** @copydoc VBOXHDDBACKEND::pfnSetLCHSGeometry */
3266static int iscsiSetLCHSGeometry(void *pBackendData,
3267 PCPDMMEDIAGEOMETRY pLCHSGeometry)
3268{
3269 LogFlowFunc(("pBackendData=%#p pLCHSGeometry=%#p LCHS=%u/%u/%u\n", pBackendData, pLCHSGeometry, pLCHSGeometry->cCylinders, pLCHSGeometry->cHeads, pLCHSGeometry->cSectors));
3270 PISCSIIMAGE pImage = (PISCSIIMAGE)pBackendData;
3271 int rc;
3272
3273 Assert(pImage);
3274
3275 if (pImage)
3276 {
3277 if (pImage->uOpenFlags & VD_OPEN_FLAGS_READONLY)
3278 {
3279 rc = VERR_VD_IMAGE_READ_ONLY;
3280 goto out;
3281 }
3282 rc = VERR_VD_GEOMETRY_NOT_SET;
3283 }
3284 else
3285 rc = VERR_VD_NOT_OPENED;
3286
3287out:
3288 LogFlowFunc(("returns %Rrc\n", rc));
3289 return rc;
3290}
3291
3292
3293/** @copydoc VBOXHDDBACKEND::pfnGetComment */
3294static int iscsiGetComment(void *pBackendData, char *pszComment,
3295 size_t cbComment)
3296{
3297 LogFlowFunc(("pBackendData=%#p pszComment=%#p cbComment=%zu\n", pBackendData, pszComment, cbComment));
3298 PISCSIIMAGE pImage = (PISCSIIMAGE)pBackendData;
3299 int rc;
3300
3301 Assert(pImage);
3302
3303 if (pImage)
3304 rc = VERR_NOT_SUPPORTED;
3305 else
3306 rc = VERR_VD_NOT_OPENED;
3307
3308 LogFlowFunc(("returns %Rrc comment='%s'\n", rc, pszComment));
3309 return rc;
3310}
3311
3312
3313/** @copydoc VBOXHDDBACKEND::pfnSetComment */
3314static int iscsiSetComment(void *pBackendData, const char *pszComment)
3315{
3316 LogFlowFunc(("pBackendData=%#p pszComment=\"%s\"\n", pBackendData, pszComment));
3317 PISCSIIMAGE pImage = (PISCSIIMAGE)pBackendData;
3318 int rc;
3319
3320 Assert(pImage);
3321
3322 if (pImage)
3323 {
3324 if (!(pImage->uOpenFlags & VD_OPEN_FLAGS_READONLY))
3325 rc = VERR_NOT_SUPPORTED;
3326 else
3327 rc = VERR_VD_IMAGE_READ_ONLY;
3328 }
3329 else
3330 rc = VERR_VD_NOT_OPENED;
3331
3332 LogFlowFunc(("returns %Rrc\n", rc));
3333 return rc;
3334}
3335
3336
3337/** @copydoc VBOXHDDBACKEND::pfnGetUuid */
3338static int iscsiGetUuid(void *pBackendData, PRTUUID pUuid)
3339{
3340 LogFlowFunc(("pBackendData=%#p pUuid=%#p\n", pBackendData, pUuid));
3341 PISCSIIMAGE pImage = (PISCSIIMAGE)pBackendData;
3342 int rc;
3343
3344 Assert(pImage);
3345
3346 if (pImage)
3347 rc = VERR_NOT_SUPPORTED;
3348 else
3349 rc = VERR_VD_NOT_OPENED;
3350
3351 LogFlowFunc(("returns %Rrc (%RTuuid)\n", rc, pUuid));
3352 return rc;
3353}
3354
3355
3356/** @copydoc VBOXHDDBACKEND::pfnSetUuid */
3357static int iscsiSetUuid(void *pBackendData, PCRTUUID pUuid)
3358{
3359 LogFlowFunc(("pBackendData=%#p Uuid=%RTuuid\n", pBackendData, pUuid));
3360 PISCSIIMAGE pImage = (PISCSIIMAGE)pBackendData;
3361 int rc;
3362
3363 LogFlowFunc(("%RTuuid\n", pUuid));
3364 Assert(pImage);
3365
3366 if (pImage)
3367 {
3368 if (!(pImage->uOpenFlags & VD_OPEN_FLAGS_READONLY))
3369 rc = VERR_NOT_SUPPORTED;
3370 else
3371 rc = VERR_VD_IMAGE_READ_ONLY;
3372 }
3373 else
3374 rc = VERR_VD_NOT_OPENED;
3375
3376 LogFlowFunc(("returns %Rrc\n", rc));
3377 return rc;
3378}
3379
3380
3381/** @copydoc VBOXHDDBACKEND::pfnGetModificationUuid */
3382static int iscsiGetModificationUuid(void *pBackendData, PRTUUID pUuid)
3383{
3384 LogFlowFunc(("pBackendData=%#p pUuid=%#p\n", pBackendData, pUuid));
3385 PISCSIIMAGE pImage = (PISCSIIMAGE)pBackendData;
3386 int rc;
3387
3388 Assert(pImage);
3389
3390 if (pImage)
3391 rc = VERR_NOT_SUPPORTED;
3392 else
3393 rc = VERR_VD_NOT_OPENED;
3394
3395 LogFlowFunc(("returns %Rrc (%RTuuid)\n", rc, pUuid));
3396 return rc;
3397}
3398
3399
3400/** @copydoc VBOXHDDBACKEND::pfnSetModificationUuid */
3401static int iscsiSetModificationUuid(void *pBackendData, PCRTUUID pUuid)
3402{
3403 LogFlowFunc(("pBackendData=%#p Uuid=%RTuuid\n", pBackendData, pUuid));
3404 PISCSIIMAGE pImage = (PISCSIIMAGE)pBackendData;
3405 int rc;
3406
3407 LogFlowFunc(("%RTuuid\n", pUuid));
3408 Assert(pImage);
3409
3410 if (pImage)
3411 {
3412 if (!(pImage->uOpenFlags & VD_OPEN_FLAGS_READONLY))
3413 rc = VERR_NOT_SUPPORTED;
3414 else
3415 rc = VERR_VD_IMAGE_READ_ONLY;
3416 }
3417 else
3418 rc = VERR_VD_NOT_OPENED;
3419
3420 LogFlowFunc(("returns %Rrc\n", rc));
3421 return rc;
3422}
3423
3424
3425/** @copydoc VBOXHDDBACKEND::pfnGetParentUuid */
3426static int iscsiGetParentUuid(void *pBackendData, PRTUUID pUuid)
3427{
3428 LogFlowFunc(("pBackendData=%#p pUuid=%#p\n", pBackendData, pUuid));
3429 PISCSIIMAGE pImage = (PISCSIIMAGE)pBackendData;
3430 int rc;
3431
3432 Assert(pImage);
3433
3434 if (pImage)
3435 rc = VERR_NOT_SUPPORTED;
3436 else
3437 rc = VERR_VD_NOT_OPENED;
3438
3439 LogFlowFunc(("returns %Rrc (%RTuuid)\n", rc, pUuid));
3440 return rc;
3441}
3442
3443
3444/** @copydoc VBOXHDDBACKEND::pfnSetParentUuid */
3445static int iscsiSetParentUuid(void *pBackendData, PCRTUUID pUuid)
3446{
3447 LogFlowFunc(("pBackendData=%#p Uuid=%RTuuid\n", pBackendData, pUuid));
3448 PISCSIIMAGE pImage = (PISCSIIMAGE)pBackendData;
3449 int rc;
3450
3451 LogFlowFunc(("%RTuuid\n", pUuid));
3452 Assert(pImage);
3453
3454 if (pImage)
3455 {
3456 if (!(pImage->uOpenFlags & VD_OPEN_FLAGS_READONLY))
3457 rc = VERR_NOT_SUPPORTED;
3458 else
3459 rc = VERR_VD_IMAGE_READ_ONLY;
3460 }
3461 else
3462 rc = VERR_VD_NOT_OPENED;
3463
3464 LogFlowFunc(("returns %Rrc\n", rc));
3465 return rc;
3466}
3467
3468
3469/** @copydoc VBOXHDDBACKEND::pfnGetParentModificationUuid */
3470static int iscsiGetParentModificationUuid(void *pBackendData, PRTUUID pUuid)
3471{
3472 LogFlowFunc(("pBackendData=%#p pUuid=%#p\n", pBackendData, pUuid));
3473 PISCSIIMAGE pImage = (PISCSIIMAGE)pBackendData;
3474 int rc;
3475
3476 Assert(pImage);
3477
3478 if (pImage)
3479 rc = VERR_NOT_SUPPORTED;
3480 else
3481 rc = VERR_VD_NOT_OPENED;
3482
3483 LogFlowFunc(("returns %Rrc (%RTuuid)\n", rc, pUuid));
3484 return rc;
3485}
3486
3487
3488/** @copydoc VBOXHDDBACKEND::pfnSetParentModificationUuid */
3489static int iscsiSetParentModificationUuid(void *pBackendData, PCRTUUID pUuid)
3490{
3491 LogFlowFunc(("pBackendData=%#p Uuid=%RTuuid\n", pBackendData, pUuid));
3492 PISCSIIMAGE pImage = (PISCSIIMAGE)pBackendData;
3493 int rc;
3494
3495 LogFlowFunc(("%RTuuid\n", pUuid));
3496 Assert(pImage);
3497
3498 if (pImage)
3499 {
3500 if (!(pImage->uOpenFlags & VD_OPEN_FLAGS_READONLY))
3501 rc = VERR_NOT_SUPPORTED;
3502 else
3503 rc = VERR_VD_IMAGE_READ_ONLY;
3504 }
3505 else
3506 rc = VERR_VD_NOT_OPENED;
3507
3508 LogFlowFunc(("returns %Rrc\n", rc));
3509 return rc;
3510}
3511
3512
3513/** @copydoc VBOXHDDBACKEND::pfnDump */
3514static void iscsiDump(void *pBackendData)
3515{
3516 PISCSIIMAGE pImage = (PISCSIIMAGE)pBackendData;
3517
3518 Assert(pImage);
3519 if (pImage)
3520 {
3521 /** @todo put something useful here */
3522 pImage->pInterfaceErrorCallbacks->pfnMessage(pImage->pInterfaceError->pvUser, "Header: cVolume=%u\n", pImage->cVolume);
3523 }
3524}
3525
3526
3527/** @copydoc VBOXHDDBACKEND::pfnGetTimeStamp */
3528static int iscsiGetTimeStamp(void *pBackendData, PRTTIMESPEC pTimeStamp)
3529{
3530 LogFlowFunc(("pBackendData=%#p pTimeStamp=%#p\n", pBackendData, pTimeStamp));
3531 PISCSIIMAGE pImage = (PISCSIIMAGE)pBackendData;
3532 int rc = VERR_NOT_SUPPORTED;
3533
3534 Assert(pImage);
3535 NOREF(pImage);
3536
3537 LogFlowFunc(("returns %Rrc\n", rc));
3538 return rc;
3539}
3540
3541
3542/** @copydoc VBOXHDDBACKEND::pfnGetParentTimeStamp */
3543static int iscsiGetParentTimeStamp(void *pBackendData, PRTTIMESPEC pTimeStamp)
3544{
3545 LogFlowFunc(("pBackendData=%#p pTimeStamp=%#p\n", pBackendData, pTimeStamp));
3546 PISCSIIMAGE pImage = (PISCSIIMAGE)pBackendData;
3547 int rc = VERR_NOT_SUPPORTED;
3548
3549 Assert(pImage);
3550 NOREF(pImage);
3551
3552 LogFlowFunc(("returns %Rrc\n", rc));
3553 return rc;
3554}
3555
3556
3557/** @copydoc VBOXHDDBACKEND::pfnSetParentTimeStamp */
3558static int iscsiSetParentTimeStamp(void *pBackendData, PCRTTIMESPEC pTimeStamp)
3559{
3560 LogFlowFunc(("pBackendData=%#p pTimeStamp=%#p\n", pBackendData, pTimeStamp));
3561 PISCSIIMAGE pImage = (PISCSIIMAGE)pBackendData;
3562 int rc = VERR_NOT_SUPPORTED;
3563
3564 Assert(pImage);
3565 NOREF(pImage);
3566
3567 LogFlowFunc(("returns %Rrc\n", rc));
3568 return rc;
3569}
3570
3571
3572/** @copydoc VBOXHDDBACKEND::pfnGetParentFilename */
3573static int iscsiGetParentFilename(void *pBackendData, char **ppszParentFilename)
3574{
3575 LogFlowFunc(("pBackendData=%#p ppszParentFilename=%#p\n", pBackendData, ppszParentFilename));
3576 PISCSIIMAGE pImage = (PISCSIIMAGE)pBackendData;
3577 int rc = VERR_NOT_SUPPORTED;
3578
3579 Assert(pImage);
3580 NOREF(pImage);
3581
3582 LogFlowFunc(("returns %Rrc\n", rc));
3583 return rc;
3584}
3585
3586
3587/** @copydoc VBOXHDDBACKEND::pfnSetParentFilename */
3588static int iscsiSetParentFilename(void *pBackendData, const char *pszParentFilename)
3589{
3590 LogFlowFunc(("pBackendData=%#p pszParentFilename=%s\n", pBackendData, pszParentFilename));
3591 PISCSIIMAGE pImage = (PISCSIIMAGE)pBackendData;
3592 int rc = VERR_NOT_SUPPORTED;
3593
3594 Assert(pImage);
3595 NOREF(pImage);
3596
3597 LogFlowFunc(("returns %Rrc\n", rc));
3598 return rc;
3599}
3600
3601/** @copydoc VBOXHDDBACKEND::pfnComposeLocation */
3602static int iscsiComposeLocation(PVDINTERFACE pConfig, char **pszLocation)
3603{
3604 char *pszTarget = NULL;
3605 char *pszLUN = NULL;
3606 char *pszAddress = NULL;
3607 int rc = VDCFGQueryStringAlloc(VDGetInterfaceConfig(pConfig), pConfig->pvUser, "TargetName", &pszTarget);
3608 if (RT_SUCCESS(rc))
3609 {
3610 rc = VDCFGQueryStringAlloc(VDGetInterfaceConfig(pConfig), pConfig->pvUser, "LUN", &pszLUN);
3611 if (RT_SUCCESS(rc))
3612 {
3613 rc = VDCFGQueryStringAlloc(VDGetInterfaceConfig(pConfig), pConfig->pvUser, "TargetAddress", &pszAddress);
3614 if (RT_SUCCESS(rc))
3615 {
3616 if (RTStrAPrintf(pszLocation, "iscsi://%s/%s/%s",
3617 pszAddress, pszTarget, pszLUN) < 0)
3618 rc = VERR_NO_MEMORY;
3619 }
3620 }
3621 }
3622 RTMemFree(pszTarget);
3623 RTMemFree(pszLUN);
3624 RTMemFree(pszAddress);
3625 return rc;
3626}
3627
3628/** @copydoc VBOXHDDBACKEND::pfnComposeName */
3629static int iscsiComposeName(PVDINTERFACE pConfig, char **pszName)
3630{
3631 char *pszTarget = NULL;
3632 char *pszLUN = NULL;
3633 char *pszAddress = NULL;
3634 int rc = VDCFGQueryStringAlloc(VDGetInterfaceConfig(pConfig), pConfig->pvUser, "TargetName", &pszTarget);
3635 if (RT_SUCCESS(rc))
3636 {
3637 rc = VDCFGQueryStringAlloc(VDGetInterfaceConfig(pConfig), pConfig->pvUser, "LUN", &pszLUN);
3638 if (RT_SUCCESS(rc))
3639 {
3640 rc = VDCFGQueryStringAlloc(VDGetInterfaceConfig(pConfig), pConfig->pvUser, "TargetAddress", &pszAddress);
3641 if (RT_SUCCESS(rc))
3642 {
3643 /** @todo think about a nicer looking location scheme for iSCSI */
3644 if (RTStrAPrintf(pszName, "%s/%s/%s",
3645 pszAddress, pszTarget, pszLUN) < 0)
3646 rc = VERR_NO_MEMORY;
3647 }
3648 }
3649 }
3650 RTMemFree(pszTarget);
3651 RTMemFree(pszLUN);
3652 RTMemFree(pszAddress);
3653
3654 return rc;
3655}
3656
3657
3658VBOXHDDBACKEND g_ISCSIBackend =
3659{
3660 /* pszBackendName */
3661 "iSCSI",
3662 /* cbSize */
3663 sizeof(VBOXHDDBACKEND),
3664 /* uBackendCaps */
3665 VD_CAP_CONFIG | VD_CAP_TCPNET,
3666 /* papszFileExtensions */
3667 NULL,
3668 /* paConfigInfo */
3669 s_iscsiConfigInfo,
3670 /* hPlugin */
3671 NIL_RTLDRMOD,
3672 /* pfnCheckIfValid */
3673 iscsiCheckIfValid,
3674 /* pfnOpen */
3675 iscsiOpen,
3676 /* pfnCreate */
3677 iscsiCreate,
3678 /* pfnRename */
3679 iscsiRename,
3680 /* pfnClose */
3681 iscsiClose,
3682 /* pfnRead */
3683 iscsiRead,
3684 /* pfnWrite */
3685 iscsiWrite,
3686 /* pfnFlush */
3687 iscsiFlush,
3688 /* pfnGetVersion */
3689 iscsiGetVersion,
3690 /* pfnGetSize */
3691 iscsiGetSize,
3692 /* pfnGetFileSize */
3693 iscsiGetFileSize,
3694 /* pfnGetPCHSGeometry */
3695 iscsiGetPCHSGeometry,
3696 /* pfnSetPCHSGeometry */
3697 iscsiSetPCHSGeometry,
3698 /* pfnGetLCHSGeometry */
3699 iscsiGetLCHSGeometry,
3700 /* pfnSetLCHSGeometry */
3701 iscsiSetLCHSGeometry,
3702 /* pfnGetImageFlags */
3703 iscsiGetImageFlags,
3704 /* pfnGetOpenFlags */
3705 iscsiGetOpenFlags,
3706 /* pfnSetOpenFlags */
3707 iscsiSetOpenFlags,
3708 /* pfnGetComment */
3709 iscsiGetComment,
3710 /* pfnSetComment */
3711 iscsiSetComment,
3712 /* pfnGetUuid */
3713 iscsiGetUuid,
3714 /* pfnSetUuid */
3715 iscsiSetUuid,
3716 /* pfnGetModificationUuid */
3717 iscsiGetModificationUuid,
3718 /* pfnSetModificationUuid */
3719 iscsiSetModificationUuid,
3720 /* pfnGetParentUuid */
3721 iscsiGetParentUuid,
3722 /* pfnSetParentUuid */
3723 iscsiSetParentUuid,
3724 /* pfnGetParentModificationUuid */
3725 iscsiGetParentModificationUuid,
3726 /* pfnSetParentModificationUuid */
3727 iscsiSetParentModificationUuid,
3728 /* pfnDump */
3729 iscsiDump,
3730 /* pfnGetTimeStamp */
3731 iscsiGetTimeStamp,
3732 /* pfnGetParentTimeStamp */
3733 iscsiGetParentTimeStamp,
3734 /* pfnSetParentTimeStamp */
3735 iscsiSetParentTimeStamp,
3736 /* pfnGetParentFilename */
3737 iscsiGetParentFilename,
3738 /* pfnSetParentFilename */
3739 iscsiSetParentFilename,
3740 /* pfnIsAsyncIOSupported */
3741 NULL,
3742 /* pfnAsyncRead */
3743 NULL,
3744 /* pfnAsyncWrite */
3745 NULL,
3746 /* pfnComposeLocation */
3747 iscsiComposeLocation,
3748 /* pfnComposeName */
3749 iscsiComposeName
3750};
注意: 瀏覽 TracBrowser 來幫助您使用儲存庫瀏覽器

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