storage32.c 212 KB
Newer Older
1 2 3 4 5 6 7 8 9 10
/*
 * Compound Storage (32 bit version)
 * Storage implementation
 *
 * This file contains the compound file implementation
 * of the storage interface.
 *
 * Copyright 1999 Francis Beaudet
 * Copyright 1999 Sylvain St-Germain
 * Copyright 1999 Thuy Nguyen
11
 * Copyright 2005 Mike McCormack
12 13 14 15 16 17 18 19 20 21 22 23 24
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
25
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
26 27 28 29 30
 *
 * NOTES
 *  The compound file implementation of IStorage used for create
 *  and manage substorages and streams within a storage object
 *  residing in a compound file object.
31 32 33
 */

#include <assert.h>
34
#include <stdarg.h>
35
#include <stdio.h>
Patrik Stridvall's avatar
Patrik Stridvall committed
36
#include <stdlib.h>
37 38
#include <string.h>

39
#define COBJMACROS
40 41
#define NONAMELESSUNION
#define NONAMELESSSTRUCT
42

43 44
#include "windef.h"
#include "winbase.h"
45
#include "winnls.h"
46
#include "winuser.h"
47
#include "wine/unicode.h"
48
#include "wine/debug.h"
49 50

#include "storage32.h"
51
#include "ole2.h"      /* For Write/ReadClassStm */
52

53 54 55
#include "winreg.h"
#include "wine/wingdi16.h"

56
WINE_DEFAULT_DEBUG_CHANNEL(storage);
57

58 59 60 61
/* Used for OleConvertIStorageToOLESTREAM and OleConvertOLESTREAMToIStorage */
#define OLESTREAM_ID 0x501
#define OLESTREAM_MAX_STR_LEN 255

62 63 64 65 66 67
/*
 * These are signatures to detect the type of Document file.
 */
static const BYTE STORAGE_magic[8]    ={0xd0,0xcf,0x11,0xe0,0xa1,0xb1,0x1a,0xe1};
static const BYTE STORAGE_oldmagic[8] ={0xd0,0xcf,0x11,0xe0,0x0e,0x11,0xfc,0x0d};

68 69
static const char rootPropertyName[] = "Root Entry";

70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90
/****************************************************************************
 * Storage32InternalImpl definitions.
 *
 * Definition of the implementation structure for the IStorage32 interface.
 * This one implements the IStorage32 interface for storage that are
 * inside another storage.
 */
struct StorageInternalImpl
{
  struct StorageBaseImpl base;
  /*
   * There is no specific data for this class.
   */
};
typedef struct StorageInternalImpl StorageInternalImpl;

/* Method definitions for the Storage32InternalImpl class. */
static StorageInternalImpl* StorageInternalImpl_Construct(StorageImpl* ancestorStorage,
                                                          DWORD openFlags, ULONG rootTropertyIndex);
static void StorageImpl_Destroy(StorageBaseImpl* iface);
static BOOL StorageImpl_ReadBigBlock(StorageImpl* This, ULONG blockIndex, void* buffer);
91
static BOOL StorageImpl_WriteBigBlock(StorageImpl* This, ULONG blockIndex, const void* buffer);
92 93 94 95 96 97 98 99 100 101 102 103 104 105 106
static void StorageImpl_SetNextBlockInChain(StorageImpl* This, ULONG blockIndex, ULONG nextBlock);
static HRESULT StorageImpl_LoadFileHeader(StorageImpl* This);
static void StorageImpl_SaveFileHeader(StorageImpl* This);

static void Storage32Impl_AddBlockDepot(StorageImpl* This, ULONG blockIndex);
static ULONG Storage32Impl_AddExtBlockDepot(StorageImpl* This);
static ULONG Storage32Impl_GetNextExtendedBlock(StorageImpl* This, ULONG blockIndex);
static ULONG Storage32Impl_GetExtDepotBlock(StorageImpl* This, ULONG depotIndex);
static void Storage32Impl_SetExtDepotBlock(StorageImpl* This, ULONG depotIndex, ULONG blockIndex);

static ULONG BlockChainStream_GetHeadOfChain(BlockChainStream* This);
static ULARGE_INTEGER BlockChainStream_GetSize(BlockChainStream* This);
static ULONG BlockChainStream_GetCount(BlockChainStream* This);

static ULARGE_INTEGER SmallBlockChainStream_GetSize(SmallBlockChainStream* This);
107 108 109 110
static BOOL StorageImpl_WriteDWordToBigBlock( StorageImpl* This,
    ULONG blockIndex, ULONG offset, DWORD value);
static BOOL StorageImpl_ReadDWordFromBigBlock( StorageImpl*  This,
    ULONG blockIndex, ULONG offset, DWORD* value);
111 112 113

/* OLESTREAM memory structure to use for Get and Put Routines */
/* Used for OleConvertIStorageToOLESTREAM and OleConvertOLESTREAMToIStorage */
114
typedef struct
115 116 117 118 119
{
    DWORD dwOleID;
    DWORD dwTypeID;
    DWORD dwOleTypeNameLength;
    CHAR  strOleTypeName[OLESTREAM_MAX_STR_LEN];
Alexandre Julliard's avatar
Alexandre Julliard committed
120 121
    CHAR  *pstrOleObjFileName;
    DWORD dwOleObjFileNameLength;
122 123
    DWORD dwMetaFileWidth;
    DWORD dwMetaFileHeight;
124
    CHAR  strUnknown[8]; /* don't know what is this 8 byts information in OLE stream. */
125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151
    DWORD dwDataLength;
    BYTE *pData;
}OLECONVERT_OLESTREAM_DATA;

/* CompObj Stream structure */
/* Used for OleConvertIStorageToOLESTREAM and OleConvertOLESTREAMToIStorage */
typedef struct
{
    BYTE byUnknown1[12];
    CLSID clsid;
    DWORD dwCLSIDNameLength;
    CHAR strCLSIDName[OLESTREAM_MAX_STR_LEN];
    DWORD dwOleTypeNameLength;
    CHAR strOleTypeName[OLESTREAM_MAX_STR_LEN];
    DWORD dwProgIDNameLength;
    CHAR strProgIDName[OLESTREAM_MAX_STR_LEN];
    BYTE byUnknown2[16];
}OLECONVERT_ISTORAGE_COMPOBJ;


/* Ole Presention Stream structure */
/* Used for OleConvertIStorageToOLESTREAM and OleConvertOLESTREAMToIStorage */
typedef struct
{
    BYTE byUnknown1[28];
    DWORD dwExtentX;
    DWORD dwExtentY;
152
    DWORD dwSize;
153 154 155 156 157
    BYTE *pData;
}OLECONVERT_ISTORAGE_OLEPRES;



158 159 160 161
/***********************************************************************
 * Forward declaration of internal functions used by the method DestroyElement
 */
static HRESULT deleteStorageProperty(
162
  StorageImpl *parentStorage,
163 164
  ULONG        foundPropertyIndexToDelete,
  StgProperty  propertyToDelete);
165 166

static HRESULT deleteStreamProperty(
167
  StorageImpl *parentStorage,
168 169 170 171
  ULONG         foundPropertyIndexToDelete,
  StgProperty   propertyToDelete);

static HRESULT findPlaceholder(
172
  StorageImpl *storage,
173 174
  ULONG         propertyIndexToStore,
  ULONG         storagePropertyIndex,
175
  INT         typeOfRelation);
176

177
static HRESULT adjustPropertyChain(
178
  StorageImpl *This,
179 180 181
  StgProperty   propertyToDelete,
  StgProperty   parentProperty,
  ULONG         parentPropertyId,
182
  INT         typeOfRelation);
183 184 185 186 187 188

/***********************************************************************
 * Declaration of the functions used to manipulate StgProperty
 */

static ULONG getFreeProperty(
189
  StorageImpl *storage);
190 191

static void updatePropertyChain(
192
  StorageImpl *storage,
193 194 195 196
  ULONG       newPropertyIndex,
  StgProperty newProperty);

static LONG propertyNameCmp(
Eric Pouech's avatar
Eric Pouech committed
197 198
    const OLECHAR *newProperty,
    const OLECHAR *currentProperty);
199

200 201 202 203

/***********************************************************************
 * Declaration of miscellaneous functions...
 */
204
static HRESULT validateSTGM(DWORD stgmValue);
205 206 207 208 209

static DWORD GetShareModeFromSTGM(DWORD stgm);
static DWORD GetAccessModeFromSTGM(DWORD stgm);
static DWORD GetCreationModeFromSTGM(DWORD stgm);

210
extern const IPropertySetStorageVtbl IPropertySetStorage_Vtbl;
211 212


213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250
/****************************************************************************
 * IEnumSTATSTGImpl definitions.
 *
 * Definition of the implementation structure for the IEnumSTATSTGImpl interface.
 * This class allows iterating through the content of a storage and to find
 * specific items inside it.
 */
struct IEnumSTATSTGImpl
{
  const IEnumSTATSTGVtbl *lpVtbl;    /* Needs to be the first item in the struct
				* since we want to cast this in an IEnumSTATSTG pointer */

  LONG           ref;                   /* Reference count */
  StorageImpl*   parentStorage;         /* Reference to the parent storage */
  ULONG          firstPropertyNode;     /* Index of the root of the storage to enumerate */

  /*
   * The current implementation of the IEnumSTATSTGImpl class uses a stack
   * to walk the property sets to get the content of a storage. This stack
   * is implemented by the following 3 data members
   */
  ULONG          stackSize;
  ULONG          stackMaxSize;
  ULONG*         stackToVisit;

#define ENUMSTATSGT_SIZE_INCREMENT 10
};


static IEnumSTATSTGImpl* IEnumSTATSTGImpl_Construct(StorageImpl* This, ULONG firstPropertyNode);
static void IEnumSTATSTGImpl_Destroy(IEnumSTATSTGImpl* This);
static void IEnumSTATSTGImpl_PushSearchNode(IEnumSTATSTGImpl* This, ULONG nodeToPush);
static ULONG IEnumSTATSTGImpl_PopSearchNode(IEnumSTATSTGImpl* This, BOOL remove);
static ULONG IEnumSTATSTGImpl_FindProperty(IEnumSTATSTGImpl* This, const OLECHAR* lpszPropName,
                                           StgProperty* buffer);
static INT IEnumSTATSTGImpl_FindParentProperty(IEnumSTATSTGImpl *This, ULONG childProperty,
                                               StgProperty *currentProperty, ULONG *propertyId);

251 252 253 254 255 256 257 258 259 260 261 262 263
/************************************************************************
** Block Functions
*/

static ULONG BLOCK_GetBigBlockOffset(ULONG index)
{
    if (index == 0xffffffff)
        index = 0;
    else
        index ++;

    return index * BIG_BLOCK_SIZE;
}
264

265 266 267
/************************************************************************
** Storage32BaseImpl implementatiion
*/
268 269 270 271 272 273 274 275 276 277 278
static HRESULT StorageImpl_ReadAt(StorageImpl* This,
  ULARGE_INTEGER offset,
  void*          buffer,
  ULONG          size,
  ULONG*         bytesRead)
{
    return BIGBLOCKFILE_ReadAt(This->bigBlockFile,offset,buffer,size,bytesRead);
}

static HRESULT StorageImpl_WriteAt(StorageImpl* This,
  ULARGE_INTEGER offset,
279
  const void*    buffer,
280 281 282 283 284
  const ULONG    size,
  ULONG*         bytesWritten)
{
    return BIGBLOCKFILE_WriteAt(This->bigBlockFile,offset,buffer,size,bytesWritten);
}
285 286 287 288 289 290

/************************************************************************
 * Storage32BaseImpl_QueryInterface (IUnknown)
 *
 * This method implements the common QueryInterface for all IStorage32
 * implementations contained in this file.
291
 *
292 293
 * See Windows documentation for more details on IUnknown methods.
 */
294
static HRESULT WINAPI StorageBaseImpl_QueryInterface(
295
  IStorage*        iface,
296 297 298
  REFIID             riid,
  void**             ppvObject)
{
299
  StorageBaseImpl *This = (StorageBaseImpl *)iface;
300 301 302 303 304
  /*
   * Perform a sanity check on the parameters.
   */
  if ( (This==0) || (ppvObject==0) )
    return E_INVALIDARG;
305

306 307 308 309
  /*
   * Initialize the return parameter.
   */
  *ppvObject = 0;
310

311 312 313
  /*
   * Compare the riid with the interface IDs implemented by this object.
   */
314 315
  if (IsEqualGUID(&IID_IUnknown, riid) ||
      IsEqualGUID(&IID_IStorage, riid))
316
  {
317
    *ppvObject = (IStorage*)This;
318
  }
319
  else if (IsEqualGUID(&IID_IPropertySetStorage, riid))
320 321 322
  {
    *ppvObject = (IStorage*)&This->pssVtbl;
  }
323

324 325 326 327 328
  /*
   * Check that we obtained an interface.
   */
  if ((*ppvObject)==0)
    return E_NOINTERFACE;
329

330 331 332 333
  /*
   * Query Interface always increases the reference count by one when it is
   * successful
   */
334
  IStorage_AddRef(iface);
335

336
  return S_OK;
337
}
338

339 340 341 342 343
/************************************************************************
 * Storage32BaseImpl_AddRef (IUnknown)
 *
 * This method implements the common AddRef for all IStorage32
 * implementations contained in this file.
344
 *
345 346
 * See Windows documentation for more details on IUnknown methods.
 */
347
static ULONG WINAPI StorageBaseImpl_AddRef(
348
            IStorage* iface)
349
{
350
  StorageBaseImpl *This = (StorageBaseImpl *)iface;
351 352
  ULONG ref = InterlockedIncrement(&This->ref);

353
  TRACE("(%p) AddRef to %d\n", This, ref);
354 355

  return ref;
356
}
357

358 359 360 361 362
/************************************************************************
 * Storage32BaseImpl_Release (IUnknown)
 *
 * This method implements the common Release for all IStorage32
 * implementations contained in this file.
363
 *
364 365
 * See Windows documentation for more details on IUnknown methods.
 */
366
static ULONG WINAPI StorageBaseImpl_Release(
367
      IStorage* iface)
368
{
369
  StorageBaseImpl *This = (StorageBaseImpl *)iface;
370 371 372
  /*
   * Decrease the reference count on this object.
   */
373
  ULONG ref = InterlockedDecrement(&This->ref);
374

375
  TRACE("(%p) ReleaseRef to %d\n", This, ref);
376

377 378 379
  /*
   * If the reference count goes down to 0, perform suicide.
   */
380
  if (ref == 0)
381 382
  {
    /*
383 384
     * Since we are using a system of base-classes, we want to call the
     * destructor of the appropriate derived class. To do this, we are
385 386 387 388
     * using virtual functions to implement the destructor.
     */
    This->v_destructor(This);
  }
389

390
  return ref;
391 392 393 394 395 396 397 398 399
}

/************************************************************************
 * Storage32BaseImpl_OpenStream (IStorage)
 *
 * This method will open the specified stream object from the current storage.
 *
 * See Windows documentation for more details on IStorage methods.
 */
400
static HRESULT WINAPI StorageBaseImpl_OpenStream(
401 402
  IStorage*        iface,
  const OLECHAR*   pwcsName,  /* [string][in] */
403
  void*            reserved1, /* [unique][in] */
404 405 406
  DWORD            grfMode,   /* [in]  */
  DWORD            reserved2, /* [in]  */
  IStream**        ppstm)     /* [out] */
407
{
408
  StorageBaseImpl *This = (StorageBaseImpl *)iface;
409 410 411 412
  IEnumSTATSTGImpl* propertyEnumeration;
  StgStreamImpl*    newStream;
  StgProperty       currentProperty;
  ULONG             foundPropertyIndex;
Alexandre Julliard's avatar
Alexandre Julliard committed
413
  HRESULT           res = STG_E_UNKNOWN;
414

415
  TRACE("(%p, %s, %p, %x, %d, %p)\n",
416 417
	iface, debugstr_w(pwcsName), reserved1, grfMode, reserved2, ppstm);

418 419 420 421
  /*
   * Perform a sanity check on the parameters.
   */
  if ( (pwcsName==NULL) || (ppstm==0) )
Alexandre Julliard's avatar
Alexandre Julliard committed
422 423 424 425
  {
    res = E_INVALIDARG;
    goto end;
  }
426

427 428 429
  /*
   * Initialize the out parameter
   */
Alexandre Julliard's avatar
Alexandre Julliard committed
430
  *ppstm = NULL;
431

432 433 434
  /*
   * Validate the STGM flags
   */
435 436
  if ( FAILED( validateSTGM(grfMode) ) ||
       STGM_SHARE_MODE(grfMode) != STGM_SHARE_EXCLUSIVE)
Alexandre Julliard's avatar
Alexandre Julliard committed
437 438 439 440
  {
    res = STG_E_INVALIDFLAG;
    goto end;
  }
441 442 443 444

  /*
   * As documented.
   */
445
  if ( (grfMode & STGM_DELETEONRELEASE) || (grfMode & STGM_TRANSACTED) )
Alexandre Julliard's avatar
Alexandre Julliard committed
446 447 448 449
  {
    res = STG_E_INVALIDFUNCTION;
    goto end;
  }
450

451
  /*
452 453
   * Check that we're compatible with the parent's storage mode, but
   * only if we are not in transacted mode
454
   */
455
  if(!(This->ancestorStorage->base.openFlags & STGM_TRANSACTED)) {
456
    if ( STGM_ACCESS_MODE( grfMode ) > STGM_ACCESS_MODE( This->openFlags ) )
457 458 459 460
    {
      res = STG_E_ACCESSDENIED;
      goto end;
    }
461 462
  }

463 464 465 466
  /*
   * Create a property enumeration to search the properties
   */
  propertyEnumeration = IEnumSTATSTGImpl_Construct(
467
    This->ancestorStorage,
468
    This->rootPropertySetIndex);
469

470 471 472 473 474 475 476
  /*
   * Search the enumeration for the property with the given name
   */
  foundPropertyIndex = IEnumSTATSTGImpl_FindProperty(
    propertyEnumeration,
    pwcsName,
    &currentProperty);
477

478 479 480 481
  /*
   * Delete the property enumeration since we don't need it anymore
   */
  IEnumSTATSTGImpl_Destroy(propertyEnumeration);
482

483 484 485
  /*
   * If it was found, construct the stream object and return a pointer to it.
   */
486
  if ( (foundPropertyIndex!=PROPERTY_NULL) &&
487 488
       (currentProperty.propertyType==PROPTYPE_STREAM) )
  {
489
    newStream = StgStreamImpl_Construct(This, grfMode, foundPropertyIndex);
490

491 492
    if (newStream!=0)
    {
493
      newStream->grfMode = grfMode;
494
      *ppstm = (IStream*)newStream;
495

496
      /*
497
       * Since we are returning a pointer to the interface, we have to
498 499
       * nail down the reference.
       */
500
      IStream_AddRef(*ppstm);
501

Alexandre Julliard's avatar
Alexandre Julliard committed
502 503
      res = S_OK;
      goto end;
504
    }
505

Alexandre Julliard's avatar
Alexandre Julliard committed
506 507
    res = E_OUTOFMEMORY;
    goto end;
508
  }
509

Alexandre Julliard's avatar
Alexandre Julliard committed
510 511 512 513 514
  res = STG_E_FILENOTFOUND;

end:
  if (res == S_OK)
    TRACE("<-- IStream %p\n", *ppstm);
515
  TRACE("<-- %08x\n", res);
Alexandre Julliard's avatar
Alexandre Julliard committed
516
  return res;
517 518 519 520 521 522
}

/************************************************************************
 * Storage32BaseImpl_OpenStorage (IStorage)
 *
 * This method will open a new storage object from the current storage.
523
 *
524
 * See Windows documentation for more details on IStorage methods.
525
 */
526
static HRESULT WINAPI StorageBaseImpl_OpenStorage(
527
  IStorage*        iface,
528 529 530 531 532 533
  const OLECHAR*   pwcsName,      /* [string][unique][in] */
  IStorage*        pstgPriority,  /* [unique][in] */
  DWORD            grfMode,       /* [in] */
  SNB              snbExclude,    /* [unique][in] */
  DWORD            reserved,      /* [in] */
  IStorage**       ppstg)         /* [out] */
534
{
535
  StorageBaseImpl *This = (StorageBaseImpl *)iface;
536
  StorageInternalImpl* newStorage;
537 538 539
  IEnumSTATSTGImpl*      propertyEnumeration;
  StgProperty            currentProperty;
  ULONG                  foundPropertyIndex;
Alexandre Julliard's avatar
Alexandre Julliard committed
540
  HRESULT                res = STG_E_UNKNOWN;
541

542
  TRACE("(%p, %s, %p, %x, %p, %d, %p)\n",
543
	iface, debugstr_w(pwcsName), pstgPriority,
544
	grfMode, snbExclude, reserved, ppstg);
545

546 547 548 549
  /*
   * Perform a sanity check on the parameters.
   */
  if ( (This==0) || (pwcsName==NULL) || (ppstg==0) )
Alexandre Julliard's avatar
Alexandre Julliard committed
550 551 552 553
  {
    res = E_INVALIDARG;
    goto end;
  }
554

Alexandre Julliard's avatar
Alexandre Julliard committed
555 556 557 558 559 560
  /* as documented */
  if (snbExclude != NULL)
  {
    res = STG_E_INVALIDPARAMETER;
    goto end;
  }
561

562 563 564 565
  /*
   * Validate the STGM flags
   */
  if ( FAILED( validateSTGM(grfMode) ))
Alexandre Julliard's avatar
Alexandre Julliard committed
566 567 568 569
  {
    res = STG_E_INVALIDFLAG;
    goto end;
  }
570 571 572 573

  /*
   * As documented.
   */
574
  if ( STGM_SHARE_MODE(grfMode) != STGM_SHARE_EXCLUSIVE ||
575 576
        (grfMode & STGM_DELETEONRELEASE) ||
        (grfMode & STGM_PRIORITY) )
Alexandre Julliard's avatar
Alexandre Julliard committed
577 578 579 580
  {
    res = STG_E_INVALIDFUNCTION;
    goto end;
  }
581

582
  /*
583 584
   * Check that we're compatible with the parent's storage mode,
   * but only if we are not transacted
585
   */
586
  if(!(This->ancestorStorage->base.openFlags & STGM_TRANSACTED)) {
587
    if ( STGM_ACCESS_MODE( grfMode ) > STGM_ACCESS_MODE( This->openFlags ) )
588 589 590 591
    {
      res = STG_E_ACCESSDENIED;
      goto end;
    }
592 593
  }

594 595 596
  /*
   * Initialize the out parameter
   */
Alexandre Julliard's avatar
Alexandre Julliard committed
597
  *ppstg = NULL;
598

599 600 601 602
  /*
   * Create a property enumeration to search the properties
   */
  propertyEnumeration = IEnumSTATSTGImpl_Construct(
603
                          This->ancestorStorage,
604
                          This->rootPropertySetIndex);
605

606 607 608 609 610 611 612
  /*
   * Search the enumeration for the property with the given name
   */
  foundPropertyIndex = IEnumSTATSTGImpl_FindProperty(
                         propertyEnumeration,
                         pwcsName,
                         &currentProperty);
613

614 615 616 617
  /*
   * Delete the property enumeration since we don't need it anymore
   */
  IEnumSTATSTGImpl_Destroy(propertyEnumeration);
618

619 620 621
  /*
   * If it was found, construct the stream object and return a pointer to it.
   */
622
  if ( (foundPropertyIndex!=PROPERTY_NULL) &&
623 624 625 626 627
       (currentProperty.propertyType==PROPTYPE_STORAGE) )
  {
    /*
     * Construct a new Storage object
     */
628
    newStorage = StorageInternalImpl_Construct(
629
                   This->ancestorStorage,
630
                   grfMode,
631
                   foundPropertyIndex);
632

633 634
    if (newStorage != 0)
    {
635
      *ppstg = (IStorage*)newStorage;
636

637
      /*
638
       * Since we are returning a pointer to the interface,
639 640
       * we have to nail down the reference.
       */
641
      StorageBaseImpl_AddRef(*ppstg);
642

Alexandre Julliard's avatar
Alexandre Julliard committed
643 644
      res = S_OK;
      goto end;
645
    }
646

Alexandre Julliard's avatar
Alexandre Julliard committed
647 648
    res = STG_E_INSUFFICIENTMEMORY;
    goto end;
649
  }
650

Alexandre Julliard's avatar
Alexandre Julliard committed
651 652 653
  res = STG_E_FILENOTFOUND;

end:
654
  TRACE("<-- %08x\n", res);
Alexandre Julliard's avatar
Alexandre Julliard committed
655
  return res;
656 657 658 659 660
}

/************************************************************************
 * Storage32BaseImpl_EnumElements (IStorage)
 *
661
 * This method will create an enumerator object that can be used to
662
 * retrieve informatino about all the properties in the storage object.
663
 *
664
 * See Windows documentation for more details on IStorage methods.
665
 */
666
static HRESULT WINAPI StorageBaseImpl_EnumElements(
667
  IStorage*       iface,
668 669 670 671
  DWORD           reserved1, /* [in] */
  void*           reserved2, /* [size_is][unique][in] */
  DWORD           reserved3, /* [in] */
  IEnumSTATSTG**  ppenum)    /* [out] */
672
{
673
  StorageBaseImpl *This = (StorageBaseImpl *)iface;
674 675
  IEnumSTATSTGImpl* newEnum;

676
  TRACE("(%p, %d, %p, %d, %p)\n",
677 678
	iface, reserved1, reserved2, reserved3, ppenum);

679 680 681 682 683
  /*
   * Perform a sanity check on the parameters.
   */
  if ( (This==0) || (ppenum==0))
    return E_INVALIDARG;
684

685 686 687 688 689 690 691 692 693
  /*
   * Construct the enumerator.
   */
  newEnum = IEnumSTATSTGImpl_Construct(
              This->ancestorStorage,
              This->rootPropertySetIndex);

  if (newEnum!=0)
  {
694 695
    *ppenum = (IEnumSTATSTG*)newEnum;

696 697 698 699
    /*
     * Don't forget to nail down a reference to the new object before
     * returning it.
     */
700
    IEnumSTATSTG_AddRef(*ppenum);
701

702 703 704 705 706 707 708 709 710 711
    return S_OK;
  }

  return E_OUTOFMEMORY;
}

/************************************************************************
 * Storage32BaseImpl_Stat (IStorage)
 *
 * This method will retrieve information about this storage object.
712
 *
713
 * See Windows documentation for more details on IStorage methods.
714
 */
715
static HRESULT WINAPI StorageBaseImpl_Stat(
716
  IStorage*        iface,
717 718
  STATSTG*         pstatstg,     /* [out] */
  DWORD            grfStatFlag)  /* [in] */
719
{
720
  StorageBaseImpl *This = (StorageBaseImpl *)iface;
721
  StgProperty    curProperty;
Alexandre Julliard's avatar
Alexandre Julliard committed
722 723
  BOOL           readSuccessful;
  HRESULT        res = STG_E_UNKNOWN;
724

725
  TRACE("(%p, %p, %x)\n",
726 727
	iface, pstatstg, grfStatFlag);

728 729 730 731
  /*
   * Perform a sanity check on the parameters.
   */
  if ( (This==0) || (pstatstg==0))
Alexandre Julliard's avatar
Alexandre Julliard committed
732 733 734 735
  {
    res = E_INVALIDARG;
    goto end;
  }
736 737 738 739

  /*
   * Read the information from the property.
   */
740
  readSuccessful = StorageImpl_ReadProperty(
741 742 743 744
                    This->ancestorStorage,
                    This->rootPropertySetIndex,
                    &curProperty);

745
  if (readSuccessful)
746 747
  {
    StorageUtl_CopyPropertyToSTATSTG(
748 749
      pstatstg,
      &curProperty,
750
      grfStatFlag);
751

752
    pstatstg->grfMode = This->openFlags;
753
    pstatstg->grfStateBits = This->stateBits;
754

Alexandre Julliard's avatar
Alexandre Julliard committed
755 756
    res = S_OK;
    goto end;
757
  }
758

Alexandre Julliard's avatar
Alexandre Julliard committed
759 760 761 762 763
  res = E_FAIL;

end:
  if (res == S_OK)
  {
764
    TRACE("<-- STATSTG: pwcsName: %s, type: %d, cbSize.Low/High: %d/%d, grfMode: %08x, grfLocksSupported: %d, grfStateBits: %08x\n", debugstr_w(pstatstg->pwcsName), pstatstg->type, pstatstg->cbSize.u.LowPart, pstatstg->cbSize.u.HighPart, pstatstg->grfMode, pstatstg->grfLocksSupported, pstatstg->grfStateBits);
Alexandre Julliard's avatar
Alexandre Julliard committed
765
  }
766
  TRACE("<-- %08x\n", res);
Alexandre Julliard's avatar
Alexandre Julliard committed
767
  return res;
768 769 770 771 772
}

/************************************************************************
 * Storage32BaseImpl_RenameElement (IStorage)
 *
773
 * This method will rename the specified element.
774 775
 *
 * See Windows documentation for more details on IStorage methods.
776 777 778
 *
 * Implementation notes: The method used to rename consists of creating a clone
 *    of the deleted StgProperty object setting it with the new name and to
779 780
 *    perform a DestroyElement of the old StgProperty.
 */
781
static HRESULT WINAPI StorageBaseImpl_RenameElement(
782 783 784
            IStorage*        iface,
            const OLECHAR*   pwcsOldName,  /* [in] */
            const OLECHAR*   pwcsNewName)  /* [in] */
785
{
786
  StorageBaseImpl *This = (StorageBaseImpl *)iface;
787 788 789 790
  IEnumSTATSTGImpl* propertyEnumeration;
  StgProperty       currentProperty;
  ULONG             foundPropertyIndex;

791
  TRACE("(%p, %s, %s)\n",
792 793
	iface, debugstr_w(pwcsOldName), debugstr_w(pwcsNewName));

794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815
  /*
   * Create a property enumeration to search the properties
   */
  propertyEnumeration = IEnumSTATSTGImpl_Construct(This->ancestorStorage,
                                                   This->rootPropertySetIndex);

  /*
   * Search the enumeration for the new property name
   */
  foundPropertyIndex = IEnumSTATSTGImpl_FindProperty(propertyEnumeration,
                                                     pwcsNewName,
                                                     &currentProperty);

  if (foundPropertyIndex != PROPERTY_NULL)
  {
    /*
     * There is already a property with the new name
     */
    IEnumSTATSTGImpl_Destroy(propertyEnumeration);
    return STG_E_FILEALREADYEXISTS;
  }

816
  IEnumSTATSTG_Reset((IEnumSTATSTG*)propertyEnumeration);
817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837

  /*
   * Search the enumeration for the old property name
   */
  foundPropertyIndex = IEnumSTATSTGImpl_FindProperty(propertyEnumeration,
                                                     pwcsOldName,
                                                     &currentProperty);

  /*
   * Delete the property enumeration since we don't need it anymore
   */
  IEnumSTATSTGImpl_Destroy(propertyEnumeration);

  if (foundPropertyIndex != PROPERTY_NULL)
  {
    StgProperty renamedProperty;
    ULONG       renamedPropertyIndex;

    /*
     * Setup a new property for the renamed property
     */
838
    renamedProperty.sizeOfNameString =
839
      ( lstrlenW(pwcsNewName)+1 ) * sizeof(WCHAR);
840

841 842
    if (renamedProperty.sizeOfNameString > PROPERTY_NAME_BUFFER_LEN)
      return STG_E_INVALIDNAME;
843

844
    strcpyW(renamedProperty.name, pwcsNewName);
845

846 847
    renamedProperty.propertyType  = currentProperty.propertyType;
    renamedProperty.startingBlock = currentProperty.startingBlock;
848 849
    renamedProperty.size.u.LowPart  = currentProperty.size.u.LowPart;
    renamedProperty.size.u.HighPart = currentProperty.size.u.HighPart;
850

851 852
    renamedProperty.previousProperty = PROPERTY_NULL;
    renamedProperty.nextProperty     = PROPERTY_NULL;
853

854 855 856 857 858
    /*
     * Bring the dirProperty link in case it is a storage and in which
     * case the renamed storage elements don't require to be reorganized.
     */
    renamedProperty.dirProperty = currentProperty.dirProperty;
859 860

    /* call CoFileTime to get the current time
861 862 863 864
    renamedProperty.timeStampS1
    renamedProperty.timeStampD1
    renamedProperty.timeStampS2
    renamedProperty.timeStampD2
865
    renamedProperty.propertyUniqueID
866
    */
867 868

    /*
869 870 871
     * Obtain a free property in the property chain
     */
    renamedPropertyIndex = getFreeProperty(This->ancestorStorage);
872

873 874
    /*
     * Save the new property into the new property spot
875
     */
876
    StorageImpl_WriteProperty(
877
      This->ancestorStorage,
878
      renamedPropertyIndex,
879
      &renamedProperty);
880 881

    /*
882 883 884
     * Find a spot in the property chain for our newly created property.
     */
    updatePropertyChain(
885
      (StorageImpl*)This,
886
      renamedPropertyIndex,
887 888 889
      renamedProperty);

    /*
890
     * At this point the renamed property has been inserted in the tree,
891
     * now, before Destroying the old property we must zero its dirProperty
892
     * otherwise the DestroyProperty below will zap it all and we do not want
893 894 895
     * this to happen.
     * Also, we fake that the old property is a storage so the DestroyProperty
     * will not do a SetSize(0) on the stream data.
896
     *
897
     * This means that we need to tweak the StgProperty if it is a stream or a
898 899
     * non empty storage.
     */
900 901 902 903
    StorageImpl_ReadProperty(This->ancestorStorage,
                             foundPropertyIndex,
                             &currentProperty);

904 905
    currentProperty.dirProperty  = PROPERTY_NULL;
    currentProperty.propertyType = PROPTYPE_STORAGE;
906
    StorageImpl_WriteProperty(
907
      This->ancestorStorage,
908
      foundPropertyIndex,
909 910
      &currentProperty);

911 912
    /*
     * Invoke Destroy to get rid of the ole property and automatically redo
913
     * the linking of its previous and next members...
914
     */
915
    IStorage_DestroyElement((IStorage*)This->ancestorStorage, pwcsOldName);
916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931

  }
  else
  {
    /*
     * There is no property with the old name
     */
    return STG_E_FILENOTFOUND;
  }

  return S_OK;
}

/************************************************************************
 * Storage32BaseImpl_CreateStream (IStorage)
 *
932
 * This method will create a stream object within this storage
933 934 935
 *
 * See Windows documentation for more details on IStorage methods.
 */
936
static HRESULT WINAPI StorageBaseImpl_CreateStream(
937 938
            IStorage*        iface,
            const OLECHAR*   pwcsName,  /* [string][in] */
939 940 941
            DWORD            grfMode,   /* [in] */
            DWORD            reserved1, /* [in] */
            DWORD            reserved2, /* [in] */
942
            IStream**        ppstm)     /* [out] */
943
{
944
  StorageBaseImpl *This = (StorageBaseImpl *)iface;
945 946 947 948 949
  IEnumSTATSTGImpl* propertyEnumeration;
  StgStreamImpl*    newStream;
  StgProperty       currentProperty, newStreamProperty;
  ULONG             foundPropertyIndex, newPropertyIndex;

950
  TRACE("(%p, %s, %x, %d, %d, %p)\n",
951
	iface, debugstr_w(pwcsName), grfMode,
952 953
	reserved1, reserved2, ppstm);

954 955 956 957 958 959 960 961 962
  /*
   * Validate parameters
   */
  if (ppstm == 0)
    return STG_E_INVALIDPOINTER;

  if (pwcsName == 0)
    return STG_E_INVALIDNAME;

963 964 965
  if (reserved1 || reserved2)
    return STG_E_INVALIDPARAMETER;

966 967 968 969 970 971
  /*
   * Validate the STGM flags
   */
  if ( FAILED( validateSTGM(grfMode) ))
    return STG_E_INVALIDFLAG;

972
  if (STGM_SHARE_MODE(grfMode) != STGM_SHARE_EXCLUSIVE) 
973 974
    return STG_E_INVALIDFLAG;

975 976 977
  /*
   * As documented.
   */
978 979
  if ((grfMode & STGM_DELETEONRELEASE) ||
      (grfMode & STGM_TRANSACTED))
980 981
    return STG_E_INVALIDFUNCTION;

982 983
  /*
   * Check that we're compatible with the parent's storage mode
984
   * if not in transacted mode
985
   */
986 987
  if(!(This->ancestorStorage->base.openFlags & STGM_TRANSACTED)) {
    if ( STGM_ACCESS_MODE( grfMode ) > STGM_ACCESS_MODE( This->openFlags ) )
988 989
      return STG_E_ACCESSDENIED;
  }
990

991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010
  /*
   * Initialize the out parameter
   */
  *ppstm = 0;

  /*
   * Create a property enumeration to search the properties
   */
  propertyEnumeration = IEnumSTATSTGImpl_Construct(This->ancestorStorage,
                                                   This->rootPropertySetIndex);

  foundPropertyIndex = IEnumSTATSTGImpl_FindProperty(propertyEnumeration,
                                                     pwcsName,
                                                     &currentProperty);

  IEnumSTATSTGImpl_Destroy(propertyEnumeration);

  if (foundPropertyIndex != PROPERTY_NULL)
  {
    /*
1011
     * An element with this name already exists
1012
     */
1013
    if (STGM_CREATE_MODE(grfMode) == STGM_CREATE)
1014
    {
1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025
      StgStreamImpl *strm;

      LIST_FOR_EACH_ENTRY(strm, &This->strmHead, StgStreamImpl, StrmListEntry)
      {
        if (strm->ownerProperty == foundPropertyIndex)
        {
          TRACE("Stream deleted %p\n", strm);
          strm->parentStorage = NULL;
          list_remove(&strm->StrmListEntry);
        }
      }
1026
      IStorage_DestroyElement(iface, pwcsName);
1027
    }
1028
    else
1029 1030
      return STG_E_FILEALREADYEXISTS;
  }
1031 1032 1033 1034 1035
  else if (STGM_ACCESS_MODE(This->openFlags) == STGM_READ)
  {
    WARN("read-only storage\n");
    return STG_E_ACCESSDENIED;
  }
1036

1037 1038
  /*
   * memset the empty property
1039 1040 1041 1042
   */
  memset(&newStreamProperty, 0, sizeof(StgProperty));

  newStreamProperty.sizeOfNameString =
1043
      ( lstrlenW(pwcsName)+1 ) * sizeof(WCHAR);
1044 1045 1046 1047

  if (newStreamProperty.sizeOfNameString > PROPERTY_NAME_BUFFER_LEN)
    return STG_E_INVALIDNAME;

1048
  strcpyW(newStreamProperty.name, pwcsName);
1049 1050 1051

  newStreamProperty.propertyType  = PROPTYPE_STREAM;
  newStreamProperty.startingBlock = BLOCK_END_OF_CHAIN;
1052 1053
  newStreamProperty.size.u.LowPart  = 0;
  newStreamProperty.size.u.HighPart = 0;
1054 1055 1056 1057 1058

  newStreamProperty.previousProperty = PROPERTY_NULL;
  newStreamProperty.nextProperty     = PROPERTY_NULL;
  newStreamProperty.dirProperty      = PROPERTY_NULL;

1059
  /* call CoFileTime to get the current time
1060 1061 1062 1063 1064 1065 1066 1067 1068
  newStreamProperty.timeStampS1
  newStreamProperty.timeStampD1
  newStreamProperty.timeStampS2
  newStreamProperty.timeStampD2
  */

  /*  newStreamProperty.propertyUniqueID */

  /*
1069
   * Get a free property or create a new one
1070 1071 1072 1073 1074
   */
  newPropertyIndex = getFreeProperty(This->ancestorStorage);

  /*
   * Save the new property into the new property spot
1075
   */
1076
  StorageImpl_WriteProperty(
1077
    This->ancestorStorage,
1078
    newPropertyIndex,
1079 1080
    &newStreamProperty);

1081
  /*
1082 1083 1084
   * Find a spot in the property chain for our newly created property.
   */
  updatePropertyChain(
1085
    (StorageImpl*)This,
1086
    newPropertyIndex,
1087 1088
    newStreamProperty);

1089
  /*
1090 1091
   * Open the stream to return it.
   */
1092
  newStream = StgStreamImpl_Construct(This, grfMode, newPropertyIndex);
1093 1094 1095

  if (newStream != 0)
  {
1096
    *ppstm = (IStream*)newStream;
1097

1098 1099 1100 1101
    /*
     * Since we are returning a pointer to the interface, we have to nail down
     * the reference.
     */
1102
    IStream_AddRef(*ppstm);
1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114
  }
  else
  {
    return STG_E_INSUFFICIENTMEMORY;
  }

  return S_OK;
}

