<commit_before>/////////////////////////////////////////////////////////////////////////
// $Id: load32bitOShack.cc,v 1.13 2002/09/13 00:15:23 kevinlawton Exp $
/////////////////////////////////////////////////////////////////////////
//
//  Copyright (C) 2001  MandrakeSoft S.A.
//
//    MandrakeSoft S.A.
//    43, rue d'Aboukir
//    75002 Paris - France
//    http://www.linux-mandrake.com/
//    http://www.mandrakesoft.com/
//
//  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 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
//  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA

#include "bochs.h"
#define LOG_THIS genlog->

static void bx_load_linux_hack(void);
static void bx_load_null_kernel_hack(void);
static Bit32u bx_load_kernel_image(char *path, Bit32u paddr);

  void
bx_load32bitOSimagehack(void)
{
  // Replay IO from log to initialize IO devices to
  // a reasonable state needed for the OS.  This is done
  // in lieu of running the 16-bit BIOS to init things,
  // since we want to test straight 32bit stuff for
  // freemware.

  FILE *fp;

  fp = fopen(bx_options.load32bitOSImage.Oiolog->getptr (), "r");

  if (fp == NULL) {
    BX_PANIC(("could not open IO init file."));
    }

  while (1) {
    unsigned len, op, port, val;
    int ret;
    ret = fscanf(fp, "%u %u %x %x\n",
      &len, &op, &port, &val);
    if (ret != 4) {
      BX_PANIC(("could not open IO init file."));
      }
    if (op == 0) {
      // read
      (void) bx_devices.inp(port, len);
      }
    else if (op == 1) {
      // write
      bx_devices.outp(port, val, len);
      }
    else {
      BX_PANIC(("bad IO op in init filen"));
      }
    if (feof(fp)) break;
    }

  // Invoke proper hack depending on which OS image we're loading
  switch (bx_options.load32bitOSImage.OwhichOS->get ()) {
    case Load32bitOSLinux:
      bx_load_linux_hack();
      break;
    case Load32bitOSNullKernel:
      bx_load_null_kernel_hack();
      break;
    default:
      BX_PANIC(("load32bitOSImage: OS not recognized"));
    }
}

struct gdt_entry
{
  Bit32u low;
  Bit32u high;
};
struct linux_setup_params
{
   /* 0x000 */ Bit8u   orig_x;
   /* 0x001 */ Bit8u   orig_y;
   /* 0x002 */ Bit16u  memory_size_std;
   /* 0x004 */ Bit16u  orig_video_page;
   /* 0x006 */ Bit8u   orig_video_mode;
   /* 0x007 */ Bit8u   orig_video_cols;
   /* 0x008 */ Bit16u  unused1;
   /* 0x00a */ Bit16u  orig_video_ega_bx;
   /* 0x00c */ Bit16u  unused2;
   /* 0x00e */ Bit8u   orig_video_lines;
   /* 0x00f */ Bit8u   orig_video_isVGA;
   /* 0x010 */ Bit16u  orig_video_points;
   /* 0x012 */ Bit8u   pad1[0x40 - 0x12];
   /* 0x040 */ Bit8u   apm_info[0x80 - 0x40];
   /* 0x080 */ Bit8u   hd0_info[16];
   /* 0x090 */ Bit8u   hd1_info[16];
   /* 0x0a0 */ Bit8u   pad2[0x1e0 - 0xa0];
   /* 0x1e0 */ Bit32u  memory_size_ext;
   /* 0x1e4 */ Bit8u   pad3[0x1f1 - 0x1e4];
   /* 0x1f1 */ Bit8u   setup_sects;
   /* 0x1f2 */ Bit16u  mount_root_rdonly;
   /* 0x1f4 */ Bit16u  sys_size;
   /* 0x1f6 */ Bit16u  swap_dev;
   /* 0x1f8 */ Bit16u  ramdisk_flags;
   /* 0x1fa */ Bit16u  vga_mode;
   /* 0x1fc */ Bit16u  orig_root_dev;
   /* 0x1fe */ Bit16u  bootsect_magic;
   /* 0x200 */ Bit8u   pad4[0x210 - 0x200];
   /* 0x210 */ Bit32u  loader_type;
   /* 0x214 */ Bit32u  kernel_start;
   /* 0x218 */ Bit32u  initrd_start;
   /* 0x21c */ Bit32u  initrd_size;
   /* 0x220 */ Bit8u   pad5[0x400 - 0x220];
   /* 0x400 */ struct  gdt_entry gdt[128];
   /* 0x800 */ Bit8u   commandline[2048];
};

  static void
bx_load_linux_setup_params( Bit32u initrd_start, Bit32u initrd_size )
{
  BX_MEM_C *mem = BX_MEM(0);
  struct linux_setup_params *params =
         (struct linux_setup_params *) &mem->vector[0x00090000];

  memset( params, '\0', sizeof(*params) );

  /* Video settings (standard VGA) */
  params->orig_x = 0;
  params->orig_y = 0;
  params->orig_video_page = 0;
  params->orig_video_mode = 3;
  params->orig_video_cols = 80;
  params->orig_video_lines = 25;
  params->orig_video_points = 16;
  params->orig_video_isVGA = 1;
  params->orig_video_ega_bx = 3;

  /* Memory size (total mem - 1MB, in KB) */
  params->memory_size_ext = (mem->megabytes - 1) * 1024;

  /* Boot parameters */
  params->loader_type = 1;
  params->bootsect_magic = 0xaa55;
  params->mount_root_rdonly = 0;
  params->orig_root_dev = 0x0100;
  params->initrd_start = initrd_start;
  params->initrd_size  = initrd_size;

  /* Initial GDT */
  params->gdt[2].high = 0x00cf9a00;
  params->gdt[2].low  = 0x0000ffff;
  params->gdt[3].high = 0x00cf9200;
  params->gdt[3].low  = 0x0000ffff;
}

  void
bx_load_linux_hack(void)
{
  Bit32u initrd_start = 0, initrd_size = 0;

  // The RESET function will have been called first.
  // Set CPU and memory features which are assumed at this point.

  // Load Linux kernel image
  bx_load_kernel_image( bx_options.load32bitOSImage.Opath->getptr (), 0x100000 );

  // Load initial ramdisk image if requested
  if ( bx_options.load32bitOSImage.Oinitrd->getptr () )
  {
    initrd_start = 0x00800000;  /* FIXME: load at top of memory */
    initrd_size  = bx_load_kernel_image( bx_options.load32bitOSImage.Oinitrd->getptr (), initrd_start );
  }

  // Setup Linux startup parameters buffer
  bx_load_linux_setup_params( initrd_start, initrd_size );

  // Enable A20 line
  BX_SET_ENABLE_A20( 1 );

  // Setup PICs the way Linux likes it
  BX_OUTP( 0x20, 0x11, 1 );
  BX_OUTP( 0xA0, 0x11, 1 );
  BX_OUTP( 0x21, 0x20, 1 );
  BX_OUTP( 0xA1, 0x28, 1 );
  BX_OUTP( 0x21, 0x04, 1 );
  BX_OUTP( 0xA1, 0x02, 1 );
  BX_OUTP( 0x21, 0x01, 1 );
  BX_OUTP( 0xA1, 0x01, 1 );
  BX_OUTP( 0x21, 0xFF, 1 );
  BX_OUTP( 0xA1, 0xFB, 1 );

  // Disable interrupts and NMIs
  BX_CPU(0)->clear_IF ();
  BX_OUTP( 0x70, 0x80, 1 );

  // Enter protected mode
  BX_CPU(0)->cr0.pe = 1;
  BX_CPU(0)->cr0.val32 |= 0x01;

  // Set up initial GDT
  BX_CPU(0)->gdtr.limit = 0x400;
  BX_CPU(0)->gdtr.base  = 0x00090400;

  // Jump to protected mode entry point
  BX_CPU(0)->jump_protected( NULL, 0x10, 0x00100000 );
}

  void
bx_load_null_kernel_hack(void)
{
  // The RESET function will have been called first.
  // Set CPU and memory features which are assumed at this point.

  bx_load_kernel_image(bx_options.load32bitOSImage.Opath->getptr (), 0x100000);

  // EIP deltas
  BX_CPU(0)->prev_eip =
  BX_CPU(0)->dword.eip = 0x00100000;

  // CS deltas
  BX_CPU(0)->sregs[BX_SEG_REG_CS].cache.u.segment.base = 0x00000000;
  BX_CPU(0)->sregs[BX_SEG_REG_CS].cache.u.segment.limit = 0xFFFFF;
  BX_CPU(0)->sregs[BX_SEG_REG_CS].cache.u.segment.limit_scaled = 0xFFFFFFFF;
  BX_CPU(0)->sregs[BX_SEG_REG_CS].cache.u.segment.g   = 1; // page gran
  BX_CPU(0)->sregs[BX_SEG_REG_CS].cache.u.segment.d_b = 1; // 32bit

  // DS deltas
  BX_CPU(0)->sregs[BX_SEG_REG_DS].cache.u.segment.base = 0x00000000;
  BX_CPU(0)->sregs[BX_SEG_REG_DS].cache.u.segment.limit = 0xFFFFF;
  BX_CPU(0)->sregs[BX_SEG_REG_DS].cache.u.segment.limit_scaled = 0xFFFFFFFF;
  BX_CPU(0)->sregs[BX_SEG_REG_DS].cache.u.segment.g   = 1; // page gran
  BX_CPU(0)->sregs[BX_SEG_REG_DS].cache.u.segment.d_b = 1; // 32bit

  // CR0 deltas
  BX_CPU(0)->cr0.pe = 1; // protected mode
}

  Bit32u
bx_load_kernel_image(char *path, Bit32u paddr)
{
  struct stat stat_buf;
  int fd, ret;
  unsigned long size, offset;
  Bit32u page_size;

  // read in ROM BIOS image file
  fd = open(path, O_RDONLY
#ifdef O_BINARY
            | O_BINARY
#endif
           );
  if (fd < 0) {
    BX_INFO(( "load_kernel_image: couldn't open image file '%s'.", path ));
    BX_EXIT(1);
    }
  ret = fstat(fd, &stat_buf);
  if (ret) {
    BX_INFO(( "load_kernel_image: couldn't stat image file '%s'.", path ));
    BX_EXIT(1);
    }

  size = stat_buf.st_size;
  page_size = ((Bit32u)size + 0xfff) & ~0xfff;

  BX_MEM_C *mem = BX_MEM(0);
  if ( (paddr + size) > mem->len ) {
    BX_INFO(( "load_kernel_image: address range > physical memsize!" ));
    BX_EXIT(1);
    }

  offset = 0;
  while (size > 0) {
    ret = read(fd, (bx_ptr_t) &mem->vector[paddr + offset], size);
    if (ret <= 0) {
      BX_INFO(( "load_kernel_image: read failed on image" ));
      BX_EXIT(1);
      }
    size -= ret;
    offset += ret;
    }
  close(fd);
  BX_INFO(( "#(%u) load_kernel_image: '%s', size=%u read into memory at %08x",
          BX_SIM_ID, path,
          (unsigned) stat_buf.st_size,
          (unsigned) paddr ));

  return page_size;
}
<commit_msg>- applied SF patch #748414 load32bitOShack bug<commit_after>/////////////////////////////////////////////////////////////////////////
// $Id: load32bitOShack.cc,v 1.14 2003/08/08 00:05:53 cbothamy Exp $
/////////////////////////////////////////////////////////////////////////
//
//  Copyright (C) 2001  MandrakeSoft S.A.
//
//    MandrakeSoft S.A.
//    43, rue d'Aboukir
//    75002 Paris - France
//    http://www.linux-mandrake.com/
//    http://www.mandrakesoft.com/
//
//  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 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
//  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA

#include "bochs.h"
#define LOG_THIS genlog->

static void bx_load_linux_hack(void);
static void bx_load_null_kernel_hack(void);
static Bit32u bx_load_kernel_image(char *path, Bit32u paddr);

  void
bx_load32bitOSimagehack(void)
{
  // Replay IO from log to initialize IO devices to
  // a reasonable state needed for the OS.  This is done
  // in lieu of running the 16-bit BIOS to init things,
  // since we want to test straight 32bit stuff for
  // freemware.

  FILE *fp;

  fp = fopen(bx_options.load32bitOSImage.Oiolog->getptr (), "r");

  if (fp == NULL) {
    BX_PANIC(("could not open IO init file."));
    }

  while (1) {
    unsigned len, op, port, val;
    int ret;
    ret = fscanf(fp, "%u %u %x %x\n",
      &len, &op, &port, &val);
    if (ret != 4) {
      BX_PANIC(("could not open IO init file."));
      }
    if (op == 0) {
      // read
      (void) bx_devices.inp(port, len);
      }
    else if (op == 1) {
      // write
      bx_devices.outp(port, val, len);
      }
    else {
      BX_PANIC(("bad IO op in init filen"));
      }
    if (feof(fp)) break;
    }

  // Invoke proper hack depending on which OS image we're loading
  switch (bx_options.load32bitOSImage.OwhichOS->get ()) {
    case Load32bitOSLinux:
      bx_load_linux_hack();
      break;
    case Load32bitOSNullKernel:
      bx_load_null_kernel_hack();
      break;
    default:
      BX_PANIC(("load32bitOSImage: OS not recognized"));
    }
}

