VirtualBox

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

Last change on this file since 18458 was 17970, checked in by vboxsync, 16 years ago

API/HardDisk, Storage/VBoxHDD, Frontend/VBoxManage: eliminated base image type, which led to much unnecessary code duplication. Was triggered by VBoxManage finally being able to create all image variants the backends can support.

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

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