/************************************************************************
 * Storage32BaseImpl_SetClass (IStorage)
 *
1115
 * This method will write the specified CLSID in the property of this
1116 1117 1118 1119
 * storage.
 *
 * See Windows documentation for more details on IStorage methods.
 */
1120
static HRESULT WINAPI StorageBaseImpl_SetClass(
1121
  IStorage*        iface,
1122
  REFCLSID         clsid) /* [in] */
1123
{
1124
  StorageBaseImpl *This = (StorageBaseImpl *)iface;
1125 1126
  HRESULT hRes = E_FAIL;
  StgProperty curProperty;
1127
  BOOL success;
1128

1129
  TRACE("(%p, %p)\n", iface, clsid);
1130

1131
  success = StorageImpl_ReadProperty(This->ancestorStorage,
1132 1133 1134 1135 1136 1137
                                       This->rootPropertySetIndex,
                                       &curProperty);
  if (success)
  {
    curProperty.propertyUniqueID = *clsid;

1138
    success =  StorageImpl_WriteProperty(This->ancestorStorage,
1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150
                                           This->rootPropertySetIndex,
                                           &curProperty);
    if (success)
      hRes = S_OK;
  }

  return hRes;
}

/************************************************************************
** Storage32Impl implementation
*/
1151

1152
/************************************************************************
1153
 * Storage32Impl_CreateStorage (IStorage)
1154 1155 1156 1157 1158
 *
 * This method will create the storage object within the provided storage.
 *
 * See Windows documentation for more details on IStorage methods.
 */
1159
static HRESULT WINAPI StorageImpl_CreateStorage(
1160
  IStorage*      iface,
1161 1162 1163 1164 1165
  const OLECHAR  *pwcsName, /* [string][in] */
  DWORD            grfMode,   /* [in] */
  DWORD            reserved1, /* [in] */
  DWORD            reserved2, /* [in] */
  IStorage       **ppstg)   /* [out] */
1166
{
1167
  StorageImpl* const This=(StorageImpl*)iface;
1168

1169 1170 1171 1172 1173 1174 1175
  IEnumSTATSTGImpl *propertyEnumeration;
  StgProperty      currentProperty;
  StgProperty      newProperty;
  ULONG            foundPropertyIndex;
  ULONG            newPropertyIndex;
  HRESULT          hr;

1176
  TRACE("(%p, %s, %x, %d, %d, %p)\n",
1177
	iface, debugstr_w(pwcsName), grfMode,
1178
	reserved1, reserved2, ppstg);
1179

1180 1181 1182 1183 1184 1185 1186 1187 1188
  /*
   * Validate parameters
   */
  if (ppstg == 0)
    return STG_E_INVALIDPOINTER;

  if (pwcsName == 0)
    return STG_E_INVALIDNAME;

1189 1190 1191 1192 1193
  /*
   * Initialize the out parameter
   */
  *ppstg = NULL;

1194 1195 1196 1197 1198
  /*
   * Validate the STGM flags
   */
  if ( FAILED( validateSTGM(grfMode) ) ||
       (grfMode & STGM_DELETEONRELEASE) )
1199
  {
1200
    WARN("bad grfMode: 0x%x\n", grfMode);
1201
    return STG_E_INVALIDFLAG;
1202
  }
1203

1204 1205 1206
  /*
   * Check that we're compatible with the parent's storage mode
   */
1207
  if ( STGM_ACCESS_MODE( grfMode ) > STGM_ACCESS_MODE( This->base.openFlags ) )
1208 1209
  {
    WARN("access denied\n");
1210
    return STG_E_ACCESSDENIED;
1211
  }
1212 1213 1214 1215

  /*
   * Create a property enumeration and search the properties
   */
1216 1217
  propertyEnumeration = IEnumSTATSTGImpl_Construct( This->base.ancestorStorage,
                                                    This->base.rootPropertySetIndex);
1218 1219 1220 1221 1222 1223 1224 1225 1226

  foundPropertyIndex = IEnumSTATSTGImpl_FindProperty(propertyEnumeration,
                                                     pwcsName,
                                                     &currentProperty);
  IEnumSTATSTGImpl_Destroy(propertyEnumeration);

  if (foundPropertyIndex != PROPERTY_NULL)
  {
    /*
1227
     * An element with this name already exists
1228
     */
1229
    if (STGM_CREATE_MODE(grfMode) == STGM_CREATE)
1230 1231
      IStorage_DestroyElement(iface, pwcsName);
    else
1232 1233
    {
      WARN("file already exists\n");
1234
      return STG_E_FILEALREADYEXISTS;
1235
    }
1236
  }
1237 1238 1239 1240 1241
  else if (STGM_ACCESS_MODE(This->base.openFlags) == STGM_READ)
  {
    WARN("read-only storage\n");
    return STG_E_ACCESSDENIED;
  }
1242

1243 1244
  /*
   * memset the empty property
1245 1246 1247
   */
  memset(&newProperty, 0, sizeof(StgProperty));

1248
  newProperty.sizeOfNameString = (lstrlenW(pwcsName)+1)*sizeof(WCHAR);
1249 1250

  if (newProperty.sizeOfNameString > PROPERTY_NAME_BUFFER_LEN)
1251 1252
  {
    FIXME("name too long\n");
1253
    return STG_E_INVALIDNAME;
1254
  }
1255

1256
  strcpyW(newProperty.name, pwcsName);
1257 1258 1259

  newProperty.propertyType  = PROPTYPE_STORAGE;
  newProperty.startingBlock = BLOCK_END_OF_CHAIN;
1260 1261
  newProperty.size.u.LowPart  = 0;
  newProperty.size.u.HighPart = 0;
1262 1263 1264 1265 1266

  newProperty.previousProperty = PROPERTY_NULL;
  newProperty.nextProperty     = PROPERTY_NULL;
  newProperty.dirProperty      = PROPERTY_NULL;

1267
  /* call CoFileTime to get the current time
1268 1269 1270 1271 1272 1273 1274 1275
  newProperty.timeStampS1
  newProperty.timeStampD1
  newProperty.timeStampS2
  newProperty.timeStampD2
  */

  /*  newStorageProperty.propertyUniqueID */

1276
  /*
1277 1278
   * Obtain a free property in the property chain
   */
1279
  newPropertyIndex = getFreeProperty(This->base.ancestorStorage);
1280 1281 1282

  /*
   * Save the new property into the new property spot
1283
   */
1284
  StorageImpl_WriteProperty(
1285
    This->base.ancestorStorage,
1286
    newPropertyIndex,
1287 1288
    &newProperty);

1289
  /*
1290 1291 1292 1293
   * Find a spot in the property chain for our newly created property.
   */
  updatePropertyChain(
    This,
1294
    newPropertyIndex,
1295 1296
    newProperty);

1297
  /*
1298 1299
   * Open it to get a pointer to return.
   */
1300
  hr = IStorage_OpenStorage(iface, pwcsName, 0, grfMode, 0, 0, ppstg);
1301 1302 1303 1304 1305 1306

  if( (hr != S_OK) || (*ppstg == NULL))
  {
    return hr;
  }

1307

1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318
  return S_OK;
}


/***************************************************************************
 *
 * Internal Method
 *
 * Get a free property or create a new one.
 */
static ULONG getFreeProperty(
1319
  StorageImpl *storage)
1320 1321 1322
{
  ULONG       currentPropertyIndex = 0;
  ULONG       newPropertyIndex     = PROPERTY_NULL;
1323
  BOOL      readSuccessful        = TRUE;
1324 1325 1326 1327 1328 1329 1330
  StgProperty currentProperty;

  do
  {
    /*
     * Start by reading the root property
     */
1331
    readSuccessful = StorageImpl_ReadProperty(storage->base.ancestorStorage,
1332 1333
                                               currentPropertyIndex,
                                               &currentProperty);
1334
    if (readSuccessful)
1335 1336 1337
    {
      if (currentProperty.sizeOfNameString == 0)
      {
1338
        /*
1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354
         * The property existis and is available, we found it.
         */
        newPropertyIndex = currentPropertyIndex;
      }
    }
    else
    {
      /*
       * We exhausted the property list, we will create more space below
       */
      newPropertyIndex = currentPropertyIndex;
    }
    currentPropertyIndex++;

  } while (newPropertyIndex == PROPERTY_NULL);

1355 1356
  /*
   * grow the property chain
1357
   */
1358
  if (! readSuccessful)
1359 1360 1361 1362 1363 1364 1365
  {
    StgProperty    emptyProperty;
    ULARGE_INTEGER newSize;
    ULONG          propertyIndex;
    ULONG          lastProperty  = 0;
    ULONG          blockCount    = 0;

1366 1367
    /*
     * obtain the new count of property blocks
1368 1369
     */
    blockCount = BlockChainStream_GetCount(
1370
                   storage->base.ancestorStorage->rootBlockChain)+1;
1371

1372 1373
    /*
     * initialize the size used by the property stream
1374
     */
1375 1376
    newSize.u.HighPart = 0;
    newSize.u.LowPart  = storage->bigBlockSize * blockCount;
1377

1378 1379
    /*
     * add a property block to the property chain
1380
     */
1381
    BlockChainStream_SetSize(storage->base.ancestorStorage->rootBlockChain, newSize);
1382

1383 1384
    /*
     * memset the empty property in order to initialize the unused newly
1385 1386 1387 1388
     * created property
     */
    memset(&emptyProperty, 0, sizeof(StgProperty));

1389
    /*
1390 1391
     * initialize them
     */
1392 1393
    lastProperty = storage->bigBlockSize / PROPSET_BLOCK_SIZE * blockCount;

1394 1395 1396 1397 1398
    for(
      propertyIndex = newPropertyIndex;
      propertyIndex < lastProperty;
      propertyIndex++)
    {
1399
      StorageImpl_WriteProperty(
1400
        storage->base.ancestorStorage,
1401
        propertyIndex,
1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412
        &emptyProperty);
    }
  }

  return newPropertyIndex;
}

/****************************************************************************
 *
 * Internal Method
 *
1413
 * Case insensitive comparaison of StgProperty.name by first considering
1414 1415 1416 1417 1418 1419 1420
 * their size.
 *
 * Returns <0 when newPrpoerty < currentProperty
 *         >0 when newPrpoerty > currentProperty
 *          0 when newPrpoerty == currentProperty
 */
static LONG propertyNameCmp(
Eric Pouech's avatar
Eric Pouech committed
1421 1422
    const OLECHAR *newProperty,
    const OLECHAR *currentProperty)
1423
{
1424
  LONG diff      = lstrlenW(newProperty) - lstrlenW(currentProperty);
1425

1426
  if (diff == 0)
1427
  {
1428
    /*
Francois Gouget's avatar
Francois Gouget committed
1429
     * We compare the string themselves only when they are of the same length
1430
     */
1431
    diff = lstrcmpiW( newProperty, currentProperty);
1432 1433
  }

1434
  return diff;
1435 1436 1437 1438 1439 1440 1441 1442 1443
}

/****************************************************************************
 *
 * Internal Method
 *
 * Properly link this new element in the property chain.
 */
static void updatePropertyChain(
1444
  StorageImpl *storage,
1445
  ULONG         newPropertyIndex,
1446
  StgProperty   newProperty)
1447 1448 1449 1450 1451 1452
{
  StgProperty currentProperty;

  /*
   * Read the root property
   */
1453 1454
  StorageImpl_ReadProperty(storage->base.ancestorStorage,
                             storage->base.rootPropertySetIndex,
1455 1456 1457 1458
                             &currentProperty);

  if (currentProperty.dirProperty != PROPERTY_NULL)
  {
1459
    /*
1460 1461 1462
     * The root storage contains some element, therefore, start the research
     * for the appropriate location.
     */
1463
    BOOL found = 0;
1464 1465 1466 1467 1468 1469 1470 1471
    ULONG  current, next, previous, currentPropertyId;

    /*
     * Keep the StgProperty sequence number of the storage first property
     */
    currentPropertyId = currentProperty.dirProperty;

    /*
1472
     * Read
1473
     */
1474
    StorageImpl_ReadProperty(storage->base.ancestorStorage,
1475 1476 1477 1478 1479 1480 1481 1482 1483 1484
                               currentProperty.dirProperty,
                               &currentProperty);

    previous = currentProperty.previousProperty;
    next     = currentProperty.nextProperty;
    current  = currentPropertyId;

    while (found == 0)
    {
      LONG diff = propertyNameCmp( newProperty.name, currentProperty.name);
1485

1486 1487 1488 1489
      if (diff < 0)
      {
        if (previous != PROPERTY_NULL)
        {
1490
          StorageImpl_ReadProperty(storage->base.ancestorStorage,
1491 1492 1493 1494 1495 1496 1497
                                     previous,
                                     &currentProperty);
          current = previous;
        }
        else
        {
          currentProperty.previousProperty = newPropertyIndex;
1498
          StorageImpl_WriteProperty(storage->base.ancestorStorage,
1499 1500 1501 1502 1503
                                      current,
                                      &currentProperty);
          found = 1;
        }
      }
1504
      else if (diff > 0)
1505 1506 1507
      {
        if (next != PROPERTY_NULL)
        {
1508
          StorageImpl_ReadProperty(storage->base.ancestorStorage,
1509 1510 1511 1512 1513 1514 1515
                                     next,
                                     &currentProperty);
          current = next;
        }
        else
        {
          currentProperty.nextProperty = newPropertyIndex;
1516
          StorageImpl_WriteProperty(storage->base.ancestorStorage,
1517 1518 1519 1520 1521
                                      current,
                                      &currentProperty);
          found = 1;
        }
      }
1522 1523 1524 1525 1526 1527 1528 1529
      else
      {
	/*
	 * Trying to insert an item with the same name in the
	 * subtree structure.
	 */
	assert(FALSE);
      }
1530 1531 1532 1533 1534 1535 1536

      previous = currentProperty.previousProperty;
      next     = currentProperty.nextProperty;
    }
  }
  else
  {
1537
    /*
1538
     * The root storage is empty, link the new property to its dir property
1539 1540
     */
    currentProperty.dirProperty = newPropertyIndex;
1541 1542
    StorageImpl_WriteProperty(storage->base.ancestorStorage,
                                storage->base.rootPropertySetIndex,
1543 1544 1545 1546
                                &currentProperty);
  }
}

1547

1548 1549 1550
/*************************************************************************
 * CopyTo (IStorage)
 */
1551
static HRESULT WINAPI StorageImpl_CopyTo(
1552
  IStorage*   iface,
1553 1554 1555 1556
  DWORD       ciidExclude,  /* [in] */
  const IID*  rgiidExclude, /* [size_is][unique][in] */
  SNB         snbExclude,   /* [unique][in] */
  IStorage*   pstgDest)     /* [unique][in] */
1557
{
1558 1559 1560 1561 1562 1563 1564
  IEnumSTATSTG *elements     = 0;
  STATSTG      curElement, strStat;
  HRESULT      hr;
  IStorage     *pstgTmp, *pstgChild;
  IStream      *pstrTmp, *pstrChild;

  if ((ciidExclude != 0) || (rgiidExclude != NULL) || (snbExclude != NULL))
1565
    FIXME("Exclude option not implemented\n");
1566

1567
  TRACE("(%p, %d, %p, %p, %p)\n",
1568
	iface, ciidExclude, rgiidExclude,
1569
	snbExclude, pstgDest);
1570 1571 1572 1573 1574 1575 1576

  /*
   * Perform a sanity check
   */
  if ( pstgDest == 0 )
    return STG_E_INVALIDPOINTER;

1577
  /*
1578 1579 1580 1581 1582 1583 1584 1585 1586 1587
   * Enumerate the elements
   */
  hr = IStorage_EnumElements( iface, 0, 0, 0, &elements );

  if ( hr != S_OK )
    return hr;

  /*
   * set the class ID
   */
1588
  IStorage_Stat( iface, &curElement, STATFLAG_NONAME);
1589
  IStorage_SetClass( pstgDest, &curElement.clsid );
1590

1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608
  do
  {
    /*
     * Obtain the next element
     */
    hr = IEnumSTATSTG_Next( elements, 1, &curElement, NULL );

    if ( hr == S_FALSE )
    {
      hr = S_OK;   /* done, every element has been copied */
      break;
    }

    if (curElement.type == STGTY_STORAGE)
    {
      /*
       * open child source storage
       */
1609 1610 1611
      hr = IStorage_OpenStorage( iface, curElement.pwcsName, NULL,
				 STGM_READ|STGM_SHARE_EXCLUSIVE,
				 NULL, 0, &pstgChild );
1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625

      if (hr != S_OK)
        break;

      /*
       * Check if destination storage is not a child of the source
       * storage, which will cause an infinite loop
       */
      if (pstgChild == pstgDest)
      {
	IEnumSTATSTG_Release(elements);

	return STG_E_ACCESSDENIED;
      }
1626

1627 1628 1629 1630
      /*
       * create a new storage in destination storage
       */
      hr = IStorage_CreateStorage( pstgDest, curElement.pwcsName,
1631 1632
                                   STGM_FAILIFTHERE|STGM_WRITE|STGM_SHARE_EXCLUSIVE,
				   0, 0,
1633 1634 1635 1636 1637 1638 1639 1640 1641 1642
                                   &pstgTmp );
      /*
       * if it already exist, don't create a new one use this one
       */
      if (hr == STG_E_FILEALREADYEXISTS)
      {
        hr = IStorage_OpenStorage( pstgDest, curElement.pwcsName, NULL,
                                   STGM_WRITE|STGM_SHARE_EXCLUSIVE,
                                   NULL, 0, &pstgTmp );
      }
1643

1644 1645 1646
      if (hr != S_OK)
        break;

1647

1648 1649 1650 1651 1652
      /*
       * do the copy recursively
       */
      hr = IStorage_CopyTo( pstgChild, ciidExclude, rgiidExclude,
                               snbExclude, pstgTmp );
1653

1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672
      IStorage_Release( pstgTmp );
      IStorage_Release( pstgChild );
    }
    else if (curElement.type == STGTY_STREAM)
    {
      /*
       * create a new stream in destination storage. If the stream already
       * exist, it will be deleted and a new one will be created.
       */
      hr = IStorage_CreateStream( pstgDest, curElement.pwcsName,
                                  STGM_CREATE|STGM_WRITE|STGM_SHARE_EXCLUSIVE,
                                  0, 0, &pstrTmp );

      if (hr != S_OK)
        break;

      /*
       * open child stream storage
       */
1673 1674 1675
      hr = IStorage_OpenStream( iface, curElement.pwcsName, NULL,
				STGM_READ|STGM_SHARE_EXCLUSIVE,
				0, &pstrChild );
1676 1677 1678 1679 1680

      if (hr != S_OK)
        break;

      /*
1681
       * Get the size of the source stream
1682 1683
       */
      IStream_Stat( pstrChild, &strStat, STATFLAG_NONAME );
1684 1685 1686 1687 1688

      /*
       * Set the size of the destination stream.
       */
      IStream_SetSize(pstrTmp, strStat.cbSize);
1689

1690 1691 1692 1693 1694
      /*
       * do the copy
       */
      hr = IStream_CopyTo( pstrChild, pstrTmp, strStat.cbSize,
                           NULL, NULL );
1695

1696 1697 1698 1699 1700
      IStream_Release( pstrTmp );
      IStream_Release( pstrChild );
    }
    else
    {
1701
      WARN("unknown element type: %d\n", curElement.type);
1702 1703 1704 1705 1706 1707 1708 1709
    }

  } while (hr == S_OK);

  /*
   * Clean-up
   */
  IEnumSTATSTG_Release(elements);
1710

1711
  return hr;
1712
}
1713

1714 1715 1716
/*************************************************************************
 * MoveElementTo (IStorage)
 */
1717
static HRESULT WINAPI StorageImpl_MoveElementTo(
1718
  IStorage*     iface,
1719 1720 1721 1722
  const OLECHAR *pwcsName,   /* [string][in] */
  IStorage      *pstgDest,   /* [unique][in] */
  const OLECHAR *pwcsNewName,/* [string][in] */
  DWORD           grfFlags)    /* [in] */
1723
{
1724
  FIXME("(%p %s %p %s %u): stub\n", iface,
1725 1726
         debugstr_w(pwcsName), pstgDest,
         debugstr_w(pwcsNewName), grfFlags);
1727 1728
  return E_NOTIMPL;
}
1729

1730 1731
/*************************************************************************
 * Commit (IStorage)
1732 1733 1734 1735 1736 1737 1738
 *
 * Ensures that any changes made to a storage object open in transacted mode
 * are reflected in the parent storage
 *
 * NOTES
 *  Wine doesn't implement transacted mode, which seems to be a basic
 *  optimization, so we can ignore this stub for now.
1739
 */
1740
static HRESULT WINAPI StorageImpl_Commit(
1741
  IStorage*   iface,
1742
  DWORD         grfCommitFlags)/* [in] */
1743
{
1744
  FIXME("(%p %d): stub\n", iface, grfCommitFlags);
1745
  return S_OK;
1746
}
1747

1748 1749
/*************************************************************************
 * Revert (IStorage)
1750 1751
 *
 * Discard all changes that have been made since the last commit operation
1752
 */
1753
static HRESULT WINAPI StorageImpl_Revert(
1754
  IStorage* iface)
1755
{
1756
  FIXME("(%p): stub\n", iface);
1757 1758 1759 1760
  return E_NOTIMPL;
}

/*************************************************************************
1761
 * DestroyElement (IStorage)
1762
 *
1763 1764
 * Strategy: This implementation is built this way for simplicity not for speed.
 *          I always delete the topmost element of the enumeration and adjust
1765 1766
 *          the deleted element pointer all the time.  This takes longer to
 *          do but allow to reinvoke DestroyElement whenever we encounter a
1767 1768
 *          storage object.  The optimisation resides in the usage of another
 *          enumeration strategy that would give all the leaves of a storage
1769 1770
 *          first. (postfix order)
 */
1771
static HRESULT WINAPI StorageImpl_DestroyElement(
1772
  IStorage*     iface,
1773
  const OLECHAR *pwcsName)/* [string][in] */
1774
{
1775
  StorageImpl* const This=(StorageImpl*)iface;
1776

1777 1778
  IEnumSTATSTGImpl* propertyEnumeration;
  HRESULT           hr = S_OK;
1779
  BOOL            res;
1780 1781 1782 1783
  StgProperty       propertyToDelete;
  StgProperty       parentProperty;
  ULONG             foundPropertyIndexToDelete;
  ULONG             typeOfRelation;
1784
  ULONG             parentPropertyId = 0;
1785

1786
  TRACE("(%p, %s)\n",
1787 1788
	iface, debugstr_w(pwcsName));

1789 1790 1791
  /*
   * Perform a sanity check on the parameters.
   */
1792
  if (pwcsName==NULL)
1793
    return STG_E_INVALIDPOINTER;
1794

1795 1796 1797 1798
  /*
   * Create a property enumeration to search the property with the given name
   */
  propertyEnumeration = IEnumSTATSTGImpl_Construct(
1799 1800
    This->base.ancestorStorage,
    This->base.rootPropertySetIndex);
1801

1802 1803 1804 1805 1806 1807 1808
  foundPropertyIndexToDelete = IEnumSTATSTGImpl_FindProperty(
    propertyEnumeration,
    pwcsName,
    &propertyToDelete);

  IEnumSTATSTGImpl_Destroy(propertyEnumeration);

1809
  if ( foundPropertyIndexToDelete == PROPERTY_NULL )
1810 1811 1812 1813
  {
    return STG_E_FILENOTFOUND;
  }

1814 1815 1816
  /*
   * Find the parent property of the property to delete (the one that
   * link to it).  If This->dirProperty == foundPropertyIndexToDelete,
1817
   * the parent is This. Otherwise, the parent is one of its sibling...
1818 1819
   */

1820
  /*
1821 1822
   * First, read This's StgProperty..
   */
1823
  res = StorageImpl_ReadProperty(
1824 1825
          This->base.ancestorStorage,
          This->base.rootPropertySetIndex,
1826 1827
          &parentProperty);

1828
  assert(res);
1829

1830
  /*
1831 1832 1833 1834 1835
   * Second, check to see if by any chance the actual storage (This) is not
   * the parent of the property to delete... We never know...
   */
  if ( parentProperty.dirProperty == foundPropertyIndexToDelete )
  {
1836
    /*
1837 1838 1839
     * Set data as it would have been done in the else part...
     */
    typeOfRelation   = PROPERTY_RELATION_DIR;
1840
    parentPropertyId = This->base.rootPropertySetIndex;
1841
  }
1842 1843
  else
  {
1844
    /*
1845
     * Create a property enumeration to search the parent properties, and
1846 1847 1848 1849 1850
     * delete it once done.
     */
    IEnumSTATSTGImpl* propertyEnumeration2;

    propertyEnumeration2 = IEnumSTATSTGImpl_Construct(
1851 1852
      This->base.ancestorStorage,
      This->base.rootPropertySetIndex);
1853

1854 1855 1856 1857 1858 1859 1860 1861 1862
    typeOfRelation = IEnumSTATSTGImpl_FindParentProperty(
      propertyEnumeration2,
      foundPropertyIndexToDelete,
      &parentProperty,
      &parentPropertyId);

    IEnumSTATSTGImpl_Destroy(propertyEnumeration2);
  }

1863
  if ( propertyToDelete.propertyType == PROPTYPE_STORAGE )
1864 1865
  {
    hr = deleteStorageProperty(
1866
           This,
1867 1868
           foundPropertyIndexToDelete,
           propertyToDelete);
1869
  }
1870 1871 1872
  else if ( propertyToDelete.propertyType == PROPTYPE_STREAM )
  {
    hr = deleteStreamProperty(
1873
           This,
1874 1875 1876 1877
           foundPropertyIndexToDelete,
           propertyToDelete);
  }

1878
  if (hr!=S_OK)
1879 1880 1881 1882 1883 1884 1885
    return hr;

  /*
   * Adjust the property chain
   */
  hr = adjustPropertyChain(
        This,
1886
        propertyToDelete,
1887 1888 1889 1890 1891 1892 1893 1894
        parentProperty,
        parentPropertyId,
        typeOfRelation);

  return hr;
}


1895 1896 1897 1898 1899 1900
/************************************************************************
 * StorageImpl_Stat (IStorage)
 *
 * This method will retrieve information about this storage object.
 *
 * See Windows documentation for more details on IStorage methods.
1901
 */
1902
static HRESULT WINAPI StorageImpl_Stat( IStorage* iface,
1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918
                                 STATSTG*  pstatstg,     /* [out] */
                                 DWORD     grfStatFlag)  /* [in] */
{
  StorageImpl* const This = (StorageImpl*)iface;
  HRESULT result = StorageBaseImpl_Stat( iface, pstatstg, grfStatFlag );

  if ( !FAILED(result) && ((grfStatFlag & STATFLAG_NONAME) == 0) && This->pwcsName )
  {
      CoTaskMemFree(pstatstg->pwcsName);
      pstatstg->pwcsName = CoTaskMemAlloc((lstrlenW(This->pwcsName)+1)*sizeof(WCHAR));
      strcpyW(pstatstg->pwcsName, This->pwcsName);
  }

  return result;
}

1919
/******************************************************************************
1920
 * Internal stream list handlers
1921 1922
 */

1923
void StorageBaseImpl_AddStream(StorageBaseImpl * stg, StgStreamImpl * strm)
1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934
{
  TRACE("Stream added (stg=%p strm=%p)\n", stg, strm);
  list_add_tail(&stg->strmHead,&strm->StrmListEntry);
}

void StorageBaseImpl_RemoveStream(StorageBaseImpl * stg, StgStreamImpl * strm)
{
  TRACE("Stream removed (stg=%p strm=%p)\n", stg,strm);
  list_remove(&(strm->StrmListEntry));
}

1935
static void StorageBaseImpl_DeleteAll(StorageBaseImpl * stg)
1936 1937 1938 1939 1940 1941 1942
{
  struct list *cur, *cur2;
  StgStreamImpl *strm=NULL;

  LIST_FOR_EACH_SAFE(cur, cur2, &stg->strmHead) {
    strm = LIST_ENTRY(cur,StgStreamImpl,StrmListEntry);
    TRACE("Streams deleted (stg=%p strm=%p next=%p prev=%p)\n", stg,strm,cur->next,cur->prev);
1943
    strm->parentStorage = NULL;
1944 1945 1946
    list_remove(cur);
  }
}
1947 1948


1949 1950 1951 1952 1953 1954 1955 1956
/*********************************************************************
 *
 * Internal Method
 *
 * Perform the deletion of a complete storage node
 *
 */
static HRESULT deleteStorageProperty(
1957
  StorageImpl *parentStorage,
1958 1959
  ULONG        indexOfPropertyToDelete,
  StgProperty  propertyToDelete)
1960 1961
{
  IEnumSTATSTG *elements     = 0;
1962
  IStorage   *childStorage = 0;
1963 1964 1965 1966 1967 1968 1969
  STATSTG      currentElement;
  HRESULT      hr;
  HRESULT      destroyHr = S_OK;

  /*
   * Open the storage and enumerate it
   */
1970 1971
  hr = StorageBaseImpl_OpenStorage(
        (IStorage*)parentStorage,
1972
        propertyToDelete.name,
1973
        0,
1974
        STGM_WRITE | STGM_SHARE_EXCLUSIVE,
1975 1976 1977 1978 1979 1980 1981 1982 1983
        0,
        0,
        &childStorage);

  if (hr != S_OK)
  {
    return hr;
  }

1984
  /*
1985 1986
   * Enumerate the elements
   */
1987
  IStorage_EnumElements( childStorage, 0, 0, 0, &elements);
1988 1989 1990 1991 1992 1993 1994 1995 1996

  do
  {
    /*
     * Obtain the next element
     */
    hr = IEnumSTATSTG_Next(elements, 1, &currentElement, NULL);
    if (hr==S_OK)
    {
1997
      destroyHr = StorageImpl_DestroyElement(childStorage, currentElement.pwcsName);
1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009

      CoTaskMemFree(currentElement.pwcsName);
    }

    /*
     * We need to Reset the enumeration every time because we delete elements
     * and the enumeration could be invalid
     */
    IEnumSTATSTG_Reset(elements);

  } while ((hr == S_OK) && (destroyHr == S_OK));

2010
  /*
2011
   * Invalidate the property by zeroing its name member.
2012 2013 2014
   */
  propertyToDelete.sizeOfNameString = 0;

2015
  StorageImpl_WriteProperty(parentStorage->base.ancestorStorage,
2016 2017 2018
                            indexOfPropertyToDelete,
                            &propertyToDelete);

2019
  IStorage_Release(childStorage);
2020
  IEnumSTATSTG_Release(elements);
2021

2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032
  return destroyHr;
}

/*********************************************************************
 *
 * Internal Method
 *
 * Perform the deletion of a stream node
 *
 */
static HRESULT deleteStreamProperty(
2033
  StorageImpl *parentStorage,
2034 2035 2036
  ULONG         indexOfPropertyToDelete,
  StgProperty   propertyToDelete)
{
2037
  IStream      *pis;
2038 2039 2040
  HRESULT        hr;
  ULARGE_INTEGER size;

2041 2042
  size.u.HighPart = 0;
  size.u.LowPart = 0;
2043

2044 2045 2046
  hr = StorageBaseImpl_OpenStream(
         (IStorage*)parentStorage,
         (OLECHAR*)propertyToDelete.name,
2047
         NULL,
2048
         STGM_WRITE | STGM_SHARE_EXCLUSIVE,
2049 2050
         0,
         &pis);
2051

2052 2053 2054 2055 2056
  if (hr!=S_OK)
  {
    return(hr);
  }

2057 2058 2059 2060
  /*
   * Zap the stream
   */
  hr = IStream_SetSize(pis, size);
2061 2062 2063 2064 2065 2066

  if(hr != S_OK)
  {
    return hr;
  }

2067 2068 2069 2070 2071
  /*
   * Release the stream object.
   */
  IStream_Release(pis);

2072
  /*
2073
   * Invalidate the property by zeroing its name member.
2074 2075 2076
   */
  propertyToDelete.sizeOfNameString = 0;

2077
  /*
2078 2079 2080
   * Here we should re-read the property so we get the updated pointer
   * but since we are here to zap it, I don't do it...
   */
2081
  StorageImpl_WriteProperty(
2082
    parentStorage->base.ancestorStorage,
2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096
    indexOfPropertyToDelete,
    &propertyToDelete);

  return S_OK;
}

/*********************************************************************
 *
 * Internal Method
 *
 * Finds a placeholder for the StgProperty within the Storage
 *
 */
static HRESULT findPlaceholder(
2097
  StorageImpl *storage,
2098 2099
  ULONG         propertyIndexToStore,
  ULONG         storePropertyIndex,
2100
  INT         typeOfRelation)
2101 2102 2103
{
  StgProperty storeProperty;
  HRESULT     hr = S_OK;
2104
  BOOL      res = TRUE;
2105 2106 2107 2108

  /*
   * Read the storage property
   */
2109
  res = StorageImpl_ReadProperty(
2110
          storage->base.ancestorStorage,
2111
          storePropertyIndex,
2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124
          &storeProperty);

  if(! res)
  {
    return E_FAIL;
  }

  if (typeOfRelation == PROPERTY_RELATION_PREVIOUS)
  {
    if (storeProperty.previousProperty != PROPERTY_NULL)
    {
      return findPlaceholder(
               storage,
2125
               propertyIndexToStore,
2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139
               storeProperty.previousProperty,
               typeOfRelation);
    }
    else
    {
      storeProperty.previousProperty = propertyIndexToStore;
    }
  }
  else if (typeOfRelation == PROPERTY_RELATION_NEXT)
  {
    if (storeProperty.nextProperty != PROPERTY_NULL)
    {
      return findPlaceholder(
               storage,
2140
               propertyIndexToStore,
2141 2142 2143 2144 2145 2146 2147
               storeProperty.nextProperty,
               typeOfRelation);
    }
    else
    {
      storeProperty.nextProperty = propertyIndexToStore;
    }
2148
  }
2149 2150 2151 2152 2153 2154
  else if (typeOfRelation == PROPERTY_RELATION_DIR)
  {
    if (storeProperty.dirProperty != PROPERTY_NULL)
    {
      return findPlaceholder(
               storage,
2155
               propertyIndexToStore,
2156 2157 2158 2159 2160 2161 2162 2163 2164
               storeProperty.dirProperty,
               typeOfRelation);
    }
    else
    {
      storeProperty.dirProperty = propertyIndexToStore;
    }
  }

2165
  hr = StorageImpl_WriteProperty(
2166
         storage->base.ancestorStorage,
2167
         storePropertyIndex,
2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181
         &storeProperty);

  if(! hr)
  {
    return E_FAIL;
  }

  return S_OK;
}

/*************************************************************************
 *
 * Internal Method
 *
2182
 * This method takes the previous and the next property link of a property
2183 2184
 * to be deleted and find them a place in the Storage.
 */
2185
static HRESULT adjustPropertyChain(
2186
  StorageImpl *This,
2187 2188 2189
  StgProperty   propertyToDelete,
  StgProperty   parentProperty,
  ULONG         parentPropertyId,
2190
  INT         typeOfRelation)