struct gdt_entry
{
  Bit32u low;
  Bit32u high;
};
struct linux_setup_params
{
   /* 0x000 */ Bit8u   orig_x;
   /* 0x001 */ Bit8u   orig_y;
   /* 0x002 */ Bit16u  memory_size_std;
   /* 0x004 */ Bit16u  orig_video_page;
   /* 0x006 */ Bit8u   orig_video_mode;
   /* 0x007 */ Bit8u   orig_video_cols;
   /* 0x008 */ Bit16u  unused1;
   /* 0x00a */ Bit16u  orig_video_ega_bx;
   /* 0x00c */ Bit16u  unused2;
   /* 0x00e */ Bit8u   orig_video_lines;
   /* 0x00f */ Bit8u   orig_video_isVGA;
   /* 0x010 */ Bit16u  orig_video_points;
   /* 0x012 */ Bit8u   pad1[0x40 - 0x12];
   /* 0x040 */ Bit8u   apm_info[0x80 - 0x40];
   /* 0x080 */ Bit8u   hd0_info[16];
   /* 0x090 */ Bit8u   hd1_info[16];
   /* 0x0a0 */ Bit8u   pad2[0x1e0 - 0xa0];
   /* 0x1e0 */ Bit32u  memory_size_ext;
   /* 0x1e4 */ Bit8u   pad3[0x1f1 - 0x1e4];
   /* 0x1f1 */ Bit8u   setup_sects;
   /* 0x1f2 */ Bit16u  mount_root_rdonly;
   /* 0x1f4 */ Bit16u  sys_size;
   /* 0x1f6 */ Bit16u  swap_dev;
   /* 0x1f8 */ Bit16u  ramdisk_flags;
   /* 0x1fa */ Bit16u  vga_mode;
   /* 0x1fc */ Bit16u  orig_root_dev;
   /* 0x1fe */ Bit16u  bootsect_magic;
   /* 0x200 */ Bit8u   pad4[0x210 - 0x200];
   /* 0x210 */ Bit32u  loader_type;
   /* 0x214 */ Bit32u  kernel_start;
   /* 0x218 */ Bit32u  initrd_start;
   /* 0x21c */ Bit32u  initrd_size;
   /* 0x220 */ Bit8u   pad5[0x400 - 0x220];
   /* 0x400 */ struct  gdt_entry gdt[128];
   /* 0x800 */ Bit8u   commandline[2048];
};

  static void
bx_load_linux_setup_params( Bit32u initrd_start, Bit32u initrd_size )
{
  BX_MEM_C *mem = BX_MEM(0);
  struct linux_setup_params *params =
         (struct linux_setup_params *) &mem->vector[0x00090000];

  memset( params, '\0', sizeof(*params) );

  /* Video settings (standard VGA) */
  params->orig_x = 0;
  params->orig_y = 0;
  params->orig_video_page = 0;
  params->orig_video_mode = 3;
  params->orig_video_cols = 80;
  params->orig_video_lines = 25;
  params->orig_video_points = 16;
  params->orig_video_isVGA = 1;
  params->orig_video_ega_bx = 3;

  /* Memory size (total mem - 1MB, in KB) */
  params->memory_size_ext = (mem->megabytes - 1) * 1024;

  /* Boot parameters */
  params->loader_type = 1;
  params->bootsect_magic = 0xaa55;
  params->mount_root_rdonly = 0;
  params->orig_root_dev = 0x0100;
  params->initrd_start = initrd_start;
  params->initrd_size  = initrd_size;

  /* Initial GDT */
  params->gdt[2].high = 0x00cf9a00;
  params->gdt[2].low  = 0x0000ffff;
  params->gdt[3].high = 0x00cf9200;
  params->gdt[3].low  = 0x0000ffff;
}

  void
bx_load_linux_hack(void)
{
  Bit32u initrd_start = 0, initrd_size = 0;

  // The RESET function will have been called first.
  // Set CPU and memory features which are assumed at this point.

  // Load Linux kernel image
  bx_load_kernel_image( bx_options.load32bitOSImage.Opath->getptr (), 0x100000 );

  // Load initial ramdisk image if requested
  if ( bx_options.load32bitOSImage.Oinitrd->getptr () )
  {
    initrd_start = 0x00800000;  /* FIXME: load at top of memory */
    initrd_size  = bx_load_kernel_image( bx_options.load32bitOSImage.Oinitrd->getptr (), initrd_start );
  }

  // Setup Linux startup parameters buffer
  bx_load_linux_setup_params( initrd_start, initrd_size );

  // Enable A20 line
  BX_SET_ENABLE_A20( 1 );

  // Setup PICs the way Linux likes it
  BX_OUTP( 0x20, 0x11, 1 );
  BX_OUTP( 0xA0, 0x11, 1 );
  BX_OUTP( 0x21, 0x20, 1 );
  BX_OUTP( 0xA1, 0x28, 1 );
  BX_OUTP( 0x21, 0x04, 1 );
  BX_OUTP( 0xA1, 0x02, 1 );
  BX_OUTP( 0x21, 0x01, 1 );
  BX_OUTP( 0xA1, 0x01, 1 );
  BX_OUTP( 0x21, 0xFF, 1 );
  BX_OUTP( 0xA1, 0xFB, 1 );

  // Disable interrupts and NMIs
  BX_CPU(0)->clear_IF ();
  BX_OUTP( 0x70, 0x80, 1 );

  // Enter protected mode
  // Fixed by george (kyriazis at nvidia.com)
  // BX_CPU(0)->cr0.pe = 1;
  // BX_CPU(0)->cr0.val32 |= 0x01;

  BX_CPU(0)->SetCR0(BX_CPU(0)->cr0.val32 | 0x01);

  // load esi with real_mode
  BX_CPU(0)->gen_reg[BX_32BIT_REG_ESI].dword.erx = 0x90000;

  // Set up initial GDT
  BX_CPU(0)->gdtr.limit = 0x400;
  BX_CPU(0)->gdtr.base  = 0x00090400;

  // Jump to protected mode entry point
  BX_CPU(0)->jump_protected( NULL, 0x10, 0x00100000 );
}

  void
bx_load_null_kernel_hack(void)
{
  // The RESET function will have been called first.
  // Set CPU and memory features which are assumed at this point.

  bx_load_kernel_image(bx_options.load32bitOSImage.Opath->getptr (), 0x100000);

  // EIP deltas
  BX_CPU(0)->prev_eip =
  BX_CPU(0)->dword.eip = 0x00100000;

  // CS deltas
  BX_CPU(0)->sregs[BX_SEG_REG_CS].cache.u.segment.base = 0x00000000;
  BX_CPU(0)->sregs[BX_SEG_REG_CS].cache.u.segment.limit = 0xFFFFF;
  BX_CPU(0)->sregs[BX_SEG_REG_CS].cache.u.segment.limit_scaled = 0xFFFFFFFF;
  BX_CPU(0)->sregs[BX_SEG_REG_CS].cache.u.segment.g   = 1; // page gran
  BX_CPU(0)->sregs[BX_SEG_REG_CS].cache.u.segment.d_b = 1; // 32bit

  // DS deltas
  BX_CPU(0)->sregs[BX_SEG_REG_DS].cache.u.segment.base = 0x00000000;
  BX_CPU(0)->sregs[BX_SEG_REG_DS].cache.u.segment.limit = 0xFFFFF;
  BX_CPU(0)->sregs[BX_SEG_REG_DS].cache.u.segment.limit_scaled = 0xFFFFFFFF;
  BX_CPU(0)->sregs[BX_SEG_REG_DS].cache.u.segment.g   = 1; // page gran
  BX_CPU(0)->sregs[BX_SEG_REG_DS].cache.u.segment.d_b = 1; // 32bit

  // CR0 deltas
  BX_CPU(0)->cr0.pe = 1; // protected mode
}

  Bit32u
bx_load_kernel_image(char *path, Bit32u paddr)
{
  struct stat stat_buf;
  int fd, ret;
  unsigned long size, offset;
  Bit32u page_size;

  // read in ROM BIOS image file
  fd = open(path, O_RDONLY
#ifdef O_BINARY
            | O_BINARY
#endif
           );
  if (fd < 0) {
    BX_INFO(( "load_kernel_image: couldn't open image file '%s'.", path ));
    BX_EXIT(1);
    }
  ret = fstat(fd, &stat_buf);
  if (ret) {
    BX_INFO(( "load_kernel_image: couldn't stat image file '%s'.", path ));
    BX_EXIT(1);
    }

  size = stat_buf.st_size;
  page_size = ((Bit32u)size + 0xfff) & ~0xfff;

  BX_MEM_C *mem = BX_MEM(0);
  if ( (paddr + size) > mem->len ) {
    BX_INFO(( "load_kernel_image: address range > physical memsize!" ));
    BX_EXIT(1);
    }

  offset = 0;
  while (size > 0) {
    ret = read(fd, (bx_ptr_t) &mem->vector[paddr + offset], size);
    if (ret <= 0) {
      BX_INFO(( "load_kernel_image: read failed on image" ));
      BX_EXIT(1);
      }
    size -= ret;
    offset += ret;
    }
  close(fd);
  BX_INFO(( "#(%u) load_kernel_image: '%s', size=%u read into memory at %08x",
          BX_SIM_ID, path,
          (unsigned) stat_buf.st_size,
          (unsigned) paddr ));

  return page_size;
}
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: xsecparser.cxx,v $
 *
 *  $Revision: 1.6 $
 *
 *  last change: $Author: obo $ $Date: 2006-09-16 14:41:05 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    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
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_xmlsecurity.hxx"

#include "xsecparser.hxx"

#ifndef _TOOLS_DEBUG_HXX //autogen wg. DBG_ASSERT
#include <tools/debug.hxx>
#endif
#include "cppuhelper/exc_hlp.hxx"

namespace cssu = com::sun::star::uno;
namespace cssxs = com::sun::star::xml::sax;

#define RTL_ASCII_USTRINGPARAM( asciiStr ) asciiStr, strlen( asciiStr ), RTL_TEXTENCODING_ASCII_US

XSecParser::XSecParser(
    XSecController* pXSecController,
    const cssu::Reference< cssxs::XDocumentHandler >& xNextHandler )
    : m_pXSecController(pXSecController),
      m_xNextHandler(xNextHandler),
      m_bReferenceUnresolved(false)
{
}

rtl::OUString XSecParser::getIdAttr(const cssu::Reference< cssxs::XAttributeList >& xAttribs )
{
    rtl::OUString ouIdAttr = xAttribs->getValueByName(
        rtl::OUString(RTL_ASCII_USTRINGPARAM("id")));

    if (ouIdAttr == NULL)
    {
        ouIdAttr = xAttribs->getValueByName(
            rtl::OUString(RTL_ASCII_USTRINGPARAM("Id")));
    }

    return ouIdAttr;
}

/*
 * XDocumentHandler
 */
void SAL_CALL XSecParser::startDocument(  )
    throw (cssxs::SAXException, cssu::RuntimeException)
{
    m_bInX509IssuerName = false;
    m_bInX509SerialNumber = false;
    m_bInX509Certificate = false;
    m_bInSignatureValue = false;
    m_bInDigestValue = false;
    m_bInDate = false;
    //m_bInTime = false;

    if (m_xNextHandler.is())
    {
        m_xNextHandler->startDocument();
    }
}

void SAL_CALL XSecParser::endDocument(  )
    throw (cssxs::SAXException, cssu::RuntimeException)
{
    if (m_xNextHandler.is())
    {
        m_xNextHandler->endDocument();
    }
}

void SAL_CALL XSecParser::startElement(
    const rtl::OUString& aName,
    const cssu::Reference< cssxs::XAttributeList >& xAttribs )
    throw (cssxs::SAXException, cssu::RuntimeException)
{
    try
    {
        rtl::OUString ouIdAttr = getIdAttr(xAttribs);
        if (ouIdAttr != NULL)
        {
            m_pXSecController->collectToVerify( ouIdAttr );
        }

        if ( aName == rtl::OUString(RTL_ASCII_USTRINGPARAM(TAG_SIGNATURE)) )
        {
            m_pXSecController->addSignature();
            if (ouIdAttr != NULL)
            {
                m_pXSecController->setId( ouIdAttr );
            }
        }
        else if ( aName == rtl::OUString(RTL_ASCII_USTRINGPARAM(TAG_REFERENCE)) )
        {
            rtl::OUString ouUri = xAttribs->getValueByName(rtl::OUString(RTL_ASCII_USTRINGPARAM(ATTR_URI)));
            DBG_ASSERT( ouUri != NULL, "URI == NULL" );

            if (0 == ouUri.compareTo(rtl::OUString(RTL_ASCII_USTRINGPARAM(CHAR_FRAGMENT)),1))
            {
                /*
                * remove the first character '#' from the attribute value
                */
                m_pXSecController->addReference( ouUri.copy(1) );
            }
            else
            {
                /*
                * remember the uri
                */
                m_currentReferenceURI = ouUri;
                m_bReferenceUnresolved = true;
            }
        }
            else if (aName == rtl::OUString(RTL_ASCII_USTRINGPARAM(TAG_TRANSFORM)))
            {
            if ( m_bReferenceUnresolved )
            {
                rtl::OUString ouAlgorithm = xAttribs->getValueByName(rtl::OUString(RTL_ASCII_USTRINGPARAM(ATTR_ALGORITHM)));

                if (ouAlgorithm != NULL && ouAlgorithm == rtl::OUString(RTL_ASCII_USTRINGPARAM(ALGO_C14N)))
                /*
                * a xml stream
                */
                {
                    m_pXSecController->addStreamReference( m_currentReferenceURI, sal_False);
                    m_bReferenceUnresolved = false;
                }
            }
            }
            else if (aName == rtl::OUString(RTL_ASCII_USTRINGPARAM(TAG_X509ISSUERNAME)))
            {
            m_ouX509IssuerName = rtl::OUString::createFromAscii("");
            m_bInX509IssuerName = true;
            }
            else if (aName == rtl::OUString(RTL_ASCII_USTRINGPARAM(TAG_X509SERIALNUMBER)))
            {
            m_ouX509SerialNumber = rtl::OUString::createFromAscii("");
            m_bInX509SerialNumber = true;
            }
            else if (aName == rtl::OUString(RTL_ASCII_USTRINGPARAM(TAG_X509CERTIFICATE)))
            {
            m_ouX509Certificate = rtl::OUString::createFromAscii("");
            m_bInX509Certificate = true;
            }
            else if (aName == rtl::OUString(RTL_ASCII_USTRINGPARAM(TAG_SIGNATUREVALUE)))
            {
            m_ouSignatureValue = rtl::OUString::createFromAscii("");
                m_bInSignatureValue = true;
            }
            else if (aName == rtl::OUString(RTL_ASCII_USTRINGPARAM(TAG_DIGESTVALUE)))
            {
            m_ouDigestValue = rtl::OUString::createFromAscii("");
                m_bInDigestValue = true;
            }
            else if ( aName == rtl::OUString(RTL_ASCII_USTRINGPARAM(TAG_SIGNATUREPROPERTY)) )
        {
            if (ouIdAttr != NULL)
            {
                m_pXSecController->setPropertyId( ouIdAttr );
            }
        }
            else if (aName == rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(NSTAG_DC))
                        +rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(":"))
                        +rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(TAG_DATE)))
            {
            m_ouDate = rtl::OUString::createFromAscii("");
                m_bInDate = true;
            }
            /*
            else if (aName == rtl::OUString(RTL_ASCII_USTRINGPARAM(TAG_TIME)))
            {
            m_ouTime = rtl::OUString::createFromAscii("");
                m_bInTime = true;
            }
            */

        if (m_xNextHandler.is())
        {
            m_xNextHandler->startElement(aName, xAttribs);
        }
    }
    catch (cssu::Exception& )
    {//getCaughtException MUST be the first line in the catch block
        cssu::Any exc =  cppu::getCaughtException();
        throw cssxs::SAXException(
            rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(
                              "xmlsecurity: Exception in XSecParser::startElement")),
            0, exc);
    }
    catch (...)
    {
        throw cssxs::SAXException(
            rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("xmlsecurity: unexpected exception in XSecParser::startElement")), 0,
            cssu::Any());
    }
}

void SAL_CALL XSecParser::endElement( const rtl::OUString& aName )
    throw (cssxs::SAXException, cssu::RuntimeException)
{
    try
    {
        if (aName == rtl::OUString(RTL_ASCII_USTRINGPARAM(TAG_DIGESTVALUE)))
            {
                m_bInDigestValue = false;
            }
        else if ( aName == rtl::OUString(RTL_ASCII_USTRINGPARAM(TAG_REFERENCE)) )
        {
            if ( m_bReferenceUnresolved )
            /*
            * it must be a octet stream
            */
            {
                m_pXSecController->addStreamReference( m_currentReferenceURI, sal_True);
                m_bReferenceUnresolved = false;
            }

            m_pXSecController->setDigestValue( m_ouDigestValue );
        }
        else if ( aName == rtl::OUString(RTL_ASCII_USTRINGPARAM(TAG_SIGNEDINFO)) )
        {
            m_pXSecController->setReferenceCount();
        }
        else if ( aName == rtl::OUString(RTL_ASCII_USTRINGPARAM(TAG_SIGNATUREVALUE)) )
        {
            m_pXSecController->setSignatureValue( m_ouSignatureValue );
                m_bInSignatureValue = false;
        }
            else if (aName == rtl::OUString(RTL_ASCII_USTRINGPARAM(TAG_X509ISSUERNAME)))
            {
            m_pXSecController->setX509IssuerName( m_ouX509IssuerName );
            m_bInX509IssuerName = false;
            }
            else if (aName == rtl::OUString(RTL_ASCII_USTRINGPARAM(TAG_X509SERIALNUMBER)))
            {
            m_pXSecController->setX509SerialNumber( m_ouX509SerialNumber );
            m_bInX509SerialNumber = false;
            }
            else if (aName == rtl::OUString(RTL_ASCII_USTRINGPARAM(TAG_X509CERTIFICATE)))
            {
            m_pXSecController->setX509Certificate( m_ouX509Certificate );
            m_bInX509Certificate = false;
            }
            else if (aName == rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(NSTAG_DC))
                        +rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(":"))
                        +rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(TAG_DATE)))
        {
            m_pXSecController->setDate( m_ouDate );
                m_bInDate = false;
        }
        /*
        else if ( aName == rtl::OUString(RTL_ASCII_USTRINGPARAM(TAG_TIME)) )
        {
            m_pXSecController->setTime( m_ouTime );
                m_bInTime = false;
        }
        */

        if (m_xNextHandler.is())
        {
            m_xNextHandler->endElement(aName);
        }
    }
    catch (cssu::Exception& )
    {//getCaughtException MUST be the first line in the catch block
        cssu::Any exc =  cppu::getCaughtException();
        throw cssxs::SAXException(
            rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(
                              "xmlsecurity: Exception in XSecParser::endElement")),
            0, exc);
    }
    catch (...)
    {
        throw cssxs::SAXException(
            rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("xmlsecurity: unexpected exception in XSecParser::endElement")), 0,
            cssu::Any());
    }
}

void SAL_CALL XSecParser::characters( const rtl::OUString& aChars )
    throw (cssxs::SAXException, cssu::RuntimeException)
{
    if (m_bInX509IssuerName)
    {
        m_ouX509IssuerName += aChars;
    }
    else if (m_bInX509SerialNumber)
    {
        m_ouX509SerialNumber += aChars;
    }
    else if (m_bInX509Certificate)
    {
        m_ouX509Certificate += aChars;
    }
    else if (m_bInSignatureValue)
    {
        m_ouSignatureValue += aChars;
    }
    else if (m_bInDigestValue)
    {
        m_ouDigestValue += aChars;
    }
    else if (m_bInDate)
    {
        m_ouDate += aChars;
    }
    /*
    else if (m_bInTime)
    {
        m_ouTime += aChars;
    }
    */

    if (m_xNextHandler.is())
    {
        m_xNextHandler->characters(aChars);
        }
}

void SAL_CALL XSecParser::ignorableWhitespace( const rtl::OUString& aWhitespaces )
    throw (cssxs::SAXException, cssu::RuntimeException)
{
    if (m_xNextHandler.is())
    {
        m_xNextHandler->ignorableWhitespace( aWhitespaces );
        }
}

void SAL_CALL XSecParser::processingInstruction( const rtl::OUString& aTarget, const rtl::OUString& aData )
    throw (cssxs::SAXException, cssu::RuntimeException)
{
    if (m_xNextHandler.is())
    {
        m_xNextHandler->processingInstruction(aTarget, aData);
        }
}

void SAL_CALL XSecParser::setDocumentLocator( const cssu::Reference< cssxs::XLocator >& xLocator )
    throw (cssxs::SAXException, cssu::RuntimeException)
{
    if (m_xNextHandler.is())
    {
        m_xNextHandler->setDocumentLocator( xLocator );
        }
}

/*
 * XInitialization
 */
void SAL_CALL XSecParser::initialize(
    const cssu::Sequence< cssu::Any >& aArguments )
    throw(cssu::Exception, cssu::RuntimeException)
{
    aArguments[0] >>= m_xNextHandler;
}
<commit_msg>INTEGRATION: CWS gcc430two (1.6.94); FILE MERGED 2008/01/28 09:53:15 rene 1.6.94.1: more gcc 4.3.0 things<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: xsecparser.cxx,v $
 *
 *  $Revision: 1.7 $
 *
 *  last change: $Author: ihi $ $Date: 2008-02-04 13:43:11 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    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
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_xmlsecurity.hxx"

#include "xsecparser.hxx"

#ifndef _TOOLS_DEBUG_HXX //autogen wg. DBG_ASSERT
#include <tools/debug.hxx>
#endif
#include "cppuhelper/exc_hlp.hxx"

#include <string.h>

namespace cssu = com::sun::star::uno;
namespace cssxs = com::sun::star::xml::sax;

#define RTL_ASCII_USTRINGPARAM( asciiStr ) asciiStr, strlen( asciiStr ), RTL_TEXTENCODING_ASCII_US

XSecParser::XSecParser(
    XSecController* pXSecController,
    const cssu::Reference< cssxs::XDocumentHandler >& xNextHandler )
    : m_pXSecController(pXSecController),
      m_xNextHandler(xNextHandler),
      m_bReferenceUnresolved(false)
{
}

rtl::OUString XSecParser::getIdAttr(const cssu::Reference< cssxs::XAttributeList >& xAttribs )
{
    rtl::OUString ouIdAttr = xAttribs->getValueByName(
        rtl::OUString(RTL_ASCII_USTRINGPARAM("id")));

    if (ouIdAttr == NULL)
    {
        ouIdAttr = xAttribs->getValueByName(
            rtl::OUString(RTL_ASCII_USTRINGPARAM("Id")));
    }

    return ouIdAttr;
}

/*
 * XDocumentHandler
 */
void SAL_CALL XSecParser::startDocument(  )
    throw (cssxs::SAXException, cssu::RuntimeException)
{
    m_bInX509IssuerName = false;
    m_bInX509SerialNumber = false;
    m_bInX509Certificate = false;
    m_bInSignatureValue = false;
    m_bInDigestValue = false;
    m_bInDate = false;
    //m_bInTime = false;

    if (m_xNextHandler.is())
    {
        m_xNextHandler->startDocument();
    }
}

void SAL_CALL XSecParser::endDocument(  )
    throw (cssxs::SAXException, cssu::RuntimeException)
{
    if (m_xNextHandler.is())
    {
        m_xNextHandler->endDocument();
    }
}