2191 2192
{
  ULONG   newLinkProperty        = PROPERTY_NULL;
2193
  BOOL  needToFindAPlaceholder = FALSE;
2194 2195
  ULONG   storeNode              = PROPERTY_NULL;
  ULONG   toStoreNode            = PROPERTY_NULL;
2196
  INT   relationType           = 0;
2197
  HRESULT hr                     = S_OK;
2198
  BOOL  res                    = TRUE;
2199 2200

  if (typeOfRelation == PROPERTY_RELATION_PREVIOUS)
2201
  {
2202
    if (propertyToDelete.previousProperty != PROPERTY_NULL)
2203
    {
2204
      /*
2205 2206 2207 2208
       * Set the parent previous to the property to delete previous
       */
      newLinkProperty = propertyToDelete.previousProperty;

2209
      if (propertyToDelete.nextProperty != PROPERTY_NULL)
2210 2211
      {
        /*
2212
         * We also need to find a storage for the other link, setup variables
2213
         * to do this at the end...
2214
         */
2215 2216 2217 2218 2219
        needToFindAPlaceholder = TRUE;
        storeNode              = propertyToDelete.previousProperty;
        toStoreNode            = propertyToDelete.nextProperty;
        relationType           = PROPERTY_RELATION_NEXT;
      }
2220 2221
    }
    else if (propertyToDelete.nextProperty != PROPERTY_NULL)
2222
    {
2223
      /*
2224 2225 2226 2227
       * Set the parent previous to the property to delete next
       */
      newLinkProperty = propertyToDelete.nextProperty;
    }
2228 2229

    /*
2230
     * Link it for real...
2231
     */
2232
    parentProperty.previousProperty = newLinkProperty;
2233 2234 2235

  }
  else if (typeOfRelation == PROPERTY_RELATION_NEXT)
2236
  {
2237
    if (propertyToDelete.previousProperty != PROPERTY_NULL)
2238
    {
2239
      /*
2240 2241 2242
       * Set the parent next to the property to delete next previous
       */
      newLinkProperty = propertyToDelete.previousProperty;
2243 2244

      if (propertyToDelete.nextProperty != PROPERTY_NULL)
2245 2246
      {
        /*
2247
         * We also need to find a storage for the other link, setup variables
2248
         * to do this at the end...
2249
         */
2250 2251 2252 2253 2254
        needToFindAPlaceholder = TRUE;
        storeNode              = propertyToDelete.previousProperty;
        toStoreNode            = propertyToDelete.nextProperty;
        relationType           = PROPERTY_RELATION_NEXT;
      }
2255 2256
    }
    else if (propertyToDelete.nextProperty != PROPERTY_NULL)
2257
    {
2258
      /*
2259 2260 2261 2262 2263
       * Set the parent next to the property to delete next
       */
      newLinkProperty = propertyToDelete.nextProperty;
    }

2264
    /*
2265
     * Link it for real...
2266
     */
2267
    parentProperty.nextProperty = newLinkProperty;
2268
  }
2269 2270
  else /* (typeOfRelation == PROPERTY_RELATION_DIR) */
  {
2271
    if (propertyToDelete.previousProperty != PROPERTY_NULL)
2272
    {
2273
      /*
2274 2275 2276 2277
       * Set the parent dir to the property to delete previous
       */
      newLinkProperty = propertyToDelete.previousProperty;

2278
      if (propertyToDelete.nextProperty != PROPERTY_NULL)
2279 2280
      {
        /*
2281
         * We also need to find a storage for the other link, setup variables
2282
         * to do this at the end...
2283
         */
2284 2285 2286 2287 2288
        needToFindAPlaceholder = TRUE;
        storeNode              = propertyToDelete.previousProperty;
        toStoreNode            = propertyToDelete.nextProperty;
        relationType           = PROPERTY_RELATION_NEXT;
      }
2289 2290
    }
    else if (propertyToDelete.nextProperty != PROPERTY_NULL)
2291
    {
2292
      /*
2293 2294 2295 2296 2297
       * Set the parent dir to the property to delete next
       */
      newLinkProperty = propertyToDelete.nextProperty;
    }

2298
    /*
2299
     * Link it for real...
2300
     */
2301 2302 2303
    parentProperty.dirProperty = newLinkProperty;
  }

2304 2305
  /*
   * Write back the parent property
2306
   */
2307
  res = StorageImpl_WriteProperty(
2308
          This->base.ancestorStorage,
2309 2310 2311 2312 2313 2314 2315 2316
          parentPropertyId,
          &parentProperty);
  if(! res)
  {
    return E_FAIL;
  }

  /*
2317
   * If a placeholder is required for the other link, then, find one and
2318 2319
   * get out of here...
   */
2320
  if (needToFindAPlaceholder)
2321 2322
  {
    hr = findPlaceholder(
2323 2324
           This,
           toStoreNode,
2325 2326 2327 2328 2329 2330 2331 2332
           storeNode,
           relationType);
  }

  return hr;
}


2333 2334 2335
/******************************************************************************
 * SetElementTimes (IStorage)
 */
2336
static HRESULT WINAPI StorageImpl_SetElementTimes(
2337
  IStorage*     iface,
2338 2339 2340 2341
  const OLECHAR *pwcsName,/* [string][in] */
  const FILETIME  *pctime,  /* [in] */
  const FILETIME  *patime,  /* [in] */
  const FILETIME  *pmtime)  /* [in] */
2342
{
2343 2344
  FIXME("(%s,...), stub!\n",debugstr_w(pwcsName));
  return S_OK;
2345 2346
}

2347 2348 2349
/******************************************************************************
 * SetStateBits (IStorage)
 */
2350
static HRESULT WINAPI StorageImpl_SetStateBits(
2351
  IStorage*   iface,
2352 2353
  DWORD         grfStateBits,/* [in] */
  DWORD         grfMask)     /* [in] */
2354
{
2355 2356 2357
  StorageImpl* const This = (StorageImpl*)iface;
  This->base.stateBits = (This->base.stateBits & ~grfMask) | (grfStateBits & grfMask);
  return S_OK;
2358 2359
}

2360 2361 2362
/*
 * Virtual function table for the IStorage32Impl class.
 */
2363
static const IStorageVtbl Storage32Impl_Vtbl =
2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384
{
    StorageBaseImpl_QueryInterface,
    StorageBaseImpl_AddRef,
    StorageBaseImpl_Release,
    StorageBaseImpl_CreateStream,
    StorageBaseImpl_OpenStream,
    StorageImpl_CreateStorage,
    StorageBaseImpl_OpenStorage,
    StorageImpl_CopyTo,
    StorageImpl_MoveElementTo,
    StorageImpl_Commit,
    StorageImpl_Revert,
    StorageBaseImpl_EnumElements,
    StorageImpl_DestroyElement,
    StorageBaseImpl_RenameElement,
    StorageImpl_SetElementTimes,
    StorageBaseImpl_SetClass,
    StorageImpl_SetStateBits,
    StorageImpl_Stat
};

2385
static HRESULT StorageImpl_Construct(
2386 2387
  StorageImpl* This,
  HANDLE       hFile,
2388
  LPCOLESTR    pwcsName,
2389 2390
  ILockBytes*  pLkbyt,
  DWORD        openFlags,
2391 2392
  BOOL         fileBased,
  BOOL         fileCreate)
2393 2394 2395
{
  HRESULT     hr = S_OK;
  StgProperty currentProperty;
2396
  BOOL      readSuccessful;
2397
  ULONG       currentPropertyIndex;
2398

2399 2400 2401
  if ( FAILED( validateSTGM(openFlags) ))
    return STG_E_INVALIDFLAG;

2402
  memset(This, 0, sizeof(StorageImpl));
2403

2404 2405 2406 2407 2408 2409
  /*
   * Initialize stream list
   */

  list_init(&This->base.strmHead);

2410
  /*
Alexandre Julliard's avatar
Alexandre Julliard committed
2411
   * Initialize the virtual function table.
2412
   */
2413 2414 2415
  This->base.lpVtbl = &Storage32Impl_Vtbl;
  This->base.pssVtbl = &IPropertySetStorage_Vtbl;
  This->base.v_destructor = &StorageImpl_Destroy;
2416
  This->base.openFlags = (openFlags & ~STGM_CREATE);
2417

2418
  /*
Alexandre Julliard's avatar
Alexandre Julliard committed
2419
   * This is the top-level storage so initialize the ancestor pointer
2420 2421
   * to this.
   */
2422
  This->base.ancestorStorage = This;
2423

2424 2425 2426 2427
  /*
   * Initialize the physical support of the storage.
   */
  This->hFile = hFile;
2428

2429 2430 2431 2432
  /*
   * Store copy of file path.
   */
  if(pwcsName) {
2433
      This->pwcsName = HeapAlloc(GetProcessHeap(), 0,
2434 2435 2436
                                (lstrlenW(pwcsName)+1)*sizeof(WCHAR));
      if (!This->pwcsName)
         return STG_E_INSUFFICIENTMEMORY;
2437
      strcpyW(This->pwcsName, pwcsName);
2438 2439
  }

2440 2441 2442 2443 2444
  /*
   * Initialize the big block cache.
   */
  This->bigBlockSize   = DEF_BIG_BLOCK_SIZE;
  This->smallBlockSize = DEF_SMALL_BLOCK_SIZE;
2445
  This->bigBlockFile   = BIGBLOCKFILE_Construct(hFile,
2446
                                                pLkbyt,
2447
                                                openFlags,
2448 2449
                                                This->bigBlockSize,
                                                fileBased);
2450 2451 2452

  if (This->bigBlockFile == 0)
    return E_FAIL;
2453

2454
  if (fileCreate)
2455 2456
  {
    ULARGE_INTEGER size;
2457
    BYTE bigBlockBuffer[BIG_BLOCK_SIZE];
2458 2459 2460 2461 2462 2463 2464

    /*
     * Initialize all header variables:
     * - The big block depot consists of one block and it is at block 0
     * - The properties start at block 1
     * - There is no small block depot
     */
2465 2466
    memset( This->bigBlockDepotStart,
            BLOCK_UNUSED,
2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477
            sizeof(This->bigBlockDepotStart));

    This->bigBlockDepotCount    = 1;
    This->bigBlockDepotStart[0] = 0;
    This->rootStartBlock        = 1;
    This->smallBlockDepotStart  = BLOCK_END_OF_CHAIN;
    This->bigBlockSizeBits      = DEF_BIG_BLOCK_SIZE_BITS;
    This->smallBlockSizeBits    = DEF_SMALL_BLOCK_SIZE_BITS;
    This->extBigBlockDepotStart = BLOCK_END_OF_CHAIN;
    This->extBigBlockDepotCount = 0;

2478
    StorageImpl_SaveFileHeader(This);
2479 2480 2481 2482

    /*
     * Add one block for the big block depot and one block for the properties
     */
2483 2484
    size.u.HighPart = 0;
    size.u.LowPart  = This->bigBlockSize * 3;
2485 2486 2487 2488 2489 2490 2491 2492
    BIGBLOCKFILE_SetSize(This->bigBlockFile, size);

    /*
     * Initialize the big block depot
     */
    memset(bigBlockBuffer, BLOCK_UNUSED, This->bigBlockSize);
    StorageUtl_WriteDWord(bigBlockBuffer, 0, BLOCK_SPECIAL);
    StorageUtl_WriteDWord(bigBlockBuffer, sizeof(ULONG), BLOCK_END_OF_CHAIN);
2493
    StorageImpl_WriteBigBlock(This, 0, bigBlockBuffer);
2494 2495
  }
  else
2496 2497 2498 2499
  {
    /*
     * Load the header for the file.
     */
2500 2501 2502 2503 2504 2505 2506 2507
    hr = StorageImpl_LoadFileHeader(This);

    if (FAILED(hr))
    {
      BIGBLOCKFILE_Destructor(This->bigBlockFile);

      return hr;
    }
2508 2509 2510 2511 2512 2513
  }

  /*
   * There is no block depot cached yet.
   */
  This->indexBlockDepotCached = 0xFFFFFFFF;
2514 2515 2516 2517 2518

  /*
   * Start searching for free blocks with block 0.
   */
  This->prevFreeBlock = 0;
2519

2520 2521 2522
  /*
   * Create the block chain abstractions.
   */
2523 2524 2525
  if(!(This->rootBlockChain =
       BlockChainStream_Construct(This, &This->rootStartBlock, PROPERTY_NULL)))
    return STG_E_READFAULT;
2526

2527 2528 2529 2530
  if(!(This->smallBlockDepotChain =
       BlockChainStream_Construct(This, &This->smallBlockDepotStart,
				  PROPERTY_NULL)))
    return STG_E_READFAULT;
2531 2532

  /*
2533
   * Write the root property (memory only)
2534
   */
2535
  if (fileCreate)
2536 2537 2538 2539 2540 2541
  {
    StgProperty rootProp;
    /*
     * Initialize the property chain
     */
    memset(&rootProp, 0, sizeof(rootProp));
2542 2543 2544
    MultiByteToWideChar( CP_ACP, 0, rootPropertyName, -1, rootProp.name,
                         sizeof(rootProp.name)/sizeof(WCHAR) );
    rootProp.sizeOfNameString = (strlenW(rootProp.name)+1) * sizeof(WCHAR);
2545 2546 2547 2548 2549
    rootProp.propertyType     = PROPTYPE_ROOT;
    rootProp.previousProperty = PROPERTY_NULL;
    rootProp.nextProperty     = PROPERTY_NULL;
    rootProp.dirProperty      = PROPERTY_NULL;
    rootProp.startingBlock    = BLOCK_END_OF_CHAIN;
2550 2551
    rootProp.size.u.HighPart    = 0;
    rootProp.size.u.LowPart     = 0;
2552

2553
    StorageImpl_WriteProperty(This, 0, &rootProp);
2554 2555 2556
  }

  /*
Alexandre Julliard's avatar
Alexandre Julliard committed
2557
   * Find the ID of the root in the property sets.
2558 2559
   */
  currentPropertyIndex = 0;
2560

2561 2562
  do
  {
2563
    readSuccessful = StorageImpl_ReadProperty(
2564 2565
                      This,
                      currentPropertyIndex,
2566
                      &currentProperty);
2567

2568
    if (readSuccessful)
2569 2570 2571 2572
    {
      if ( (currentProperty.sizeOfNameString != 0 ) &&
           (currentProperty.propertyType     == PROPTYPE_ROOT) )
      {
2573
        This->base.rootPropertySetIndex = currentPropertyIndex;
2574 2575 2576 2577
      }
    }

    currentPropertyIndex++;
2578

2579
  } while (readSuccessful && (This->base.rootPropertySetIndex == PROPERTY_NULL) );
2580

2581
  if (!readSuccessful)
2582 2583
  {
    /* TODO CLEANUP */
2584
    return STG_E_READFAULT;
2585 2586 2587 2588 2589
  }

  /*
   * Create the block chain abstraction for the small block root chain.
   */
2590
  if(!(This->smallBlockRootChain =
2591
       BlockChainStream_Construct(This, NULL, This->base.rootPropertySetIndex)))
2592
    return STG_E_READFAULT;
2593

2594 2595 2596
  return hr;
}

2597
static void StorageImpl_Destroy(StorageBaseImpl* iface)
2598
{
2599
  StorageImpl *This = (StorageImpl*) iface;
2600
  TRACE("(%p)\n", This);
2601

2602 2603
  StorageBaseImpl_DeleteAll(&This->base);

2604
  HeapFree(GetProcessHeap(), 0, This->pwcsName);
2605

2606 2607 2608 2609 2610
  BlockChainStream_Destroy(This->smallBlockRootChain);
  BlockChainStream_Destroy(This->rootBlockChain);
  BlockChainStream_Destroy(This->smallBlockDepotChain);

  BIGBLOCKFILE_Destructor(This->bigBlockFile);
2611
  HeapFree(GetProcessHeap(), 0, This);
2612 2613 2614 2615 2616 2617 2618 2619 2620
}

/******************************************************************************
 *      Storage32Impl_GetNextFreeBigBlock
 *
 * Returns the index of the next free big block.
 * If the big block depot is filled, this method will enlarge it.
 *
 */
2621
static ULONG StorageImpl_GetNextFreeBigBlock(
2622
  StorageImpl* This)
2623 2624
{
  ULONG depotBlockIndexPos;
2625 2626
  BYTE depotBuffer[BIG_BLOCK_SIZE];
  BOOL success;
2627 2628 2629 2630
  ULONG depotBlockOffset;
  ULONG blocksPerDepot    = This->bigBlockSize / sizeof(ULONG);
  ULONG nextBlockIndex    = BLOCK_SPECIAL;
  int   depotIndex        = 0;
2631 2632 2633 2634
  ULONG freeBlock         = BLOCK_UNUSED;

  depotIndex = This->prevFreeBlock / blocksPerDepot;
  depotBlockOffset = (This->prevFreeBlock % blocksPerDepot) * sizeof(ULONG);
2635 2636 2637 2638

  /*
   * Scan the entire big block depot until we find a block marked free
   */
2639
  while (nextBlockIndex != BLOCK_UNUSED)
2640
  {
2641
    if (depotIndex < COUNT_BBDEPOTINHEADER)
2642
    {
2643 2644
      depotBlockIndexPos = This->bigBlockDepotStart[depotIndex];

2645
      /*
2646
       * Grow the primary depot.
2647
       */
2648 2649 2650
      if (depotBlockIndexPos == BLOCK_UNUSED)
      {
        depotBlockIndexPos = depotIndex*blocksPerDepot;
2651

2652 2653 2654 2655 2656 2657
        /*
         * Add a block depot.
         */
        Storage32Impl_AddBlockDepot(This, depotBlockIndexPos);
        This->bigBlockDepotCount++;
        This->bigBlockDepotStart[depotIndex] = depotBlockIndexPos;
2658

2659 2660 2661
        /*
         * Flag it as a block depot.
         */
2662
        StorageImpl_SetNextBlockInChain(This,
2663 2664
                                          depotBlockIndexPos,
                                          BLOCK_SPECIAL);
2665

2666 2667
        /* Save new header information.
         */
2668
        StorageImpl_SaveFileHeader(This);
2669
      }
2670 2671 2672 2673
    }
    else
    {
      depotBlockIndexPos = Storage32Impl_GetExtDepotBlock(This, depotIndex);
2674

2675 2676 2677 2678 2679 2680 2681 2682
      if (depotBlockIndexPos == BLOCK_UNUSED)
      {
        /*
         * Grow the extended depot.
         */
        ULONG extIndex       = BLOCK_UNUSED;
        ULONG numExtBlocks   = depotIndex - COUNT_BBDEPOTINHEADER;
        ULONG extBlockOffset = numExtBlocks % (blocksPerDepot - 1);
2683

2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703
        if (extBlockOffset == 0)
        {
          /* We need an extended block.
           */
          extIndex = Storage32Impl_AddExtBlockDepot(This);
          This->extBigBlockDepotCount++;
          depotBlockIndexPos = extIndex + 1;
        }
        else
          depotBlockIndexPos = depotIndex * blocksPerDepot;

        /*
         * Add a block depot and mark it in the extended block.
         */
        Storage32Impl_AddBlockDepot(This, depotBlockIndexPos);
        This->bigBlockDepotCount++;
        Storage32Impl_SetExtDepotBlock(This, depotIndex, depotBlockIndexPos);

        /* Flag the block depot.
         */
2704
        StorageImpl_SetNextBlockInChain(This,
2705 2706 2707 2708 2709 2710
                                          depotBlockIndexPos,
                                          BLOCK_SPECIAL);

        /* If necessary, flag the extended depot block.
         */
        if (extIndex != BLOCK_UNUSED)
2711
          StorageImpl_SetNextBlockInChain(This, extIndex, BLOCK_EXTBBDEPOT);
2712 2713 2714

        /* Save header information.
         */
2715
        StorageImpl_SaveFileHeader(This);
2716
      }
2717 2718
    }

2719
    success = StorageImpl_ReadBigBlock(This, depotBlockIndexPos, depotBuffer);
2720

2721
    if (success)
2722
    {
2723
      while ( ( (depotBlockOffset/sizeof(ULONG) ) < blocksPerDepot) &&
2724 2725 2726 2727
              ( nextBlockIndex != BLOCK_UNUSED))
      {
        StorageUtl_ReadDWord(depotBuffer, depotBlockOffset, &nextBlockIndex);

2728 2729 2730 2731 2732
        if (nextBlockIndex == BLOCK_UNUSED)
        {
          freeBlock = (depotIndex * blocksPerDepot) +
                      (depotBlockOffset/sizeof(ULONG));
        }
2733 2734 2735 2736 2737 2738

        depotBlockOffset += sizeof(ULONG);
      }
    }

    depotIndex++;
2739
    depotBlockOffset = 0;
2740 2741
  }

2742 2743 2744 2745 2746
  /*
   * make sure that the block physically exists before using it
   */
  BIGBLOCKFILE_EnsureExists(This->bigBlockFile, freeBlock);

2747 2748 2749
  This->prevFreeBlock = freeBlock;

  return freeBlock;
2750 2751
}

2752 2753 2754 2755 2756 2757
/******************************************************************************
 *      Storage32Impl_AddBlockDepot
 *
 * This will create a depot block, essentially it is a block initialized
 * to BLOCK_UNUSEDs.
 */
2758
static void Storage32Impl_AddBlockDepot(StorageImpl* This, ULONG blockIndex)
2759
{
2760
  BYTE blockBuffer[BIG_BLOCK_SIZE];
2761 2762 2763 2764 2765

  /*
   * Initialize blocks as free
   */
  memset(blockBuffer, BLOCK_UNUSED, This->bigBlockSize);
2766
  StorageImpl_WriteBigBlock(This, blockIndex, blockBuffer);
2767 2768 2769 2770 2771 2772 2773 2774 2775
}

/******************************************************************************
 *      Storage32Impl_GetExtDepotBlock
 *
 * Returns the index of the block that corresponds to the specified depot
 * index. This method is only for depot indexes equal or greater than
 * COUNT_BBDEPOTINHEADER.
 */
2776
static ULONG Storage32Impl_GetExtDepotBlock(StorageImpl* This, ULONG depotIndex)
2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796
{
  ULONG depotBlocksPerExtBlock = (This->bigBlockSize / sizeof(ULONG)) - 1;
  ULONG numExtBlocks           = depotIndex - COUNT_BBDEPOTINHEADER;
  ULONG extBlockCount          = numExtBlocks / depotBlocksPerExtBlock;
  ULONG extBlockOffset         = numExtBlocks % depotBlocksPerExtBlock;
  ULONG blockIndex             = BLOCK_UNUSED;
  ULONG extBlockIndex          = This->extBigBlockDepotStart;

  assert(depotIndex >= COUNT_BBDEPOTINHEADER);

  if (This->extBigBlockDepotStart == BLOCK_END_OF_CHAIN)
    return BLOCK_UNUSED;

  while (extBlockCount > 0)
  {
    extBlockIndex = Storage32Impl_GetNextExtendedBlock(This, extBlockIndex);
    extBlockCount--;
  }

  if (extBlockIndex != BLOCK_UNUSED)
2797 2798
    StorageImpl_ReadDWordFromBigBlock(This, extBlockIndex,
                        extBlockOffset * sizeof(ULONG), &blockIndex);
2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809

  return blockIndex;
}

/******************************************************************************
 *      Storage32Impl_SetExtDepotBlock
 *
 * Associates the specified block index to the specified depot index.
 * This method is only for depot indexes equal or greater than
 * COUNT_BBDEPOTINHEADER.
 */
2810
static void Storage32Impl_SetExtDepotBlock(StorageImpl* This, ULONG depotIndex, ULONG blockIndex)
2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827
{
  ULONG depotBlocksPerExtBlock = (This->bigBlockSize / sizeof(ULONG)) - 1;
  ULONG numExtBlocks           = depotIndex - COUNT_BBDEPOTINHEADER;
  ULONG extBlockCount          = numExtBlocks / depotBlocksPerExtBlock;
  ULONG extBlockOffset         = numExtBlocks % depotBlocksPerExtBlock;
  ULONG extBlockIndex          = This->extBigBlockDepotStart;

  assert(depotIndex >= COUNT_BBDEPOTINHEADER);

  while (extBlockCount > 0)
  {
    extBlockIndex = Storage32Impl_GetNextExtendedBlock(This, extBlockIndex);
    extBlockCount--;
  }

  if (extBlockIndex != BLOCK_UNUSED)
  {
2828 2829 2830
    StorageImpl_WriteDWordToBigBlock(This, extBlockIndex,
                        extBlockOffset * sizeof(ULONG),
                        blockIndex);
2831 2832 2833 2834 2835 2836 2837 2838
  }
}

/******************************************************************************
 *      Storage32Impl_AddExtBlockDepot
 *
 * Creates an extended depot block.
 */
2839
static ULONG Storage32Impl_AddExtBlockDepot(StorageImpl* This)
2840 2841 2842
{
  ULONG numExtBlocks           = This->extBigBlockDepotCount;
  ULONG nextExtBlock           = This->extBigBlockDepotStart;
2843
  BYTE  depotBuffer[BIG_BLOCK_SIZE];
2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860
  ULONG index                  = BLOCK_UNUSED;
  ULONG nextBlockOffset        = This->bigBlockSize - sizeof(ULONG);
  ULONG blocksPerDepotBlock    = This->bigBlockSize / sizeof(ULONG);
  ULONG depotBlocksPerExtBlock = blocksPerDepotBlock - 1;

  index = (COUNT_BBDEPOTINHEADER + (numExtBlocks * depotBlocksPerExtBlock)) *
          blocksPerDepotBlock;

  if ((numExtBlocks == 0) && (nextExtBlock == BLOCK_END_OF_CHAIN))
  {
    /*
     * The first extended block.
     */
    This->extBigBlockDepotStart = index;
  }
  else
  {
2861
    unsigned int i;
2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872
    /*
     * Follow the chain to the last one.
     */
    for (i = 0; i < (numExtBlocks - 1); i++)
    {
      nextExtBlock = Storage32Impl_GetNextExtendedBlock(This, nextExtBlock);
    }

    /*
     * Add the new extended block to the chain.
     */
2873 2874
    StorageImpl_WriteDWordToBigBlock(This, nextExtBlock, nextBlockOffset,
                                     index);
2875 2876 2877 2878 2879 2880
  }

  /*
   * Initialize this block.
   */
  memset(depotBuffer, BLOCK_UNUSED, This->bigBlockSize);
2881
  StorageImpl_WriteBigBlock(This, index, depotBuffer);
2882 2883 2884 2885

  return index;
}

2886 2887 2888 2889 2890
/******************************************************************************
 *      Storage32Impl_FreeBigBlock
 *
 * This method will flag the specified block as free in the big block depot.
 */
2891
static void StorageImpl_FreeBigBlock(
2892
  StorageImpl* This,
2893 2894
  ULONG          blockIndex)
{
2895
  StorageImpl_SetNextBlockInChain(This, blockIndex, BLOCK_UNUSED);
2896 2897 2898

  if (blockIndex < This->prevFreeBlock)
    This->prevFreeBlock = blockIndex;
2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909
}

/************************************************************************
 * Storage32Impl_GetNextBlockInChain
 *
 * This method will retrieve the block index of the next big block in
 * in the chain.
 *
 * Params:  This       - Pointer to the Storage object.
 *          blockIndex - Index of the block to retrieve the chain
 *                       for.
2910
 *          nextBlockIndex - receives the return value.
2911 2912 2913 2914 2915 2916 2917 2918 2919
 *
 * Returns: This method returns the index of the next block in the chain.
 *          It will return the constants:
 *              BLOCK_SPECIAL - If the block given was not part of a
 *                              chain.
 *              BLOCK_END_OF_CHAIN - If the block given was the last in
 *                                   a chain.
 *              BLOCK_UNUSED - If the block given was not past of a chain
 *                             and is available.
2920 2921 2922
 *              BLOCK_EXTBBDEPOT - This block is part of the extended
 *                                 big block depot.
 *
2923
 * See Windows documentation for more details on IStorage methods.
2924
 */
2925
static HRESULT StorageImpl_GetNextBlockInChain(
2926
  StorageImpl* This,
2927 2928
  ULONG        blockIndex,
  ULONG*       nextBlockIndex)
2929 2930 2931 2932
{
  ULONG offsetInDepot    = blockIndex * sizeof (ULONG);
  ULONG depotBlockCount  = offsetInDepot / This->bigBlockSize;
  ULONG depotBlockOffset = offsetInDepot % This->bigBlockSize;
2933 2934
  BYTE depotBuffer[BIG_BLOCK_SIZE];
  BOOL success;
2935
  ULONG depotBlockIndexPos;
2936
  int index;
2937

2938 2939 2940 2941
  *nextBlockIndex   = BLOCK_SPECIAL;

  if(depotBlockCount >= This->bigBlockDepotCount)
  {
2942
    WARN("depotBlockCount %d, bigBlockDepotCount %d\n", depotBlockCount,
2943 2944 2945
	 This->bigBlockDepotCount);
    return STG_E_READFAULT;
  }
2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965

  /*
   * Cache the currently accessed depot block.
   */
  if (depotBlockCount != This->indexBlockDepotCached)
  {
    This->indexBlockDepotCached = depotBlockCount;

    if (depotBlockCount < COUNT_BBDEPOTINHEADER)
    {
      depotBlockIndexPos = This->bigBlockDepotStart[depotBlockCount];
    }
    else
    {
      /*
       * We have to look in the extended depot.
       */
      depotBlockIndexPos = Storage32Impl_GetExtDepotBlock(This, depotBlockCount);
    }

2966
    success = StorageImpl_ReadBigBlock(This, depotBlockIndexPos, depotBuffer);
2967

2968
    if (!success)
2969
      return STG_E_READFAULT;
2970

2971 2972 2973 2974
    for (index = 0; index < NUM_BLOCKS_PER_DEPOT_BLOCK; index++)
    {
      StorageUtl_ReadDWord(depotBuffer, index*sizeof(ULONG), nextBlockIndex);
      This->blockDepotCached[index] = *nextBlockIndex;
2975 2976 2977
    }
  }

2978
  *nextBlockIndex = This->blockDepotCached[depotBlockOffset/sizeof(ULONG)];
2979

2980
  return S_OK;
2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997
}

/******************************************************************************
 *      Storage32Impl_GetNextExtendedBlock
 *
 * Given an extended block this method will return the next extended block.
 *
 * NOTES:
 * The last ULONG of an extended block is the block index of the next
 * extended block. Extended blocks are marked as BLOCK_EXTBBDEPOT in the
 * depot.
 *
 * Return values:
 *    - The index of the next extended block
 *    - BLOCK_UNUSED: there is no next extended block.
 *    - Any other return values denotes failure.
 */
2998
static ULONG Storage32Impl_GetNextExtendedBlock(StorageImpl* This, ULONG blockIndex)
2999 3000 3001
{
  ULONG nextBlockIndex   = BLOCK_SPECIAL;
  ULONG depotBlockOffset = This->bigBlockSize - sizeof(ULONG);
3002

3003 3004
  StorageImpl_ReadDWordFromBigBlock(This, blockIndex, depotBlockOffset,
                        &nextBlockIndex);
3005

3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022
  return nextBlockIndex;
}

/******************************************************************************
 *      Storage32Impl_SetNextBlockInChain
 *
 * This method will write the index of the specified block's next block
 * in the big block depot.
 *
 * For example: to create the chain 3 -> 1 -> 7 -> End of Chain
 *              do the following
 *
 * Storage32Impl_SetNextBlockInChain(This, 3, 1);
 * Storage32Impl_SetNextBlockInChain(This, 1, 7);
 * Storage32Impl_SetNextBlockInChain(This, 7, BLOCK_END_OF_CHAIN);
 *
 */
3023
static void StorageImpl_SetNextBlockInChain(
3024
          StorageImpl* This,
3025 3026 3027 3028 3029 3030 3031 3032 3033
          ULONG          blockIndex,
          ULONG          nextBlock)
{
  ULONG offsetInDepot    = blockIndex * sizeof (ULONG);
  ULONG depotBlockCount  = offsetInDepot / This->bigBlockSize;
  ULONG depotBlockOffset = offsetInDepot % This->bigBlockSize;
  ULONG depotBlockIndexPos;

  assert(depotBlockCount < This->bigBlockDepotCount);
Thuy Nguyen's avatar
Thuy Nguyen committed
3034
  assert(blockIndex != nextBlock);
3035

3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046
  if (depotBlockCount < COUNT_BBDEPOTINHEADER)
  {
    depotBlockIndexPos = This->bigBlockDepotStart[depotBlockCount];
  }
  else
  {
    /*
     * We have to look in the extended depot.
     */
    depotBlockIndexPos = Storage32Impl_GetExtDepotBlock(This, depotBlockCount);
  }
3047

3048 3049
  StorageImpl_WriteDWordToBigBlock(This, depotBlockIndexPos, depotBlockOffset,
                        nextBlock);
3050 3051 3052 3053 3054 3055 3056
  /*
   * Update the cached block depot, if necessary.
   */
  if (depotBlockCount == This->indexBlockDepotCached)
  {
    This->blockDepotCached[depotBlockOffset/sizeof(ULONG)] = nextBlock;
  }
3057 3058 3059 3060 3061 3062 3063
}

/******************************************************************************
 *      Storage32Impl_LoadFileHeader
 *
 * This method will read in the file header, i.e. big block index -1.
 */
3064
static HRESULT StorageImpl_LoadFileHeader(
3065
          StorageImpl* This)
3066 3067
{
  HRESULT hr = STG_E_FILENOTFOUND;
3068 3069
  BYTE    headerBigBlock[BIG_BLOCK_SIZE];
  BOOL    success;
3070 3071
  int     index;

3072
  TRACE("\n");
3073 3074 3075
  /*
   * Get a pointer to the big block of data containing the header.
   */
3076
  success = StorageImpl_ReadBigBlock(This, -1, headerBigBlock);
3077 3078 3079 3080

  /*
   * Extract the information from the header.
   */
3081
  if (success)
3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097
  {
    /*
     * Check for the "magic number" signature and return an error if it is not
     * found.
     */
    if (memcmp(headerBigBlock, STORAGE_oldmagic, sizeof(STORAGE_oldmagic))==0)
    {
      return STG_E_OLDFORMAT;
    }

    if (memcmp(headerBigBlock, STORAGE_magic, sizeof(STORAGE_magic))!=0)
    {
      return STG_E_INVALIDHEADER;
    }

    StorageUtl_ReadWord(
3098 3099
      headerBigBlock,
      OFFSET_BIGBLOCKSIZEBITS,
3100 3101 3102
      &This->bigBlockSizeBits);

    StorageUtl_ReadWord(
3103 3104
      headerBigBlock,
      OFFSET_SMALLBLOCKSIZEBITS,
3105 3106 3107
      &This->smallBlockSizeBits);

    StorageUtl_ReadDWord(
3108 3109
      headerBigBlock,
      OFFSET_BBDEPOTCOUNT,
3110 3111 3112
      &This->bigBlockDepotCount);

    StorageUtl_ReadDWord(
3113 3114
      headerBigBlock,
      OFFSET_ROOTSTARTBLOCK,
3115 3116 3117
      &This->rootStartBlock);

    StorageUtl_ReadDWord(
3118 3119
      headerBigBlock,
      OFFSET_SBDEPOTSTART,
3120 3121
      &This->smallBlockDepotStart);

3122 3123 3124
    StorageUtl_ReadDWord(
      headerBigBlock,
      OFFSET_EXTBBDEPOTSTART,
3125 3126 3127
      &This->extBigBlockDepotStart);

    StorageUtl_ReadDWord(
3128 3129
      headerBigBlock,
      OFFSET_EXTBBDEPOTCOUNT,
3130
      &This->extBigBlockDepotCount);
3131

3132 3133 3134
    for (index = 0; index < COUNT_BBDEPOTINHEADER; index ++)
    {
      StorageUtl_ReadDWord(
3135
        headerBigBlock,
3136 3137 3138
        OFFSET_BBDEPOTSTART + (sizeof(ULONG)*index),
        &(This->bigBlockDepotStart[index]));
    }
3139

3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152
    /*
     * Make the bitwise arithmetic to get the size of the blocks in bytes.
     */
    if ((1 << 2) == 4)
    {
      This->bigBlockSize   = 0x000000001 << (DWORD)This->bigBlockSizeBits;
      This->smallBlockSize = 0x000000001 << (DWORD)This->smallBlockSizeBits;
    }
    else
    {
      This->bigBlockSize   = 0x000000001 >> (DWORD)This->bigBlockSizeBits;
      This->smallBlockSize = 0x000000001 >> (DWORD)This->smallBlockSizeBits;
    }
3153

3154
    /*
3155
     * Right now, the code is making some assumptions about the size of the
3156 3157
     * blocks, just make sure they are what we're expecting.
     */
Alexandre Julliard's avatar
Alexandre Julliard committed
3158 3159 3160 3161 3162 3163 3164 3165
    if (This->bigBlockSize != DEF_BIG_BLOCK_SIZE ||
	This->smallBlockSize != DEF_SMALL_BLOCK_SIZE)
    {
	WARN("Broken OLE storage file\n");
	hr = STG_E_INVALIDHEADER;
    }
    else
	hr = S_OK;
3166
  }
3167

3168 3169 3170 3171 3172 3173 3174 3175
  return hr;
}

/******************************************************************************
 *      Storage32Impl_SaveFileHeader
 *
 * This method will save to the file the header, i.e. big block -1.
 */
3176
static void StorageImpl_SaveFileHeader(
3177
          StorageImpl* This)