void SAL_CALL XSecParser::startElement(
    const rtl::OUString& aName,
    const cssu::Reference< cssxs::XAttributeList >& xAttribs )
    throw (cssxs::SAXException, cssu::RuntimeException)
{
    try
    {
        rtl::OUString ouIdAttr = getIdAttr(xAttribs);
        if (ouIdAttr != NULL)
        {
            m_pXSecController->collectToVerify( ouIdAttr );
        }

        if ( aName == rtl::OUString(RTL_ASCII_USTRINGPARAM(TAG_SIGNATURE)) )
        {
            m_pXSecController->addSignature();
            if (ouIdAttr != NULL)
            {
                m_pXSecController->setId( ouIdAttr );
            }
        }
        else if ( aName == rtl::OUString(RTL_ASCII_USTRINGPARAM(TAG_REFERENCE)) )
        {
            rtl::OUString ouUri = xAttribs->getValueByName(rtl::OUString(RTL_ASCII_USTRINGPARAM(ATTR_URI)));
            DBG_ASSERT( ouUri != NULL, "URI == NULL" );

            if (0 == ouUri.compareTo(rtl::OUString(RTL_ASCII_USTRINGPARAM(CHAR_FRAGMENT)),1))
            {
                /*
                * remove the first character '#' from the attribute value
                */
                m_pXSecController->addReference( ouUri.copy(1) );
            }
            else
            {
                /*
                * remember the uri
                */
                m_currentReferenceURI = ouUri;
                m_bReferenceUnresolved = true;
            }
        }
            else if (aName == rtl::OUString(RTL_ASCII_USTRINGPARAM(TAG_TRANSFORM)))
            {
            if ( m_bReferenceUnresolved )
            {
                rtl::OUString ouAlgorithm = xAttribs->getValueByName(rtl::OUString(RTL_ASCII_USTRINGPARAM(ATTR_ALGORITHM)));

                if (ouAlgorithm != NULL && ouAlgorithm == rtl::OUString(RTL_ASCII_USTRINGPARAM(ALGO_C14N)))
                /*
                * a xml stream
                */
                {
                    m_pXSecController->addStreamReference( m_currentReferenceURI, sal_False);
                    m_bReferenceUnresolved = false;
                }
            }
            }
            else if (aName == rtl::OUString(RTL_ASCII_USTRINGPARAM(TAG_X509ISSUERNAME)))
            {
            m_ouX509IssuerName = rtl::OUString::createFromAscii("");
            m_bInX509IssuerName = true;
            }
            else if (aName == rtl::OUString(RTL_ASCII_USTRINGPARAM(TAG_X509SERIALNUMBER)))
            {
            m_ouX509SerialNumber = rtl::OUString::createFromAscii("");
            m_bInX509SerialNumber = true;
            }
            else if (aName == rtl::OUString(RTL_ASCII_USTRINGPARAM(TAG_X509CERTIFICATE)))
            {
            m_ouX509Certificate = rtl::OUString::createFromAscii("");
            m_bInX509Certificate = true;
            }
            else if (aName == rtl::OUString(RTL_ASCII_USTRINGPARAM(TAG_SIGNATUREVALUE)))
            {
            m_ouSignatureValue = rtl::OUString::createFromAscii("");
                m_bInSignatureValue = true;
            }
            else if (aName == rtl::OUString(RTL_ASCII_USTRINGPARAM(TAG_DIGESTVALUE)))
            {
            m_ouDigestValue = rtl::OUString::createFromAscii("");
                m_bInDigestValue = true;
            }
            else if ( aName == rtl::OUString(RTL_ASCII_USTRINGPARAM(TAG_SIGNATUREPROPERTY)) )
        {
            if (ouIdAttr != NULL)
            {
                m_pXSecController->setPropertyId( ouIdAttr );
            }
        }
            else if (aName == rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(NSTAG_DC))
                        +rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(":"))
                        +rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(TAG_DATE)))
            {
            m_ouDate = rtl::OUString::createFromAscii("");
                m_bInDate = true;
            }
            /*
            else if (aName == rtl::OUString(RTL_ASCII_USTRINGPARAM(TAG_TIME)))
            {
            m_ouTime = rtl::OUString::createFromAscii("");
                m_bInTime = true;
            }
            */

        if (m_xNextHandler.is())
        {
            m_xNextHandler->startElement(aName, xAttribs);
        }
    }
    catch (cssu::Exception& )
    {//getCaughtException MUST be the first line in the catch block
        cssu::Any exc =  cppu::getCaughtException();
        throw cssxs::SAXException(
            rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(
                              "xmlsecurity: Exception in XSecParser::startElement")),
            0, exc);
    }
    catch (...)
    {
        throw cssxs::SAXException(
            rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("xmlsecurity: unexpected exception in XSecParser::startElement")), 0,
            cssu::Any());
    }
}

void SAL_CALL XSecParser::endElement( const rtl::OUString& aName )
    throw (cssxs::SAXException, cssu::RuntimeException)
{
    try
    {
        if (aName == rtl::OUString(RTL_ASCII_USTRINGPARAM(TAG_DIGESTVALUE)))
            {
                m_bInDigestValue = false;
            }
        else if ( aName == rtl::OUString(RTL_ASCII_USTRINGPARAM(TAG_REFERENCE)) )
        {
            if ( m_bReferenceUnresolved )
            /*
            * it must be a octet stream
            */
            {
                m_pXSecController->addStreamReference( m_currentReferenceURI, sal_True);
                m_bReferenceUnresolved = false;
            }

            m_pXSecController->setDigestValue( m_ouDigestValue );
        }
        else if ( aName == rtl::OUString(RTL_ASCII_USTRINGPARAM(TAG_SIGNEDINFO)) )
        {
            m_pXSecController->setReferenceCount();
        }
        else if ( aName == rtl::OUString(RTL_ASCII_USTRINGPARAM(TAG_SIGNATUREVALUE)) )
        {
            m_pXSecController->setSignatureValue( m_ouSignatureValue );
                m_bInSignatureValue = false;
        }
            else if (aName == rtl::OUString(RTL_ASCII_USTRINGPARAM(TAG_X509ISSUERNAME)))
            {
            m_pXSecController->setX509IssuerName( m_ouX509IssuerName );
            m_bInX509IssuerName = false;
            }
            else if (aName == rtl::OUString(RTL_ASCII_USTRINGPARAM(TAG_X509SERIALNUMBER)))
            {
            m_pXSecController->setX509SerialNumber( m_ouX509SerialNumber );
            m_bInX509SerialNumber = false;
            }
            else if (aName == rtl::OUString(RTL_ASCII_USTRINGPARAM(TAG_X509CERTIFICATE)))
            {
            m_pXSecController->setX509Certificate( m_ouX509Certificate );
            m_bInX509Certificate = false;
            }
            else if (aName == rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(NSTAG_DC))
                        +rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(":"))
                        +rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(TAG_DATE)))
        {
            m_pXSecController->setDate( m_ouDate );
                m_bInDate = false;
        }
        /*
        else if ( aName == rtl::OUString(RTL_ASCII_USTRINGPARAM(TAG_TIME)) )
        {
            m_pXSecController->setTime( m_ouTime );
                m_bInTime = false;
        }
        */

        if (m_xNextHandler.is())
        {
            m_xNextHandler->endElement(aName);
        }
    }
    catch (cssu::Exception& )
    {//getCaughtException MUST be the first line in the catch block
        cssu::Any exc =  cppu::getCaughtException();
        throw cssxs::SAXException(
            rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(
                              "xmlsecurity: Exception in XSecParser::endElement")),
            0, exc);
    }
    catch (...)
    {
        throw cssxs::SAXException(
            rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("xmlsecurity: unexpected exception in XSecParser::endElement")), 0,
            cssu::Any());
    }
}

void SAL_CALL XSecParser::characters( const rtl::OUString& aChars )
    throw (cssxs::SAXException, cssu::RuntimeException)
{
    if (m_bInX509IssuerName)
    {
        m_ouX509IssuerName += aChars;
    }
    else if (m_bInX509SerialNumber)
    {
        m_ouX509SerialNumber += aChars;
    }
    else if (m_bInX509Certificate)
    {
        m_ouX509Certificate += aChars;
    }
    else if (m_bInSignatureValue)
    {
        m_ouSignatureValue += aChars;
    }
    else if (m_bInDigestValue)
    {
        m_ouDigestValue += aChars;
    }
    else if (m_bInDate)
    {
        m_ouDate += aChars;
    }
    /*
    else if (m_bInTime)
    {
        m_ouTime += aChars;
    }
    */

    if (m_xNextHandler.is())
    {
        m_xNextHandler->characters(aChars);
        }
}

void SAL_CALL XSecParser::ignorableWhitespace( const rtl::OUString& aWhitespaces )
    throw (cssxs::SAXException, cssu::RuntimeException)
{
    if (m_xNextHandler.is())
    {
        m_xNextHandler->ignorableWhitespace( aWhitespaces );
        }
}

void SAL_CALL XSecParser::processingInstruction( const rtl::OUString& aTarget, const rtl::OUString& aData )
    throw (cssxs::SAXException, cssu::RuntimeException)
{
    if (m_xNextHandler.is())
    {
        m_xNextHandler->processingInstruction(aTarget, aData);
        }
}

void SAL_CALL XSecParser::setDocumentLocator( const cssu::Reference< cssxs::XLocator >& xLocator )
    throw (cssxs::SAXException, cssu::RuntimeException)
{
    if (m_xNextHandler.is())
    {
        m_xNextHandler->setDocumentLocator( xLocator );
        }
}

/*
 * XInitialization
 */
void SAL_CALL XSecParser::initialize(
    const cssu::Sequence< cssu::Any >& aArguments )
    throw(cssu::Exception, cssu::RuntimeException)
{
    aArguments[0] >>= m_xNextHandler;
}
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: ZipFile.cxx,v $
 *
 *  $Revision: 1.22 $
 *
 *  last change: $Author: mtg $ $Date: 2001-05-31 09:48:20 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  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
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (the "License"); You may not use this file
 *  except in compliance with the License. You may obtain a copy of the
 *  License at http://www.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): Martin Gallwey (gallwey@sun.com)
 *
 *
 ************************************************************************/
#ifndef _ZIP_FILE_HXX
#include <ZipFile.hxx>
#endif
#ifndef _ENTRY_INPUT_STREAM_HXX
#include <EntryInputStream.hxx>
#endif
#ifndef _ZIP_ENUMERATION_HXX
#include <ZipEnumeration.hxx>
#endif
#ifndef _VOS_DIAGNOSE_H_
#include <vos/diagnose.hxx>
#endif
#ifndef _COM_SUN_STAR_PACKAGES_ZIPCONSTANTS_HPP_
#include <com/sun/star/packages/ZipConstants.hpp>
#endif
#include <vector>

using namespace rtl;
using namespace com::sun::star;
using namespace com::sun::star::uno;
using namespace com::sun::star::packages;
using namespace com::sun::star::packages::ZipConstants;

/** This class is used to read entries from a zip file
 */
ZipFile::ZipFile( Reference < io::XInputStream > &xInput, sal_Bool bInitialise)
    throw(io::IOException, ZipException, RuntimeException)
: xStream(xInput)
, aGrabber(xInput)
, aInflater (sal_True)
{
    if (bInitialise)
        readCEN();
}
void ZipFile::setInputStream ( Reference < io::XInputStream > xNewStream )
{
    xStream = xNewStream;
    aGrabber.setInputStream ( xStream );
}

ZipFile::~ZipFile()
{
    aEntries.clear();
}

void SAL_CALL ZipFile::close(  )
    throw(io::IOException, RuntimeException)
{
}

ZipEnumeration * SAL_CALL ZipFile::entries(  )
{
    return new ZipEnumeration ( aEntries );
}

::rtl::OUString SAL_CALL ZipFile::getName(  )
    throw(RuntimeException)
{
    return sName;
}

sal_Int32 SAL_CALL ZipFile::getSize(  )
    throw(RuntimeException)
{
    return aEntries.size();
}

Type SAL_CALL ZipFile::getElementType(  )
    throw(RuntimeException)
{
    return ::getCppuType((ZipEntry *) 0);
}

sal_Bool SAL_CALL ZipFile::hasElements(  )
    throw(RuntimeException)
{
    return (aEntries.size()>0);
}

Any SAL_CALL ZipFile::getByName( const ::rtl::OUString& aName )
        throw(container::NoSuchElementException, lang::WrappedTargetException, RuntimeException)
{
    Any aAny;
    EntryHash::const_iterator aCI = aEntries.find(sName);
    if (aCI == aEntries.end())
        throw container::NoSuchElementException();
    aAny <<= (*aCI).second;
     return aAny;
}

Sequence< ::rtl::OUString > SAL_CALL ZipFile::getElementNames(  )
        throw(RuntimeException)
{
    sal_uInt32 i=0, nSize = aEntries.size();
    OUString *pNames = new OUString[aEntries.size()];
    for (EntryHash::const_iterator aIterator = aEntries.begin(); aIterator != aEntries.end(); aIterator++,i++)
        pNames[i] = (*aIterator).first;
    return Sequence<OUString> (pNames, nSize);
}

sal_Bool SAL_CALL ZipFile::hasByName( const ::rtl::OUString& aName )
        throw(RuntimeException)
{
    return aEntries.find(aName) != aEntries.end();
}

Reference< io::XInputStream > SAL_CALL ZipFile::getInputStream( ZipEntry& rEntry,
        const vos::ORef < EncryptionData > &rData)
    throw(io::IOException, ZipException, RuntimeException)
{
    if (rEntry.nOffset <= 0)
        readLOC(rEntry);
    Reference< io::XInputStream > xStreamRef = new EntryInputStream(xStream, rEntry, rData, sal_False );
    return xStreamRef;
}

Reference< io::XInputStream > SAL_CALL ZipFile::getRawStream( ZipEntry& rEntry,
        const vos::ORef < EncryptionData > &rData)
    throw(io::IOException, ZipException, RuntimeException)
{
    if (rEntry.nOffset <= 0)
        readLOC(rEntry);
    Reference< io::XInputStream > xStreamRef = new EntryInputStream(xStream, rEntry, rData, sal_True );
    return xStreamRef;
}