3178 3179 3180
{
  BYTE   headerBigBlock[BIG_BLOCK_SIZE];
  int    index;
3181
  BOOL success;
3182 3183 3184 3185

  /*
   * Get a pointer to the big block of data containing the header.
   */
3186
  success = StorageImpl_ReadBigBlock(This, -1, headerBigBlock);
3187

3188 3189 3190 3191 3192 3193 3194 3195 3196
  /*
   * If the block read failed, the file is probably new.
   */
  if (!success)
  {
    /*
     * Initialize for all unknown fields.
     */
    memset(headerBigBlock, 0, BIG_BLOCK_SIZE);
3197

3198 3199 3200 3201
    /*
     * Initialize the magic number.
     */
    memcpy(headerBigBlock, STORAGE_magic, sizeof(STORAGE_magic));
3202

3203 3204 3205 3206 3207 3208 3209 3210
    /*
     * And a bunch of things we don't know what they mean
     */
    StorageUtl_WriteWord(headerBigBlock,  0x18, 0x3b);
    StorageUtl_WriteWord(headerBigBlock,  0x1a, 0x3);
    StorageUtl_WriteWord(headerBigBlock,  0x1c, (WORD)-2);
    StorageUtl_WriteDWord(headerBigBlock, 0x38, (DWORD)0x1000);
  }
3211

3212 3213 3214
  /*
   * Write the information to the header.
   */
3215 3216 3217 3218
  StorageUtl_WriteWord(
    headerBigBlock,
    OFFSET_BIGBLOCKSIZEBITS,
    This->bigBlockSizeBits);
3219

3220 3221 3222 3223
  StorageUtl_WriteWord(
    headerBigBlock,
    OFFSET_SMALLBLOCKSIZEBITS,
    This->smallBlockSizeBits);
3224

3225 3226 3227 3228
  StorageUtl_WriteDWord(
    headerBigBlock,
    OFFSET_BBDEPOTCOUNT,
    This->bigBlockDepotCount);
3229

3230 3231 3232 3233
  StorageUtl_WriteDWord(
    headerBigBlock,
    OFFSET_ROOTSTARTBLOCK,
    This->rootStartBlock);
3234

3235 3236 3237 3238
  StorageUtl_WriteDWord(
    headerBigBlock,
    OFFSET_SBDEPOTSTART,
    This->smallBlockDepotStart);
3239

3240 3241 3242 3243 3244 3245 3246 3247 3248 3249
  StorageUtl_WriteDWord(
    headerBigBlock,
    OFFSET_SBDEPOTCOUNT,
    This->smallBlockDepotChain ?
     BlockChainStream_GetCount(This->smallBlockDepotChain) : 0);

  StorageUtl_WriteDWord(
    headerBigBlock,
    OFFSET_EXTBBDEPOTSTART,
    This->extBigBlockDepotStart);
3250

3251 3252 3253 3254 3255 3256 3257
  StorageUtl_WriteDWord(
    headerBigBlock,
    OFFSET_EXTBBDEPOTCOUNT,
    This->extBigBlockDepotCount);

  for (index = 0; index < COUNT_BBDEPOTINHEADER; index ++)
  {
3258
    StorageUtl_WriteDWord(
3259
      headerBigBlock,
3260 3261
      OFFSET_BBDEPOTSTART + (sizeof(ULONG)*index),
      (This->bigBlockDepotStart[index]));
3262
  }
3263

3264 3265 3266
  /*
   * Write the big block back to the file.
   */
3267
  StorageImpl_WriteBigBlock(This, -1, headerBigBlock);
3268 3269 3270 3271 3272 3273 3274
}

/******************************************************************************
 *      Storage32Impl_ReadProperty
 *
 * This method will read the specified property from the property chain.
 */
3275 3276
BOOL StorageImpl_ReadProperty(
  StorageImpl* This,
3277 3278 3279 3280 3281
  ULONG          index,
  StgProperty*   buffer)
{
  BYTE           currentProperty[PROPSET_BLOCK_SIZE];
  ULARGE_INTEGER offsetInPropSet;
3282
  HRESULT        readRes;
3283
  ULONG          bytesRead;
Thuy Nguyen's avatar
Thuy Nguyen committed
3284

3285 3286
  offsetInPropSet.u.HighPart = 0;
  offsetInPropSet.u.LowPart  = index * PROPSET_BLOCK_SIZE;
3287

3288
  readRes = BlockChainStream_ReadAt(
3289 3290 3291 3292 3293
                    This->rootBlockChain,
                    offsetInPropSet,
                    PROPSET_BLOCK_SIZE,
                    currentProperty,
                    &bytesRead);
Alexandre Julliard's avatar
Alexandre Julliard committed
3294

3295
  if (SUCCEEDED(readRes))
3296
  {
Alexandre Julliard's avatar
Alexandre Julliard committed
3297
    /* replace the name of root entry (often "Root Entry") by the file name */
3298
    WCHAR *propName = (index == This->base.rootPropertySetIndex) ?
Alexandre Julliard's avatar
Alexandre Julliard committed
3299 3300
	    		This->filename : (WCHAR *)currentProperty+OFFSET_PS_NAME;

3301 3302
    memset(buffer->name, 0, sizeof(buffer->name));
    memcpy(
3303 3304
      buffer->name,
      propName,
3305
      PROPERTY_NAME_BUFFER_LEN );
Alexandre Julliard's avatar
Alexandre Julliard committed
3306
    TRACE("storage name: %s\n", debugstr_w(buffer->name));
3307 3308

    memcpy(&buffer->propertyType, currentProperty + OFFSET_PS_PROPERTYTYPE, 1);
3309

3310
    StorageUtl_ReadWord(
3311 3312
      currentProperty,
      OFFSET_PS_NAMELENGTH,
3313 3314 3315
      &buffer->sizeOfNameString);

    StorageUtl_ReadDWord(
3316 3317
      currentProperty,
      OFFSET_PS_PREVIOUSPROP,
3318 3319 3320
      &buffer->previousProperty);

    StorageUtl_ReadDWord(
3321 3322
      currentProperty,
      OFFSET_PS_NEXTPROP,
3323 3324 3325
      &buffer->nextProperty);

    StorageUtl_ReadDWord(
3326 3327
      currentProperty,
      OFFSET_PS_DIRPROP,
3328 3329 3330
      &buffer->dirProperty);

    StorageUtl_ReadGUID(
3331 3332
      currentProperty,
      OFFSET_PS_GUID,
3333 3334 3335
      &buffer->propertyUniqueID);

    StorageUtl_ReadDWord(
3336 3337
      currentProperty,
      OFFSET_PS_TSS1,
3338 3339 3340
      &buffer->timeStampS1);

    StorageUtl_ReadDWord(
3341 3342
      currentProperty,
      OFFSET_PS_TSD1,
3343 3344 3345
      &buffer->timeStampD1);

    StorageUtl_ReadDWord(
3346 3347
      currentProperty,
      OFFSET_PS_TSS2,
3348 3349 3350
      &buffer->timeStampS2);

    StorageUtl_ReadDWord(
3351 3352
      currentProperty,
      OFFSET_PS_TSD2,
3353 3354 3355
      &buffer->timeStampD2);

    StorageUtl_ReadDWord(
3356 3357
      currentProperty,
      OFFSET_PS_STARTBLOCK,
3358 3359 3360
      &buffer->startingBlock);

    StorageUtl_ReadDWord(
3361 3362
      currentProperty,
      OFFSET_PS_SIZE,
3363
      &buffer->size.u.LowPart);
3364

3365
    buffer->size.u.HighPart = 0;
3366 3367
  }

3368
  return SUCCEEDED(readRes) ? TRUE : FALSE;
3369 3370 3371 3372 3373
}

/*********************************************************************
 * Write the specified property into the property chain
 */
3374
BOOL StorageImpl_WriteProperty(
3375 3376 3377
  StorageImpl*          This,
  ULONG                 index,
  const StgProperty*    buffer)
3378 3379 3380
{
  BYTE           currentProperty[PROPSET_BLOCK_SIZE];
  ULARGE_INTEGER offsetInPropSet;
3381
  HRESULT        writeRes;
3382 3383
  ULONG          bytesWritten;

3384 3385
  offsetInPropSet.u.HighPart = 0;
  offsetInPropSet.u.LowPart  = index * PROPSET_BLOCK_SIZE;
3386 3387 3388 3389

  memset(currentProperty, 0, PROPSET_BLOCK_SIZE);

  memcpy(
3390 3391
    currentProperty + OFFSET_PS_NAME,
    buffer->name,
3392 3393 3394 3395 3396
    PROPERTY_NAME_BUFFER_LEN );

  memcpy(currentProperty + OFFSET_PS_PROPERTYTYPE, &buffer->propertyType, 1);

  StorageUtl_WriteWord(
3397 3398
    currentProperty,
      OFFSET_PS_NAMELENGTH,
3399 3400 3401
      buffer->sizeOfNameString);

  StorageUtl_WriteDWord(
3402 3403
    currentProperty,
      OFFSET_PS_PREVIOUSPROP,
3404 3405 3406
      buffer->previousProperty);

  StorageUtl_WriteDWord(
3407 3408
    currentProperty,
      OFFSET_PS_NEXTPROP,
3409 3410 3411
      buffer->nextProperty);

  StorageUtl_WriteDWord(
3412 3413
    currentProperty,
      OFFSET_PS_DIRPROP,
3414 3415 3416
      buffer->dirProperty);

  StorageUtl_WriteGUID(
3417 3418
    currentProperty,
      OFFSET_PS_GUID,
3419 3420 3421
      &buffer->propertyUniqueID);

  StorageUtl_WriteDWord(
3422 3423
    currentProperty,
      OFFSET_PS_TSS1,
3424 3425 3426
      buffer->timeStampS1);

  StorageUtl_WriteDWord(
3427 3428
    currentProperty,
      OFFSET_PS_TSD1,
3429 3430 3431
      buffer->timeStampD1);

  StorageUtl_WriteDWord(
3432 3433
    currentProperty,
      OFFSET_PS_TSS2,
3434 3435 3436
      buffer->timeStampS2);

  StorageUtl_WriteDWord(
3437 3438
    currentProperty,
      OFFSET_PS_TSD2,
3439 3440 3441
      buffer->timeStampD2);

  StorageUtl_WriteDWord(
3442 3443
    currentProperty,
      OFFSET_PS_STARTBLOCK,
3444 3445 3446
      buffer->startingBlock);

  StorageUtl_WriteDWord(
3447 3448
    currentProperty,
      OFFSET_PS_SIZE,
3449
      buffer->size.u.LowPart);
3450

3451 3452 3453 3454 3455 3456
  writeRes = BlockChainStream_WriteAt(This->rootBlockChain,
                                      offsetInPropSet,
                                      PROPSET_BLOCK_SIZE,
                                      currentProperty,
                                      &bytesWritten);
  return SUCCEEDED(writeRes) ? TRUE : FALSE;
3457 3458
}

3459
static BOOL StorageImpl_ReadBigBlock(
3460
  StorageImpl* This,
3461 3462 3463
  ULONG          blockIndex,
  void*          buffer)
{
3464 3465
  ULARGE_INTEGER ulOffset;
  DWORD  read;
3466

3467 3468
  ulOffset.u.HighPart = 0;
  ulOffset.u.LowPart = BLOCK_GetBigBlockOffset(blockIndex);
3469

3470 3471 3472
  StorageImpl_ReadAt(This, ulOffset, buffer, This->bigBlockSize, &read);
  return (read == This->bigBlockSize);
}
3473

3474 3475 3476 3477 3478 3479 3480 3481 3482
static BOOL StorageImpl_ReadDWordFromBigBlock(
  StorageImpl*  This,
  ULONG         blockIndex,
  ULONG         offset,
  DWORD*        value)
{
  ULARGE_INTEGER ulOffset;
  DWORD  read;
  DWORD  tmp;
3483

3484 3485 3486
  ulOffset.u.HighPart = 0;
  ulOffset.u.LowPart = BLOCK_GetBigBlockOffset(blockIndex);
  ulOffset.u.LowPart += offset;
3487

3488 3489 3490
  StorageImpl_ReadAt(This, ulOffset, &tmp, sizeof(DWORD), &read);
  *value = le32toh(tmp);
  return (read == sizeof(DWORD));
3491 3492
}

3493
static BOOL StorageImpl_WriteBigBlock(
3494 3495 3496
  StorageImpl*  This,
  ULONG         blockIndex,
  const void*   buffer)
3497
{
3498 3499
  ULARGE_INTEGER ulOffset;
  DWORD  wrote;
3500

3501 3502
  ulOffset.u.HighPart = 0;
  ulOffset.u.LowPart = BLOCK_GetBigBlockOffset(blockIndex);
3503

3504 3505
  StorageImpl_WriteAt(This, ulOffset, buffer, This->bigBlockSize, &wrote);
  return (wrote == This->bigBlockSize);
3506 3507
}

3508
static BOOL StorageImpl_WriteDWordToBigBlock(
3509
  StorageImpl* This,
3510 3511 3512
  ULONG         blockIndex,
  ULONG         offset,
  DWORD         value)
3513
{
3514 3515
  ULARGE_INTEGER ulOffset;
  DWORD  wrote;
3516

3517 3518 3519
  ulOffset.u.HighPart = 0;
  ulOffset.u.LowPart = BLOCK_GetBigBlockOffset(blockIndex);
  ulOffset.u.LowPart += offset;
3520

3521 3522 3523
  value = htole32(value);
  StorageImpl_WriteAt(This, ulOffset, &value, sizeof(DWORD), &wrote);
  return (wrote == sizeof(DWORD));
3524 3525
}

3526 3527 3528 3529 3530 3531 3532
/******************************************************************************
 *              Storage32Impl_SmallBlocksToBigBlocks
 *
 * This method will convert a small block chain to a big block chain.
 * The small block chain will be destroyed.
 */
BlockChainStream* Storage32Impl_SmallBlocksToBigBlocks(
3533
                      StorageImpl* This,
3534 3535 3536 3537
                      SmallBlockChainStream** ppsbChain)
{
  ULONG bbHeadOfChain = BLOCK_END_OF_CHAIN;
  ULARGE_INTEGER size, offset;
3538 3539
  ULONG cbRead, cbWritten;
  ULARGE_INTEGER cbTotalRead;
3540
  ULONG propertyIndex;
3541
  HRESULT resWrite = S_OK;
3542
  HRESULT resRead;
3543
  StgProperty chainProperty;
3544
  BYTE *buffer;
3545 3546 3547 3548 3549 3550 3551 3552 3553 3554 3555
  BlockChainStream *bbTempChain = NULL;
  BlockChainStream *bigBlockChain = NULL;

  /*
   * Create a temporary big block chain that doesn't have
   * an associated property. This temporary chain will be
   * used to copy data from small blocks to big blocks.
   */
  bbTempChain = BlockChainStream_Construct(This,
                                           &bbHeadOfChain,
                                           PROPERTY_NULL);
3556
  if(!bbTempChain) return NULL;
3557 3558 3559 3560 3561 3562 3563 3564 3565 3566
  /*
   * Grow the big block chain.
   */
  size = SmallBlockChainStream_GetSize(*ppsbChain);
  BlockChainStream_SetSize(bbTempChain, size);

  /*
   * Copy the contents of the small block chain to the big block chain
   * by small block size increments.
   */
3567 3568
  offset.u.LowPart = 0;
  offset.u.HighPart = 0;
3569
  cbTotalRead.QuadPart = 0;
3570

3571
  buffer = HeapAlloc(GetProcessHeap(),0,DEF_SMALL_BLOCK_SIZE);
3572 3573
  do
  {
3574 3575
    resRead = SmallBlockChainStream_ReadAt(*ppsbChain,
                                           offset,
3576
                                           This->smallBlockSize,
3577 3578 3579
                                           buffer,
                                           &cbRead);
    if (FAILED(resRead))
3580 3581 3582 3583
        break;

    if (cbRead > 0)
    {
3584
        cbTotalRead.QuadPart += cbRead;
3585

3586
        resWrite = BlockChainStream_WriteAt(bbTempChain,
3587
                                            offset,
3588
                                            cbRead,
3589 3590
                                            buffer,
                                            &cbWritten);
3591

3592
        if (FAILED(resWrite))
3593
            break;
3594

3595 3596
        offset.u.LowPart += This->smallBlockSize;
    }
3597
  } while (cbTotalRead.QuadPart < size.QuadPart);
3598
  HeapFree(GetProcessHeap(),0,buffer);
3599

3600 3601
  if (FAILED(resRead) || FAILED(resWrite))
  {
3602
    ERR("conversion failed: resRead = 0x%08x, resWrite = 0x%08x\n", resRead, resWrite);
3603 3604 3605
    BlockChainStream_Destroy(bbTempChain);
    return NULL;
  }
3606 3607 3608 3609 3610

  /*
   * Destroy the small block chain.
   */
  propertyIndex = (*ppsbChain)->ownerPropertyIndex;
3611 3612
  size.u.HighPart = 0;
  size.u.LowPart  = 0;
3613 3614 3615 3616 3617 3618 3619 3620
  SmallBlockChainStream_SetSize(*ppsbChain, size);
  SmallBlockChainStream_Destroy(*ppsbChain);
  *ppsbChain = 0;

  /*
   * Change the property information. This chain is now a big block chain
   * and it doesn't reside in the small blocks chain anymore.
   */
3621
  StorageImpl_ReadProperty(This, propertyIndex, &chainProperty);
3622 3623 3624

  chainProperty.startingBlock = bbHeadOfChain;

3625
  StorageImpl_WriteProperty(This, propertyIndex, &chainProperty);
3626 3627 3628 3629 3630 3631 3632 3633 3634 3635 3636 3637 3638

  /*
   * Destroy the temporary propertyless big block chain.
   * Create a new big block chain associated with this property.
   */
  BlockChainStream_Destroy(bbTempChain);
  bigBlockChain = BlockChainStream_Construct(This,
                                             NULL,
                                             propertyIndex);

  return bigBlockChain;
}

3639
static void StorageInternalImpl_Destroy( StorageBaseImpl *iface)
3640
{
3641 3642 3643
  StorageInternalImpl* This = (StorageInternalImpl*) iface;

  StorageBaseImpl_Release((IStorage*)This->base.ancestorStorage);
3644 3645 3646 3647 3648 3649 3650 3651 3652 3653
  HeapFree(GetProcessHeap(), 0, This);
}

/******************************************************************************
**
** Storage32InternalImpl_Commit
**
** The non-root storages cannot be opened in transacted mode thus this function
** does nothing.
*/
3654
static HRESULT WINAPI StorageInternalImpl_Commit(
3655
  IStorage*            iface,
3656
  DWORD                  grfCommitFlags)  /* [in] */
3657 3658 3659
{
  return S_OK;
}
3660

3661 3662 3663 3664 3665 3666 3667
/******************************************************************************
**
** Storage32InternalImpl_Revert
**
** The non-root storages cannot be opened in transacted mode thus this function
** does nothing.
*/
3668
static HRESULT WINAPI StorageInternalImpl_Revert(
3669
  IStorage*            iface)
3670 3671 3672 3673
{
  return S_OK;
}

3674
static void IEnumSTATSTGImpl_Destroy(IEnumSTATSTGImpl* This)
3675
{
3676
  IStorage_Release((IStorage*)This->parentStorage);
3677 3678 3679 3680
  HeapFree(GetProcessHeap(), 0, This->stackToVisit);
  HeapFree(GetProcessHeap(), 0, This);
}

3681
static HRESULT WINAPI IEnumSTATSTGImpl_QueryInterface(
3682
  IEnumSTATSTG*     iface,
3683 3684 3685
  REFIID            riid,
  void**            ppvObject)
{
3686 3687
  IEnumSTATSTGImpl* const This=(IEnumSTATSTGImpl*)iface;

3688 3689 3690 3691 3692 3693 3694 3695 3696 3697 3698 3699 3700 3701
  /*
   * Perform a sanity check on the parameters.
   */
  if (ppvObject==0)
    return E_INVALIDARG;

  /*
   * Initialize the return parameter.
   */
  *ppvObject = 0;

  /*
   * Compare the riid with the interface IDs implemented by this object.
   */
3702
  if (IsEqualGUID(&IID_IUnknown, riid) ||
3703
      IsEqualGUID(&IID_IEnumSTATSTG, riid))
3704 3705
  {
    *ppvObject = (IEnumSTATSTG*)This;
3706 3707
    IEnumSTATSTG_AddRef((IEnumSTATSTG*)This);
    return S_OK;
3708 3709
  }

3710
  return E_NOINTERFACE;
3711
}
3712

3713
static ULONG   WINAPI IEnumSTATSTGImpl_AddRef(
3714
  IEnumSTATSTG* iface)
3715
{
3716
  IEnumSTATSTGImpl* const This=(IEnumSTATSTGImpl*)iface;
3717
  return InterlockedIncrement(&This->ref);
3718
}
3719

3720
static ULONG   WINAPI IEnumSTATSTGImpl_Release(
3721
  IEnumSTATSTG* iface)
3722
{
3723 3724
  IEnumSTATSTGImpl* const This=(IEnumSTATSTGImpl*)iface;

3725 3726
  ULONG newRef;

3727
  newRef = InterlockedDecrement(&This->ref);
3728 3729 3730 3731 3732 3733 3734 3735 3736

  /*
   * If the reference count goes down to 0, perform suicide.
   */
  if (newRef==0)
  {
    IEnumSTATSTGImpl_Destroy(This);
  }

3737
  return newRef;
3738 3739
}

3740
static HRESULT WINAPI IEnumSTATSTGImpl_Next(
3741
  IEnumSTATSTG* iface,
3742 3743 3744 3745
  ULONG             celt,
  STATSTG*          rgelt,
  ULONG*            pceltFetched)
{
3746 3747
  IEnumSTATSTGImpl* const This=(IEnumSTATSTGImpl*)iface;

3748 3749 3750 3751 3752 3753 3754 3755 3756
  StgProperty currentProperty;
  STATSTG*    currentReturnStruct = rgelt;
  ULONG       objectFetched       = 0;
  ULONG      currentSearchNode;

  /*
   * Perform a sanity check on the parameters.
   */
  if ( (rgelt==0) || ( (celt!=1) && (pceltFetched==0) ) )
3757 3758
    return E_INVALIDARG;

3759 3760 3761 3762 3763 3764
  /*
   * To avoid the special case, get another pointer to a ULONG value if
   * the caller didn't supply one.
   */
  if (pceltFetched==0)
    pceltFetched = &objectFetched;
3765

3766 3767 3768 3769 3770 3771 3772 3773 3774 3775 3776
  /*
   * Start the iteration, we will iterate until we hit the end of the
   * linked list or until we hit the number of items to iterate through
   */
  *pceltFetched = 0;

  /*
   * Start with the node at the top of the stack.
   */
  currentSearchNode = IEnumSTATSTGImpl_PopSearchNode(This, FALSE);

3777
  while ( ( *pceltFetched < celt) &&
3778 3779
          ( currentSearchNode!=PROPERTY_NULL) )
  {
3780
    /*
3781 3782 3783 3784 3785 3786 3787
     * Remove the top node from the stack
     */
    IEnumSTATSTGImpl_PopSearchNode(This, TRUE);

    /*
     * Read the property from the storage.
     */
3788
    StorageImpl_ReadProperty(This->parentStorage,
3789
      currentSearchNode,
3790 3791 3792 3793 3794 3795 3796 3797
      &currentProperty);

    /*
     * Copy the information to the return buffer.
     */
    StorageUtl_CopyPropertyToSTATSTG(currentReturnStruct,
      &currentProperty,
      STATFLAG_DEFAULT);
3798

3799 3800 3801 3802 3803 3804 3805 3806 3807 3808 3809 3810 3811 3812 3813 3814 3815 3816 3817 3818 3819 3820 3821
    /*
     * Step to the next item in the iteration
     */
    (*pceltFetched)++;
    currentReturnStruct++;

    /*
     * Push the next search node in the search stack.
     */
    IEnumSTATSTGImpl_PushSearchNode(This, currentProperty.nextProperty);

    /*
     * continue the iteration.
     */
    currentSearchNode = IEnumSTATSTGImpl_PopSearchNode(This, FALSE);
  }

  if (*pceltFetched == celt)
    return S_OK;

  return S_FALSE;
}

3822

3823
static HRESULT WINAPI IEnumSTATSTGImpl_Skip(
3824
  IEnumSTATSTG* iface,
3825 3826
  ULONG             celt)
{
3827 3828
  IEnumSTATSTGImpl* const This=(IEnumSTATSTGImpl*)iface;

3829 3830 3831 3832 3833 3834 3835 3836 3837
  StgProperty currentProperty;
  ULONG       objectFetched       = 0;
  ULONG       currentSearchNode;

  /*
   * Start with the node at the top of the stack.
   */
  currentSearchNode = IEnumSTATSTGImpl_PopSearchNode(This, FALSE);

3838
  while ( (objectFetched < celt) &&
3839 3840
          (currentSearchNode!=PROPERTY_NULL) )
  {
3841
    /*
3842 3843 3844 3845 3846 3847 3848
     * Remove the top node from the stack
     */
    IEnumSTATSTGImpl_PopSearchNode(This, TRUE);

    /*
     * Read the property from the storage.
     */
3849
    StorageImpl_ReadProperty(This->parentStorage,
3850
      currentSearchNode,
3851
      &currentProperty);
3852

3853 3854 3855 3856 3857 3858 3859 3860 3861 3862 3863 3864 3865 3866 3867 3868 3869 3870 3871 3872 3873
    /*
     * Step to the next item in the iteration
     */
    objectFetched++;

    /*
     * Push the next search node in the search stack.
     */
    IEnumSTATSTGImpl_PushSearchNode(This, currentProperty.nextProperty);

    /*
     * continue the iteration.
     */
    currentSearchNode = IEnumSTATSTGImpl_PopSearchNode(This, FALSE);
  }

  if (objectFetched == celt)
    return S_OK;

  return S_FALSE;
}
3874

3875
static HRESULT WINAPI IEnumSTATSTGImpl_Reset(
3876
  IEnumSTATSTG* iface)
3877
{
3878 3879
  IEnumSTATSTGImpl* const This=(IEnumSTATSTGImpl*)iface;

3880
  StgProperty rootProperty;
3881
  BOOL      readSuccessful;
3882 3883 3884 3885 3886 3887 3888 3889 3890

  /*
   * Re-initialize the search stack to an empty stack
   */
  This->stackSize = 0;

  /*
   * Read the root property from the storage.
   */
3891
  readSuccessful = StorageImpl_ReadProperty(
3892
                    This->parentStorage,
3893
                    This->firstPropertyNode,
3894 3895
                    &rootProperty);

3896
  if (readSuccessful)
3897 3898 3899 3900 3901 3902 3903 3904 3905 3906 3907
  {
    assert(rootProperty.sizeOfNameString!=0);

    /*
     * Push the search node in the search stack.
     */
    IEnumSTATSTGImpl_PushSearchNode(This, rootProperty.dirProperty);
  }

  return S_OK;
}
3908

3909
static HRESULT WINAPI IEnumSTATSTGImpl_Clone(
3910
  IEnumSTATSTG* iface,
3911 3912
  IEnumSTATSTG**    ppenum)
{
3913 3914
  IEnumSTATSTGImpl* const This=(IEnumSTATSTGImpl*)iface;

3915 3916 3917 3918 3919 3920 3921
  IEnumSTATSTGImpl* newClone;

  /*
   * Perform a sanity check on the parameters.
   */
  if (ppenum==0)
    return E_INVALIDARG;
3922

3923 3924 3925
  newClone = IEnumSTATSTGImpl_Construct(This->parentStorage,
               This->firstPropertyNode);

3926

3927 3928 3929 3930 3931 3932
  /*
   * The new clone enumeration must point to the same current node as
   * the ole one.
   */
  newClone->stackSize    = This->stackSize    ;
  newClone->stackMaxSize = This->stackMaxSize ;
3933
  newClone->stackToVisit =
3934 3935 3936
    HeapAlloc(GetProcessHeap(), 0, sizeof(ULONG) * newClone->stackMaxSize);

  memcpy(
3937 3938
    newClone->stackToVisit,
    This->stackToVisit,
3939 3940
    sizeof(ULONG) * newClone->stackSize);

3941 3942
  *ppenum = (IEnumSTATSTG*)newClone;

3943 3944 3945 3946
  /*
   * Don't forget to nail down a reference to the clone before
   * returning it.
   */
3947
  IEnumSTATSTGImpl_AddRef(*ppenum);
3948 3949 3950 3951

  return S_OK;
}

3952
static INT IEnumSTATSTGImpl_FindParentProperty(
3953
  IEnumSTATSTGImpl *This,
3954
  ULONG             childProperty,
3955 3956 3957 3958 3959 3960 3961 3962 3963 3964 3965 3966 3967 3968 3969 3970 3971
  StgProperty      *currentProperty,
  ULONG            *thisNodeId)
{
  ULONG currentSearchNode;
  ULONG foundNode;

  /*
   * To avoid the special case, get another pointer to a ULONG value if
   * the caller didn't supply one.
   */
  if (thisNodeId==0)
    thisNodeId = &foundNode;

  /*
   * Start with the node at the top of the stack.
   */
  currentSearchNode = IEnumSTATSTGImpl_PopSearchNode(This, FALSE);
3972

3973 3974 3975 3976 3977 3978 3979 3980

  while (currentSearchNode!=PROPERTY_NULL)
  {
    /*
     * Store the current node in the returned parameters
     */
    *thisNodeId = currentSearchNode;

3981
    /*
3982 3983 3984 3985 3986 3987 3988
     * Remove the top node from the stack
     */
    IEnumSTATSTGImpl_PopSearchNode(This, TRUE);

    /*
     * Read the property from the storage.
     */
3989
    StorageImpl_ReadProperty(
3990
      This->parentStorage,
3991
      currentSearchNode,
3992
      currentProperty);
3993

3994 3995 3996
    if (currentProperty->previousProperty == childProperty)
      return PROPERTY_RELATION_PREVIOUS;

3997
    else if (currentProperty->nextProperty == childProperty)
3998
      return PROPERTY_RELATION_NEXT;
3999

4000 4001
    else if (currentProperty->dirProperty == childProperty)
      return PROPERTY_RELATION_DIR;
4002

4003 4004 4005 4006 4007 4008 4009 4010 4011 4012 4013 4014 4015 4016
    /*
     * Push the next search node in the search stack.
     */
    IEnumSTATSTGImpl_PushSearchNode(This, currentProperty->nextProperty);

    /*
     * continue the iteration.
     */
    currentSearchNode = IEnumSTATSTGImpl_PopSearchNode(This, FALSE);
  }

  return PROPERTY_NULL;
}

4017
static ULONG IEnumSTATSTGImpl_FindProperty(
4018
  IEnumSTATSTGImpl* This,
4019
  const OLECHAR*  lpszPropName,
4020 4021 4022 4023 4024 4025 4026 4027 4028 4029 4030
  StgProperty*      currentProperty)
{
  ULONG currentSearchNode;

  /*
   * Start with the node at the top of the stack.
   */
  currentSearchNode = IEnumSTATSTGImpl_PopSearchNode(This, FALSE);

  while (currentSearchNode!=PROPERTY_NULL)
  {
4031
    /*
4032 4033 4034 4035 4036 4037 4038
     * Remove the top node from the stack
     */
    IEnumSTATSTGImpl_PopSearchNode(This, TRUE);

    /*
     * Read the property from the storage.
     */
4039
    StorageImpl_ReadProperty(This->parentStorage,
4040
      currentSearchNode,
4041 4042 4043
      currentProperty);

    if ( propertyNameCmp(
4044
          (const OLECHAR*)currentProperty->name, lpszPropName) == 0)
4045 4046 4047 4048 4049 4050 4051 4052 4053 4054 4055 4056 4057 4058 4059 4060
      return currentSearchNode;

    /*
     * Push the next search node in the search stack.
     */
    IEnumSTATSTGImpl_PushSearchNode(This, currentProperty->nextProperty);

    /*
     * continue the iteration.
     */
    currentSearchNode = IEnumSTATSTGImpl_PopSearchNode(This, FALSE);
  }

  return PROPERTY_NULL;
}

4061
static void IEnumSTATSTGImpl_PushSearchNode(
4062 4063 4064 4065
  IEnumSTATSTGImpl* This,
  ULONG             nodeToPush)
{
  StgProperty rootProperty;
4066
  BOOL      readSuccessful;
4067 4068 4069 4070 4071 4072 4073 4074 4075 4076 4077 4078 4079 4080 4081

  /*
   * First, make sure we're not trying to push an unexisting node.
   */
  if (nodeToPush==PROPERTY_NULL)
    return;

  /*
   * First push the node to the stack
   */
  if (This->stackSize == This->stackMaxSize)
  {
    This->stackMaxSize += ENUMSTATSGT_SIZE_INCREMENT;

    This->stackToVisit = HeapReAlloc(
4082
                           GetProcessHeap(),
4083 4084 4085 4086 4087 4088 4089 4090 4091 4092 4093
                           0,
                           This->stackToVisit,
                           sizeof(ULONG) * This->stackMaxSize);
  }

  This->stackToVisit[This->stackSize] = nodeToPush;
  This->stackSize++;

  /*
   * Read the root property from the storage.
   */
4094
  readSuccessful = StorageImpl_ReadProperty(
4095
                    This->parentStorage,
4096
                    nodeToPush,
4097 4098
                    &rootProperty);

4099
  if (readSuccessful)
4100 4101 4102 4103 4104 4105 4106 4107 4108 4109
  {
    assert(rootProperty.sizeOfNameString!=0);

    /*
     * Push the previous search node in the search stack.
     */
    IEnumSTATSTGImpl_PushSearchNode(This, rootProperty.previousProperty);
  }
}

4110
static ULONG IEnumSTATSTGImpl_PopSearchNode(
4111
  IEnumSTATSTGImpl* This,
4112
  BOOL            remove)
4113 4114 4115 4116 4117 4118 4119 4120 4121 4122 4123 4124 4125 4126
{
  ULONG topNode;

  if (This->stackSize == 0)
    return PROPERTY_NULL;

  topNode = This->stackToVisit[This->stackSize-1];

  if (remove)
    This->stackSize--;

  return topNode;
}

4127 4128 4129
/*
 * Virtual function table for the IEnumSTATSTGImpl class.
 */
4130
static const IEnumSTATSTGVtbl IEnumSTATSTGImpl_Vtbl =
4131 4132 4133 4134 4135 4136 4137 4138 4139 4140 4141 4142 4143 4144
{
    IEnumSTATSTGImpl_QueryInterface,
    IEnumSTATSTGImpl_AddRef,
    IEnumSTATSTGImpl_Release,
    IEnumSTATSTGImpl_Next,
    IEnumSTATSTGImpl_Skip,
    IEnumSTATSTGImpl_Reset,
    IEnumSTATSTGImpl_Clone
};

/******************************************************************************
** IEnumSTATSTGImpl implementation
*/

4145
static IEnumSTATSTGImpl* IEnumSTATSTGImpl_Construct(
4146 4147 4148 4149 4150 4151 4152 4153 4154 4155 4156 4157 4158 4159 4160 4161 4162 4163 4164 4165 4166 4167 4168 4169 4170 4171 4172 4173 4174 4175 4176 4177 4178 4179 4180 4181 4182 4183 4184 4185 4186 4187 4188 4189
  StorageImpl* parentStorage,
  ULONG          firstPropertyNode)
{
  IEnumSTATSTGImpl* newEnumeration;

  newEnumeration = HeapAlloc(GetProcessHeap(), 0, sizeof(IEnumSTATSTGImpl));

  if (newEnumeration!=0)
  {
    /*
     * Set-up the virtual function table and reference count.
     */
    newEnumeration->lpVtbl    = &IEnumSTATSTGImpl_Vtbl;
    newEnumeration->ref       = 0;

    /*
     * We want to nail-down the reference to the storage in case the
     * enumeration out-lives the storage in the client application.
     */
    newEnumeration->parentStorage = parentStorage;
    IStorage_AddRef((IStorage*)newEnumeration->parentStorage);

    newEnumeration->firstPropertyNode   = firstPropertyNode;

    /*
     * Initialize the search stack
     */
    newEnumeration->stackSize    = 0;
    newEnumeration->stackMaxSize = ENUMSTATSGT_SIZE_INCREMENT;
    newEnumeration->stackToVisit =
      HeapAlloc(GetProcessHeap(), 0, sizeof(ULONG)*ENUMSTATSGT_SIZE_INCREMENT);

    /*
     * Make sure the current node of the iterator is the first one.
     */
    IEnumSTATSTGImpl_Reset((IEnumSTATSTG*)newEnumeration);
  }

  return newEnumeration;
}

/*
 * Virtual function table for the Storage32InternalImpl class.
 */
4190
static const IStorageVtbl Storage32InternalImpl_Vtbl =
4191 4192 4193 4194 4195 4196 4197 4198 4199 4200 4201 4202 4203 4204 4205 4206 4207 4208 4209 4210 4211 4212 4213 4214 4215
{
    StorageBaseImpl_QueryInterface,
    StorageBaseImpl_AddRef,
    StorageBaseImpl_Release,
    StorageBaseImpl_CreateStream,
    StorageBaseImpl_OpenStream,
    StorageImpl_CreateStorage,
    StorageBaseImpl_OpenStorage,
    StorageImpl_CopyTo,
    StorageImpl_MoveElementTo,
    StorageInternalImpl_Commit,
    StorageInternalImpl_Revert,
    StorageBaseImpl_EnumElements,
    StorageImpl_DestroyElement,
    StorageBaseImpl_RenameElement,
    StorageImpl_SetElementTimes,
    StorageBaseImpl_SetClass,
    StorageImpl_SetStateBits,
    StorageBaseImpl_Stat
};

/******************************************************************************
** Storage32InternalImpl implementation
*/

4216
static StorageInternalImpl* StorageInternalImpl_Construct(
4217
  StorageImpl* ancestorStorage,
4218 4219
  DWORD        openFlags,
  ULONG        rootPropertyIndex)
4220 4221 4222 4223 4224 4225
{
  StorageInternalImpl* newStorage;

  /*
   * Allocate space for the new storage object
   */
4226
  newStorage = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(StorageInternalImpl));
4227 4228 4229

  if (newStorage!=0)
  {
4230 4231 4232 4233 4234
    /*
     * Initialize the stream list
     */
    list_init(&newStorage->base.strmHead);

4235 4236 4237 4238 4239
    /*
     * Initialize the virtual function table.
     */
    newStorage->base.lpVtbl = &Storage32InternalImpl_Vtbl;
    newStorage->base.v_destructor = &StorageInternalImpl_Destroy;
4240
    newStorage->base.openFlags = (openFlags & ~STGM_CREATE);
4241 4242 4243 4244 4245 4246 4247 4248 4249 4250 4251 4252 4253 4254 4255 4256 4257 4258

    /*
     * Keep the ancestor storage pointer and nail a reference to it.
     */
    newStorage->base.ancestorStorage = ancestorStorage;
    StorageBaseImpl_AddRef((IStorage*)(newStorage->base.ancestorStorage));

    /*
     * Keep the index of the root property set for this storage,
     */
    newStorage->base.rootPropertySetIndex = rootPropertyIndex;

    return newStorage;
  }

  return 0;
}

4259 4260 4261 4262
/******************************************************************************
** StorageUtl implementation
*/

4263
void StorageUtl_ReadWord(const BYTE* buffer, ULONG offset, WORD* value)
4264
{
4265 4266 4267 4268
  WORD tmp;

  memcpy(&tmp, buffer+offset, sizeof(WORD));
  *value = le16toh(tmp);
4269 4270
}

4271
void StorageUtl_WriteWord(BYTE* buffer, ULONG offset, WORD value)
4272
{
4273
  value = htole16(value);
4274
  memcpy(buffer+offset, &value, sizeof(WORD));
4275 4276
}

4277
void StorageUtl_ReadDWord(const BYTE* buffer, ULONG offset, DWORD* value)
4278
{
4279 4280 4281 4282
  DWORD tmp;

  memcpy(&tmp, buffer+offset, sizeof(DWORD));
  *value = le32toh(tmp);
4283 4284
}

4285
void StorageUtl_WriteDWord(BYTE* buffer, ULONG offset, DWORD value)
4286
{
4287
  value = htole32(value);
4288
  memcpy(buffer+offset, &value, sizeof(DWORD));
4289 4290
}

Juan Lang's avatar
Juan Lang committed
4291 4292 4293 4294 4295 4296 4297
void StorageUtl_ReadULargeInteger(const BYTE* buffer, ULONG offset,
 ULARGE_INTEGER* value)
{
#ifdef WORDS_BIGENDIAN
    ULARGE_INTEGER tmp;

    memcpy(&tmp, buffer + offset, sizeof(ULARGE_INTEGER));
4298 4299
    value->u.LowPart = htole32(tmp.u.HighPart);
    value->u.HighPart = htole32(tmp.u.LowPart);
Juan Lang's avatar
Juan Lang committed
4300 4301 4302 4303 4304 4305 4306 4307 4308 4309 4310
#else
    memcpy(value, buffer + offset, sizeof(ULARGE_INTEGER));
#endif
}

void StorageUtl_WriteULargeInteger(BYTE* buffer, ULONG offset,
 const ULARGE_INTEGER *value)
{
#ifdef WORDS_BIGENDIAN
    ULARGE_INTEGER tmp;

4311 4312
    tmp.u.LowPart = htole32(value->u.HighPart);
    tmp.u.HighPart = htole32(value->u.LowPart);
Juan Lang's avatar
Juan Lang committed
4313 4314 4315 4316 4317 4318
    memcpy(buffer + offset, &tmp, sizeof(ULARGE_INTEGER));
#else
    memcpy(buffer + offset, value, sizeof(ULARGE_INTEGER));
#endif
}

4319
void StorageUtl_ReadGUID(const BYTE* buffer, ULONG offset, GUID* value)
4320 4321 4322 4323 4324
{
  StorageUtl_ReadDWord(buffer, offset,   &(value->Data1));
  StorageUtl_ReadWord(buffer,  offset+4, &(value->Data2));
  StorageUtl_ReadWord(buffer,  offset+6, &(value->Data3));

4325
  memcpy(value->Data4, buffer+offset+8, sizeof(value->Data4));
4326 4327
}

4328
void StorageUtl_WriteGUID(BYTE* buffer, ULONG offset, const GUID* value)
4329 4330 4331 4332 4333
{
  StorageUtl_WriteDWord(buffer, offset,   value->Data1);
  StorageUtl_WriteWord(buffer,  offset+4, value->Data2);
  StorageUtl_WriteWord(buffer,  offset+6, value->Data3);

4334
  memcpy(buffer+offset+8, value->Data4, sizeof(value->Data4));
4335 4336 4337
}

void StorageUtl_CopyPropertyToSTATSTG(
4338 4339 4340
  STATSTG*              destination,
  const StgProperty*    source,
  int                   statFlags)
4341 4342 4343 4344
{
  /*
   * The copy of the string occurs only when the flag is not set
   */
4345 4346 4347
  if( ((statFlags & STATFLAG_NONAME) != 0) || 
       (source->name == NULL) || 
       (source->name[0] == 0) )
4348 4349 4350 4351 4352
  {
    destination->pwcsName = 0;
  }
  else
  {
4353
    destination->pwcsName =
4354
      CoTaskMemAlloc((lstrlenW(source->name)+1)*sizeof(WCHAR));
4355

4356
    strcpyW((LPWSTR)destination->pwcsName, source->name);
4357
  }
4358

4359 4360 4361 4362 4363 4364 4365 4366 4367 4368 4369
  switch (source->propertyType)
  {
    case PROPTYPE_STORAGE:
    case PROPTYPE_ROOT:
      destination->type = STGTY_STORAGE;
      break;
    case PROPTYPE_STREAM:
      destination->type = STGTY_STREAM;
      break;
    default:
      destination->type = STGTY_STREAM;
4370
      break;
4371 4372 4373
  }

  destination->cbSize            = source->size;
4374
/*
4375 4376
  currentReturnStruct->mtime     = {0}; TODO
  currentReturnStruct->ctime     = {0};
4377
  currentReturnStruct->atime     = {0};
4378 4379
*/
  destination->grfMode           = 0;
4380
  destination->grfLocksSupported = 0;
4381
  destination->clsid             = source->propertyUniqueID;
4382 4383
  destination->grfStateBits      = 0;
  destination->reserved          = 0;
4384 4385 4386 4387 4388 4389 4390
}

/******************************************************************************
** BlockChainStream implementation
*/

BlockChainStream* BlockChainStream_Construct(
4391
  StorageImpl* parentStorage,
4392 4393 4394 4395
  ULONG*         headOfStreamPlaceHolder,
  ULONG          propertyIndex)
{
  BlockChainStream* newStream;
Thuy Nguyen's avatar
Thuy Nguyen committed
4396
  ULONG blockIndex;
4397 4398 4399 4400 4401 4402

  newStream = HeapAlloc(GetProcessHeap(), 0, sizeof(BlockChainStream));

  newStream->parentStorage           = parentStorage;
  newStream->headOfStreamPlaceHolder = headOfStreamPlaceHolder;
  newStream->ownerPropertyIndex      = propertyIndex;
Thuy Nguyen's avatar
Thuy Nguyen committed
4403 4404 4405 4406 4407 4408 4409 4410 4411 4412 4413
  newStream->lastBlockNoInSequence   = 0xFFFFFFFF;
  newStream->tailIndex               = BLOCK_END_OF_CHAIN;
  newStream->numBlocks               = 0;

  blockIndex = BlockChainStream_GetHeadOfChain(newStream);

  while (blockIndex != BLOCK_END_OF_CHAIN)
  {
    newStream->numBlocks++;
    newStream->tailIndex = blockIndex;

4414 4415 4416 4417 4418 4419 4420 4421
    if(FAILED(StorageImpl_GetNextBlockInChain(
	      parentStorage,
	      blockIndex,
	      &blockIndex)))
    {
      HeapFree(GetProcessHeap(), 0, newStream);
      return NULL;
    }
Thuy Nguyen's avatar
Thuy Nguyen committed
4422
  }
4423 4424 4425 4426 4427 4428 4429 4430 4431 4432 4433 4434 4435 4436 4437 4438 4439

  return newStream;
}

void BlockChainStream_Destroy(BlockChainStream* This)
{
  HeapFree(GetProcessHeap(), 0, This);
}

/******************************************************************************
 *      BlockChainStream_GetHeadOfChain
 *
 * Returns the head of this stream chain.
 * Some special chains don't have properties, their heads are kept in
 * This->headOfStreamPlaceHolder.
 *
 */
4440
static ULONG BlockChainStream_GetHeadOfChain(BlockChainStream* This)
4441 4442
{
  StgProperty chainProperty;
4443
  BOOL      readSuccessful;
4444 4445 4446 4447 4448 4449

  if (This->headOfStreamPlaceHolder != 0)
    return *(This->headOfStreamPlaceHolder);

  if (This->ownerPropertyIndex != PROPERTY_NULL)
  {
4450
    readSuccessful = StorageImpl_ReadProperty(
4451 4452 4453 4454
                      This->parentStorage,
                      This->ownerPropertyIndex,
                      &chainProperty);

4455
    if (readSuccessful)
4456 4457 4458 4459 4460 4461 4462 4463 4464 4465 4466 4467 4468
    {
      return chainProperty.startingBlock;
    }
  }

  return BLOCK_END_OF_CHAIN;
}

/******************************************************************************
 *       BlockChainStream_GetCount
 *
 * Returns the number of blocks that comprises this chain.
 * This is not the size of the stream as the last block may not be full!
4469
 *
4470
 */
4471
static ULONG BlockChainStream_GetCount(BlockChainStream* This)
4472 4473 4474 4475 4476 4477 4478 4479 4480 4481
{
  ULONG blockIndex;
  ULONG count = 0;

  blockIndex = BlockChainStream_GetHeadOfChain(This);

  while (blockIndex != BLOCK_END_OF_CHAIN)
  {
    count++;

4482
    if(FAILED(StorageImpl_GetNextBlockInChain(
4483
                   This->parentStorage,
4484 4485 4486
                   blockIndex,
		   &blockIndex)))
      return 0;
4487 4488 4489 4490 4491 4492
  }

  return count;
}

/******************************************************************************
4493
 *      BlockChainStream_ReadAt
4494 4495 4496 4497 4498
 *
 * Reads a specified number of bytes from this chain at the specified offset.
 * bytesRead may be NULL.
 * Failure will be returned if the specified number of bytes has not been read.
 */
4499
HRESULT BlockChainStream_ReadAt(BlockChainStream* This,
4500 4501 4502 4503 4504
  ULARGE_INTEGER offset,
  ULONG          size,
  void*          buffer,
  ULONG*         bytesRead)
{
4505 4506
  ULONG blockNoInSequence = offset.u.LowPart / This->parentStorage->bigBlockSize;
  ULONG offsetInBlock     = offset.u.LowPart % This->parentStorage->bigBlockSize;
4507 4508 4509
  ULONG bytesToReadInBuffer;
  ULONG blockIndex;
  BYTE* bufferWalker;
4510 4511

  TRACE("(%p)-> %i %p %i %p\n",This, offset.u.LowPart, buffer, size, bytesRead);
4512 4513 4514 4515

  /*
   * Find the first block in the stream that contains part of the buffer.
   */
4516 4517 4518 4519 4520 4521 4522 4523
  if ( (This->lastBlockNoInSequence == 0xFFFFFFFF) ||
       (This->lastBlockNoInSequenceIndex == BLOCK_END_OF_CHAIN) ||
       (blockNoInSequence < This->lastBlockNoInSequence) )
  {
    blockIndex = BlockChainStream_GetHeadOfChain(This);
    This->lastBlockNoInSequence = blockNoInSequence;
  }
  else
Thuy Nguyen's avatar
Thuy Nguyen committed
4524 4525 4526 4527 4528 4529 4530
  {
    ULONG temp = blockNoInSequence;

    blockIndex = This->lastBlockNoInSequenceIndex;
    blockNoInSequence -= This->lastBlockNoInSequence;
    This->lastBlockNoInSequence = temp;
  }
4531 4532 4533

  while ( (blockNoInSequence > 0) &&  (blockIndex != BLOCK_END_OF_CHAIN))
  {
4534
    if(FAILED(StorageImpl_GetNextBlockInChain(This->parentStorage, blockIndex, &blockIndex)))
4535
      return STG_E_DOCFILECORRUPT;
4536 4537 4538
    blockNoInSequence--;
  }

4539
  if ((blockNoInSequence > 0) && (blockIndex == BLOCK_END_OF_CHAIN))
4540
      return STG_E_DOCFILECORRUPT; /* We failed to find the starting block */
4541

Thuy Nguyen's avatar
Thuy Nguyen committed
4542 4543
  This->lastBlockNoInSequenceIndex = blockIndex;

4544 4545 4546 4547 4548
  /*
   * Start reading the buffer.
   */
  *bytesRead   = 0;
  bufferWalker = buffer;
4549

4550 4551
  while ( (size > 0) && (blockIndex != BLOCK_END_OF_CHAIN) )
  {
4552 4553
    ULARGE_INTEGER ulOffset;
    DWORD bytesReadAt;
4554 4555 4556
    /*
     * Calculate how many bytes we can copy from this big block.
     */
4557
    bytesToReadInBuffer =
4558
      min(This->parentStorage->bigBlockSize - offsetInBlock, size);
4559

4560 4561 4562 4563
     TRACE("block %i\n",blockIndex);
     ulOffset.u.HighPart = 0;
     ulOffset.u.LowPart = BLOCK_GetBigBlockOffset(blockIndex) +
                             offsetInBlock;
4564

4565 4566 4567 4568 4569
     StorageImpl_ReadAt(This->parentStorage,
         ulOffset,
         bufferWalker,
         bytesToReadInBuffer,
         &bytesReadAt);
4570 4571 4572
    /*
     * Step to the next big block.
     */
4573
    if( size > bytesReadAt && FAILED(StorageImpl_GetNextBlockInChain(This->parentStorage, blockIndex, &blockIndex)))
4574
      return STG_E_DOCFILECORRUPT;
4575

4576 4577 4578
    bufferWalker += bytesReadAt;
    size         -= bytesReadAt;
    *bytesRead   += bytesReadAt;
4579 4580
    offsetInBlock = 0;  /* There is no offset on the next block */

4581 4582
    if (bytesToReadInBuffer != bytesReadAt)
        break;
4583
  }
4584

4585
  return (size == 0) ? S_OK : STG_E_READFAULT;
4586 4587 4588 4589 4590 4591 4592 4593 4594
}

/******************************************************************************
 *      BlockChainStream_WriteAt
 *
 * Writes the specified number of bytes to this chain at the specified offset.
 * bytesWritten may be NULL.
 * Will fail if not all specified number of bytes have been written.
 */
4595
HRESULT BlockChainStream_WriteAt(BlockChainStream* This,
4596 4597 4598 4599 4600
  ULARGE_INTEGER    offset,
  ULONG             size,
  const void*       buffer,
  ULONG*            bytesWritten)
{
4601 4602
  ULONG blockNoInSequence = offset.u.LowPart / This->parentStorage->bigBlockSize;
  ULONG offsetInBlock     = offset.u.LowPart % This->parentStorage->bigBlockSize;
4603 4604
  ULONG bytesToWrite;
  ULONG blockIndex;
Eric Pouech's avatar
Eric Pouech committed
4605
  const BYTE* bufferWalker;
4606 4607 4608 4609

  /*
   * Find the first block in the stream that contains part of the buffer.
   */
4610 4611 4612 4613 4614 4615 4616 4617
  if ( (This->lastBlockNoInSequence == 0xFFFFFFFF) ||
       (This->lastBlockNoInSequenceIndex == BLOCK_END_OF_CHAIN) ||
       (blockNoInSequence < This->lastBlockNoInSequence) )
  {
    blockIndex = BlockChainStream_GetHeadOfChain(This);
    This->lastBlockNoInSequence = blockNoInSequence;
  }
  else
Thuy Nguyen's avatar
Thuy Nguyen committed
4618 4619 4620 4621 4622 4623 4624 4625
  {
    ULONG temp = blockNoInSequence;

    blockIndex = This->lastBlockNoInSequenceIndex;
    blockNoInSequence -= This->lastBlockNoInSequence;
    This->lastBlockNoInSequence = temp;
  }

4626 4627
  while ( (blockNoInSequence > 0) &&  (blockIndex != BLOCK_END_OF_CHAIN))
  {
4628 4629
    if(FAILED(StorageImpl_GetNextBlockInChain(This->parentStorage, blockIndex,
					      &blockIndex)))
4630
      return STG_E_DOCFILECORRUPT;
4631 4632 4633
    blockNoInSequence--;
  }

Thuy Nguyen's avatar
Thuy Nguyen committed
4634 4635
  This->lastBlockNoInSequenceIndex = blockIndex;

4636 4637 4638 4639 4640 4641 4642 4643
  /* BlockChainStream_SetSize should have already been called to ensure we have
   * enough blocks in the chain to write into */
  if (blockIndex == BLOCK_END_OF_CHAIN)
  {
    ERR("not enough blocks in chain to write data\n");
    return STG_E_DOCFILECORRUPT;
  }

4644
  *bytesWritten   = 0;
Eric Pouech's avatar
Eric Pouech committed
4645
  bufferWalker = (const BYTE*)buffer;
4646 4647 4648

  while ( (size > 0) && (blockIndex != BLOCK_END_OF_CHAIN) )
  {
4649 4650
    ULARGE_INTEGER ulOffset;
    DWORD bytesWrittenAt;
4651 4652 4653
    /*
     * Calculate how many bytes we can copy from this big block.
     */
4654
    bytesToWrite =
4655
      min(This->parentStorage->bigBlockSize - offsetInBlock, size);
4656

4657 4658 4659 4660
    TRACE("block %i\n",blockIndex);
    ulOffset.u.HighPart = 0;
    ulOffset.u.LowPart = BLOCK_GetBigBlockOffset(blockIndex) +
                             offsetInBlock;
4661

4662 4663
    StorageImpl_WriteAt(This->parentStorage,
         ulOffset,
4664
         bufferWalker,
4665 4666
         bytesToWrite,
         &bytesWrittenAt);
4667

4668 4669 4670
    /*
     * Step to the next big block.
     */
4671
    if(size > bytesWrittenAt && FAILED(StorageImpl_GetNextBlockInChain(This->parentStorage, blockIndex,
4672
					      &blockIndex)))
4673
      return STG_E_DOCFILECORRUPT;
4674 4675 4676 4677

    bufferWalker  += bytesWrittenAt;
    size          -= bytesWrittenAt;
    *bytesWritten += bytesWrittenAt;
4678
    offsetInBlock  = 0;      /* There is no offset on the next block */
4679 4680 4681

    if (bytesWrittenAt != bytesToWrite)
      break;
4682
  }
4683

4684
  return (size == 0) ? S_OK : STG_E_WRITEFAULT;
4685 4686 4687 4688 4689 4690 4691
}

/******************************************************************************
 *      BlockChainStream_Shrink
 *
 * Shrinks this chain in the big block depot.
 */
4692 4693
static BOOL BlockChainStream_Shrink(BlockChainStream* This,
                                    ULARGE_INTEGER    newSize)
4694 4695 4696 4697 4698
{
  ULONG blockIndex, extraBlock;
  ULONG numBlocks;
  ULONG count = 1;

4699 4700 4701 4702 4703 4704
  /*
   * Reset the last accessed block cache.
   */
  This->lastBlockNoInSequence = 0xFFFFFFFF;
  This->lastBlockNoInSequenceIndex = BLOCK_END_OF_CHAIN;

4705 4706 4707
  /*
   * Figure out how many blocks are needed to contain the new size
   */
4708
  numBlocks = newSize.u.LowPart / This->parentStorage->bigBlockSize;
4709

4710
  if ((newSize.u.LowPart % This->parentStorage->bigBlockSize) != 0)
4711 4712 4713 4714 4715 4716 4717 4718 4719
    numBlocks++;

  blockIndex = BlockChainStream_GetHeadOfChain(This);

  /*
   * Go to the new end of chain
   */
  while (count < numBlocks)
  {
4720 4721 4722
    if(FAILED(StorageImpl_GetNextBlockInChain(This->parentStorage, blockIndex,
					      &blockIndex)))
      return FALSE;
4723 4724 4725 4726
    count++;
  }

  /* Get the next block before marking the new end */
4727 4728 4729
  if(FAILED(StorageImpl_GetNextBlockInChain(This->parentStorage, blockIndex,
					    &extraBlock)))
    return FALSE;
4730 4731

  /* Mark the new end of chain */
4732
  StorageImpl_SetNextBlockInChain(
4733 4734
    This->parentStorage,
    blockIndex,
4735 4736
    BLOCK_END_OF_CHAIN);

Thuy Nguyen's avatar
Thuy Nguyen committed
4737 4738 4739
  This->tailIndex = blockIndex;
  This->numBlocks = numBlocks;

4740 4741 4742 4743 4744
  /*
   * Mark the extra blocks as free
   */
  while (extraBlock != BLOCK_END_OF_CHAIN)
  {
4745 4746 4747
    if(FAILED(StorageImpl_GetNextBlockInChain(This->parentStorage, extraBlock,
					      &blockIndex)))
      return FALSE;
4748
    StorageImpl_FreeBigBlock(This->parentStorage, extraBlock);
4749 4750 4751 4752 4753 4754 4755 4756 4757 4758 4759
    extraBlock = blockIndex;
  }

  return TRUE;
}

/******************************************************************************
 *      BlockChainStream_Enlarge
 *
 * Grows this chain in the big block depot.
 */
4760 4761
static BOOL BlockChainStream_Enlarge(BlockChainStream* This,
                                     ULARGE_INTEGER    newSize)
4762 4763 4764 4765 4766 4767 4768 4769
{
  ULONG blockIndex, currentBlock;
  ULONG newNumBlocks;
  ULONG oldNumBlocks = 0;

  blockIndex = BlockChainStream_GetHeadOfChain(This);

  /*
4770
   * Empty chain. Create the head.
4771 4772 4773
   */
  if (blockIndex == BLOCK_END_OF_CHAIN)
  {
4774 4775
    blockIndex = StorageImpl_GetNextFreeBigBlock(This->parentStorage);
    StorageImpl_SetNextBlockInChain(This->parentStorage,
4776 4777 4778 4779 4780 4781 4782 4783 4784
                                      blockIndex,
                                      BLOCK_END_OF_CHAIN);

    if (This->headOfStreamPlaceHolder != 0)
    {
      *(This->headOfStreamPlaceHolder) = blockIndex;
    }
    else
    {
Thuy Nguyen's avatar
Thuy Nguyen committed
4785 4786
      StgProperty chainProp;
      assert(This->ownerPropertyIndex != PROPERTY_NULL);
4787

Thuy Nguyen's avatar
Thuy Nguyen committed
4788
      StorageImpl_ReadProperty(
4789
        This->parentStorage,
Thuy Nguyen's avatar
Thuy Nguyen committed
4790 4791
        This->ownerPropertyIndex,
        &chainProp);
4792

4793
      chainProp.startingBlock = blockIndex;
4794

Thuy Nguyen's avatar
Thuy Nguyen committed
4795
      StorageImpl_WriteProperty(
4796
        This->parentStorage,
Thuy Nguyen's avatar
Thuy Nguyen committed
4797 4798 4799
        This->ownerPropertyIndex,
        &chainProp);
    }
4800

Thuy Nguyen's avatar
Thuy Nguyen committed
4801 4802 4803
    This->tailIndex = blockIndex;
    This->numBlocks = 1;
  }
4804 4805 4806 4807

  /*
   * Figure out how many blocks are needed to contain this stream
   */
4808
  newNumBlocks = newSize.u.LowPart / This->parentStorage->bigBlockSize;
4809

4810
  if ((newSize.u.LowPart % This->parentStorage->bigBlockSize) != 0)
4811 4812 4813 4814 4815
    newNumBlocks++;

  /*
   * Go to the current end of chain
   */
Thuy Nguyen's avatar
Thuy Nguyen committed
4816
  if (This->tailIndex == BLOCK_END_OF_CHAIN)
4817 4818 4819
  {
    currentBlock = blockIndex;

Thuy Nguyen's avatar
Thuy Nguyen committed
4820 4821 4822 4823 4824
    while (blockIndex != BLOCK_END_OF_CHAIN)
    {
      This->numBlocks++;
      currentBlock = blockIndex;

4825 4826 4827
      if(FAILED(StorageImpl_GetNextBlockInChain(This->parentStorage, currentBlock,
						&blockIndex)))
	return FALSE;
Thuy Nguyen's avatar
Thuy Nguyen committed
4828 4829 4830
    }

    This->tailIndex = currentBlock;
4831 4832
  }

Thuy Nguyen's avatar
Thuy Nguyen committed
4833 4834 4835
  currentBlock = This->tailIndex;
  oldNumBlocks = This->numBlocks;

4836 4837 4838
  /*
   * Add new blocks to the chain
   */
4839
  if (oldNumBlocks < newNumBlocks)
4840
  {
4841 4842 4843
    while (oldNumBlocks < newNumBlocks)
    {
      blockIndex = StorageImpl_GetNextFreeBigBlock(This->parentStorage);
4844

4845
      StorageImpl_SetNextBlockInChain(
4846 4847
	This->parentStorage,
	currentBlock,
4848
	blockIndex);
4849

4850
      StorageImpl_SetNextBlockInChain(
4851 4852
        This->parentStorage,
	blockIndex,
4853
	BLOCK_END_OF_CHAIN);
4854

4855 4856 4857
      currentBlock = blockIndex;
      oldNumBlocks++;
    }
4858

4859 4860 4861
    This->tailIndex = blockIndex;
    This->numBlocks = newNumBlocks;
  }
Thuy Nguyen's avatar
Thuy Nguyen committed
4862

4863 4864 4865 4866 4867 4868 4869 4870 4871 4872 4873
  return TRUE;
}

/******************************************************************************
 *      BlockChainStream_SetSize
 *
 * Sets the size of this stream. The big block depot will be updated.
 * The file will grow if we grow the chain.
 *
 * TODO: Free the actual blocks in the file when we shrink the chain.
 *       Currently, the blocks are still in the file. So the file size
4874
 *       doesn't shrink even if we shrink streams.
4875
 */
4876
BOOL BlockChainStream_SetSize(
4877 4878 4879 4880 4881
  BlockChainStream* This,
  ULARGE_INTEGER    newSize)
{
  ULARGE_INTEGER size = BlockChainStream_GetSize(This);

4882
  if (newSize.u.LowPart == size.u.LowPart)
4883 4884
    return TRUE;

4885
  if (newSize.u.LowPart < size.u.LowPart)
4886 4887 4888 4889 4890 4891 4892 4893 4894 4895 4896 4897 4898 4899 4900 4901 4902
  {
    BlockChainStream_Shrink(This, newSize);
  }
  else
  {
    BlockChainStream_Enlarge(This, newSize);
  }

  return TRUE;
}

/******************************************************************************
 *      BlockChainStream_GetSize
 *
 * Returns the size of this chain.
 * Will return the block count if this chain doesn't have a property.
 */
4903
static ULARGE_INTEGER BlockChainStream_GetSize(BlockChainStream* This)
4904 4905 4906 4907 4908
{
  StgProperty chainProperty;

  if(This->headOfStreamPlaceHolder == NULL)
  {
4909 4910
    /*
     * This chain is a data stream read the property and return
4911 4912
     * the appropriate size
     */
4913
    StorageImpl_ReadProperty(
4914 4915 4916 4917 4918 4919 4920 4921 4922
      This->parentStorage,
      This->ownerPropertyIndex,
      &chainProperty);

    return chainProperty.size;
  }
  else
  {
    /*
4923 4924
     * this chain is a chain that does not have a property, figure out the
     * size by making the product number of used blocks times the
4925 4926 4927
     * size of them
     */
    ULARGE_INTEGER result;
4928
    result.u.HighPart = 0;
4929

4930
    result.u.LowPart  =
4931
      BlockChainStream_GetCount(This) *
4932 4933 4934 4935 4936 4937 4938 4939 4940 4941 4942
      This->parentStorage->bigBlockSize;

    return result;
  }
}

/******************************************************************************
** SmallBlockChainStream implementation
*/

SmallBlockChainStream* SmallBlockChainStream_Construct(
4943
  StorageImpl* parentStorage,
4944 4945 4946 4947 4948 4949 4950 4951 4952 4953 4954 4955 4956 4957 4958 4959 4960 4961 4962 4963 4964 4965 4966
  ULONG          propertyIndex)
{
  SmallBlockChainStream* newStream;

  newStream = HeapAlloc(GetProcessHeap(), 0, sizeof(SmallBlockChainStream));

  newStream->parentStorage      = parentStorage;
  newStream->ownerPropertyIndex = propertyIndex;

  return newStream;
}

void SmallBlockChainStream_Destroy(
  SmallBlockChainStream* This)
{
  HeapFree(GetProcessHeap(), 0, This);
}

/******************************************************************************
 *      SmallBlockChainStream_GetHeadOfChain
 *
 * Returns the head of this chain of small blocks.
 */
4967
static ULONG SmallBlockChainStream_GetHeadOfChain(
4968 4969 4970
  SmallBlockChainStream* This)
{
  StgProperty chainProperty;
4971
  BOOL      readSuccessful;
4972 4973 4974

  if (This->ownerPropertyIndex)
  {
4975
    readSuccessful = StorageImpl_ReadProperty(
4976 4977 4978 4979
                      This->parentStorage,
                      This->ownerPropertyIndex,
                      &chainProperty);

4980
    if (readSuccessful)
4981 4982 4983 4984 4985 4986 4987 4988 4989 4990 4991 4992 4993
    {
      return chainProperty.startingBlock;
    }

  }

  return BLOCK_END_OF_CHAIN;
}

/******************************************************************************
 *      SmallBlockChainStream_GetNextBlockInChain
 *
 * Returns the index of the next small block in this chain.
4994
 *
4995 4996 4997 4998
 * Return Values:
 *    - BLOCK_END_OF_CHAIN: end of this chain
 *    - BLOCK_UNUSED: small block 'blockIndex' is free
 */
4999
static HRESULT SmallBlockChainStream_GetNextBlockInChain(
5000
  SmallBlockChainStream* This,
5001 5002
  ULONG                  blockIndex,
  ULONG*                 nextBlockInChain)
5003 5004 5005 5006
{
  ULARGE_INTEGER offsetOfBlockInDepot;
  DWORD  buffer;
  ULONG  bytesRead;
5007
  HRESULT res;
5008

5009 5010
  *nextBlockInChain = BLOCK_END_OF_CHAIN;

5011 5012
  offsetOfBlockInDepot.u.HighPart = 0;
  offsetOfBlockInDepot.u.LowPart  = blockIndex * sizeof(ULONG);
5013 5014 5015 5016

  /*
   * Read those bytes in the buffer from the small block file.
   */
5017
  res = BlockChainStream_ReadAt(
5018 5019 5020 5021 5022 5023
              This->parentStorage->smallBlockDepotChain,
              offsetOfBlockInDepot,
              sizeof(DWORD),
              &buffer,
              &bytesRead);

5024
  if (SUCCEEDED(res))
5025
  {
5026
    StorageUtl_ReadDWord((BYTE *)&buffer, 0, nextBlockInChain);
5027
    return S_OK;
5028 5029
  }

5030
  return res;
5031 5032 5033 5034 5035 5036 5037 5038 5039 5040
}

/******************************************************************************
 *       SmallBlockChainStream_SetNextBlockInChain
 *
 * Writes the index of the next block of the specified block in the small
 * block depot.
 * To set the end of chain use BLOCK_END_OF_CHAIN as nextBlock.
 * To flag a block as free use BLOCK_UNUSED as nextBlock.
 */
5041
static void SmallBlockChainStream_SetNextBlockInChain(
5042 5043 5044 5045 5046 5047 5048 5049
  SmallBlockChainStream* This,
  ULONG                  blockIndex,
  ULONG                  nextBlock)
{
  ULARGE_INTEGER offsetOfBlockInDepot;
  DWORD  buffer;
  ULONG  bytesWritten;

5050 5051
  offsetOfBlockInDepot.u.HighPart = 0;
  offsetOfBlockInDepot.u.LowPart  = blockIndex * sizeof(ULONG);
5052

5053
  StorageUtl_WriteDWord((BYTE *)&buffer, 0, nextBlock);
5054 5055 5056 5057 5058 5059 5060 5061 5062 5063 5064 5065 5066 5067 5068 5069 5070

  /*
   * Read those bytes in the buffer from the small block file.
   */
  BlockChainStream_WriteAt(
    This->parentStorage->smallBlockDepotChain,
    offsetOfBlockInDepot,
    sizeof(DWORD),
    &buffer,
    &bytesWritten);
}

/******************************************************************************
 *      SmallBlockChainStream_FreeBlock
 *
 * Flag small block 'blockIndex' as free in the small block depot.
 */
5071
static void SmallBlockChainStream_FreeBlock(
5072 5073 5074 5075 5076 5077 5078 5079 5080 5081 5082 5083 5084
  SmallBlockChainStream* This,
  ULONG                  blockIndex)
{
  SmallBlockChainStream_SetNextBlockInChain(This, blockIndex, BLOCK_UNUSED);
}

/******************************************************************************
 *      SmallBlockChainStream_GetNextFreeBlock
 *
 * Returns the index of a free small block. The small block depot will be
 * enlarged if necessary. The small block chain will also be enlarged if
 * necessary.
 */
5085
static ULONG SmallBlockChainStream_GetNextFreeBlock(
5086 5087 5088 5089 5090 5091 5092
  SmallBlockChainStream* This)
{
  ULARGE_INTEGER offsetOfBlockInDepot;
  DWORD buffer;
  ULONG bytesRead;
  ULONG blockIndex = 0;
  ULONG nextBlockIndex = BLOCK_END_OF_CHAIN;
5093
  HRESULT res = S_OK;
5094 5095
  ULONG smallBlocksPerBigBlock;

5096
  offsetOfBlockInDepot.u.HighPart = 0;
5097 5098 5099 5100 5101 5102

  /*
   * Scan the small block depot for a free block
   */
  while (nextBlockIndex != BLOCK_UNUSED)
  {
5103
    offsetOfBlockInDepot.u.LowPart = blockIndex * sizeof(ULONG);
5104

5105
    res = BlockChainStream_ReadAt(
5106 5107 5108 5109 5110 5111 5112 5113 5114
                This->parentStorage->smallBlockDepotChain,
                offsetOfBlockInDepot,
                sizeof(DWORD),
                &buffer,
                &bytesRead);

    /*
     * If we run out of space for the small block depot, enlarge it
     */
5115
    if (SUCCEEDED(res))
5116
    {
5117
      StorageUtl_ReadDWord((BYTE *)&buffer, 0, &nextBlockIndex);
5118 5119 5120 5121 5122 5123

      if (nextBlockIndex != BLOCK_UNUSED)
        blockIndex++;
    }
    else
    {
5124
      ULONG count =
5125 5126 5127 5128
        BlockChainStream_GetCount(This->parentStorage->smallBlockDepotChain);

      ULONG sbdIndex = This->parentStorage->smallBlockDepotStart;
      ULONG nextBlock, newsbdIndex;
5129
      BYTE smallBlockDepot[BIG_BLOCK_SIZE];
5130 5131 5132 5133 5134

      nextBlock = sbdIndex;
      while (nextBlock != BLOCK_END_OF_CHAIN)
      {
        sbdIndex = nextBlock;
5135
	StorageImpl_GetNextBlockInChain(This->parentStorage, sbdIndex, &nextBlock);
5136 5137
      }

5138
      newsbdIndex = StorageImpl_GetNextFreeBigBlock(This->parentStorage);
5139
      if (sbdIndex != BLOCK_END_OF_CHAIN)
5140
        StorageImpl_SetNextBlockInChain(
5141 5142
          This->parentStorage,
          sbdIndex,
5143 5144
          newsbdIndex);

5145
      StorageImpl_SetNextBlockInChain(
5146 5147
        This->parentStorage,
        newsbdIndex,
5148 5149 5150 5151 5152 5153
        BLOCK_END_OF_CHAIN);

      /*
       * Initialize all the small blocks to free
       */
      memset(smallBlockDepot, BLOCK_UNUSED, This->parentStorage->bigBlockSize);
5154
      StorageImpl_WriteBigBlock(This->parentStorage, newsbdIndex, smallBlockDepot);
5155 5156 5157 5158 5159 5160 5161

      if (count == 0)
      {
        /*
         * We have just created the small block depot.
         */
        StgProperty rootProp;
5162
        ULONG sbStartIndex;
5163 5164 5165 5166 5167

        /*
         * Save it in the header
         */
        This->parentStorage->smallBlockDepotStart = newsbdIndex;
5168
        StorageImpl_SaveFileHeader(This->parentStorage);
5169 5170

        /*
5171
         * And allocate the first big block that will contain small blocks
5172
         */
5173
        sbStartIndex =
5174
          StorageImpl_GetNextFreeBigBlock(This->parentStorage);
5175

5176
        StorageImpl_SetNextBlockInChain(
5177 5178
          This->parentStorage,
          sbStartIndex,
5179 5180
          BLOCK_END_OF_CHAIN);

5181
        StorageImpl_ReadProperty(
5182
          This->parentStorage,
5183
          This->parentStorage->base.rootPropertySetIndex,
5184 5185 5186
          &rootProp);

        rootProp.startingBlock = sbStartIndex;
5187 5188
        rootProp.size.u.HighPart = 0;
        rootProp.size.u.LowPart  = This->parentStorage->bigBlockSize;
5189

5190
        StorageImpl_WriteProperty(
5191
          This->parentStorage,
5192
          This->parentStorage->base.rootPropertySetIndex,
5193 5194
          &rootProp);
      }
5195 5196
      else
        StorageImpl_SaveFileHeader(This->parentStorage);
5197 5198 5199
    }
  }

5200
  smallBlocksPerBigBlock =
5201 5202 5203 5204 5205 5206 5207 5208 5209 5210
    This->parentStorage->bigBlockSize / This->parentStorage->smallBlockSize;

  /*
   * Verify if we have to allocate big blocks to contain small blocks
   */
  if (blockIndex % smallBlocksPerBigBlock == 0)
  {
    StgProperty rootProp;
    ULONG blocksRequired = (blockIndex / smallBlocksPerBigBlock) + 1;

5211
    StorageImpl_ReadProperty(
5212
      This->parentStorage,
5213
      This->parentStorage->base.rootPropertySetIndex,
5214 5215
      &rootProp);

5216
    if (rootProp.size.u.LowPart <
5217 5218
       (blocksRequired * This->parentStorage->bigBlockSize))
    {
5219
      rootProp.size.u.LowPart += This->parentStorage->bigBlockSize;
5220 5221

      BlockChainStream_SetSize(
5222
        This->parentStorage->smallBlockRootChain,
5223 5224
        rootProp.size);

5225
      StorageImpl_WriteProperty(
5226
        This->parentStorage,
5227
        This->parentStorage->base.rootPropertySetIndex,
5228 5229 5230 5231 5232 5233 5234 5235 5236 5237 5238 5239
        &rootProp);
    }
  }

  return blockIndex;
}

/******************************************************************************
 *      SmallBlockChainStream_ReadAt
 *
 * Reads a specified number of bytes from this chain at the specified offset.
 * bytesRead may be NULL.
5240
 * Failure will be returned if the specified number of bytes has not been read.
5241
 */