sal_Bool ZipFile::readLOC( ZipEntry &rEntry )
    throw(io::IOException, ZipException, RuntimeException)
{
    sal_uInt32 nTestSig, nTime, nCRC, nSize, nCompressedSize;
    sal_uInt16 nVersion, nFlag, nHow, nNameLen, nExtraLen;
    sal_Int32 nPos = -rEntry.nOffset;

    aGrabber.seek(nPos);
    aGrabber >> nTestSig;

    if (nTestSig != LOCSIG)
        throw ZipException( OUString( RTL_CONSTASCII_USTRINGPARAM ( "Invalid LOC header (bad signature") ), Reference < XInterface > () );
    aGrabber >> nVersion;
    aGrabber >> nFlag;
    aGrabber >> nHow;
    aGrabber >> nTime;
    aGrabber >> nCRC;
    aGrabber >> nCompressedSize;
    aGrabber >> nSize;
    aGrabber >> nNameLen;
    aGrabber >> nExtraLen;
    rEntry.nOffset = static_cast < sal_Int32 > (aGrabber.getPosition()) + nNameLen + nExtraLen;
    return sal_True;
}

sal_Int32 ZipFile::findEND( )
    throw(io::IOException, ZipException, RuntimeException)
{
    sal_Int32 nLength=0, nPos=0;
    Sequence < sal_Int8 > aByteSeq;
    nLength = nPos = static_cast <sal_Int32 > (aGrabber.getLength());

    if (nLength == 0)
        return -1;
        //throw (ZipException( OUString::createFromAscii("Trying to find Zip END signature in a zero length file!"), Reference < XInterface> () ));

    aGrabber.seek( nLength );

    while (nLength - nPos < 0xFFFF)
    {
        sal_uInt32 nCount = 0xFFFF - ( nLength - nPos);
        if (nCount > ENDHDR)
            nCount = ENDHDR;
        nPos -= nCount;

        for (sal_uInt16 i=0; i <nCount;i++)
        {
            sal_uInt32 nTest=0, nFoo=ENDSIG;
            aGrabber.seek (nPos+i);
            aGrabber >> nTest;
            if (nTest == ENDSIG)
            {
                sal_uInt16 nCommentLength;
                sal_Int32 nEndPos = nPos + i;
                aGrabber.seek(nEndPos+ENDCOM);
                aGrabber >> nCommentLength;
                if (nEndPos + ENDHDR + nCommentLength == nLength)
                {
                    if (nCommentLength>0)
                    {
                        aByteSeq.realloc(nCommentLength+1);
                        aGrabber.readBytes(Sequence< sal_Int8>(aByteSeq.getArray(), nCommentLength), nCommentLength);
                        aByteSeq[nCommentLength]='\0';
                        sComment = OUString((sal_Char*)aByteSeq.getConstArray(), nCommentLength+1, RTL_TEXTENCODING_ASCII_US);

                    }
                    return nPos + i;
                }
            }
        }
    }
    throw ZipException( OUString( RTL_CONSTASCII_USTRINGPARAM ( "Zip END signature not found!") ), Reference < XInterface> () );
}

sal_Int32 ZipFile::readCEN()
    throw(io::IOException, ZipException, RuntimeException)
{
    sal_Int32 nEndPos, nLocPos;
    sal_Int16  nCount, nTotal;
    sal_Int32 nCenLen, nCenPos, nCenOff;

    nEndPos = findEND();
    if (nEndPos == -1)
        return -1;
    aGrabber.seek(nEndPos + ENDTOT);
    aGrabber >> nTotal;
    aGrabber >> nCenLen;
    aGrabber >> nCenOff;

    if (nTotal<0 || nTotal * CENHDR > nCenLen)
        throw ZipException(OUString( RTL_CONSTASCII_USTRINGPARAM ( "invalid END header (bad entry count)") ), Reference < XInterface > ());

    if (nTotal > ZIP_MAXENTRIES)
        throw ZipException(OUString( RTL_CONSTASCII_USTRINGPARAM ( "too many entries in ZIP File") ), Reference < XInterface > ());

    if (nCenLen < 0 || nCenLen > nEndPos)
        throw ZipException(OUString( RTL_CONSTASCII_USTRINGPARAM ( "Invalid END header (bad central directory size)") ), Reference < XInterface > ());

    nCenPos = nEndPos - nCenLen;

    if (nCenOff < 0 || nCenOff > nCenPos)
        throw ZipException(OUString( RTL_CONSTASCII_USTRINGPARAM ( "Invalid END header (bad central directory size)") ), Reference < XInterface > ());

    nLocPos = nCenPos - nCenOff;
    aGrabber.seek(nCenPos);

    ZipEntry *pEntry = new ZipEntry;
    for (nCount = 0 ; nCount < nTotal; nCount++)
    {
        sal_Int32 nTestSig, nCRC, nCompressedSize, nTime, nSize, nExtAttr, nOffset;
        sal_Int16 nVerMade, nVersion, nFlag, nHow, nNameLen, nExtraLen, nCommentLen;
        sal_Int16 nDisk, nIntAttr;

        if (aGrabber.getPosition() - nCenPos + CENHDR > nCenLen)
            throw ZipException(OUString( RTL_CONSTASCII_USTRINGPARAM ( "Invalid CEN header (bad header size check 1)") ), Reference < XInterface > ());

        aGrabber >> nTestSig;
        if (nTestSig != CENSIG)
            throw ZipException(OUString( RTL_CONSTASCII_USTRINGPARAM ( "Invalid CEN header (bad signature)") ), Reference < XInterface > ());

        aGrabber >> nVerMade;
        aGrabber >> nVersion;
        if ((nVersion & 1) == 1)
            throw ZipException(OUString( RTL_CONSTASCII_USTRINGPARAM ( "Invalid CEN header (encrypted entry)") ), Reference < XInterface > ());

        aGrabber >> nFlag;
        aGrabber >> nHow;
        if (nHow != STORED && nHow != DEFLATED)
            throw ZipException(OUString( RTL_CONSTASCII_USTRINGPARAM ( "Invalid CEN header (bad compression method)") ), Reference < XInterface > ());

        aGrabber >> nTime;
        aGrabber >> nCRC;
        aGrabber >> nCompressedSize;
        aGrabber >> nSize;
        aGrabber >> nNameLen;
        aGrabber >> nExtraLen;
        aGrabber >> nCommentLen;
        aGrabber >> nDisk;
        aGrabber >> nIntAttr;
        aGrabber >> nExtAttr;
        aGrabber >> nOffset;

        if (aGrabber.getPosition() - nCenPos + nNameLen + nExtraLen + nCommentLen > nCenLen)
            throw ZipException(OUString( RTL_CONSTASCII_USTRINGPARAM ( "Invalid CEN header (bad header size check 2)") ), Reference < XInterface > ());

        if (nNameLen > ZIP_MAXNAMELEN)
            throw ZipException(OUString( RTL_CONSTASCII_USTRINGPARAM ( "name length exceeds 512 bytes" ) ), Reference < XInterface > ());

        if (nExtraLen > ZIP_MAXEXTRA)
            throw ZipException(OUString( RTL_CONSTASCII_USTRINGPARAM ( "extra header info exceeds 256 bytes") ), Reference < XInterface > ());

        pEntry->nTime   = nTime;
        pEntry->nCrc    = nCRC;
        pEntry->nSize   = nSize;
        pEntry->nCompressedSize = nCompressedSize;
        pEntry->nMethod = nHow;
        pEntry->nFlag   = nFlag;
        pEntry->nVersion= nVersion;
        pEntry->nOffset = nOffset + nLocPos;

        pEntry->nOffset *= -1;
        /*
        if (nHow == STORED)
            pEntry->nCompressedSize = 0;
        */
        Sequence < sal_Int8> aSequence (nNameLen);
        aGrabber.readBytes(aSequence, nNameLen);
        pEntry->sName = OUString((sal_Char*)aSequence.getConstArray(), nNameLen, RTL_TEXTENCODING_ASCII_US);

        aGrabber.seek(aGrabber.getPosition() + nExtraLen);
        if (nCommentLen>0)
        {
            Sequence < sal_Int8 > aCommentSeq( nCommentLen );
            aGrabber.readBytes(aCommentSeq, nCommentLen);
            pEntry->sComment = OUString((sal_Char*)aCommentSeq.getConstArray(), nNameLen, RTL_TEXTENCODING_ASCII_US);
        }
        aEntries[pEntry->sName] = *pEntry;
    }
    delete pEntry;

    if (nCount != nTotal)
        throw ZipException(OUString( RTL_CONSTASCII_USTRINGPARAM ( "Count != Total") ), Reference < XInterface > ());

    return nCenPos;
}
<commit_msg>#88256# If we have a potentially corrupt file, just assert and then keep going<commit_after>/*************************************************************************
 *
 *  $RCSfile: ZipFile.cxx,v $
 *
 *  $Revision: 1.23 $
 *
 *  last change: $Author: mtg $ $Date: 2001-06-14 17:36:15 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  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
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (the "License"); You may not use this file
 *  except in compliance with the License. You may obtain a copy of the
 *  License at http://www.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): Martin Gallwey (gallwey@sun.com)
 *
 *
 ************************************************************************/
#ifndef _ZIP_FILE_HXX
#include <ZipFile.hxx>
#endif
#ifndef _ENTRY_INPUT_STREAM_HXX
#include <EntryInputStream.hxx>
#endif
#ifndef _ZIP_ENUMERATION_HXX
#include <ZipEnumeration.hxx>
#endif
#ifndef _VOS_DIAGNOSE_H_
#include <vos/diagnose.hxx>
#endif
#ifndef _COM_SUN_STAR_PACKAGES_ZIPCONSTANTS_HPP_
#include <com/sun/star/packages/ZipConstants.hpp>
#endif
#include <vector>

using namespace rtl;
using namespace com::sun::star;
using namespace com::sun::star::uno;
using namespace com::sun::star::packages;
using namespace com::sun::star::packages::ZipConstants;

/** This class is used to read entries from a zip file
 */
ZipFile::ZipFile( Reference < io::XInputStream > &xInput, sal_Bool bInitialise)
    throw(io::IOException, ZipException, RuntimeException)
: xStream(xInput)
, aGrabber(xInput)
, aInflater (sal_True)
{
    if (bInitialise)
        readCEN();
}
void ZipFile::setInputStream ( Reference < io::XInputStream > xNewStream )
{
    xStream = xNewStream;
    aGrabber.setInputStream ( xStream );
}

ZipFile::~ZipFile()
{
    aEntries.clear();
}

void SAL_CALL ZipFile::close(  )
    throw(io::IOException, RuntimeException)
{
}

ZipEnumeration * SAL_CALL ZipFile::entries(  )
{
    return new ZipEnumeration ( aEntries );
}

::rtl::OUString SAL_CALL ZipFile::getName(  )
    throw(RuntimeException)
{
    return sName;
}

sal_Int32 SAL_CALL ZipFile::getSize(  )
    throw(RuntimeException)
{
    return aEntries.size();
}

Type SAL_CALL ZipFile::getElementType(  )
    throw(RuntimeException)
{
    return ::getCppuType((ZipEntry *) 0);
}

sal_Bool SAL_CALL ZipFile::hasElements(  )
    throw(RuntimeException)
{
    return (aEntries.size()>0);
}

Any SAL_CALL ZipFile::getByName( const ::rtl::OUString& aName )
        throw(container::NoSuchElementException, lang::WrappedTargetException, RuntimeException)
{
    Any aAny;
    EntryHash::const_iterator aCI = aEntries.find(sName);
    if (aCI == aEntries.end())
        throw container::NoSuchElementException();
    aAny <<= (*aCI).second;
     return aAny;
}

Sequence< ::rtl::OUString > SAL_CALL ZipFile::getElementNames(  )
        throw(RuntimeException)
{
    sal_uInt32 i=0, nSize = aEntries.size();
    OUString *pNames = new OUString[aEntries.size()];
    for (EntryHash::const_iterator aIterator = aEntries.begin(); aIterator != aEntries.end(); aIterator++,i++)
        pNames[i] = (*aIterator).first;
    return Sequence<OUString> (pNames, nSize);
}

sal_Bool SAL_CALL ZipFile::hasByName( const ::rtl::OUString& aName )
        throw(RuntimeException)
{
    return aEntries.find(aName) != aEntries.end();
}

Reference< io::XInputStream > SAL_CALL ZipFile::getInputStream( ZipEntry& rEntry,
        const vos::ORef < EncryptionData > &rData)
    throw(io::IOException, ZipException, RuntimeException)
{
    if (rEntry.nOffset <= 0)
        readLOC(rEntry);
    Reference< io::XInputStream > xStreamRef = new EntryInputStream(xStream, rEntry, rData, sal_False );
    return xStreamRef;
}

Reference< io::XInputStream > SAL_CALL ZipFile::getRawStream( ZipEntry& rEntry,
        const vos::ORef < EncryptionData > &rData)
    throw(io::IOException, ZipException, RuntimeException)
{
    if (rEntry.nOffset <= 0)
        readLOC(rEntry);
    Reference< io::XInputStream > xStreamRef = new EntryInputStream(xStream, rEntry, rData, sal_True );
    return xStreamRef;
}

sal_Bool ZipFile::readLOC( ZipEntry &rEntry )
    throw(io::IOException, ZipException, RuntimeException)
{
    sal_uInt32 nTestSig, nTime, nCRC, nSize, nCompressedSize;
    sal_uInt16 nVersion, nFlag, nHow, nNameLen, nExtraLen;
    sal_Int32 nPos = -rEntry.nOffset;

    aGrabber.seek(nPos);
    aGrabber >> nTestSig;

    if (nTestSig != LOCSIG)
        throw ZipException( OUString( RTL_CONSTASCII_USTRINGPARAM ( "Invalid LOC header (bad signature") ), Reference < XInterface > () );
    aGrabber >> nVersion;
    aGrabber >> nFlag;
    aGrabber >> nHow;
    aGrabber >> nTime;
    aGrabber >> nCRC;
    aGrabber >> nCompressedSize;
    aGrabber >> nSize;
    aGrabber >> nNameLen;
    aGrabber >> nExtraLen;
    rEntry.nOffset = static_cast < sal_Int32 > (aGrabber.getPosition()) + nNameLen + nExtraLen;
    return sal_True;
}

sal_Int32 ZipFile::findEND( )
    throw(io::IOException, ZipException, RuntimeException)
{
    sal_Int32 nLength=0, nPos=0;
    Sequence < sal_Int8 > aByteSeq;
    nLength = nPos = static_cast <sal_Int32 > (aGrabber.getLength());

    if (nLength == 0)
        return -1;
        //throw (ZipException( OUString::createFromAscii("Trying to find Zip END signature in a zero length file!"), Reference < XInterface> () ));

    aGrabber.seek( nLength );

    while (nLength - nPos < 0xFFFF)
    {
        sal_uInt32 nCount = 0xFFFF - ( nLength - nPos);
        if (nCount > ENDHDR)
            nCount = ENDHDR;
        nPos -= nCount;

        for (sal_uInt16 i=0; i <nCount;i++)
        {
            sal_uInt32 nTest=0, nFoo=ENDSIG;
            aGrabber.seek (nPos+i);
            aGrabber >> nTest;
            if (nTest == ENDSIG)
            {

                sal_uInt16 nCommentLength;
                sal_Int32 nEndPos = nPos + i;
                aGrabber.seek(nEndPos+ENDCOM);
                aGrabber >> nCommentLength;
                /*
                if (nEndPos + ENDHDR + nCommentLength == nLength)
                {
                    Since we don't actually use the comment ourselves, we'll just ignore it, and also skip the check
                    below. Neither WinZip nor InfoZip's unzip perform such checking and happily open files with
                    garbage bytes on the end, so we should do so too! I will 'assert' however that the file has garbage
                    at the end, and hope that the file hasn't suffered any other abuse

                    if (nCommentLength>0)
                    {
                        aByteSeq.realloc(nCommentLength+1);
                        aGrabber.readBytes(Sequence< sal_Int8>(aByteSeq.getArray(), nCommentLength), nCommentLength);
                        aByteSeq[nCommentLength]='\0';
                        sComment = OUString((sal_Char*)aByteSeq.getConstArray(), nCommentLength+1, RTL_TEXTENCODING_ASCII_US);

                    }
                }
                */
                VOS_ENSURE ( nEndPos + ENDHDR + nCommentLength == nLength, "This Zip File is potentially corrupt - it has garbage after the END descriptor! Hoping for the best...!");
                return nPos + i;
            }
        }
    }
    throw ZipException( OUString( RTL_CONSTASCII_USTRINGPARAM ( "Zip END signature not found!") ), Reference < XInterface> () );
}

sal_Int32 ZipFile::readCEN()
    throw(io::IOException, ZipException, RuntimeException)
{
    sal_Int32 nEndPos, nLocPos;
    sal_Int16  nCount, nTotal;
    sal_Int32 nCenLen, nCenPos, nCenOff;

    nEndPos = findEND();
    if (nEndPos == -1)
        return -1;
    aGrabber.seek(nEndPos + ENDTOT);
    aGrabber >> nTotal;
    aGrabber >> nCenLen;
    aGrabber >> nCenOff;

    if (nTotal<0 || nTotal * CENHDR > nCenLen)
        throw ZipException(OUString( RTL_CONSTASCII_USTRINGPARAM ( "invalid END header (bad entry count)") ), Reference < XInterface > ());

    if (nTotal > ZIP_MAXENTRIES)
        throw ZipException(OUString( RTL_CONSTASCII_USTRINGPARAM ( "too many entries in ZIP File") ), Reference < XInterface > ());

    if (nCenLen < 0 || nCenLen > nEndPos)
        throw ZipException(OUString( RTL_CONSTASCII_USTRINGPARAM ( "Invalid END header (bad central directory size)") ), Reference < XInterface > ());

    nCenPos = nEndPos - nCenLen;

    if (nCenOff < 0 || nCenOff > nCenPos)
        throw ZipException(OUString( RTL_CONSTASCII_USTRINGPARAM ( "Invalid END header (bad central directory size)") ), Reference < XInterface > ());

    nLocPos = nCenPos - nCenOff;
    aGrabber.seek(nCenPos);

    ZipEntry *pEntry = new ZipEntry;
    for (nCount = 0 ; nCount < nTotal; nCount++)
    {
        sal_Int32 nTestSig, nCRC, nCompressedSize, nTime, nSize, nExtAttr, nOffset;
        sal_Int16 nVerMade, nVersion, nFlag, nHow, nNameLen, nExtraLen, nCommentLen;
        sal_Int16 nDisk, nIntAttr;

        if (aGrabber.getPosition() - nCenPos + CENHDR > nCenLen)
            throw ZipException(OUString( RTL_CONSTASCII_USTRINGPARAM ( "Invalid CEN header (bad header size check 1)") ), Reference < XInterface > ());

        aGrabber >> nTestSig;
        if (nTestSig != CENSIG)
            throw ZipException(OUString( RTL_CONSTASCII_USTRINGPARAM ( "Invalid CEN header (bad signature)") ), Reference < XInterface > ());

        aGrabber >> nVerMade;
        aGrabber >> nVersion;
        if ((nVersion & 1) == 1)
            throw ZipException(OUString( RTL_CONSTASCII_USTRINGPARAM ( "Invalid CEN header (encrypted entry)") ), Reference < XInterface > ());

        aGrabber >> nFlag;
        aGrabber >> nHow;
        if (nHow != STORED && nHow != DEFLATED)
            throw ZipException(OUString( RTL_CONSTASCII_USTRINGPARAM ( "Invalid CEN header (bad compression method)") ), Reference < XInterface > ());

        aGrabber >> nTime;
        aGrabber >> nCRC;
        aGrabber >> nCompressedSize;
        aGrabber >> nSize;
        aGrabber >> nNameLen;
        aGrabber >> nExtraLen;
        aGrabber >> nCommentLen;
        aGrabber >> nDisk;
        aGrabber >> nIntAttr;
        aGrabber >> nExtAttr;
        aGrabber >> nOffset;

        if (aGrabber.getPosition() - nCenPos + nNameLen + nExtraLen + nCommentLen > nCenLen)
            throw ZipException(OUString( RTL_CONSTASCII_USTRINGPARAM ( "Invalid CEN header (bad header size check 2)") ), Reference < XInterface > ());

        if (nNameLen > ZIP_MAXNAMELEN)
            throw ZipException(OUString( RTL_CONSTASCII_USTRINGPARAM ( "name length exceeds 512 bytes" ) ), Reference < XInterface > ());

        if (nExtraLen > ZIP_MAXEXTRA)
            throw ZipException(OUString( RTL_CONSTASCII_USTRINGPARAM ( "extra header info exceeds 256 bytes") ), Reference < XInterface > ());

        pEntry->nTime   = nTime;
        pEntry->nCrc    = nCRC;
        pEntry->nSize   = nSize;
        pEntry->nCompressedSize = nCompressedSize;
        pEntry->nMethod = nHow;
        pEntry->nFlag   = nFlag;
        pEntry->nVersion= nVersion;
        pEntry->nOffset = nOffset + nLocPos;

        pEntry->nOffset *= -1;
        /*
        if (nHow == STORED)
            pEntry->nCompressedSize = 0;
        */
        Sequence < sal_Int8> aSequence (nNameLen);
        aGrabber.readBytes(aSequence, nNameLen);
        pEntry->sName = OUString((sal_Char*)aSequence.getConstArray(), nNameLen, RTL_TEXTENCODING_ASCII_US);

        aGrabber.seek(aGrabber.getPosition() + nExtraLen);
        if (nCommentLen>0)
        {
            Sequence < sal_Int8 > aCommentSeq( nCommentLen );
            aGrabber.readBytes(aCommentSeq, nCommentLen);
            pEntry->sComment = OUString((sal_Char*)aCommentSeq.getConstArray(), nNameLen, RTL_TEXTENCODING_ASCII_US);
        }
        aEntries[pEntry->sName] = *pEntry;
    }
    delete pEntry;

    if (nCount != nTotal)
        throw ZipException(OUString( RTL_CONSTASCII_USTRINGPARAM ( "Count != Total") ), Reference < XInterface > ());

    return nCenPos;
}
<|endoftext|>


<commit_before>/// Project specific
// This class
#include <Manager/EntitySpawnManager.hpp>
// Handlers
#include <EntityComponent/EntityHandler.hpp>
#include <EntityComponent/EntityHandlerServer.hpp>
#include <EventHandler/EventHandler.hpp>
#include <PlayerHandler.hpp>
// Components
#include <EntityComponent/Components/EntitySpawnerComponent.hpp>
#include <EntityComponent/Components/PhysicsMaterialComponent.hpp>
#include <EntityComponent/Components/RigidBodyComponent.hpp>
#include <EntityComponent/Components/EntityTypeComponent.hpp>
#include <EntityComponent/Components/TransformComponent.hpp>
#include <EntityComponent/Components/PotentialFieldComponent.hpp>
#include <EntityComponent/Components/HealthComponent.hpp>
// Events
#include <EventHandler/Events/SpecialEntityCreatedEvent.hpp>

/// Engine
// Physics
#include <DoremiEngine/Physics/Include/PhysicsModule.hpp>
#include <DoremiEngine/Physics/Include/PhysicsMaterialManager.hpp>
#include <DoremiEngine/Physics/Include/RigidBodyManager.hpp>
#include <DoremiEngine/Physics/Include/CharacterControlManager.hpp>
// AI
#include <DoremiEngine/AI/Include/Interface/SubModule/PotentialFieldSubModule.hpp>
#include <DoremiEngine/AI/Include/Interface/PotentialField/PotentialFieldActor.hpp>
#include <DoremiEngine/AI/Include/AIModule.hpp>
/// Third party
#include <DirectXMath.h>
using namespace DirectX;

// DEBUG
#include <iostream>
#include <Doremi/Core/Include/EntityComponent/Components/RenderComponent.hpp>
using namespace std;

namespace Doremi
{
    namespace Core
    {
        EntitySpawnManager::EntitySpawnManager(const DoremiEngine::Core::SharedContext& p_sharedContext)
            : Manager(p_sharedContext, "EntitySpawnManager")
        {
        }

        EntitySpawnManager::~EntitySpawnManager() {}

        void EntitySpawnManager::Update(double p_dt)
        {
			static int DEBUGcount = 0;
            EntityHandler& entityHandler = EntityHandler::GetInstance();
            // Loop through all entities
            const size_t length = EntityHandler::GetInstance().GetLastEntityIndex();
            for(size_t i = 0; i < length; i++)
            {
                // Check that the current entity has the relevant components
                if(EntityHandler::GetInstance().HasComponents(i, (int)ComponentType::EntitySpawner) | (int)ComponentType::Transform)
                {
                    // We've found an entity spawner
                    EntitySpawnComponent* spawnComp = EntityHandler::GetInstance().GetComponentFromStorage<EntitySpawnComponent>(i);
                    // Check if its a timed spawned
                    if(spawnComp->type == SpawnerType::TimedSpawner)
                    {
                        // Update time since last spawn
                        spawnComp->timeSinceLastSpawn += p_dt;
                        // Check if it's time to spawn and if we haven't already spawned the max number
                        if(spawnComp->timeSinceLastSpawn >= spawnComp->timeBetweenSpawns && spawnComp->currentNumSpawnedEntities < spawnComp->maxNumSpawnedEntites)
                        {
                            // Hax to ensure nothing spawns when no players are active, which apparently is a no-can-do
                            if(PlayerHandler::GetInstance()->GetPlayerMap().size() > 0)
                            {
                                // We should spawn something
                                CreateEntity(spawnComp->entityBlueprint, i);
                                spawnComp->currentNumSpawnedEntities++;
                            }
                            // Reset timer
                            spawnComp->timeSinceLastSpawn = 0;
                        }
                        else
                        {
                            // Nothing
                        }
                    }
                    else
                    {
                        // nothing
                    }
                }
            }
        }