5242
HRESULT SmallBlockChainStream_ReadAt(
5243 5244 5245 5246 5247 5248
  SmallBlockChainStream* This,
  ULARGE_INTEGER         offset,
  ULONG                  size,
  void*                  buffer,
  ULONG*                 bytesRead)
{
5249
  HRESULT rc = S_OK;
5250
  ULARGE_INTEGER offsetInBigBlockFile;
5251
  ULONG blockNoInSequence =
5252
    offset.u.LowPart / This->parentStorage->smallBlockSize;
5253

5254
  ULONG offsetInBlock = offset.u.LowPart % This->parentStorage->smallBlockSize;
5255 5256 5257 5258 5259 5260 5261 5262
  ULONG bytesToReadInBuffer;
  ULONG blockIndex;
  ULONG bytesReadFromBigBlockFile;
  BYTE* bufferWalker;

  /*
   * This should never happen on a small block file.
   */
5263
  assert(offset.u.HighPart==0);
5264 5265 5266 5267 5268 5269 5270 5271

  /*
   * Find the first block in the stream that contains part of the buffer.
   */
  blockIndex = SmallBlockChainStream_GetHeadOfChain(This);

  while ( (blockNoInSequence > 0) &&  (blockIndex != BLOCK_END_OF_CHAIN))
  {
5272 5273 5274
    rc = SmallBlockChainStream_GetNextBlockInChain(This, blockIndex, &blockIndex);
    if(FAILED(rc))
      return rc;
5275 5276 5277 5278 5279 5280 5281 5282 5283 5284 5285 5286 5287 5288
    blockNoInSequence--;
  }

  /*
   * Start reading the buffer.
   */
  *bytesRead   = 0;
  bufferWalker = buffer;

  while ( (size > 0) && (blockIndex != BLOCK_END_OF_CHAIN) )
  {
    /*
     * Calculate how many bytes we can copy from this small block.
     */
5289
    bytesToReadInBuffer =
5290
      min(This->parentStorage->smallBlockSize - offsetInBlock, size);
5291 5292 5293 5294

    /*
     * Calculate the offset of the small block in the small block file.
     */
5295 5296
    offsetInBigBlockFile.u.HighPart  = 0;
    offsetInBigBlockFile.u.LowPart   =
5297 5298
      blockIndex * This->parentStorage->smallBlockSize;

5299
    offsetInBigBlockFile.u.LowPart  += offsetInBlock;
5300 5301 5302

    /*
     * Read those bytes in the buffer from the small block file.
5303 5304
     * The small block has already been identified so it shouldn't fail
     * unless the file is corrupt.
5305
     */
5306
    rc = BlockChainStream_ReadAt(This->parentStorage->smallBlockRootChain,
5307 5308 5309
      offsetInBigBlockFile,
      bytesToReadInBuffer,
      bufferWalker,
5310 5311 5312 5313
      &bytesReadFromBigBlockFile);

    if (FAILED(rc))
      return rc;
5314 5315 5316 5317

    /*
     * Step to the next big block.
     */
5318 5319
    rc = SmallBlockChainStream_GetNextBlockInChain(This, blockIndex, &blockIndex);
    if(FAILED(rc))
5320
      return STG_E_DOCFILECORRUPT;
5321

5322 5323 5324 5325
    bufferWalker += bytesReadFromBigBlockFile;
    size         -= bytesReadFromBigBlockFile;
    *bytesRead   += bytesReadFromBigBlockFile;
    offsetInBlock = (offsetInBlock + bytesReadFromBigBlockFile) % This->parentStorage->smallBlockSize;
5326 5327
  }

5328
  return (size == 0) ? S_OK : STG_E_READFAULT;
5329 5330 5331 5332 5333 5334 5335 5336 5337
}

/******************************************************************************
 *       SmallBlockChainStream_WriteAt
 *
 * Writes the specified number of bytes to this chain at the specified offset.
 * bytesWritten may be NULL.
 * Will fail if not all specified number of bytes have been written.
 */
5338
HRESULT SmallBlockChainStream_WriteAt(
5339 5340 5341 5342 5343 5344 5345
  SmallBlockChainStream* This,
  ULARGE_INTEGER offset,
  ULONG          size,
  const void*    buffer,
  ULONG*         bytesWritten)
{
  ULARGE_INTEGER offsetInBigBlockFile;
5346
  ULONG blockNoInSequence =
5347
    offset.u.LowPart / This->parentStorage->smallBlockSize;
5348

5349
  ULONG offsetInBlock = offset.u.LowPart % This->parentStorage->smallBlockSize;
5350 5351
  ULONG bytesToWriteInBuffer;
  ULONG blockIndex;
5352
  ULONG bytesWrittenToBigBlockFile;
Eric Pouech's avatar
Eric Pouech committed
5353
  const BYTE* bufferWalker;
5354
  HRESULT res;
5355

5356 5357 5358
  /*
   * This should never happen on a small block file.
   */
5359
  assert(offset.u.HighPart==0);
5360

5361 5362 5363 5364
  /*
   * Find the first block in the stream that contains part of the buffer.
   */
  blockIndex = SmallBlockChainStream_GetHeadOfChain(This);
5365

5366 5367
  while ( (blockNoInSequence > 0) &&  (blockIndex != BLOCK_END_OF_CHAIN))
  {
5368
    if(FAILED(SmallBlockChainStream_GetNextBlockInChain(This, blockIndex, &blockIndex)))
5369
      return STG_E_DOCFILECORRUPT;
5370 5371
    blockNoInSequence--;
  }
5372

5373 5374 5375 5376 5377 5378 5379
  /*
   * Start writing the buffer.
   *
   * Here, I'm casting away the constness on the buffer variable
   * This is OK since we don't intend to modify that buffer.
   */
  *bytesWritten   = 0;
Eric Pouech's avatar
Eric Pouech committed
5380
  bufferWalker = (const BYTE*)buffer;
5381 5382 5383 5384 5385
  while ( (size > 0) && (blockIndex != BLOCK_END_OF_CHAIN) )
  {
    /*
     * Calculate how many bytes we can copy to this small block.
     */
5386
    bytesToWriteInBuffer =
5387
      min(This->parentStorage->smallBlockSize - offsetInBlock, size);
5388

5389 5390 5391
    /*
     * Calculate the offset of the small block in the small block file.
     */
5392 5393
    offsetInBigBlockFile.u.HighPart  = 0;
    offsetInBigBlockFile.u.LowPart   =
5394 5395
      blockIndex * This->parentStorage->smallBlockSize;

5396
    offsetInBigBlockFile.u.LowPart  += offsetInBlock;
5397

5398 5399 5400
    /*
     * Write those bytes in the buffer to the small block file.
     */
5401 5402
    res = BlockChainStream_WriteAt(
      This->parentStorage->smallBlockRootChain,
5403 5404 5405
      offsetInBigBlockFile,
      bytesToWriteInBuffer,
      bufferWalker,
5406
      &bytesWrittenToBigBlockFile);
5407 5408
    if (FAILED(res))
      return res;
5409

5410 5411 5412
    /*
     * Step to the next big block.
     */
5413 5414 5415
    if(FAILED(SmallBlockChainStream_GetNextBlockInChain(This, blockIndex,
							&blockIndex)))
      return FALSE;
5416 5417 5418 5419
    bufferWalker  += bytesWrittenToBigBlockFile;
    size          -= bytesWrittenToBigBlockFile;
    *bytesWritten += bytesWrittenToBigBlockFile;
    offsetInBlock  = (offsetInBlock + bytesWrittenToBigBlockFile) % This->parentStorage->smallBlockSize;
5420
  }
5421

5422
  return (size == 0) ? S_OK : STG_E_WRITEFAULT;
5423 5424 5425 5426 5427
}

/******************************************************************************
 *       SmallBlockChainStream_Shrink
 *
5428
 * Shrinks this chain in the small block depot.
5429
 */
5430
static BOOL SmallBlockChainStream_Shrink(
5431 5432 5433 5434 5435
  SmallBlockChainStream* This,
  ULARGE_INTEGER newSize)
{
  ULONG blockIndex, extraBlock;
  ULONG numBlocks;
5436
  ULONG count = 0;
5437

5438
  numBlocks = newSize.u.LowPart / This->parentStorage->smallBlockSize;
5439

5440
  if ((newSize.u.LowPart % This->parentStorage->smallBlockSize) != 0)
5441 5442 5443 5444 5445 5446 5447 5448 5449
    numBlocks++;

  blockIndex = SmallBlockChainStream_GetHeadOfChain(This);

  /*
   * Go to the new end of chain
   */
  while (count < numBlocks)
  {
5450 5451 5452
    if(FAILED(SmallBlockChainStream_GetNextBlockInChain(This, blockIndex,
							&blockIndex)))
      return FALSE;
5453 5454 5455
    count++;
  }

5456 5457
  /*
   * If the count is 0, we have a special case, the head of the chain was
5458
   * just freed.
5459 5460 5461 5462
   */
  if (count == 0)
  {
    StgProperty chainProp;
5463

5464
    StorageImpl_ReadProperty(This->parentStorage,
5465 5466 5467 5468 5469 5470 5471 5472 5473 5474 5475 5476 5477 5478 5479 5480 5481
			     This->ownerPropertyIndex,
			     &chainProp);

    chainProp.startingBlock = BLOCK_END_OF_CHAIN;

    StorageImpl_WriteProperty(This->parentStorage,
			      This->ownerPropertyIndex,
			      &chainProp);

    /*
     * We start freeing the chain at the head block.
     */
    extraBlock = blockIndex;
  }
  else
  {
    /* Get the next block before marking the new end */
5482 5483 5484
    if(FAILED(SmallBlockChainStream_GetNextBlockInChain(This, blockIndex,
							&extraBlock)))
      return FALSE;
5485 5486 5487

    /* Mark the new end of chain */
    SmallBlockChainStream_SetNextBlockInChain(
5488 5489
      This,
      blockIndex,
5490 5491
      BLOCK_END_OF_CHAIN);
  }
5492 5493 5494 5495 5496 5497

  /*
   * Mark the extra blocks as free
   */
  while (extraBlock != BLOCK_END_OF_CHAIN)
  {
5498 5499 5500
    if(FAILED(SmallBlockChainStream_GetNextBlockInChain(This, extraBlock,
							&blockIndex)))
      return FALSE;
5501 5502 5503 5504
    SmallBlockChainStream_FreeBlock(This, extraBlock);
    extraBlock = blockIndex;
  }

5505
  return TRUE;
5506 5507 5508 5509 5510 5511 5512
}

/******************************************************************************
 *      SmallBlockChainStream_Enlarge
 *
 * Grows this chain in the small block depot.
 */
5513
static BOOL SmallBlockChainStream_Enlarge(
5514 5515 5516 5517 5518 5519 5520 5521 5522 5523 5524 5525 5526 5527
  SmallBlockChainStream* This,
  ULARGE_INTEGER newSize)
{
  ULONG blockIndex, currentBlock;
  ULONG newNumBlocks;
  ULONG oldNumBlocks = 0;

  blockIndex = SmallBlockChainStream_GetHeadOfChain(This);

  /*
   * Empty chain
   */
  if (blockIndex == BLOCK_END_OF_CHAIN)
  {
5528

5529 5530
    StgProperty chainProp;

5531
    StorageImpl_ReadProperty(This->parentStorage, This->ownerPropertyIndex,
5532 5533 5534 5535
                               &chainProp);

    chainProp.startingBlock = SmallBlockChainStream_GetNextFreeBlock(This);

5536
    StorageImpl_WriteProperty(This->parentStorage, This->ownerPropertyIndex,
5537 5538 5539 5540
                                &chainProp);

    blockIndex = chainProp.startingBlock;
    SmallBlockChainStream_SetNextBlockInChain(
5541 5542
      This,
      blockIndex,
5543 5544 5545 5546 5547 5548 5549 5550
      BLOCK_END_OF_CHAIN);
  }

  currentBlock = blockIndex;

  /*
   * Figure out how many blocks are needed to contain this stream
   */
5551
  newNumBlocks = newSize.u.LowPart / This->parentStorage->smallBlockSize;
5552

5553
  if ((newSize.u.LowPart % This->parentStorage->smallBlockSize) != 0)
5554 5555 5556 5557 5558 5559 5560 5561 5562
    newNumBlocks++;

  /*
   * Go to the current end of chain
   */
  while (blockIndex != BLOCK_END_OF_CHAIN)
  {
    oldNumBlocks++;
    currentBlock = blockIndex;
5563 5564
    if(FAILED(SmallBlockChainStream_GetNextBlockInChain(This, currentBlock, &blockIndex)))
      return FALSE;
5565 5566 5567 5568 5569 5570 5571 5572 5573 5574 5575
  }

  /*
   * Add new blocks to the chain
   */
  while (oldNumBlocks < newNumBlocks)
  {
    blockIndex = SmallBlockChainStream_GetNextFreeBlock(This);
    SmallBlockChainStream_SetNextBlockInChain(This, currentBlock, blockIndex);

    SmallBlockChainStream_SetNextBlockInChain(
5576 5577
      This,
      blockIndex,
5578 5579 5580 5581 5582 5583 5584 5585 5586 5587 5588 5589 5590 5591 5592 5593 5594
      BLOCK_END_OF_CHAIN);

    currentBlock = blockIndex;
    oldNumBlocks++;
  }

  return TRUE;
}

/******************************************************************************
 *      SmallBlockChainStream_SetSize
 *
 * Sets the size of this stream.
 * The file will grow if we grow the chain.
 *
 * TODO: Free the actual blocks in the file when we shrink the chain.
 *       Currently, the blocks are still in the file. So the file size
5595
 *       doesn't shrink even if we shrink streams.
5596
 */
5597
BOOL SmallBlockChainStream_SetSize(
5598 5599 5600 5601 5602
                SmallBlockChainStream* This,
                ULARGE_INTEGER    newSize)
{
  ULARGE_INTEGER size = SmallBlockChainStream_GetSize(This);

5603
  if (newSize.u.LowPart == size.u.LowPart)
5604 5605
    return TRUE;

5606
  if (newSize.u.LowPart < size.u.LowPart)
5607 5608 5609 5610 5611 5612 5613 5614 5615 5616 5617 5618 5619 5620 5621 5622
  {
    SmallBlockChainStream_Shrink(This, newSize);
  }
  else
  {
    SmallBlockChainStream_Enlarge(This, newSize);
  }

  return TRUE;
}

/******************************************************************************
 *      SmallBlockChainStream_GetSize
 *
 * Returns the size of this chain.
 */
5623
static ULARGE_INTEGER SmallBlockChainStream_GetSize(SmallBlockChainStream* This)
5624 5625 5626
{
  StgProperty chainProperty;

5627
  StorageImpl_ReadProperty(
5628 5629 5630 5631 5632 5633 5634 5635
    This->parentStorage,
    This->ownerPropertyIndex,
    &chainProperty);

  return chainProperty.size;
}

/******************************************************************************
5636
 *    StgCreateDocfile  [OLE32.@]
5637 5638 5639 5640 5641 5642 5643 5644 5645
 * Creates a new compound file storage object
 *
 * PARAMS
 *  pwcsName  [ I] Unicode string with filename (can be relative or NULL)
 *  grfMode   [ I] Access mode for opening the new storage object (see STGM_ constants)
 *  reserved  [ ?] unused?, usually 0
 *  ppstgOpen [IO] A pointer to IStorage pointer to the new onject
 *
 * RETURNS
5646
 *  S_OK if the file was successfully created
5647 5648 5649 5650 5651 5652
 *  some STG_E_ value if error
 * NOTES
 *  if pwcsName is NULL, create file with new unique name
 *  the function can returns
 *  STG_S_CONVERTED if the specified file was successfully converted to storage format
 *  (unrealized now)
5653
 */
5654 5655
HRESULT WINAPI StgCreateDocfile(
  LPCOLESTR pwcsName,
5656 5657
  DWORD       grfMode,
  DWORD       reserved,
5658
  IStorage  **ppstgOpen)
5659
{
5660 5661
  StorageImpl* newStorage = 0;
  HANDLE       hFile      = INVALID_HANDLE_VALUE;
5662
  HRESULT        hr         = STG_E_INVALIDFLAG;
5663 5664 5665 5666
  DWORD          shareMode;
  DWORD          accessMode;
  DWORD          creationMode;
  DWORD          fileAttributes;
5667
  WCHAR          tempFileName[MAX_PATH];
5668

5669
  TRACE("(%s, %x, %d, %p)\n",
5670
	debugstr_w(pwcsName), grfMode,
5671 5672
	reserved, ppstgOpen);

5673 5674 5675
  /*
   * Validate the parameters
   */
5676
  if (ppstgOpen == 0)
5677
    return STG_E_INVALIDPOINTER;
5678 5679
  if (reserved != 0)
    return STG_E_INVALIDPARAMETER;
5680

5681 5682 5683 5684
  /* if no share mode given then DENY_NONE is the default */
  if (STGM_SHARE_MODE(grfMode) == 0)
      grfMode |= STGM_SHARE_DENY_NONE;

5685 5686 5687 5688
  /*
   * Validate the STGM flags
   */
  if ( FAILED( validateSTGM(grfMode) ))
5689
    goto end;
5690

5691
  /* StgCreateDocFile seems to refuse readonly access, despite MSDN */
5692 5693 5694 5695 5696 5697
  switch(STGM_ACCESS_MODE(grfMode))
  {
  case STGM_WRITE:
  case STGM_READWRITE:
    break;
  default:
5698
    goto end;
5699
  }
5700

5701 5702
  /* in direct mode, can only use SHARE_EXCLUSIVE */
  if (!(grfMode & STGM_TRANSACTED) && (STGM_SHARE_MODE(grfMode) != STGM_SHARE_EXCLUSIVE))
5703
    goto end;
5704

5705 5706
  /* but in transacted mode, any share mode is valid */

5707 5708 5709 5710 5711 5712
  /*
   * Generate a unique name.
   */
  if (pwcsName == 0)
  {
    WCHAR tempPath[MAX_PATH];
5713
    static const WCHAR prefix[] = { 'S', 'T', 'O', 0 };
5714 5715 5716 5717 5718 5719 5720 5721 5722 5723

    memset(tempPath, 0, sizeof(tempPath));
    memset(tempFileName, 0, sizeof(tempFileName));

    if ((GetTempPathW(MAX_PATH, tempPath)) == 0 )
      tempPath[0] = '.';

    if (GetTempFileNameW(tempPath, prefix, 0, tempFileName) != 0)
      pwcsName = tempFileName;
    else
5724 5725 5726 5727
    {
      hr = STG_E_INSUFFICIENTMEMORY;
      goto end;
    }
5728 5729 5730 5731 5732 5733

    creationMode = TRUNCATE_EXISTING;
  }
  else
  {
    creationMode = GetCreationModeFromSTGM(grfMode);
5734 5735
  }

5736
  /*
5737
   * Interpret the STGM value grfMode
5738 5739 5740 5741 5742 5743 5744 5745 5746 5747
   */
  shareMode    = GetShareModeFromSTGM(grfMode);
  accessMode   = GetAccessModeFromSTGM(grfMode);

  if (grfMode & STGM_DELETEONRELEASE)
    fileAttributes = FILE_FLAG_RANDOM_ACCESS | FILE_FLAG_DELETE_ON_CLOSE;
  else
    fileAttributes = FILE_ATTRIBUTE_NORMAL | FILE_FLAG_RANDOM_ACCESS;

  if (grfMode & STGM_TRANSACTED)
5748
    FIXME("Transacted mode not implemented.\n");
5749

5750 5751 5752 5753 5754
  /*
   * Initialize the "out" parameter.
   */
  *ppstgOpen = 0;

5755
  hFile = CreateFileW(pwcsName,
5756 5757
                        accessMode,
                        shareMode,
5758
                        NULL,
5759 5760
                        creationMode,
                        fileAttributes,
5761
                        0);
5762

5763
  if (hFile == INVALID_HANDLE_VALUE)
5764
  {
5765
    if(GetLastError() == ERROR_FILE_EXISTS)
5766 5767 5768 5769
      hr = STG_E_FILEALREADYEXISTS;
    else
      hr = E_FAIL;
    goto end;
5770 5771 5772 5773 5774
  }

  /*
   * Allocate and initialize the new IStorage32object.
   */
5775
  newStorage = HeapAlloc(GetProcessHeap(), 0, sizeof(StorageImpl));
5776

5777
  if (newStorage == 0)
5778 5779 5780 5781
  {
    hr = STG_E_INSUFFICIENTMEMORY;
    goto end;
  }
5782

5783
  hr = StorageImpl_Construct(
5784 5785
         newStorage,
         hFile,
5786
        pwcsName,
5787 5788
         NULL,
         grfMode,
5789
         TRUE,
5790
         TRUE);
5791

5792
  if (FAILED(hr))
5793 5794
  {
    HeapFree(GetProcessHeap(), 0, newStorage);
5795
    goto end;
5796
  }
5797 5798 5799 5800

  /*
   * Get an "out" pointer for the caller.
   */
5801 5802
  hr = StorageBaseImpl_QueryInterface(
         (IStorage*)newStorage,
5803
         (REFIID)&IID_IStorage,
5804
         (void**)ppstgOpen);
5805
end:
5806
  TRACE("<-- %p  r = %08x\n", *ppstgOpen, hr);
5807 5808 5809 5810

  return hr;
}

5811 5812 5813
/******************************************************************************
 *              StgCreateStorageEx        [OLE32.@]
 */
5814 5815
HRESULT WINAPI StgCreateStorageEx(const WCHAR* pwcsName, DWORD grfMode, DWORD stgfmt, DWORD grfAttrs, STGOPTIONS* pStgOptions, void* reserved, REFIID riid, void** ppObjectOpen)
{
5816
    TRACE("(%s, %x, %x, %x, %p, %p, %p, %p)\n", debugstr_w(pwcsName),
5817
          grfMode, stgfmt, grfAttrs, pStgOptions, reserved, riid, ppObjectOpen);
5818 5819 5820 5821 5822 5823 5824

    if (stgfmt != STGFMT_FILE && grfAttrs != 0)
    {
        ERR("grfAttrs must be 0 if stgfmt != STGFMT_FILE\n");
        return STG_E_INVALIDPARAMETER;  
    }

5825
    if (stgfmt == STGFMT_FILE && grfAttrs != 0 && grfAttrs != FILE_FLAG_NO_BUFFERING)
5826 5827 5828 5829 5830 5831 5832 5833 5834 5835 5836 5837 5838 5839 5840 5841 5842 5843 5844
    {
        ERR("grfAttrs must be 0 or FILE_FLAG_NO_BUFFERING if stgfmt == STGFMT_FILE\n");
        return STG_E_INVALIDPARAMETER;  
    }

    if (stgfmt == STGFMT_FILE)
    {
        ERR("Cannot use STGFMT_FILE - this is NTFS only\n");  
        return STG_E_INVALIDPARAMETER;
    }

    if (stgfmt == STGFMT_STORAGE || stgfmt == STGFMT_DOCFILE)
    {
        FIXME("Stub: calling StgCreateDocfile, but ignoring pStgOptions and grfAttrs\n");
        return StgCreateDocfile(pwcsName, grfMode, 0, (IStorage **)ppObjectOpen); 
    }

    ERR("Invalid stgfmt argument\n");
    return STG_E_INVALIDPARAMETER;
5845 5846
}

5847 5848 5849 5850 5851 5852 5853 5854
/******************************************************************************
 *              StgCreatePropSetStg       [OLE32.@]
 */
HRESULT WINAPI StgCreatePropSetStg(IStorage *pstg, DWORD reserved,
 IPropertySetStorage **ppPropSetStg)
{
    HRESULT hr;

5855
    TRACE("(%p, 0x%x, %p)\n", pstg, reserved, ppPropSetStg);
5856 5857 5858 5859 5860 5861 5862 5863
    if (reserved)
        hr = STG_E_INVALIDPARAMETER;
    else
        hr = StorageBaseImpl_QueryInterface(pstg, &IID_IPropertySetStorage,
         (void**)ppPropSetStg);
    return hr;
}

5864 5865 5866 5867 5868
/******************************************************************************
 *              StgOpenStorageEx      [OLE32.@]
 */
HRESULT WINAPI StgOpenStorageEx(const WCHAR* pwcsName, DWORD grfMode, DWORD stgfmt, DWORD grfAttrs, STGOPTIONS* pStgOptions, void* reserved, REFIID riid, void** ppObjectOpen)
{
5869
    TRACE("(%s, %x, %x, %x, %p, %p, %p, %p)\n", debugstr_w(pwcsName),
5870 5871 5872 5873 5874 5875 5876 5877
          grfMode, stgfmt, grfAttrs, pStgOptions, reserved, riid, ppObjectOpen);

    if (stgfmt != STGFMT_DOCFILE && grfAttrs != 0)
    {
        ERR("grfAttrs must be 0 if stgfmt != STGFMT_DOCFILE\n");
        return STG_E_INVALIDPARAMETER;  
    }

5878
    switch (stgfmt)
5879
    {
5880
    case STGFMT_FILE:
5881 5882
        ERR("Cannot use STGFMT_FILE - this is NTFS only\n");  
        return STG_E_INVALIDPARAMETER;
5883 5884 5885
        
    case STGFMT_STORAGE:
        break;
5886

5887 5888 5889 5890 5891 5892
    case STGFMT_DOCFILE:
        if (grfAttrs && grfAttrs != FILE_FLAG_NO_BUFFERING)
        {
            ERR("grfAttrs must be 0 or FILE_FLAG_NO_BUFFERING if stgfmt == STGFMT_DOCFILE\n");
            return STG_E_INVALIDPARAMETER;  
        }
5893
        FIXME("Stub: calling StgOpenStorage, but ignoring pStgOptions and grfAttrs\n");
5894 5895 5896 5897 5898 5899 5900 5901
        break;

    case STGFMT_ANY:
        WARN("STGFMT_ANY assuming storage\n");
        break;

    default:
        return STG_E_INVALIDPARAMETER;
5902 5903
    }

5904
    return StgOpenStorage(pwcsName, NULL, grfMode, (SNB)NULL, 0, (IStorage **)ppObjectOpen); 
5905 5906 5907
}


5908
/******************************************************************************
5909
 *              StgOpenStorage        [OLE32.@]
5910
 */
5911 5912 5913
HRESULT WINAPI StgOpenStorage(
  const OLECHAR *pwcsName,
  IStorage      *pstgPriority,
5914 5915 5916 5917
  DWORD          grfMode,
  SNB            snbExclude,
  DWORD          reserved,
  IStorage     **ppstgOpen)
5918
{
5919
  StorageImpl*   newStorage = 0;
5920
  HRESULT        hr = S_OK;
5921
  HANDLE         hFile = 0;
5922 5923
  DWORD          shareMode;
  DWORD          accessMode;
Alexandre Julliard's avatar
Alexandre Julliard committed
5924
  WCHAR          fullname[MAX_PATH];
5925

5926
  TRACE("(%s, %p, %x, %p, %d, %p)\n",
5927 5928 5929
	debugstr_w(pwcsName), pstgPriority, grfMode,
	snbExclude, reserved, ppstgOpen);

5930
  /*
5931
   * Perform sanity checks
5932
   */
5933 5934 5935 5936 5937 5938 5939
  if (pwcsName == 0)
  {
    hr = STG_E_INVALIDNAME;
    goto end;
  }

  if (ppstgOpen == 0)
Alexandre Julliard's avatar
Alexandre Julliard committed
5940 5941 5942 5943
  {
    hr = STG_E_INVALIDPOINTER;
    goto end;
  }
5944

5945 5946 5947 5948 5949 5950
  if (reserved)
  {
    hr = STG_E_INVALIDPARAMETER;
    goto end;
  }

5951 5952
  if (grfMode & STGM_PRIORITY)
  {
5953 5954 5955 5956 5957 5958
    if (grfMode & (STGM_TRANSACTED|STGM_SIMPLE|STGM_NOSCRATCH|STGM_NOSNAPSHOT))
      return STG_E_INVALIDFLAG;
    if (grfMode & STGM_DELETEONRELEASE)
      return STG_E_INVALIDFUNCTION;
    if(STGM_ACCESS_MODE(grfMode) != STGM_READ)
      return STG_E_INVALIDFLAG;
5959
    grfMode &= ~0xf0; /* remove the existing sharing mode */
5960 5961 5962 5963 5964 5965 5966 5967
    grfMode |= STGM_SHARE_DENY_NONE;

    /* STGM_PRIORITY stops other IStorage objects on the same file from
     * committing until the STGM_PRIORITY IStorage is closed. it also
     * stops non-transacted mode StgOpenStorage calls with write access from
     * succeeding. obviously, both of these cannot be achieved through just
     * file share flags */
    FIXME("STGM_PRIORITY mode not implemented correctly\n");
5968 5969
  }

5970 5971 5972
  /*
   * Validate the sharing mode
   */
5973
  if (!(grfMode & (STGM_TRANSACTED|STGM_PRIORITY)))
5974 5975 5976 5977 5978 5979 5980 5981 5982
    switch(STGM_SHARE_MODE(grfMode))
    {
      case STGM_SHARE_EXCLUSIVE:
      case STGM_SHARE_DENY_WRITE:
        break;
      default:
        hr = STG_E_INVALIDFLAG;
        goto end;
    }
5983

5984 5985 5986
  /*
   * Validate the STGM flags
   */
5987 5988
  if ( FAILED( validateSTGM(grfMode) ) ||
       (grfMode&STGM_CREATE))
Alexandre Julliard's avatar
Alexandre Julliard committed
5989 5990 5991 5992
  {
    hr = STG_E_INVALIDFLAG;
    goto end;
  }
5993

5994 5995 5996 5997 5998 5999 6000 6001 6002
  /* shared reading requires transacted mode */
  if( STGM_SHARE_MODE(grfMode) == STGM_SHARE_DENY_WRITE &&
      STGM_ACCESS_MODE(grfMode) == STGM_READWRITE &&
     !(grfMode&STGM_TRANSACTED) )
  {
    hr = STG_E_INVALIDFLAG;
    goto end;
  }

6003 6004 6005 6006 6007 6008
  /*
   * Interpret the STGM value grfMode
   */
  shareMode    = GetShareModeFromSTGM(grfMode);
  accessMode   = GetAccessModeFromSTGM(grfMode);

6009 6010 6011 6012
  /*
   * Initialize the "out" parameter.
   */
  *ppstgOpen = 0;
6013

6014 6015 6016 6017 6018 6019 6020
  hFile = CreateFileW( pwcsName,
                       accessMode,
                       shareMode,
                       NULL,
                       OPEN_EXISTING,
                       FILE_ATTRIBUTE_NORMAL | FILE_FLAG_RANDOM_ACCESS,
                       0);
6021

6022
  if (hFile==INVALID_HANDLE_VALUE)
6023
  {
6024 6025
    DWORD last_error = GetLastError();

Alexandre Julliard's avatar
Alexandre Julliard committed
6026 6027
    hr = E_FAIL;

6028 6029 6030 6031 6032 6033 6034 6035 6036 6037 6038 6039 6040 6041 6042 6043 6044 6045 6046 6047 6048 6049 6050
    switch (last_error)
    {
      case ERROR_FILE_NOT_FOUND:
        hr = STG_E_FILENOTFOUND;
        break;

      case ERROR_PATH_NOT_FOUND:
        hr = STG_E_PATHNOTFOUND;
        break;

      case ERROR_ACCESS_DENIED:
      case ERROR_WRITE_PROTECT:
        hr = STG_E_ACCESSDENIED;
        break;

      case ERROR_SHARING_VIOLATION:
        hr = STG_E_SHAREVIOLATION;
        break;

      default:
        hr = E_FAIL;
    }

Alexandre Julliard's avatar
Alexandre Julliard committed
6051
    goto end;
6052 6053
  }

6054 6055 6056 6057
  /*
   * Refuse to open the file if it's too small to be a structured storage file
   * FIXME: verify the file when reading instead of here
   */
6058
  if (GetFileSize(hFile, NULL) < 0x100)
6059 6060 6061 6062 6063
  {
    CloseHandle(hFile);
    hr = STG_E_FILEALREADYEXISTS;
    goto end;
  }
6064

6065 6066 6067
  /*
   * Allocate and initialize the new IStorage32object.
   */
6068
  newStorage = HeapAlloc(GetProcessHeap(), 0, sizeof(StorageImpl));
6069

6070
  if (newStorage == 0)
Alexandre Julliard's avatar
Alexandre Julliard committed
6071 6072 6073 6074
  {
    hr = STG_E_INSUFFICIENTMEMORY;
    goto end;
  }
6075

6076
  /* Initialize the storage */
6077
  hr = StorageImpl_Construct(
6078 6079
         newStorage,
         hFile,
6080
         pwcsName,
6081 6082
         NULL,
         grfMode,
6083
         TRUE,
6084
         FALSE );
6085

6086
  if (FAILED(hr))
6087 6088
  {
    HeapFree(GetProcessHeap(), 0, newStorage);
6089 6090 6091 6092
    /*
     * According to the docs if the file is not a storage, return STG_E_FILEALREADYEXISTS
     */
    if(hr == STG_E_INVALIDHEADER)
Alexandre Julliard's avatar
Alexandre Julliard committed
6093 6094
	hr = STG_E_FILEALREADYEXISTS;
    goto end;
6095
  }
6096

Alexandre Julliard's avatar
Alexandre Julliard committed
6097 6098 6099
  /* prepare the file name string given in lieu of the root property name */
  GetFullPathNameW(pwcsName, MAX_PATH, fullname, NULL);
  memcpy(newStorage->filename, fullname, PROPERTY_NAME_BUFFER_LEN);
6100
  newStorage->filename[PROPERTY_NAME_BUFFER_LEN-1] = '\0';
Alexandre Julliard's avatar
Alexandre Julliard committed
6101

6102 6103 6104
  /*
   * Get an "out" pointer for the caller.
   */
6105 6106
  hr = StorageBaseImpl_QueryInterface(
         (IStorage*)newStorage,
6107
         (REFIID)&IID_IStorage,
6108
         (void**)ppstgOpen);
6109

Alexandre Julliard's avatar
Alexandre Julliard committed
6110
end:
6111
  TRACE("<-- %08x, IStorage %p\n", hr, ppstgOpen ? *ppstgOpen : NULL);
6112 6113 6114 6115
  return hr;
}

/******************************************************************************
6116
 *    StgCreateDocfileOnILockBytes    [OLE32.@]
6117 6118 6119 6120 6121 6122 6123 6124 6125 6126 6127 6128 6129 6130 6131 6132 6133 6134 6135 6136 6137 6138 6139 6140 6141 6142 6143
 */
HRESULT WINAPI StgCreateDocfileOnILockBytes(
      ILockBytes *plkbyt,
      DWORD grfMode,
      DWORD reserved,
      IStorage** ppstgOpen)
{
  StorageImpl*   newStorage = 0;
  HRESULT        hr         = S_OK;

  /*
   * Validate the parameters
   */
  if ((ppstgOpen == 0) || (plkbyt == 0))
    return STG_E_INVALIDPOINTER;

  /*
   * Allocate and initialize the new IStorage object.
   */
  newStorage = HeapAlloc(GetProcessHeap(), 0, sizeof(StorageImpl));

  if (newStorage == 0)
    return STG_E_INSUFFICIENTMEMORY;

  hr = StorageImpl_Construct(
         newStorage,
         0,
6144
        0,
6145 6146
         plkbyt,
         grfMode,
6147 6148
         FALSE,
         TRUE);
6149 6150 6151 6152 6153 6154 6155 6156 6157 6158 6159 6160 6161 6162 6163

  if (FAILED(hr))
  {
    HeapFree(GetProcessHeap(), 0, newStorage);
    return hr;
  }

  /*
   * Get an "out" pointer for the caller.
   */
  hr = StorageBaseImpl_QueryInterface(
         (IStorage*)newStorage,
         (REFIID)&IID_IStorage,
         (void**)ppstgOpen);

6164
  return hr;
6165 6166 6167
}

/******************************************************************************
6168
 *    StgOpenStorageOnILockBytes    [OLE32.@]
6169 6170 6171 6172 6173 6174 6175 6176 6177 6178 6179 6180 6181 6182 6183 6184 6185 6186 6187 6188 6189 6190 6191 6192 6193 6194 6195 6196 6197 6198 6199 6200 6201
 */
HRESULT WINAPI StgOpenStorageOnILockBytes(
      ILockBytes *plkbyt,
      IStorage *pstgPriority,
      DWORD grfMode,
      SNB snbExclude,
      DWORD reserved,
      IStorage **ppstgOpen)
{
  StorageImpl* newStorage = 0;
  HRESULT        hr = S_OK;

  /*
   * Perform a sanity check
   */
  if ((plkbyt == 0) || (ppstgOpen == 0))
    return STG_E_INVALIDPOINTER;

  /*
   * Validate the STGM flags
   */
  if ( FAILED( validateSTGM(grfMode) ))
    return STG_E_INVALIDFLAG;

  /*
   * Initialize the "out" parameter.
   */
  *ppstgOpen = 0;

  /*
   * Allocate and initialize the new IStorage object.
   */
  newStorage = HeapAlloc(GetProcessHeap(), 0, sizeof(StorageImpl));
6202

6203 6204 6205 6206 6207 6208
  if (newStorage == 0)
    return STG_E_INSUFFICIENTMEMORY;

  hr = StorageImpl_Construct(
         newStorage,
         0,
6209
         0,
6210 6211
         plkbyt,
         grfMode,
6212
         FALSE,
6213 6214 6215 6216 6217 6218 6219 6220 6221 6222 6223 6224 6225 6226 6227 6228 6229 6230 6231
         FALSE);

  if (FAILED(hr))
  {
    HeapFree(GetProcessHeap(), 0, newStorage);
    return hr;
  }

  /*
   * Get an "out" pointer for the caller.
   */
  hr = StorageBaseImpl_QueryInterface(
         (IStorage*)newStorage,
         (REFIID)&IID_IStorage,
         (void**)ppstgOpen);

  return hr;
}

Jim Aston's avatar
Jim Aston committed
6232
/******************************************************************************
6233 6234
 *              StgSetTimes [ole32.@]
 *              StgSetTimes [OLE32.@]
Jim Aston's avatar
Jim Aston committed
6235 6236 6237
 *
 *
 */
Mike McCormack's avatar
Mike McCormack committed
6238 6239
HRESULT WINAPI StgSetTimes(OLECHAR const *str, FILETIME const *pctime,
                           FILETIME const *patime, FILETIME const *pmtime)
Jim Aston's avatar
Jim Aston committed
6240
{
Mike McCormack's avatar
Mike McCormack committed
6241 6242 6243 6244 6245 6246 6247 6248 6249 6250 6251 6252 6253 6254
  IStorage *stg = NULL;
  HRESULT r;
 
  TRACE("%s %p %p %p\n", debugstr_w(str), pctime, patime, pmtime);

  r = StgOpenStorage(str, NULL, STGM_READWRITE | STGM_SHARE_DENY_WRITE,
                     0, 0, &stg);
  if( SUCCEEDED(r) )
  {
    r = IStorage_SetElementTimes(stg, NULL, pctime, patime, pmtime);
    IStorage_Release(stg);
  }

  return r;
Jim Aston's avatar
Jim Aston committed
6255 6256
}

6257
/******************************************************************************
6258
 *              StgIsStorageILockBytes        [OLE32.@]
6259 6260 6261 6262 6263 6264 6265 6266
 *
 * Determines if the ILockBytes contains a storage object.
 */
HRESULT WINAPI StgIsStorageILockBytes(ILockBytes *plkbyt)
{
  BYTE sig[8];
  ULARGE_INTEGER offset;

6267 6268
  offset.u.HighPart = 0;
  offset.u.LowPart  = 0;
6269 6270 6271 6272 6273 6274 6275 6276 6277 6278

  ILockBytes_ReadAt(plkbyt, offset, sig, sizeof(sig), NULL);

  if (memcmp(sig, STORAGE_magic, sizeof(STORAGE_magic)) == 0)
    return S_OK;

  return S_FALSE;
}

/******************************************************************************
6279
 *              WriteClassStg        [OLE32.@]
6280 6281 6282
 *
 * This method will store the specified CLSID in the specified storage object
 */
6283
HRESULT WINAPI WriteClassStg(IStorage* pStg, REFCLSID rclsid)
6284 6285 6286
{
  HRESULT hRes;

6287 6288
  if(!pStg)
    return E_INVALIDARG;
6289

6290
  hRes = IStorage_SetClass(pStg, rclsid);
6291 6292 6293 6294

  return hRes;
}

6295
/***********************************************************************
6296
 *    ReadClassStg (OLE32.@)
Noomen Hamza's avatar
Noomen Hamza committed
6297
 *
6298 6299 6300 6301 6302 6303 6304 6305 6306 6307
 * This method reads the CLSID previously written to a storage object with
 * the WriteClassStg.
 *
 * PARAMS
 *  pstg    [I] IStorage pointer
 *  pclsid  [O] Pointer to where the CLSID is written
 *
 * RETURNS
 *  Success: S_OK.
 *  Failure: HRESULT code.
Noomen Hamza's avatar
Noomen Hamza committed
6308 6309 6310 6311 6312
 */
HRESULT WINAPI ReadClassStg(IStorage *pstg,CLSID *pclsid){

    STATSTG pstatstg;
    HRESULT hRes;
6313

6314 6315 6316 6317
    TRACE("(%p, %p)\n", pstg, pclsid);

    if(!pstg || !pclsid)
        return E_INVALIDARG;
Noomen Hamza's avatar
Noomen Hamza committed
6318 6319 6320 6321 6322 6323 6324 6325 6326 6327 6328 6329

   /*
    * read a STATSTG structure (contains the clsid) from the storage
    */
    hRes=IStorage_Stat(pstg,&pstatstg,STATFLAG_DEFAULT);

    if(SUCCEEDED(hRes))
        *pclsid=pstatstg.clsid;

    return hRes;
}

6330
/***********************************************************************
6331
 *    OleLoadFromStream (OLE32.@)
Noomen Hamza's avatar
Noomen Hamza committed
6332 6333 6334 6335 6336
 *
 * This function loads an object from stream
 */
HRESULT  WINAPI OleLoadFromStream(IStream *pStm,REFIID iidInterface,void** ppvObj)
{
6337 6338 6339
    CLSID	clsid;
    HRESULT	res;
    LPPERSISTSTREAM	xstm;
Noomen Hamza's avatar
Noomen Hamza committed
6340

6341
    TRACE("(%p,%s,%p)\n",pStm,debugstr_guid(iidInterface),ppvObj);
Noomen Hamza's avatar
Noomen Hamza committed
6342 6343

    res=ReadClassStm(pStm,&clsid);
6344 6345 6346 6347 6348
    if (!SUCCEEDED(res))
	return res;
    res=CoCreateInstance(&clsid,NULL,CLSCTX_INPROC_SERVER,iidInterface,ppvObj);
    if (!SUCCEEDED(res))
	return res;
6349
    res=IUnknown_QueryInterface((IUnknown*)*ppvObj,&IID_IPersistStream,(LPVOID*)&xstm);
6350 6351 6352
    if (!SUCCEEDED(res)) {
	IUnknown_Release((IUnknown*)*ppvObj);
	return res;
Noomen Hamza's avatar
Noomen Hamza committed
6353
    }
6354 6355 6356 6357 6358 6359 6360
    res=IPersistStream_Load(xstm,pStm);
    IPersistStream_Release(xstm);
    /* FIXME: all refcounts ok at this point? I think they should be:
     * 		pStm	: unchanged
     *		ppvObj	: 1
     *		xstm	: 0 (released)
     */
Noomen Hamza's avatar
Noomen Hamza committed
6361 6362 6363
    return res;
}

6364
/***********************************************************************
6365
 *    OleSaveToStream (OLE32.@)
Noomen Hamza's avatar
Noomen Hamza committed
6366
 *
6367 6368
 * This function saves an object with the IPersistStream interface on it
 * to the specified stream.
Noomen Hamza's avatar
Noomen Hamza committed
6369 6370 6371 6372 6373 6374
 */
HRESULT  WINAPI OleSaveToStream(IPersistStream *pPStm,IStream *pStm)
{

    CLSID clsid;
    HRESULT res;
6375

6376
    TRACE("(%p,%p)\n",pPStm,pStm);
Noomen Hamza's avatar
Noomen Hamza committed
6377 6378 6379 6380

    res=IPersistStream_GetClassID(pPStm,&clsid);

    if (SUCCEEDED(res)){
6381

Noomen Hamza's avatar
Noomen Hamza committed
6382 6383 6384 6385
        res=WriteClassStm(pStm,&clsid);

        if (SUCCEEDED(res))

6386
            res=IPersistStream_Save(pPStm,pStm,TRUE);
Noomen Hamza's avatar
Noomen Hamza committed
6387 6388
    }

6389
    TRACE("Finished Save\n");
Noomen Hamza's avatar
Noomen Hamza committed
6390 6391
    return res;
}
6392

6393 6394 6395
/****************************************************************************
 * This method validate a STGM parameter that can contain the values below
 *
6396 6397 6398
 * The stgm modes in 0x0000ffff are not bit masks, but distinct 4 bit values.
 * The stgm values contained in 0xffff0000 are bitmasks.
 *
6399 6400 6401
 * STGM_DIRECT               0x00000000
 * STGM_TRANSACTED           0x00010000
 * STGM_SIMPLE               0x08000000
6402
 *
6403 6404 6405
 * STGM_READ                 0x00000000
 * STGM_WRITE                0x00000001
 * STGM_READWRITE            0x00000002
6406
 *
6407 6408 6409 6410
 * STGM_SHARE_DENY_NONE      0x00000040
 * STGM_SHARE_DENY_READ      0x00000030
 * STGM_SHARE_DENY_WRITE     0x00000020
 * STGM_SHARE_EXCLUSIVE      0x00000010
6411
 *
6412 6413 6414 6415 6416 6417 6418 6419 6420 6421 6422 6423
 * STGM_PRIORITY             0x00040000
 * STGM_DELETEONRELEASE      0x04000000
 *
 * STGM_CREATE               0x00001000
 * STGM_CONVERT              0x00020000
 * STGM_FAILIFTHERE          0x00000000
 *
 * STGM_NOSCRATCH            0x00100000
 * STGM_NOSNAPSHOT           0x00200000
 */
static HRESULT validateSTGM(DWORD stgm)
{
6424 6425 6426
  DWORD access = STGM_ACCESS_MODE(stgm);
  DWORD share  = STGM_SHARE_MODE(stgm);
  DWORD create = STGM_CREATE_MODE(stgm);
6427

6428 6429
  if (stgm&~STGM_KNOWN_FLAGS)
  {
6430
    ERR("unknown flags %08x\n", stgm);
6431 6432
    return E_FAIL;
  }
6433

6434 6435 6436 6437 6438 6439 6440 6441 6442
  switch (access)
  {
  case STGM_READ:
  case STGM_WRITE:
  case STGM_READWRITE:
    break;
  default:
    return E_FAIL;
  }
6443

6444 6445 6446 6447 6448 6449 6450 6451 6452 6453
  switch (share)
  {
  case STGM_SHARE_DENY_NONE:
  case STGM_SHARE_DENY_READ:
  case STGM_SHARE_DENY_WRITE:
  case STGM_SHARE_EXCLUSIVE:
    break;
  default:
    return E_FAIL;
  }
6454

6455 6456 6457 6458 6459 6460 6461 6462
  switch (create)
  {
  case STGM_CREATE:
  case STGM_FAILIFTHERE:
    break;
  default:
    return E_FAIL;
  }
6463

6464
  /*
6465 6466
   * STGM_DIRECT | STGM_TRANSACTED | STGM_SIMPLE
   */
6467
  if ( (stgm & STGM_TRANSACTED) && (stgm & STGM_SIMPLE) )
6468 6469 6470 6471 6472 6473
      return E_FAIL;

  /*
   * STGM_CREATE | STGM_CONVERT
   * if both are false, STGM_FAILIFTHERE is set to TRUE
   */
6474
  if ( create == STGM_CREATE && (stgm & STGM_CONVERT) )
6475 6476 6477 6478 6479
    return E_FAIL;

  /*
   * STGM_NOSCRATCH requires STGM_TRANSACTED
   */
6480
  if ( (stgm & STGM_NOSCRATCH) && !(stgm & STGM_TRANSACTED) )
6481
    return E_FAIL;
6482

6483
  /*
6484
   * STGM_NOSNAPSHOT requires STGM_TRANSACTED and
6485 6486
   * not STGM_SHARE_EXCLUSIVE or STGM_SHARE_DENY_WRITE`
   */
6487 6488 6489 6490
  if ( (stgm & STGM_NOSNAPSHOT) &&
        (!(stgm & STGM_TRANSACTED) ||
         share == STGM_SHARE_EXCLUSIVE ||
         share == STGM_SHARE_DENY_WRITE) )
6491 6492 6493 6494 6495 6496 6497 6498 6499
    return E_FAIL;

  return S_OK;
}

/****************************************************************************
 *      GetShareModeFromSTGM
 *
 * This method will return a share mode flag from a STGM value.
6500
 * The STGM value is assumed valid.
6501 6502 6503
 */
static DWORD GetShareModeFromSTGM(DWORD stgm)
{
6504 6505 6506 6507 6508 6509 6510 6511 6512 6513 6514 6515 6516 6517
  switch (STGM_SHARE_MODE(stgm))
  {
  case STGM_SHARE_DENY_NONE:
    return FILE_SHARE_READ | FILE_SHARE_WRITE;
  case STGM_SHARE_DENY_READ:
    return FILE_SHARE_WRITE;
  case STGM_SHARE_DENY_WRITE:
    return FILE_SHARE_READ;
  case STGM_SHARE_EXCLUSIVE:
    return 0;
  }
  ERR("Invalid share mode!\n");
  assert(0);
  return 0;
6518 6519 6520 6521 6522 6523 6524 6525 6526 6527
}

/****************************************************************************
 *      GetAccessModeFromSTGM
 *
 * This method will return an access mode flag from a STGM value.
 * The STGM value is assumed valid.
 */
static DWORD GetAccessModeFromSTGM(DWORD stgm)
{
6528 6529 6530 6531 6532 6533 6534 6535 6536 6537 6538
  switch (STGM_ACCESS_MODE(stgm))
  {
  case STGM_READ:
    return GENERIC_READ;
  case STGM_WRITE:
  case STGM_READWRITE:
    return GENERIC_READ | GENERIC_WRITE;
  }
  ERR("Invalid access mode!\n");
  assert(0);
  return 0;
6539 6540 6541 6542 6543 6544 6545 6546 6547 6548
}

/****************************************************************************
 *      GetCreationModeFromSTGM
 *
 * This method will return a creation mode flag from a STGM value.
 * The STGM value is assumed valid.
 */
static DWORD GetCreationModeFromSTGM(DWORD stgm)
{
6549 6550 6551
  switch(STGM_CREATE_MODE(stgm))
  {
  case STGM_CREATE:
6552
    return CREATE_ALWAYS;
6553
  case STGM_CONVERT:
6554
    FIXME("STGM_CONVERT not implemented!\n");
6555
    return CREATE_NEW;
6556 6557
  case STGM_FAILIFTHERE:
    return CREATE_NEW;
6558
  }
6559 6560 6561
  ERR("Invalid create mode!\n");
  assert(0);
  return 0;
6562
}
6563 6564 6565


/*************************************************************************
6566
 * OLECONVERT_LoadOLE10 [Internal]
6567
 *
6568
 * Loads the OLE10 STREAM to memory
6569 6570 6571 6572 6573 6574 6575 6576 6577 6578 6579 6580
 *
 * PARAMS
 *     pOleStream   [I] The OLESTREAM
 *     pData        [I] Data Structure for the OLESTREAM Data
 *
 * RETURNS
 *     Success:  S_OK
 *     Failure:  CONVERT10_E_OLESTREAM_GET for invalid Get
 *               CONVERT10_E_OLESTREAM_FMT if the OLEID is invalide
 *
 * NOTES
 *     This function is used by OleConvertOLESTREAMToIStorage only.
6581
 *
6582 6583
 *     Memory allocated for pData must be freed by the caller
 */
6584
static HRESULT OLECONVERT_LoadOLE10(LPOLESTREAM pOleStream, OLECONVERT_OLESTREAM_DATA *pData, BOOL bStrem1)
6585 6586 6587
{
	DWORD dwSize;
	HRESULT hRes = S_OK;
Alexandre Julliard's avatar
Alexandre Julliard committed
6588 6589 6590
	int nTryCnt=0;
	int max_try = 6;

6591
	pData->pData = NULL;
Alexandre Julliard's avatar
Alexandre Julliard committed
6592
	pData->pstrOleObjFileName = (CHAR *) NULL;
6593

Alexandre Julliard's avatar
Alexandre Julliard committed
6594 6595
	for( nTryCnt=0;nTryCnt < max_try; nTryCnt++)
	{
6596 6597 6598 6599 6600 6601 6602 6603 6604 6605
	/* Get the OleID */
	dwSize = pOleStream->lpstbl->Get(pOleStream, (void *)&(pData->dwOleID), sizeof(pData->dwOleID));
	if(dwSize != sizeof(pData->dwOleID))
	{
		hRes = CONVERT10_E_OLESTREAM_GET;
	}
	else if(pData->dwOleID != OLESTREAM_ID)
	{
		hRes = CONVERT10_E_OLESTREAM_FMT;
	}
Alexandre Julliard's avatar
Alexandre Julliard committed
6606 6607 6608 6609 6610 6611
		else
		{
			hRes = S_OK;
			break;
		}
	}
6612 6613 6614 6615 6616 6617 6618 6619 6620 6621 6622 6623 6624 6625

	if(hRes == S_OK)
	{
		/* Get the TypeID...more info needed for this field */
		dwSize = pOleStream->lpstbl->Get(pOleStream, (void *)&(pData->dwTypeID), sizeof(pData->dwTypeID));
		if(dwSize != sizeof(pData->dwTypeID))
		{
			hRes = CONVERT10_E_OLESTREAM_GET;
		}
	}
	if(hRes == S_OK)
	{
		if(pData->dwTypeID != 0)
		{
Francois Gouget's avatar
Francois Gouget committed
6626
			/* Get the length of the OleTypeName */
6627 6628 6629 6630 6631 6632 6633 6634 6635 6636 6637 6638 6639 6640 6641 6642 6643 6644
			dwSize = pOleStream->lpstbl->Get(pOleStream, (void *) &(pData->dwOleTypeNameLength), sizeof(pData->dwOleTypeNameLength));
			if(dwSize != sizeof(pData->dwOleTypeNameLength))
			{
				hRes = CONVERT10_E_OLESTREAM_GET;
			}

			if(hRes == S_OK)
			{
				if(pData->dwOleTypeNameLength > 0)
				{
					/* Get the OleTypeName */
					dwSize = pOleStream->lpstbl->Get(pOleStream, (void *)pData->strOleTypeName, pData->dwOleTypeNameLength);
					if(dwSize != pData->dwOleTypeNameLength)
					{
						hRes = CONVERT10_E_OLESTREAM_GET;
					}
				}
			}
Alexandre Julliard's avatar
Alexandre Julliard committed
6645 6646 6647 6648 6649 6650 6651
			if(bStrem1)
			{
				dwSize = pOleStream->lpstbl->Get(pOleStream, (void *)&(pData->dwOleObjFileNameLength), sizeof(pData->dwOleObjFileNameLength));
				if(dwSize != sizeof(pData->dwOleObjFileNameLength))
				{
					hRes = CONVERT10_E_OLESTREAM_GET;
				}
6652
			if(hRes == S_OK)
Alexandre Julliard's avatar
Alexandre Julliard committed
6653
			{
6654
					if(pData->dwOleObjFileNameLength < 1) /* there is no file name exist */
Alexandre Julliard's avatar
Alexandre Julliard committed
6655
						pData->dwOleObjFileNameLength = sizeof(pData->dwOleObjFileNameLength);
6656
					pData->pstrOleObjFileName = HeapAlloc(GetProcessHeap(), 0, pData->dwOleObjFileNameLength);
Alexandre Julliard's avatar
Alexandre Julliard committed
6657 6658 6659 6660 6661 6662 6663 6664 6665 6666 6667 6668 6669
					if(pData->pstrOleObjFileName)
					{
						dwSize = pOleStream->lpstbl->Get(pOleStream, (void *)(pData->pstrOleObjFileName),pData->dwOleObjFileNameLength);
						if(dwSize != pData->dwOleObjFileNameLength)
						{
							hRes = CONVERT10_E_OLESTREAM_GET;
						}
					}
					else
						hRes = CONVERT10_E_OLESTREAM_GET;
				}
			}
			else
6670 6671 6672 6673 6674 6675 6676 6677 6678 6679 6680 6681 6682 6683 6684 6685
			{
				/* Get the Width of the Metafile */
				dwSize = pOleStream->lpstbl->Get(pOleStream, (void *)&(pData->dwMetaFileWidth), sizeof(pData->dwMetaFileWidth));
				if(dwSize != sizeof(pData->dwMetaFileWidth))
				{
					hRes = CONVERT10_E_OLESTREAM_GET;
				}
			if(hRes == S_OK)
			{
				/* Get the Height of the Metafile */
				dwSize = pOleStream->lpstbl->Get(pOleStream, (void *)&(pData->dwMetaFileHeight), sizeof(pData->dwMetaFileHeight));
				if(dwSize != sizeof(pData->dwMetaFileHeight))
				{
					hRes = CONVERT10_E_OLESTREAM_GET;
				}
			}
Alexandre Julliard's avatar
Alexandre Julliard committed
6686
			}
6687 6688
			if(hRes == S_OK)
			{
Francois Gouget's avatar
Francois Gouget committed
6689
				/* Get the Length of the Data */
6690 6691 6692 6693 6694 6695 6696
				dwSize = pOleStream->lpstbl->Get(pOleStream, (void *)&(pData->dwDataLength), sizeof(pData->dwDataLength));
				if(dwSize != sizeof(pData->dwDataLength))
				{
					hRes = CONVERT10_E_OLESTREAM_GET;
				}
			}

6697
			if(hRes == S_OK) /* I don't know what is this 8 byts information is we have to figure out */
Alexandre Julliard's avatar
Alexandre Julliard committed
6698
			{
6699
				if(!bStrem1) /* if it is a second OLE stream data */
Alexandre Julliard's avatar
Alexandre Julliard committed
6700 6701 6702 6703 6704 6705 6706 6707 6708
				{
					pData->dwDataLength -= 8;
					dwSize = pOleStream->lpstbl->Get(pOleStream, (void *)(pData->strUnknown), sizeof(pData->strUnknown));
					if(dwSize != sizeof(pData->strUnknown))
					{
						hRes = CONVERT10_E_OLESTREAM_GET;
					}
				}
			}
6709 6710 6711 6712
			if(hRes == S_OK)
			{
				if(pData->dwDataLength > 0)
				{
6713
					pData->pData = HeapAlloc(GetProcessHeap(),0,pData->dwDataLength);
6714 6715 6716 6717 6718 6719 6720 6721 6722 6723 6724 6725 6726 6727 6728 6729 6730 6731 6732 6733 6734 6735

					/* Get Data (ex. IStorage, Metafile, or BMP) */
					if(pData->pData)
					{
						dwSize = pOleStream->lpstbl->Get(pOleStream, (void *)pData->pData, pData->dwDataLength);
						if(dwSize != pData->dwDataLength)
						{
							hRes = CONVERT10_E_OLESTREAM_GET;
						}
					}
					else
					{
						hRes = CONVERT10_E_OLESTREAM_GET;
					}
				}
			}
		}
	}
	return hRes;
}

/*************************************************************************
6736
 * OLECONVERT_SaveOLE10 [Internal]
6737
 *
6738
 * Saves the OLE10 STREAM From memory
6739 6740 6741 6742 6743 6744 6745 6746 6747 6748 6749
 *
 * PARAMS
 *     pData        [I] Data Structure for the OLESTREAM Data
 *     pOleStream   [I] The OLESTREAM to save
 *
 * RETURNS
 *     Success:  S_OK
 *     Failure:  CONVERT10_E_OLESTREAM_PUT for invalid Put
 *
 * NOTES
 *     This function is used by OleConvertIStorageToOLESTREAM only.
6750
 *
6751
 */
6752
static HRESULT OLECONVERT_SaveOLE10(OLECONVERT_OLESTREAM_DATA *pData, LPOLESTREAM pOleStream)
6753 6754 6755 6756 6757 6758 6759 6760 6761 6762 6763 6764 6765 6766 6767 6768 6769 6770 6771 6772 6773 6774 6775 6776
{
    DWORD dwSize;
    HRESULT hRes = S_OK;


   /* Set the OleID */
    dwSize = pOleStream->lpstbl->Put(pOleStream, (void *)&(pData->dwOleID), sizeof(pData->dwOleID));
    if(dwSize != sizeof(pData->dwOleID))
    {
        hRes = CONVERT10_E_OLESTREAM_PUT;
    }

    if(hRes == S_OK)
    {
        /* Set the TypeID */
        dwSize = pOleStream->lpstbl->Put(pOleStream, (void *)&(pData->dwTypeID), sizeof(pData->dwTypeID));
        if(dwSize != sizeof(pData->dwTypeID))
        {
            hRes = CONVERT10_E_OLESTREAM_PUT;
        }
    }

    if(pData->dwOleID == OLESTREAM_ID && pData->dwTypeID != 0 && hRes == S_OK)
    {
Francois Gouget's avatar
Francois Gouget committed
6777
        /* Set the Length of the OleTypeName */
6778 6779 6780 6781 6782 6783 6784 6785 6786 6787 6788 6789 6790 6791 6792 6793 6794 6795 6796 6797 6798 6799 6800 6801 6802 6803 6804 6805 6806 6807 6808 6809 6810 6811 6812 6813 6814 6815 6816 6817 6818
        dwSize = pOleStream->lpstbl->Put(pOleStream, (void *)&(pData->dwOleTypeNameLength), sizeof(pData->dwOleTypeNameLength));
        if(dwSize != sizeof(pData->dwOleTypeNameLength))
        {
            hRes = CONVERT10_E_OLESTREAM_PUT;
        }

        if(hRes == S_OK)
        {
            if(pData->dwOleTypeNameLength > 0)
            {
                /* Set the OleTypeName */
                dwSize = pOleStream->lpstbl->Put(pOleStream, (void *)  pData->strOleTypeName, pData->dwOleTypeNameLength);
                if(dwSize != pData->dwOleTypeNameLength)
                {
                    hRes = CONVERT10_E_OLESTREAM_PUT;
                }
            }
        }

        if(hRes == S_OK)
        {
            /* Set the width of the Metafile */
            dwSize = pOleStream->lpstbl->Put(pOleStream, (void *)&(pData->dwMetaFileWidth), sizeof(pData->dwMetaFileWidth));
            if(dwSize != sizeof(pData->dwMetaFileWidth))
            {
                hRes = CONVERT10_E_OLESTREAM_PUT;
            }
        }

        if(hRes == S_OK)
        {
            /* Set the height of the Metafile */
            dwSize = pOleStream->lpstbl->Put(pOleStream, (void *)&(pData->dwMetaFileHeight), sizeof(pData->dwMetaFileHeight));
            if(dwSize != sizeof(pData->dwMetaFileHeight))
            {
                hRes = CONVERT10_E_OLESTREAM_PUT;
            }
        }

        if(hRes == S_OK)
        {
Francois Gouget's avatar
Francois Gouget committed
6819
            /* Set the length of the Data */
6820 6821 6822 6823 6824 6825 6826 6827 6828 6829 6830 6831 6832 6833 6834 6835 6836 6837 6838 6839 6840 6841 6842 6843
            dwSize = pOleStream->lpstbl->Put(pOleStream, (void *)&(pData->dwDataLength), sizeof(pData->dwDataLength));
            if(dwSize != sizeof(pData->dwDataLength))
            {
                hRes = CONVERT10_E_OLESTREAM_PUT;
            }
        }

        if(hRes == S_OK)
        {
            if(pData->dwDataLength > 0)
            {
                /* Set the Data (eg. IStorage, Metafile, Bitmap) */
                dwSize = pOleStream->lpstbl->Put(pOleStream, (void *)  pData->pData, pData->dwDataLength);
                if(dwSize != pData->dwDataLength)
                {
                    hRes = CONVERT10_E_OLESTREAM_PUT;
                }
            }
        }
    }
    return hRes;
}

/*************************************************************************
6844
 * OLECONVERT_GetOLE20FromOLE10[Internal]
6845 6846
 *
 * This function copies OLE10 Data (the IStorage in the OLESTREAM) to disk,
6847
 * opens it, and copies the content to the dest IStorage for
6848
 * OleConvertOLESTREAMToIStorage
6849
 *
6850 6851 6852 6853 6854 6855 6856 6857 6858 6859
 *
 * PARAMS
 *     pDestStorage  [I] The IStorage to copy the data to
 *     pBuffer       [I] Buffer that contains the IStorage from the OLESTREAM
 *     nBufferLength [I] The size of the buffer
 *
 * RETURNS
 *     Nothing
 *
 * NOTES
6860 6861
 *
 *
6862
 */
6863
static void OLECONVERT_GetOLE20FromOLE10(LPSTORAGE pDestStorage, const BYTE *pBuffer, DWORD nBufferLength)
6864 6865 6866 6867 6868 6869
{
    HRESULT hRes;
    HANDLE hFile;
    IStorage *pTempStorage;
    DWORD dwNumOfBytesWritten;
    WCHAR wstrTempDir[MAX_PATH], wstrTempFile[MAX_PATH];
6870
    static const WCHAR wstrPrefix[] = {'s', 'i', 's', 0};
6871 6872 6873 6874

    /* Create a temp File */
    GetTempPathW(MAX_PATH, wstrTempDir);
    GetTempFileNameW(wstrTempDir, wstrPrefix, 0, wstrTempFile);
Patrik Stridvall's avatar
Patrik Stridvall committed
6875
    hFile = CreateFileW(wstrTempFile, GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, 0);
6876 6877 6878 6879 6880 6881 6882 6883 6884 6885 6886

    if(hFile != INVALID_HANDLE_VALUE)
    {
        /* Write IStorage Data to File */
        WriteFile(hFile, pBuffer, nBufferLength, &dwNumOfBytesWritten, NULL);
        CloseHandle(hFile);

        /* Open and copy temp storage to the Dest Storage */
        hRes = StgOpenStorage(wstrTempFile, NULL, STGM_READ, NULL, 0, &pTempStorage);
        if(hRes == S_OK)
        {
Patrik Stridvall's avatar
Patrik Stridvall committed
6887
            hRes = StorageImpl_CopyTo(pTempStorage, 0, NULL, NULL, pDestStorage);
6888 6889 6890 6891 6892 6893 6894 6895
            StorageBaseImpl_Release(pTempStorage);
        }
        DeleteFileW(wstrTempFile);
    }
}


/*************************************************************************
6896
 * OLECONVERT_WriteOLE20ToBuffer [Internal]
6897
 *
6898
 * Saves the OLE10 STREAM From memory
6899 6900 6901 6902 6903 6904 6905 6906 6907 6908 6909 6910
 *
 * PARAMS
 *     pStorage  [I] The Src IStorage to copy
 *     pData     [I] The Dest Memory to write to.
 *
 * RETURNS
 *     The size in bytes allocated for pData
 *
 * NOTES
 *     Memory allocated for pData must be freed by the caller
 *
 *     Used by OleConvertIStorageToOLESTREAM only.
6911
 *
6912
 */
6913
static DWORD OLECONVERT_WriteOLE20ToBuffer(LPSTORAGE pStorage, BYTE **pData)
6914 6915 6916 6917 6918 6919
{
    HANDLE hFile;
    HRESULT hRes;
    DWORD nDataLength = 0;
    IStorage *pTempStorage;
    WCHAR wstrTempDir[MAX_PATH], wstrTempFile[MAX_PATH];
6920
    static const WCHAR wstrPrefix[] = {'s', 'i', 's', 0};
6921 6922

    *pData = NULL;
6923

6924 6925 6926
    /* Create temp Storage */
    GetTempPathW(MAX_PATH, wstrTempDir);
    GetTempFileNameW(wstrTempDir, wstrPrefix, 0, wstrTempFile);
Patrik Stridvall's avatar
Patrik Stridvall committed
6927
    hRes = StgCreateDocfile(wstrTempFile, STGM_CREATE | STGM_READWRITE | STGM_SHARE_EXCLUSIVE, 0, &pTempStorage);
6928 6929 6930 6931

    if(hRes == S_OK)
    {
        /* Copy Src Storage to the Temp Storage */
Patrik Stridvall's avatar
Patrik Stridvall committed
6932
        StorageImpl_CopyTo(pStorage, 0, NULL, NULL, pTempStorage);
6933 6934 6935
        StorageBaseImpl_Release(pTempStorage);

        /* Open Temp Storage as a file and copy to memory */
Patrik Stridvall's avatar
Patrik Stridvall committed
6936
        hFile = CreateFileW(wstrTempFile, GENERIC_READ, 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);
6937 6938 6939
        if(hFile != INVALID_HANDLE_VALUE)
        {
            nDataLength = GetFileSize(hFile, NULL);
6940
            *pData = HeapAlloc(GetProcessHeap(),0,nDataLength);
6941 6942 6943 6944 6945 6946 6947 6948 6949
            ReadFile(hFile, *pData, nDataLength, &nDataLength, 0);
            CloseHandle(hFile);
        }
        DeleteFileW(wstrTempFile);
    }
    return nDataLength;
}

/*************************************************************************
6950
 * OLECONVERT_CreateOleStream [Internal]
6951
 *
6952
 * Creates the "\001OLE" stream in the IStorage if necessary.
6953 6954 6955 6956 6957 6958 6959 6960 6961 6962 6963 6964
 *
 * PARAMS
 *     pStorage     [I] Dest storage to create the stream in
 *
 * RETURNS
 *     Nothing
 *
 * NOTES
 *     This function is used by OleConvertOLESTREAMToIStorage only.
 *
 *     This stream is still unknown, MS Word seems to have extra data
 *     but since the data is stored in the OLESTREAM there should be
6965
 *     no need to recreate the stream.  If the stream is manually
6966
 *     deleted it will create it with this default data.
6967
 *
6968 6969 6970 6971 6972
 */
void OLECONVERT_CreateOleStream(LPSTORAGE pStorage)
{
    HRESULT hRes;
    IStream *pStream;
6973
    static const WCHAR wstrStreamName[] = {1,'O', 'l', 'e', 0};
6974
    BYTE pOleStreamHeader [] =
6975
    {
6976 6977 6978
        0x01, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, 0x00,
        0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
        0x00, 0x00, 0x00, 0x00
6979
    };
6980

6981
    /* Create stream if not present */
6982
    hRes = IStorage_CreateStream(pStorage, wstrStreamName,
6983 6984 6985 6986 6987 6988 6989 6990 6991 6992
        STGM_WRITE  | STGM_SHARE_EXCLUSIVE, 0, 0, &pStream );

    if(hRes == S_OK)
    {
        /* Write default Data */
        hRes = IStream_Write(pStream, pOleStreamHeader, sizeof(pOleStreamHeader), NULL);
        IStream_Release(pStream);
    }
}

6993 6994 6995 6996 6997 6998 6999 7000 7001
/* write a string to a stream, preceded by its length */
static HRESULT STREAM_WriteString( IStream *stm, LPCWSTR string )
{
    HRESULT r;
    LPSTR str;
    DWORD len = 0;

    if( string )
        len = WideCharToMultiByte( CP_ACP, 0, string, -1, NULL, 0, NULL, NULL);
7002
    r = IStream_Write( stm, &len, sizeof(len), NULL);
7003 7004 7005 7006 7007 7008 7009 7010 7011 7012 7013 7014 7015 7016 7017 7018 7019 7020 7021
    if( FAILED( r ) )
        return r;
    if(len == 0)
        return r;
    str = CoTaskMemAlloc( len );
    WideCharToMultiByte( CP_ACP, 0, string, -1, str, len, NULL, NULL);
    r = IStream_Write( stm, str, len, NULL);
    CoTaskMemFree( str );
    return r;
}

/* read a string preceded by its length from a stream */
static HRESULT STREAM_ReadString( IStream *stm, LPWSTR *string )
{
    HRESULT r;
    DWORD len, count = 0;
    LPSTR str;
    LPWSTR wstr;

7022
    r = IStream_Read( stm, &len, sizeof(len), &count );
7023 7024
    if( FAILED( r ) )
        return r;
7025
    if( count != sizeof(len) )
7026 7027
        return E_OUTOFMEMORY;

7028
    TRACE("%d bytes\n",len);
7029 7030 7031 7032 7033 7034 7035 7036 7037 7038 7039 7040 7041 7042 7043 7044 7045 7046 7047 7048 7049 7050 7051 7052 7053 7054 7055 7056 7057 7058 7059 7060 7061
    
    str = CoTaskMemAlloc( len );
    if( !str )
        return E_OUTOFMEMORY;
    count = 0;
    r = IStream_Read( stm, str, len, &count );
    if( FAILED( r ) )
        return r;
    if( count != len )
    {
        CoTaskMemFree( str );
        return E_OUTOFMEMORY;
    }

    TRACE("Read string %s\n",debugstr_an(str,len));

    len = MultiByteToWideChar( CP_ACP, 0, str, count, NULL, 0 );
    wstr = CoTaskMemAlloc( (len + 1)*sizeof (WCHAR) );
    if( wstr )
         MultiByteToWideChar( CP_ACP, 0, str, count, wstr, len );
    CoTaskMemFree( str );

    *string = wstr;

    return r;
}


static HRESULT STORAGE_WriteCompObj( LPSTORAGE pstg, CLSID *clsid,
    LPCWSTR lpszUserType, LPCWSTR szClipName, LPCWSTR szProgIDName )
{
    IStream *pstm;
    HRESULT r = S_OK;
7062
    static const WCHAR szwStreamName[] = {1, 'C', 'o', 'm', 'p', 'O', 'b', 'j', 0};
7063 7064 7065 7066 7067 7068 7069 7070 7071 7072 7073 7074 7075 7076 7077 7078 7079 7080 7081

    static const BYTE unknown1[12] =
       { 0x01, 0x00, 0xFE, 0xFF, 0x03, 0x0A, 0x00, 0x00,
         0xFF, 0xFF, 0xFF, 0xFF};
    static const BYTE unknown2[16] =
       { 0xF4, 0x39, 0xB2, 0x71, 0x00, 0x00, 0x00, 0x00,
         0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 };

    TRACE("%p %s %s %s %s\n", pstg, debugstr_guid(clsid),
           debugstr_w(lpszUserType), debugstr_w(szClipName),
           debugstr_w(szProgIDName));

    /*  Create a CompObj stream if it doesn't exist */
    r = IStorage_CreateStream(pstg, szwStreamName,
        STGM_WRITE  | STGM_SHARE_EXCLUSIVE, 0, 0, &pstm );
    if( FAILED (r) )
        return r;

    /* Write CompObj Structure to stream */
7082
    r = IStream_Write(pstm, unknown1, sizeof(unknown1), NULL);
7083 7084 7085 7086 7087 7088 7089 7090 7091 7092 7093

    if( SUCCEEDED( r ) )
        r = WriteClassStm( pstm, clsid );

    if( SUCCEEDED( r ) )
        r = STREAM_WriteString( pstm, lpszUserType );
    if( SUCCEEDED( r ) )
        r = STREAM_WriteString( pstm, szClipName );
    if( SUCCEEDED( r ) )
        r = STREAM_WriteString( pstm, szProgIDName );
    if( SUCCEEDED( r ) )
7094
        r = IStream_Write(pstm, unknown2, sizeof(unknown2), NULL);
7095 7096 7097 7098 7099 7100 7101

    IStream_Release( pstm );

    return r;
}

/***********************************************************************
7102
 *               WriteFmtUserTypeStg (OLE32.@)
7103 7104 7105 7106 7107 7108
 */