        void EntitySpawnManager::OnEvent(Event* p_event) {}

        void EntitySpawnManager::CreateEntity(Blueprints p_blueprint, int p_spawnerID)
        {
            EntityHandler& entityHandler = EntityHandler::GetInstance();
            switch(p_blueprint)
            {
                case Blueprints::EnemyEntity:
                    TransformComponent* transComp = entityHandler.GetComponentFromStorage<TransformComponent>(p_spawnerID);
                    // Spawn inside the spawner. This might be changed in the future
                    XMFLOAT3 spawnPosition = transComp->position;
                    int newID = EntityHandlerServer::GetInstance().CreateEntity(Blueprints::EnemyEntity, spawnPosition);

                    // TODOCONFIG HP pool for monsters
                    // healthComp->maxHealth = 200;
                    // healthComp->currentHealth = 200;

                    // Send event that enemy has been created

                    SpecialEntityCreatedEvent* AIGroupActorCreated = new Core::SpecialEntityCreatedEvent(newID, Core::EventType::AiGroupActorCreation);

                    EventHandler::GetInstance()->BroadcastEvent(AIGroupActorCreated);
                    break;

                    // case Blueprints::PlayerEntity:
                    //    TransformComponent* transComp = entityHandler.GetComponentFromStorage<TransformComponent>(p_spawnerID);
                    //    // Spawn inside the spawner. This might be changed in the future
                    //    XMFLOAT3 spawnPosition = transComp->position;
                    //    int newID = EntityHandlerServer::GetInstance().CreateEntity(Blueprints::PlayerEntity, spawnPosition);

                    //    // Send event that enemy has been created
                    //    EntityCreatedEvent* PlayerCreated = new Core::EntityCreatedEvent(newID, Core::EventType::PlayerCreation);
                    //    EventHandler::GetInstance()->BroadcastEvent(PlayerCreated);
                    //    break;
            }
        }
    }
}<commit_msg>WORK IN PROGRESS removed all AI spawned from spawners<commit_after>/// Project specific
// This class
#include <Manager/EntitySpawnManager.hpp>
// Handlers
#include <EntityComponent/EntityHandler.hpp>
#include <EntityComponent/EntityHandlerServer.hpp>
#include <EventHandler/EventHandler.hpp>
#include <PlayerHandler.hpp>
// Components
#include <EntityComponent/Components/EntitySpawnerComponent.hpp>
#include <EntityComponent/Components/PhysicsMaterialComponent.hpp>
#include <EntityComponent/Components/RigidBodyComponent.hpp>
#include <EntityComponent/Components/EntityTypeComponent.hpp>
#include <EntityComponent/Components/TransformComponent.hpp>
#include <EntityComponent/Components/PotentialFieldComponent.hpp>
#include <EntityComponent/Components/HealthComponent.hpp>
// Events
#include <EventHandler/Events/SpecialEntityCreatedEvent.hpp>

/// Engine
// Physics
#include <DoremiEngine/Physics/Include/PhysicsModule.hpp>
#include <DoremiEngine/Physics/Include/PhysicsMaterialManager.hpp>
#include <DoremiEngine/Physics/Include/RigidBodyManager.hpp>
#include <DoremiEngine/Physics/Include/CharacterControlManager.hpp>
// AI
#include <DoremiEngine/AI/Include/Interface/SubModule/PotentialFieldSubModule.hpp>
#include <DoremiEngine/AI/Include/Interface/PotentialField/PotentialFieldActor.hpp>
#include <DoremiEngine/AI/Include/AIModule.hpp>
/// Third party
#include <DirectXMath.h>
using namespace DirectX;

// DEBUG
#include <iostream>
#include <Doremi/Core/Include/EntityComponent/Components/RenderComponent.hpp>
using namespace std;

namespace Doremi
{
    namespace Core
    {
        EntitySpawnManager::EntitySpawnManager(const DoremiEngine::Core::SharedContext& p_sharedContext)
            : Manager(p_sharedContext, "EntitySpawnManager")
        {
        }

        EntitySpawnManager::~EntitySpawnManager() {}

        void EntitySpawnManager::Update(double p_dt)
        {
			static int DEBUGcount = 0;
            EntityHandler& entityHandler = EntityHandler::GetInstance();
            // Loop through all entities
            const size_t length = EntityHandler::GetInstance().GetLastEntityIndex();
            for(size_t i = 0; i < length; i++)
            {
                // Check that the current entity has the relevant components
                if(EntityHandler::GetInstance().HasComponents(i, (int)ComponentType::EntitySpawner) | (int)ComponentType::Transform)
                {
                    // We've found an entity spawner
                    EntitySpawnComponent* spawnComp = EntityHandler::GetInstance().GetComponentFromStorage<EntitySpawnComponent>(i);
                    // Check if its a timed spawned
                    if(spawnComp->type == SpawnerType::TimedSpawner)
                    {
                        // Update time since last spawn
                        spawnComp->timeSinceLastSpawn += p_dt;
                        // Check if it's time to spawn and if we haven't already spawned the max number
                        if(spawnComp->timeSinceLastSpawn >= spawnComp->timeBetweenSpawns && spawnComp->currentNumSpawnedEntities < spawnComp->maxNumSpawnedEntites)
                        {
                            // Hax to ensure nothing spawns when no players are active, which apparently is a no-can-do
                            if(PlayerHandler::GetInstance()->GetPlayerMap().size() > 0)
                            {
                                // We should spawn something
                                //CreateEntity(spawnComp->entityBlueprint, i);
                                //spawnComp->currentNumSpawnedEntities++;
                            }
                            // Reset timer
                            spawnComp->timeSinceLastSpawn = 0;
                        }
                        else
                        {
                            // Nothing
                        }
                    }
                    else
                    {
                        // nothing
                    }
                }
            }
        }

        void EntitySpawnManager::OnEvent(Event* p_event) {}

        void EntitySpawnManager::CreateEntity(Blueprints p_blueprint, int p_spawnerID)
        {
            EntityHandler& entityHandler = EntityHandler::GetInstance();
            switch(p_blueprint)
            {
                case Blueprints::EnemyEntity:
                    TransformComponent* transComp = entityHandler.GetComponentFromStorage<TransformComponent>(p_spawnerID);
                    // Spawn inside the spawner. This might be changed in the future
                    XMFLOAT3 spawnPosition = transComp->position;
                    int newID = EntityHandlerServer::GetInstance().CreateEntity(Blueprints::EnemyEntity, spawnPosition);

                    // TODOCONFIG HP pool for monsters
                    // healthComp->maxHealth = 200;
                    // healthComp->currentHealth = 200;

                    // Send event that enemy has been created

                    SpecialEntityCreatedEvent* AIGroupActorCreated = new Core::SpecialEntityCreatedEvent(newID, Core::EventType::AiGroupActorCreation);

                    EventHandler::GetInstance()->BroadcastEvent(AIGroupActorCreated);
                    break;

                    // case Blueprints::PlayerEntity:
                    //    TransformComponent* transComp = entityHandler.GetComponentFromStorage<TransformComponent>(p_spawnerID);
                    //    // Spawn inside the spawner. This might be changed in the future
                    //    XMFLOAT3 spawnPosition = transComp->position;
                    //    int newID = EntityHandlerServer::GetInstance().CreateEntity(Blueprints::PlayerEntity, spawnPosition);

                    //    // Send event that enemy has been created
                    //    EntityCreatedEvent* PlayerCreated = new Core::EntityCreatedEvent(newID, Core::EventType::PlayerCreation);
                    //    EventHandler::GetInstance()->BroadcastEvent(PlayerCreated);
                    //    break;
            }
        }
    }
}<|endoftext|>


<commit_before>/*
   +----------------------------------------------------------------------+
   | All rights reserved                                                  |
   |                                                                      |
   | Redistribution and use in source and binary forms, with or without   |
   | modification, are permitted provided that the following conditions   |
   | are met:                                                             |
   |                                                                      |
   | 1. Redistributions of source code must retain the above copyright    |
   |    notice, this list of conditions and the following disclaimer.     |
   | 2. Redistributions in binary form must reproduce the above copyright |
   |    notice, this list of conditions and the following disclaimer in   |
   |    the documentation and/or other materials provided with the        |
   |    distribution.                                                     |
   |                                                                      |
   | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS  |
   | "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT    |
   | LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS    |
   | FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE       |
   | COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,  |
   | INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, |
   | BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;     |
   | LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER     |
   | CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT   |
   | LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN    |
   | ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE      |
   | POSSIBILITY OF SUCH DAMAGE.                                          |
   +----------------------------------------------------------------------+
   | Authors: David Soria Parra <dsp@php.net>                             |
   +----------------------------------------------------------------------+
*/

/* $ Id: $ */

#include "php_ktaglib.h"
#include "ktaglibrary.h"

#if HAVE_TAGLIB

/* {{{ Class definitions */

/*    {{{ Class KTaglib_File */
PHPAPI zend_class_entry *ktaglib_ce_FileNotFoundException;
PHPAPI zend_class_entry *ktaglib_ce_TagNotFoundException;

static zend_class_entry * KTaglib_File_ce_ptr = NULL;

void ktaglib_ref_class(ze_ktaglib_object * zo, ze_ktaglib_file_object *zo_file)
{
	zo->zo_file = zo_file;
	zo_file->refcount++;
}

/* Exceptions */
void ktaglib_init_class(zend_class_entry ** ppce, zend_class_entry *pce, const char * name, zend_function_entry * functions TSRMLS_DC)
{
	zend_class_entry ce;

	INIT_CLASS_ENTRY(ce, name, functions);
	ce.name_length = strlen(name);
	*ppce = zend_register_internal_class_ex(&ce, pce, NULL TSRMLS_CC);
	(*ppce)->create_object = pce->create_object;
}

void ktaglib_init_KTaglib_Exceptions(void)
{
	ktaglib_init_class(&ktaglib_ce_FileNotFoundException, zend_exception_get_default(TSRMLS_C), "KTaglib_FileNotFoundException", NULL);
	ktaglib_init_class(&ktaglib_ce_TagNotFoundException, zend_exception_get_default(TSRMLS_C), "KTaglib_TagNotFoundException", NULL);
}

void ktaglib_init_KTaglib_File_free(void *object TSRMLS_DC) /* {{{ */
{
	ze_ktaglib_file_object * intern = (ze_ktaglib_file_object *) object;

	intern->refcount--;
	if (intern->refcount <= 0 && intern->file) {
		delete intern->file;
	}

	zend_object_std_dtor(&intern->zo TSRMLS_CC);
	efree(intern);
}

void ktaglib_init_KTaglib_free(void *object TSRMLS_DC) /* {{{ */
{
	ze_ktaglib_object * intern = (ze_ktaglib_object *) object;

	if (intern->zo_file) {
		intern->zo_file->refcount--;
	}

	zend_object_std_dtor(&intern->zo TSRMLS_CC);
	efree(intern);
}

zend_object_value ktaglib_init_KTaglib_File_new(zend_class_entry *class_type TSRMLS_DC) /* {{{ */
{
	ze_ktaglib_file_object *intern;
	zval *tmp;
	zend_object_value retval;

	intern = (ze_ktaglib_file_object*) emalloc(sizeof(ze_ktaglib_file_object));
	memset(&intern->zo, 0, sizeof(zend_object));

	intern->file = NULL;
	intern->refcount = 1;

	zend_object_std_init(&intern->zo, class_type TSRMLS_CC);
	zend_hash_copy(intern->zo.properties, &class_type->default_properties, (copy_ctor_func_t) zval_add_ref,
					(void *) &tmp, sizeof(zval *));

	retval.handle = zend_objects_store_put(intern,
						NULL,
						(zend_objects_free_object_storage_t) ktaglib_init_KTaglib_File_free,
						NULL TSRMLS_CC);

	retval.handlers = zend_get_std_object_handlers();

       /* Preventing object cloning is easier than creating the handlers for clone :) */
       retval.handlers->clone_obj = NULL;
	return retval;

}

zend_object_value ktaglib_init_KTaglib_new(zend_class_entry *class_type TSRMLS_DC) /* {{{ */
{
	ze_ktaglib_object *intern;
	zval *tmp;
	zend_object_value retval;

	intern = (ze_ktaglib_object*) emalloc(sizeof(ze_ktaglib_object));
	memset(&intern->zo, 0, sizeof(zend_object));

	intern->zo_file = NULL;
	intern->tag = NULL;
	intern->frame = NULL;

	zend_object_std_init(&intern->zo, class_type TSRMLS_CC);
	zend_hash_copy(intern->zo.properties, &class_type->default_properties, (copy_ctor_func_t) zval_add_ref,
					(void *) &tmp, sizeof(zval *));

	retval.handle = zend_objects_store_put(intern,
						NULL,
						(zend_objects_free_object_storage_t) ktaglib_init_KTaglib_free,
						NULL TSRMLS_CC);

	retval.handlers = zend_get_std_object_handlers();
	retval.handlers->clone_obj = NULL;
	return retval;

}

/*       }}} Methods */
/*    }}} Class KTaglib */

/* {{{ ktaglib_functions[] */
function_entry ktaglib_functions[] = {
	{ NULL, NULL, NULL }
};
/* }}} */

/* {{{ ktaglib_module_entry
 */
zend_module_entry ktaglib_module_entry = {
	STANDARD_MODULE_HEADER,
	"ktaglib",
	ktaglib_functions,
	PHP_MINIT(ktaglib),     /* Replace with NULL if there is nothing to do at php startup   */
	PHP_MSHUTDOWN(ktaglib), /* Replace with NULL if there is nothing to do at php shutdown  */
	PHP_RINIT(ktaglib),     /* Replace with NULL if there is nothing to do at request start */
	PHP_RSHUTDOWN(ktaglib), /* Replace with NULL if there is nothing to do at request end   */
	PHP_MINFO(ktaglib),
	PHP_KTAGLIB_VERSION,
	STANDARD_MODULE_PROPERTIES
};
/* }}} */

#ifdef COMPILE_DL_KTAGLIB
extern "C" {
ZEND_GET_MODULE(ktaglib)
} // extern "C"
#endif

/* {{{ PHP_MINIT_FUNCTION */
PHP_MINIT_FUNCTION(ktaglib)
{
	ktaglib_init_KTaglib_Exceptions();
	ktaglib_init_KTaglib_MPEG_File();
	ktaglib_init_KTaglib_Tag();
	ktaglib_init_KTaglib_ID3v1_Tag();
	ktaglib_init_KTaglib_ID3v2_Tag();
	ktaglib_init_KTaglib_ID3v2_Frame();
	ktaglib_init_KTaglib_ID3v2_PictureFrame();
	ktaglib_init_KTaglib_ID3v2_CommentsFrame();
	ktaglib_init_KTaglib_MPEG_AudioProperties();
	ktaglib_init_KTaglib_MPEG_Header();

	return SUCCESS;
}
/* }}} */

/* {{{ PHP_MSHUTDOWN_FUNCTION */
PHP_MSHUTDOWN_FUNCTION(ktaglib)
{
	return SUCCESS;
}
/* }}} */

/* {{{ PHP_RINIT_FUNCTION */
PHP_RINIT_FUNCTION(ktaglib)
{
	return SUCCESS;
}
/* }}} */

/* {{{ PHP_RSHUTDOWN_FUNCTION */
PHP_RSHUTDOWN_FUNCTION(ktaglib)
{
	return SUCCESS;
}
/* }}} */

/* {{{ PHP_MINFO_FUNCTION */
PHP_MINFO_FUNCTION(ktaglib)
{
	char version[5];

	sprintf(version, "%1d.%1d.%1d",
			TAGLIB_MAJOR_VERSION, TAGLIB_MINOR_VERSION, TAGLIB_PATCH_VERSION);

	php_info_print_table_start();
	php_info_print_table_row(2, "ktaglib Support", "enabled");
	php_info_print_table_row(2, "taglib Version", version);
	php_info_print_table_row(2, "Supported Formats", "ID3v1, ID3v2");
	php_info_print_table_row(2, "Version", PHP_KTAGLIB_VERSION);
	php_info_print_table_end();

}
/* }}} */

#endif /* HAVE_TAGLIB */

/*
 * Local variables:
 * tab-width: 4
 * c-basic-offset: 4
 * End:
 * vim600: noet sw=4 ts=4 fdm=marker
 * vim<600: noet sw=4 ts=4
 */
<commit_msg>Coding style<commit_after>/*
   +----------------------------------------------------------------------+
   | All rights reserved                                                  |
   |                                                                      |
   | Redistribution and use in source and binary forms, with or without   |
   | modification, are permitted provided that the following conditions   |
   | are met:                                                             |
   |                                                                      |
   | 1. Redistributions of source code must retain the above copyright    |
   |    notice, this list of conditions and the following disclaimer.     |
   | 2. Redistributions in binary form must reproduce the above copyright |
   |    notice, this list of conditions and the following disclaimer in   |
   |    the documentation and/or other materials provided with the        |
   |    distribution.                                                     |
   |                                                                      |
   | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS  |
   | "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT    |
   | LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS    |
   | FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE       |
   | COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,  |
   | INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, |
   | BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;     |
   | LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER     |
   | CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT   |
   | LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN    |
   | ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE      |
   | POSSIBILITY OF SUCH DAMAGE.                                          |
   +----------------------------------------------------------------------+
   | Authors: David Soria Parra <dsp@php.net>                             |
   +----------------------------------------------------------------------+
*/

/* $ Id: $ */

#include "php_ktaglib.h"
#include "ktaglibrary.h"

#if HAVE_TAGLIB

/* {{{ Class definitions */

/*    {{{ Class KTaglib_File */
PHPAPI zend_class_entry *ktaglib_ce_FileNotFoundException;
PHPAPI zend_class_entry *ktaglib_ce_TagNotFoundException;

static zend_class_entry * KTaglib_File_ce_ptr = NULL;

void ktaglib_ref_class(ze_ktaglib_object * zo, ze_ktaglib_file_object *zo_file)
{
	zo->zo_file = zo_file;
	zo_file->refcount++;
}

/* Exceptions */
void ktaglib_init_class(zend_class_entry ** ppce, zend_class_entry *pce, const char * name, zend_function_entry * functions TSRMLS_DC)
{
	zend_class_entry ce;

	INIT_CLASS_ENTRY(ce, name, functions);
	ce.name_length = strlen(name);
	*ppce = zend_register_internal_class_ex(&ce, pce, NULL TSRMLS_CC);
	(*ppce)->create_object = pce->create_object;
}

void ktaglib_init_KTaglib_Exceptions(void)
{
	ktaglib_init_class(&ktaglib_ce_FileNotFoundException, zend_exception_get_default(TSRMLS_C), "KTaglib_FileNotFoundException", NULL);
	ktaglib_init_class(&ktaglib_ce_TagNotFoundException, zend_exception_get_default(TSRMLS_C), "KTaglib_TagNotFoundException", NULL);
}

void ktaglib_init_KTaglib_File_free(void *object TSRMLS_DC) /* {{{ */
{
	ze_ktaglib_file_object * intern = (ze_ktaglib_file_object *) object;

	intern->refcount--;
	if (intern->refcount <= 0 && intern->file) {
		delete intern->file;
	}

	zend_object_std_dtor(&intern->zo TSRMLS_CC);
	efree(intern);
}

void ktaglib_init_KTaglib_free(void *object TSRMLS_DC) /* {{{ */
{
	ze_ktaglib_object * intern = (ze_ktaglib_object *) object;

	if (intern->zo_file) {
		intern->zo_file->refcount--;
	}

	zend_object_std_dtor(&intern->zo TSRMLS_CC);
	efree(intern);
}

zend_object_value ktaglib_init_KTaglib_File_new(zend_class_entry *class_type TSRMLS_DC) /* {{{ */
{
	ze_ktaglib_file_object *intern;
	zval *tmp;
	zend_object_value retval;

	intern = (ze_ktaglib_file_object*) emalloc(sizeof(ze_ktaglib_file_object));
	memset(&intern->zo, 0, sizeof(zend_object));

	intern->file = NULL;
	intern->refcount = 1;

	zend_object_std_init(&intern->zo, class_type TSRMLS_CC);
	zend_hash_copy(intern->zo.properties, &class_type->default_properties, (copy_ctor_func_t) zval_add_ref,
					(void *) &tmp, sizeof(zval *));

	retval.handle = zend_objects_store_put(intern,
						NULL,
						(zend_objects_free_object_storage_t) ktaglib_init_KTaglib_File_free,
						NULL TSRMLS_CC);

	retval.handlers = zend_get_std_object_handlers();

	/* Preventing object cloning is easier than creating the handlers for clone :) */
	retval.handlers->clone_obj = NULL;

	return retval;

}

zend_object_value ktaglib_init_KTaglib_new(zend_class_entry *class_type TSRMLS_DC) /* {{{ */
{
	ze_ktaglib_object *intern;
	zval *tmp;
	zend_object_value retval;

	intern = (ze_ktaglib_object*) emalloc(sizeof(ze_ktaglib_object));
	memset(&intern->zo, 0, sizeof(zend_object));

	intern->zo_file = NULL;
	intern->tag = NULL;
	intern->frame = NULL;

	zend_object_std_init(&intern->zo, class_type TSRMLS_CC);
	zend_hash_copy(intern->zo.properties, &class_type->default_properties, (copy_ctor_func_t) zval_add_ref,
					(void *) &tmp, sizeof(zval *));

	retval.handle = zend_objects_store_put(intern,
						NULL,
						(zend_objects_free_object_storage_t) ktaglib_init_KTaglib_free,
						NULL TSRMLS_CC);

	retval.handlers = zend_get_std_object_handlers();
	retval.handlers->clone_obj = NULL;
	return retval;

}

/*       }}} Methods */
/*    }}} Class KTaglib */

/* {{{ ktaglib_functions[] */
function_entry ktaglib_functions[] = {
	{ NULL, NULL, NULL }
};
/* }}} */

/* {{{ ktaglib_module_entry
 */
zend_module_entry ktaglib_module_entry = {
	STANDARD_MODULE_HEADER,
	"ktaglib",
	ktaglib_functions,
	PHP_MINIT(ktaglib),     /* Replace with NULL if there is nothing to do at php startup   */
	PHP_MSHUTDOWN(ktaglib), /* Replace with NULL if there is nothing to do at php shutdown  */
	PHP_RINIT(ktaglib),     /* Replace with NULL if there is nothing to do at request start */
	PHP_RSHUTDOWN(ktaglib), /* Replace with NULL if there is nothing to do at request end   */
	PHP_MINFO(ktaglib),
	PHP_KTAGLIB_VERSION,
	STANDARD_MODULE_PROPERTIES
};
/* }}} */

#ifdef COMPILE_DL_KTAGLIB
extern "C" {
ZEND_GET_MODULE(ktaglib)
} // extern "C"
#endif

/* {{{ PHP_MINIT_FUNCTION */
PHP_MINIT_FUNCTION(ktaglib)
{
	ktaglib_init_KTaglib_Exceptions();
	ktaglib_init_KTaglib_MPEG_File();
	ktaglib_init_KTaglib_Tag();
	ktaglib_init_KTaglib_ID3v1_Tag();
	ktaglib_init_KTaglib_ID3v2_Tag();
	ktaglib_init_KTaglib_ID3v2_Frame();
	ktaglib_init_KTaglib_ID3v2_PictureFrame();
	ktaglib_init_KTaglib_ID3v2_CommentsFrame();
	ktaglib_init_KTaglib_MPEG_AudioProperties();
	ktaglib_init_KTaglib_MPEG_Header();

	return SUCCESS;
}
/* }}} */

/* {{{ PHP_MSHUTDOWN_FUNCTION */
PHP_MSHUTDOWN_FUNCTION(ktaglib)
{
	return SUCCESS;
}
/* }}} */

/* {{{ PHP_RINIT_FUNCTION */
PHP_RINIT_FUNCTION(ktaglib)
{
	return SUCCESS;
}
/* }}} */

/* {{{ PHP_RSHUTDOWN_FUNCTION */
PHP_RSHUTDOWN_FUNCTION(ktaglib)
{
	return SUCCESS;
}
/* }}} */

/* {{{ PHP_MINFO_FUNCTION */
PHP_MINFO_FUNCTION(ktaglib)
{
	char version[5];

	sprintf(version, "%1d.%1d.%1d",
			TAGLIB_MAJOR_VERSION, TAGLIB_MINOR_VERSION, TAGLIB_PATCH_VERSION);

	php_info_print_table_start();
	php_info_print_table_row(2, "ktaglib Support", "enabled");
	php_info_print_table_row(2, "taglib Version", version);
	php_info_print_table_row(2, "Supported Formats", "ID3v1, ID3v2");
	php_info_print_table_row(2, "Version", PHP_KTAGLIB_VERSION);
	php_info_print_table_end();

}
/* }}} */

#endif /* HAVE_TAGLIB */

/*
 * Local variables:
 * tab-width: 4
 * c-basic-offset: 4
 * End:
 * vim600: noet sw=4 ts=4 fdm=marker
 * vim<600: noet sw=4 ts=4
 */
<|endoftext|>