HRESULT WINAPI WriteFmtUserTypeStg(
	  LPSTORAGE pstg, CLIPFORMAT cf, LPOLESTR lpszUserType)
{
    HRESULT r;
    WCHAR szwClipName[0x40];
7109 7110
    CLSID clsid = CLSID_NULL;
    LPWSTR wstrProgID = NULL;
7111 7112 7113 7114 7115
    DWORD n;

    TRACE("(%p,%x,%s)\n",pstg,cf,debugstr_w(lpszUserType));

    /* get the clipboard format name */
7116
    n = GetClipboardFormatNameW( cf, szwClipName, sizeof(szwClipName)/sizeof(szwClipName[0]) );
7117 7118 7119 7120
    szwClipName[n]=0;

    TRACE("Clipboard name is %s\n", debugstr_w(szwClipName));

7121 7122 7123 7124
    /* FIXME: There's room to save a CLSID and its ProgID, but
       the CLSID is not looked up in the registry and in all the
       tests I wrote it was CLSID_NULL.  Where does it come from?
    */
7125

7126 7127
    /* get the real program ID.  This may fail, but that's fine */
    ProgIDFromCLSID(&clsid, &wstrProgID);
7128 7129 7130

    TRACE("progid is %s\n",debugstr_w(wstrProgID));

7131 7132
    r = STORAGE_WriteCompObj( pstg, &clsid, 
                              lpszUserType, szwClipName, wstrProgID );
7133

7134
    CoTaskMemFree(wstrProgID);
7135 7136 7137 7138 7139 7140

    return r;
}


/******************************************************************************
7141
 *              ReadFmtUserTypeStg        [OLE32.@]
7142 7143 7144 7145 7146
 */
HRESULT WINAPI ReadFmtUserTypeStg (LPSTORAGE pstg, CLIPFORMAT* pcf, LPOLESTR* lplpszUserType)
{
    HRESULT r;
    IStream *stm = 0;
7147
    static const WCHAR szCompObj[] = { 1, 'C','o','m','p','O','b','j', 0 };
7148 7149 7150 7151 7152 7153 7154 7155 7156 7157 7158 7159
    unsigned char unknown1[12];
    unsigned char unknown2[16];
    DWORD count;
    LPWSTR szProgIDName = NULL, szCLSIDName = NULL, szOleTypeName = NULL;
    CLSID clsid;

    TRACE("(%p,%p,%p)\n", pstg, pcf, lplpszUserType);

    r = IStorage_OpenStream( pstg, szCompObj, NULL, 
                    STGM_READ | STGM_SHARE_EXCLUSIVE, 0, &stm );
    if( FAILED ( r ) )
    {
7160
        WARN("Failed to open stream r = %08x\n", r);
7161 7162 7163 7164
        return r;
    }

    /* read the various parts of the structure */
7165 7166
    r = IStream_Read( stm, unknown1, sizeof(unknown1), &count );
    if( FAILED( r ) || ( count != sizeof(unknown1) ) )
7167 7168 7169 7170 7171 7172 7173 7174 7175 7176 7177 7178 7179 7180 7181 7182 7183
        goto end;
    r = ReadClassStm( stm, &clsid );
    if( FAILED( r ) )
        goto end;

    r = STREAM_ReadString( stm, &szCLSIDName );
    if( FAILED( r ) )
        goto end;

    r = STREAM_ReadString( stm, &szOleTypeName );
    if( FAILED( r ) )
        goto end;

    r = STREAM_ReadString( stm, &szProgIDName );
    if( FAILED( r ) )
        goto end;

7184 7185
    r = IStream_Read( stm, unknown2, sizeof(unknown2), &count );
    if( FAILED( r ) || ( count != sizeof(unknown2) ) )
7186 7187 7188 7189 7190 7191 7192 7193 7194 7195 7196 7197 7198 7199 7200 7201 7202
        goto end;

    /* ok, success... now we just need to store what we found */
    if( pcf )
        *pcf = RegisterClipboardFormatW( szOleTypeName );
    CoTaskMemFree( szOleTypeName );

    if( lplpszUserType )
        *lplpszUserType = szCLSIDName;
    CoTaskMemFree( szProgIDName );

end:
    IStream_Release( stm );

    return r;
}

7203 7204

/*************************************************************************
7205
 * OLECONVERT_CreateCompObjStream [Internal]
7206 7207 7208 7209
 *
 * Creates a "\001CompObj" is the destination IStorage if necessary.
 *
 * PARAMS
7210
 *     pStorage       [I] The dest IStorage to create the CompObj Stream
7211 7212 7213 7214 7215 7216 7217 7218 7219 7220 7221
 *                        if necessary.
 *     strOleTypeName [I] The ProgID
 *
 * RETURNS
 *     Success:  S_OK
 *     Failure:  REGDB_E_CLASSNOTREG if cannot reconstruct the stream
 *
 * NOTES
 *     This function is used by OleConvertOLESTREAMToIStorage only.
 *
 *     The stream data is stored in the OLESTREAM and there should be
7222
 *     no need to recreate the stream.  If the stream is manually
7223 7224
 *     deleted it will attempt to create it by querying the registry.
 *
7225
 *
7226 7227 7228 7229 7230 7231
 */
HRESULT OLECONVERT_CreateCompObjStream(LPSTORAGE pStorage, LPCSTR strOleTypeName)
{
    IStream *pStream;
    HRESULT hStorageRes, hRes = S_OK;
    OLECONVERT_ISTORAGE_COMPOBJ IStorageCompObj;
7232
    static const WCHAR wstrStreamName[] = {1,'C', 'o', 'm', 'p', 'O', 'b', 'j', 0};
7233
    WCHAR bufferW[OLESTREAM_MAX_STR_LEN];
7234 7235 7236 7237 7238 7239 7240 7241 7242 7243 7244

    BYTE pCompObjUnknown1[] = {0x01, 0x00, 0xFE, 0xFF, 0x03, 0x0A, 0x00, 0x00, 0xFF, 0xFF, 0xFF, 0xFF};
    BYTE pCompObjUnknown2[] = {0xF4, 0x39, 0xB2, 0x71};

    /* Initialize the CompObj structure */
    memset(&IStorageCompObj, 0, sizeof(IStorageCompObj));
    memcpy(&(IStorageCompObj.byUnknown1), pCompObjUnknown1, sizeof(pCompObjUnknown1));
    memcpy(&(IStorageCompObj.byUnknown2), pCompObjUnknown2, sizeof(pCompObjUnknown2));


    /*  Create a CompObj stream if it doesn't exist */
7245
    hStorageRes = IStorage_CreateStream(pStorage, wstrStreamName,
7246 7247 7248 7249 7250 7251 7252 7253
        STGM_WRITE  | STGM_SHARE_EXCLUSIVE, 0, 0, &pStream );
    if(hStorageRes == S_OK)
    {
        /* copy the OleTypeName to the compobj struct */
        IStorageCompObj.dwOleTypeNameLength = strlen(strOleTypeName)+1;
        strcpy(IStorageCompObj.strOleTypeName, strOleTypeName);

        /* copy the OleTypeName to the compobj struct */
7254
        /* Note: in the test made, these were Identical      */
7255 7256 7257 7258
        IStorageCompObj.dwProgIDNameLength = strlen(strOleTypeName)+1;
        strcpy(IStorageCompObj.strProgIDName, strOleTypeName);

        /* Get the CLSID */
7259 7260 7261
        MultiByteToWideChar( CP_ACP, 0, IStorageCompObj.strProgIDName, -1,
                             bufferW, OLESTREAM_MAX_STR_LEN );
        hRes = CLSIDFromProgID(bufferW, &(IStorageCompObj.clsid));
7262

7263
        if(hRes == S_OK)
7264 7265 7266 7267
        {
            HKEY hKey;
            LONG hErr;
            /* Get the CLSID Default Name from the Registry */
7268
            hErr = RegOpenKeyA(HKEY_CLASSES_ROOT, IStorageCompObj.strProgIDName, &hKey);
7269 7270 7271 7272
            if(hErr == ERROR_SUCCESS)
            {
                char strTemp[OLESTREAM_MAX_STR_LEN];
                IStorageCompObj.dwCLSIDNameLength = OLESTREAM_MAX_STR_LEN;
7273
                hErr = RegQueryValueA(hKey, NULL, strTemp, (LONG*) &(IStorageCompObj.dwCLSIDNameLength));
7274 7275 7276 7277 7278 7279 7280 7281
                if(hErr == ERROR_SUCCESS)
                {
                    strcpy(IStorageCompObj.strCLSIDName, strTemp);
                }
                RegCloseKey(hKey);
            }
        }

7282 7283 7284 7285 7286 7287 7288
        /* Write CompObj Structure to stream */
        hRes = IStream_Write(pStream, IStorageCompObj.byUnknown1, sizeof(IStorageCompObj.byUnknown1), NULL);

        WriteClassStm(pStream,&(IStorageCompObj.clsid));

        hRes = IStream_Write(pStream, &(IStorageCompObj.dwCLSIDNameLength), sizeof(IStorageCompObj.dwCLSIDNameLength), NULL);
        if(IStorageCompObj.dwCLSIDNameLength > 0)
7289
        {
7290 7291 7292 7293 7294 7295 7296 7297 7298 7299 7300
            hRes = IStream_Write(pStream, IStorageCompObj.strCLSIDName, IStorageCompObj.dwCLSIDNameLength, NULL);
        }
        hRes = IStream_Write(pStream, &(IStorageCompObj.dwOleTypeNameLength) , sizeof(IStorageCompObj.dwOleTypeNameLength), NULL);
        if(IStorageCompObj.dwOleTypeNameLength > 0)
        {
            hRes = IStream_Write(pStream, IStorageCompObj.strOleTypeName , IStorageCompObj.dwOleTypeNameLength, NULL);
        }
        hRes = IStream_Write(pStream, &(IStorageCompObj.dwProgIDNameLength) , sizeof(IStorageCompObj.dwProgIDNameLength), NULL);
        if(IStorageCompObj.dwProgIDNameLength > 0)
        {
            hRes = IStream_Write(pStream, IStorageCompObj.strProgIDName , IStorageCompObj.dwProgIDNameLength, NULL);
7301
        }
7302
        hRes = IStream_Write(pStream, IStorageCompObj.byUnknown2 , sizeof(IStorageCompObj.byUnknown2), NULL);
7303 7304 7305 7306 7307 7308 7309
        IStream_Release(pStream);
    }
    return hRes;
}


/*************************************************************************
7310
 * OLECONVERT_CreateOlePresStream[Internal]
7311 7312 7313 7314 7315 7316
 *
 * Creates the "\002OlePres000" Stream with the Metafile data
 *
 * PARAMS
 *     pStorage     [I] The dest IStorage to create \002OLEPres000 stream in.
 *     dwExtentX    [I] Width of the Metafile
7317
 *     dwExtentY    [I] Height of the Metafile
7318 7319 7320 7321 7322 7323 7324 7325 7326
 *     pData        [I] Metafile data
 *     dwDataLength [I] Size of the Metafile data
 *
 * RETURNS
 *     Success:  S_OK
 *     Failure:  CONVERT10_E_OLESTREAM_PUT for invalid Put
 *
 * NOTES
 *     This function is used by OleConvertOLESTREAMToIStorage only.
7327
 *
7328
 */
7329
static void OLECONVERT_CreateOlePresStream(LPSTORAGE pStorage, DWORD dwExtentX, DWORD dwExtentY , BYTE *pData, DWORD dwDataLength)
7330 7331 7332
{
    HRESULT hRes;
    IStream *pStream;
7333
    static const WCHAR wstrStreamName[] = {2, 'O', 'l', 'e', 'P', 'r', 'e', 's', '0', '0', '0', 0};
7334
    BYTE pOlePresStreamHeader [] =
7335
    {
7336 7337
        0xFF, 0xFF, 0xFF, 0xFF, 0x03, 0x00, 0x00, 0x00,
        0x04, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00,
7338 7339 7340 7341
        0xFF, 0xFF, 0xFF, 0xFF, 0x00, 0x00, 0x00, 0x00,
        0x00, 0x00, 0x00, 0x00
    };

7342
    BYTE pOlePresStreamHeaderEmpty [] =
7343
    {
7344 7345
        0x00, 0x00, 0x00, 0x00,
        0x04, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00,
7346 7347 7348
        0xFF, 0xFF, 0xFF, 0xFF, 0x00, 0x00, 0x00, 0x00,
        0x00, 0x00, 0x00, 0x00
    };
7349

7350
    /* Create the OlePres000 Stream */
7351
    hRes = IStorage_CreateStream(pStorage, wstrStreamName,
7352 7353 7354 7355 7356 7357 7358 7359 7360 7361 7362 7363 7364 7365 7366 7367 7368 7369 7370 7371 7372 7373 7374
        STGM_CREATE | STGM_WRITE  | STGM_SHARE_EXCLUSIVE, 0, 0, &pStream );

    if(hRes == S_OK)
    {
        DWORD nHeaderSize;
        OLECONVERT_ISTORAGE_OLEPRES OlePres;

        memset(&OlePres, 0, sizeof(OlePres));
        /* Do we have any metafile data to save */
        if(dwDataLength > 0)
        {
            memcpy(OlePres.byUnknown1, pOlePresStreamHeader, sizeof(pOlePresStreamHeader));
            nHeaderSize = sizeof(pOlePresStreamHeader);
        }
        else
        {
            memcpy(OlePres.byUnknown1, pOlePresStreamHeaderEmpty, sizeof(pOlePresStreamHeaderEmpty));
            nHeaderSize = sizeof(pOlePresStreamHeaderEmpty);
        }
        /* Set width and height of the metafile */
        OlePres.dwExtentX = dwExtentX;
        OlePres.dwExtentY = -dwExtentY;

Francois Gouget's avatar
Francois Gouget committed
7375
        /* Set Data and Length */
7376 7377 7378 7379 7380 7381 7382 7383 7384 7385 7386 7387 7388 7389 7390 7391 7392 7393 7394
        if(dwDataLength > sizeof(METAFILEPICT16))
        {
            OlePres.dwSize = dwDataLength - sizeof(METAFILEPICT16);
            OlePres.pData = &(pData[8]);
        }
        /* Save OlePres000 Data to Stream */
        hRes = IStream_Write(pStream, OlePres.byUnknown1, nHeaderSize, NULL);
        hRes = IStream_Write(pStream, &(OlePres.dwExtentX), sizeof(OlePres.dwExtentX), NULL);
        hRes = IStream_Write(pStream, &(OlePres.dwExtentY), sizeof(OlePres.dwExtentY), NULL);
        hRes = IStream_Write(pStream, &(OlePres.dwSize), sizeof(OlePres.dwSize), NULL);
        if(OlePres.dwSize > 0)
        {
            hRes = IStream_Write(pStream, OlePres.pData, OlePres.dwSize, NULL);
        }
        IStream_Release(pStream);
    }
}

/*************************************************************************
7395
 * OLECONVERT_CreateOle10NativeStream [Internal]
7396 7397 7398 7399 7400 7401 7402 7403 7404 7405 7406 7407 7408 7409 7410
 *
 * Creates the "\001Ole10Native" Stream (should contain a BMP)
 *
 * PARAMS
 *     pStorage     [I] Dest storage to create the stream in
 *     pData        [I] Ole10 Native Data (ex. bmp)
 *     dwDataLength [I] Size of the Ole10 Native Data
 *
 * RETURNS
 *     Nothing
 *
 * NOTES
 *     This function is used by OleConvertOLESTREAMToIStorage only.
 *
 *     Might need to verify the data and return appropriate error message
7411
 *
7412
 */
7413
static void OLECONVERT_CreateOle10NativeStream(LPSTORAGE pStorage, const BYTE *pData, DWORD dwDataLength)
7414 7415 7416
{
    HRESULT hRes;
    IStream *pStream;
7417
    static const WCHAR wstrStreamName[] = {1, 'O', 'l', 'e', '1', '0', 'N', 'a', 't', 'i', 'v', 'e', 0};
7418

7419
    /* Create the Ole10Native Stream */
7420
    hRes = IStorage_CreateStream(pStorage, wstrStreamName,
7421 7422 7423 7424 7425 7426 7427 7428 7429 7430 7431 7432 7433
        STGM_CREATE | STGM_WRITE  | STGM_SHARE_EXCLUSIVE, 0, 0, &pStream );

    if(hRes == S_OK)
    {
        /* Write info to stream */
        hRes = IStream_Write(pStream, &dwDataLength, sizeof(dwDataLength), NULL);
        hRes = IStream_Write(pStream, pData, dwDataLength, NULL);
        IStream_Release(pStream);
    }

}

/*************************************************************************
7434
 * OLECONVERT_GetOLE10ProgID [Internal]
7435 7436 7437 7438 7439 7440 7441 7442 7443 7444 7445 7446 7447 7448 7449
 *
 * Finds the ProgID (or OleTypeID) from the IStorage
 *
 * PARAMS
 *     pStorage        [I] The Src IStorage to get the ProgID
 *     strProgID       [I] the ProgID string to get
 *     dwSize          [I] the size of the string
 *
 * RETURNS
 *     Success:  S_OK
 *     Failure:  REGDB_E_CLASSNOTREG if cannot reconstruct the stream
 *
 * NOTES
 *     This function is used by OleConvertIStorageToOLESTREAM only.
 *
7450
 *
7451
 */
7452
static HRESULT OLECONVERT_GetOLE10ProgID(LPSTORAGE pStorage, char *strProgID, DWORD *dwSize)
7453 7454 7455 7456 7457
{
    HRESULT hRes;
    IStream *pStream;
    LARGE_INTEGER iSeekPos;
    OLECONVERT_ISTORAGE_COMPOBJ CompObj;
7458
    static const WCHAR wstrStreamName[] = {1,'C', 'o', 'm', 'p', 'O', 'b', 'j', 0};
7459 7460

    /* Open the CompObj Stream */
7461
    hRes = IStorage_OpenStream(pStorage, wstrStreamName, NULL,
7462 7463 7464 7465 7466
        STGM_READ  | STGM_SHARE_EXCLUSIVE, 0, &pStream );
    if(hRes == S_OK)
    {

        /*Get the OleType from the CompObj Stream */
7467 7468
        iSeekPos.u.LowPart = sizeof(CompObj.byUnknown1) + sizeof(CompObj.clsid);
        iSeekPos.u.HighPart = 0;
7469 7470 7471

        IStream_Seek(pStream, iSeekPos, STREAM_SEEK_SET, NULL);
        IStream_Read(pStream, &CompObj.dwCLSIDNameLength, sizeof(CompObj.dwCLSIDNameLength), NULL);
7472
        iSeekPos.u.LowPart = CompObj.dwCLSIDNameLength;
7473 7474
        IStream_Seek(pStream, iSeekPos, STREAM_SEEK_CUR , NULL);
        IStream_Read(pStream, &CompObj.dwOleTypeNameLength, sizeof(CompObj.dwOleTypeNameLength), NULL);
7475
        iSeekPos.u.LowPart = CompObj.dwOleTypeNameLength;
7476 7477 7478 7479 7480 7481 7482 7483 7484 7485 7486 7487 7488 7489 7490 7491 7492 7493 7494 7495 7496 7497
        IStream_Seek(pStream, iSeekPos, STREAM_SEEK_CUR , NULL);

        IStream_Read(pStream, dwSize, sizeof(*dwSize), NULL);
        if(*dwSize > 0)
        {
            IStream_Read(pStream, strProgID, *dwSize, NULL);
        }
        IStream_Release(pStream);
    }
    else
    {
        STATSTG stat;
        LPOLESTR wstrProgID;

        /* Get the OleType from the registry */
        REFCLSID clsid = &(stat.clsid);
        IStorage_Stat(pStorage, &stat, STATFLAG_NONAME);
        hRes = ProgIDFromCLSID(clsid, &wstrProgID);
        if(hRes == S_OK)
        {
            *dwSize = WideCharToMultiByte(CP_ACP, 0, wstrProgID, -1, strProgID, *dwSize, NULL, FALSE);
        }
7498

7499 7500 7501 7502 7503
    }
    return hRes;
}

/*************************************************************************
7504
 * OLECONVERT_GetOle10PresData [Internal]
7505 7506 7507 7508 7509 7510 7511 7512 7513 7514 7515 7516 7517 7518
 *
 * Converts IStorage "/001Ole10Native" stream to a OLE10 Stream
 *
 * PARAMS
 *     pStorage     [I] Src IStroage
 *     pOleStream   [I] Dest OleStream Mem Struct
 *
 * RETURNS
 *     Nothing
 *
 * NOTES
 *     This function is used by OleConvertIStorageToOLESTREAM only.
 *
 *     Memory allocated for pData must be freed by the caller
7519 7520
 *
 *
7521
 */
7522
static void OLECONVERT_GetOle10PresData(LPSTORAGE pStorage, OLECONVERT_OLESTREAM_DATA *pOleStreamData)
7523 7524 7525 7526
{

    HRESULT hRes;
    IStream *pStream;
7527
    static const WCHAR wstrStreamName[] = {1, 'O', 'l', 'e', '1', '0', 'N', 'a', 't', 'i', 'v', 'e', 0};
7528 7529 7530 7531 7532 7533 7534 7535 7536 7537 7538 7539

    /* Initialize Default data for OLESTREAM */
    pOleStreamData[0].dwOleID = OLESTREAM_ID;
    pOleStreamData[0].dwTypeID = 2;
    pOleStreamData[1].dwOleID = OLESTREAM_ID;
    pOleStreamData[1].dwTypeID = 0;
    pOleStreamData[0].dwMetaFileWidth = 0;
    pOleStreamData[0].dwMetaFileHeight = 0;
    pOleStreamData[0].pData = NULL;
    pOleStreamData[1].pData = NULL;

    /* Open Ole10Native Stream */
7540
    hRes = IStorage_OpenStream(pStorage, wstrStreamName, NULL,
7541 7542 7543 7544 7545 7546 7547 7548
        STGM_READ  | STGM_SHARE_EXCLUSIVE, 0, &pStream );
    if(hRes == S_OK)
    {

        /* Read Size and Data */
        IStream_Read(pStream, &(pOleStreamData->dwDataLength), sizeof(pOleStreamData->dwDataLength), NULL);
        if(pOleStreamData->dwDataLength > 0)
        {
7549
            pOleStreamData->pData = HeapAlloc(GetProcessHeap(),0,pOleStreamData->dwDataLength);
7550 7551 7552 7553 7554 7555 7556 7557 7558
            IStream_Read(pStream, pOleStreamData->pData, pOleStreamData->dwDataLength, NULL);
        }
        IStream_Release(pStream);
    }

}


/*************************************************************************
7559
 * OLECONVERT_GetOle20PresData[Internal]
7560 7561 7562 7563 7564 7565 7566 7567 7568 7569 7570 7571
 *
 * Converts IStorage "/002OlePres000" stream to a OLE10 Stream
 *
 * PARAMS
 *     pStorage         [I] Src IStroage
 *     pOleStreamData   [I] Dest OleStream Mem Struct
 *
 * RETURNS
 *     Nothing
 *
 * NOTES
 *     This function is used by OleConvertIStorageToOLESTREAM only.
7572
 *
7573 7574
 *     Memory allocated for pData must be freed by the caller
 */
7575
static void OLECONVERT_GetOle20PresData(LPSTORAGE pStorage, OLECONVERT_OLESTREAM_DATA *pOleStreamData)
7576 7577 7578 7579
{
    HRESULT hRes;
    IStream *pStream;
    OLECONVERT_ISTORAGE_OLEPRES olePress;
7580
    static const WCHAR wstrStreamName[] = {2, 'O', 'l', 'e', 'P', 'r', 'e', 's', '0', '0', '0', 0};
7581 7582 7583 7584 7585 7586 7587 7588 7589 7590 7591 7592 7593 7594 7595 7596 7597 7598

    /* Initialize Default data for OLESTREAM */
    pOleStreamData[0].dwOleID = OLESTREAM_ID;
    pOleStreamData[0].dwTypeID = 2;
    pOleStreamData[0].dwMetaFileWidth = 0;
    pOleStreamData[0].dwMetaFileHeight = 0;
    pOleStreamData[0].dwDataLength = OLECONVERT_WriteOLE20ToBuffer(pStorage, &(pOleStreamData[0].pData));
    pOleStreamData[1].dwOleID = OLESTREAM_ID;
    pOleStreamData[1].dwTypeID = 0;
    pOleStreamData[1].dwOleTypeNameLength = 0;
    pOleStreamData[1].strOleTypeName[0] = 0;
    pOleStreamData[1].dwMetaFileWidth = 0;
    pOleStreamData[1].dwMetaFileHeight = 0;
    pOleStreamData[1].pData = NULL;
    pOleStreamData[1].dwDataLength = 0;


    /* Open OlePress000 stream */
7599
    hRes = IStorage_OpenStream(pStorage, wstrStreamName, NULL,
7600 7601 7602 7603 7604
        STGM_READ  | STGM_SHARE_EXCLUSIVE, 0, &pStream );
    if(hRes == S_OK)
    {
        LARGE_INTEGER iSeekPos;
        METAFILEPICT16 MetaFilePict;
7605
        static const char strMetafilePictName[] = "METAFILEPICT";
7606 7607 7608 7609 7610 7611 7612 7613

        /* Set the TypeID for a Metafile */
        pOleStreamData[1].dwTypeID = 5;

        /* Set the OleTypeName to Metafile */
        pOleStreamData[1].dwOleTypeNameLength = strlen(strMetafilePictName) +1;
        strcpy(pOleStreamData[1].strOleTypeName, strMetafilePictName);

7614 7615
        iSeekPos.u.HighPart = 0;
        iSeekPos.u.LowPart = sizeof(olePress.byUnknown1);
7616 7617 7618 7619 7620 7621 7622 7623 7624 7625 7626 7627 7628 7629 7630 7631 7632 7633 7634 7635 7636 7637

        /* Get Presentation Data */
        IStream_Seek(pStream, iSeekPos, STREAM_SEEK_SET, NULL);
        IStream_Read(pStream, &(olePress.dwExtentX), sizeof(olePress.dwExtentX), NULL);
        IStream_Read(pStream, &(olePress.dwExtentY), sizeof(olePress.dwExtentY), NULL);
        IStream_Read(pStream, &(olePress.dwSize), sizeof(olePress.dwSize), NULL);

        /*Set width and Height */
        pOleStreamData[1].dwMetaFileWidth = olePress.dwExtentX;
        pOleStreamData[1].dwMetaFileHeight = -olePress.dwExtentY;
        if(olePress.dwSize > 0)
        {
            /* Set Length */
            pOleStreamData[1].dwDataLength  = olePress.dwSize + sizeof(METAFILEPICT16);

            /* Set MetaFilePict struct */
            MetaFilePict.mm = 8;
            MetaFilePict.xExt = olePress.dwExtentX;
            MetaFilePict.yExt = olePress.dwExtentY;
            MetaFilePict.hMF = 0;

            /* Get Metafile Data */
7638
            pOleStreamData[1].pData = HeapAlloc(GetProcessHeap(),0,pOleStreamData[1].dwDataLength);
7639 7640 7641 7642 7643 7644 7645 7646
            memcpy(pOleStreamData[1].pData, &MetaFilePict, sizeof(MetaFilePict));
            IStream_Read(pStream, &(pOleStreamData[1].pData[sizeof(MetaFilePict)]), pOleStreamData[1].dwDataLength-sizeof(METAFILEPICT16), NULL);
        }
        IStream_Release(pStream);
    }
}

/*************************************************************************
7647
 * OleConvertOLESTREAMToIStorage [OLE32.@]
7648 7649 7650 7651 7652 7653 7654 7655
 *
 * Read info on MSDN
 *
 * TODO
 *      DVTARGETDEVICE paramenter is not handled
 *      Still unsure of some mem fields for OLE 10 Stream
 *      Still some unknowns for the IStorage: "\002OlePres000", "\001CompObj",
 *      and "\001OLE" streams
7656
 *
7657 7658
 */
HRESULT WINAPI OleConvertOLESTREAMToIStorage (
7659 7660
    LPOLESTREAM pOleStream,
    LPSTORAGE pstg,
7661 7662 7663 7664 7665 7666
    const DVTARGETDEVICE* ptd)
{
    int i;
    HRESULT hRes=S_OK;
    OLECONVERT_OLESTREAM_DATA pOleStreamData[2];

7667 7668
    TRACE("%p %p %p\n", pOleStream, pstg, ptd);

7669 7670 7671 7672 7673 7674 7675 7676 7677 7678 7679 7680 7681 7682 7683
    memset(pOleStreamData, 0, sizeof(pOleStreamData));

    if(ptd != NULL)
    {
        FIXME("DVTARGETDEVICE is not NULL, unhandled parameter\n");
    }

    if(pstg == NULL || pOleStream == NULL)
    {
        hRes = E_INVALIDARG;
    }

    if(hRes == S_OK)
    {
        /* Load the OLESTREAM to Memory */
Alexandre Julliard's avatar
Alexandre Julliard committed
7684
        hRes = OLECONVERT_LoadOLE10(pOleStream, &pOleStreamData[0], TRUE);
7685 7686 7687 7688 7689
    }

    if(hRes == S_OK)
    {
        /* Load the OLESTREAM to Memory (part 2)*/
Alexandre Julliard's avatar
Alexandre Julliard committed
7690
        hRes = OLECONVERT_LoadOLE10(pOleStream, &pOleStreamData[1], FALSE);
7691 7692 7693 7694 7695 7696 7697 7698 7699 7700 7701 7702 7703 7704 7705 7706 7707 7708 7709 7710 7711 7712 7713 7714 7715 7716 7717 7718 7719 7720 7721 7722 7723 7724 7725 7726 7727 7728
    }

    if(hRes == S_OK)
    {

        if(pOleStreamData[0].dwDataLength > sizeof(STORAGE_magic))
        {
            /* Do we have the IStorage Data in the OLESTREAM */
            if(memcmp(pOleStreamData[0].pData, STORAGE_magic, sizeof(STORAGE_magic)) ==0)
            {
                OLECONVERT_GetOLE20FromOLE10(pstg, pOleStreamData[0].pData, pOleStreamData[0].dwDataLength);
                OLECONVERT_CreateOlePresStream(pstg, pOleStreamData[1].dwMetaFileWidth, pOleStreamData[1].dwMetaFileHeight, pOleStreamData[1].pData, pOleStreamData[1].dwDataLength);
            }
            else
            {
                /* It must be an original OLE 1.0 source */
                OLECONVERT_CreateOle10NativeStream(pstg, pOleStreamData[0].pData, pOleStreamData[0].dwDataLength);
            }
        }
        else
        {
            /* It must be an original OLE 1.0 source */
            OLECONVERT_CreateOle10NativeStream(pstg, pOleStreamData[0].pData, pOleStreamData[0].dwDataLength);
        }

        /* Create CompObj Stream if necessary */
        hRes = OLECONVERT_CreateCompObjStream(pstg, pOleStreamData[0].strOleTypeName);
        if(hRes == S_OK)
        {
            /*Create the Ole Stream if necessary */
            OLECONVERT_CreateOleStream(pstg);
        }
    }


    /* Free allocated memory */
    for(i=0; i < 2; i++)
    {
7729 7730 7731
        HeapFree(GetProcessHeap(),0,pOleStreamData[i].pData);
        HeapFree(GetProcessHeap(),0,pOleStreamData[i].pstrOleObjFileName);
        pOleStreamData[i].pstrOleObjFileName = NULL;
7732 7733 7734 7735 7736
    }
    return hRes;
}

/*************************************************************************
7737
 * OleConvertIStorageToOLESTREAM [OLE32.@]
7738 7739 7740 7741 7742 7743 7744 7745 7746
 *
 * Read info on MSDN
 *
 * Read info on MSDN
 *
 * TODO
 *      Still unsure of some mem fields for OLE 10 Stream
 *      Still some unknowns for the IStorage: "\002OlePres000", "\001CompObj",
 *      and "\001OLE" streams.
7747
 *
7748 7749
 */
HRESULT WINAPI OleConvertIStorageToOLESTREAM (
7750
    LPSTORAGE pstg,
7751 7752 7753 7754 7755 7756
    LPOLESTREAM pOleStream)
{
    int i;
    HRESULT hRes = S_OK;
    IStream *pStream;
    OLECONVERT_OLESTREAM_DATA pOleStreamData[2];
7757
    static const WCHAR wstrStreamName[] = {1, 'O', 'l', 'e', '1', '0', 'N', 'a', 't', 'i', 'v', 'e', 0};
7758

7759
    TRACE("%p %p\n", pstg, pOleStream);
7760 7761 7762 7763 7764 7765 7766 7767 7768 7769 7770 7771 7772 7773 7774

    memset(pOleStreamData, 0, sizeof(pOleStreamData));

    if(pstg == NULL || pOleStream == NULL)
    {
        hRes = E_INVALIDARG;
    }
    if(hRes == S_OK)
    {
        /* Get the ProgID */
        pOleStreamData[0].dwOleTypeNameLength = OLESTREAM_MAX_STR_LEN;
        hRes = OLECONVERT_GetOLE10ProgID(pstg, pOleStreamData[0].strOleTypeName, &(pOleStreamData[0].dwOleTypeNameLength));
    }
    if(hRes == S_OK)
    {
Alexandre Julliard's avatar
Alexandre Julliard committed
7775
        /* Was it originally Ole10 */
7776
        hRes = IStorage_OpenStream(pstg, wstrStreamName, 0, STGM_READ | STGM_SHARE_EXCLUSIVE, 0, &pStream);
7777 7778 7779
        if(hRes == S_OK)
        {
            IStream_Release(pStream);
Alexandre Julliard's avatar
Alexandre Julliard committed
7780
            /* Get Presentation Data for Ole10Native */
7781 7782 7783 7784
            OLECONVERT_GetOle10PresData(pstg, pOleStreamData);
        }
        else
        {
Alexandre Julliard's avatar
Alexandre Julliard committed
7785
            /* Get Presentation Data (OLE20) */
7786 7787 7788 7789 7790 7791 7792 7793 7794 7795 7796 7797 7798 7799 7800
            OLECONVERT_GetOle20PresData(pstg, pOleStreamData);
        }

        /* Save OLESTREAM */
        hRes = OLECONVERT_SaveOLE10(&(pOleStreamData[0]), pOleStream);
        if(hRes == S_OK)
        {
            hRes = OLECONVERT_SaveOLE10(&(pOleStreamData[1]), pOleStream);
        }

    }

    /* Free allocated memory */
    for(i=0; i < 2; i++)
    {
7801
        HeapFree(GetProcessHeap(),0,pOleStreamData[i].pData);
7802 7803 7804 7805
    }

    return hRes;
}
7806

7807
/***********************************************************************
7808
 *		GetConvertStg (OLE32.@)
7809
 */
7810 7811
HRESULT WINAPI GetConvertStg(IStorage *stg) {
    FIXME("unimplemented stub!\n");
7812 7813
    return E_FAIL;
}
7814 7815

/******************************************************************************
7816
 * StgIsStorageFile [OLE32.@]
7817 7818 7819 7820 7821 7822 7823 7824
 * Verify if the file contains a storage object
 *
 * PARAMS
 *  fn      [ I] Filename
 *
 * RETURNS
 *  S_OK    if file has magic bytes as a storage object
 *  S_FALSE if file is not storage
7825 7826 7827 7828 7829 7830 7831 7832
 */
HRESULT WINAPI
StgIsStorageFile(LPCOLESTR fn)
{
	HANDLE		hf;
	BYTE		magic[8];
	DWORD		bytes_read;

7833
	TRACE("%s\n", debugstr_w(fn));
7834 7835 7836 7837 7838 7839 7840 7841 7842 7843 7844 7845 7846 7847 7848 7849 7850 7851 7852 7853 7854 7855 7856 7857 7858 7859 7860 7861 7862
	hf = CreateFileW(fn, GENERIC_READ,
	                 FILE_SHARE_DELETE | FILE_SHARE_READ | FILE_SHARE_WRITE,
	                 NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);

	if (hf == INVALID_HANDLE_VALUE)
		return STG_E_FILENOTFOUND;

	if (!ReadFile(hf, magic, 8, &bytes_read, NULL))
	{
		WARN(" unable to read file\n");
		CloseHandle(hf);
		return S_FALSE;
	}

	CloseHandle(hf);

	if (bytes_read != 8) {
		WARN(" too short\n");
		return S_FALSE;
	}

	if (!memcmp(magic,STORAGE_magic,8)) {
		WARN(" -> YES\n");
		return S_OK;
	}

	WARN(" -> Invalid header.\n");
	return S_FALSE;
}
7863 7864 7865 7866 7867 7868 7869 7870 7871 7872 7873 7874 7875 7876 7877 7878 7879 7880

/***********************************************************************
 *		WriteClassStm (OLE32.@)
 *
 * Writes a CLSID to a stream.
 *
 * PARAMS
 *  pStm   [I] Stream to write to.
 *  rclsid [I] CLSID to write.
 *
 * RETURNS
 *  Success: S_OK.
 *  Failure: HRESULT code.
 */
HRESULT WINAPI WriteClassStm(IStream *pStm,REFCLSID rclsid)
{
    TRACE("(%p,%p)\n",pStm,rclsid);

7881
    if (!pStm || !rclsid)
7882 7883 7884 7885 7886 7887 7888 7889 7890 7891 7892 7893 7894 7895 7896 7897 7898 7899 7900 7901 7902 7903 7904 7905 7906
        return E_INVALIDARG;

    return IStream_Write(pStm,rclsid,sizeof(CLSID),NULL);
}

/***********************************************************************
 *		ReadClassStm (OLE32.@)
 *
 * Reads a CLSID from a stream.
 *
 * PARAMS
 *  pStm   [I] Stream to read from.
 *  rclsid [O] CLSID to read.
 *
 * RETURNS
 *  Success: S_OK.
 *  Failure: HRESULT code.
 */
HRESULT WINAPI ReadClassStm(IStream *pStm,CLSID *pclsid)
{
    ULONG nbByte;
    HRESULT res;

    TRACE("(%p,%p)\n",pStm,pclsid);

7907
    if (!pStm || !pclsid)
7908 7909
        return E_INVALIDARG;

7910
    /* clear the output args */
7911
    *pclsid = CLSID_NULL;
7912

7913 7914 7915 7916 7917 7918
    res = IStream_Read(pStm,(void*)pclsid,sizeof(CLSID),&nbByte);

    if (FAILED(res))
        return res;

    if (nbByte != sizeof(CLSID))
7919
        return STG_E_READFAULT;
7920 7921 7922
    else
        return S_OK;
}