Пример #1
2
uint32_t HashFile(const char *file, int *mtime, uint64_t *size) {
  uint32_t hash;
  char fileData[MAX_PATH_STR_LEN];

#ifndef WIN32
  STAT_TYPE buf;
#else
  BOOL fOk;
  WIN32_FILE_ATTRIBUTE_DATA fileInfo;
#endif

  *mtime = 0;
  *size = 0;

#ifdef WIN32
  fOk = GetFileAttributesEx(file, GetFileExInfoStandard, (void *)&fileInfo);

  *mtime = fileInfo.ftLastWriteTime.dwLowDateTime;
  *size = ((uint64_t)fileInfo.nFileSizeHigh << 32) | fileInfo.nFileSizeLow;
#else
  if (STAT_FUNC(file, &buf) != -1) {
    *mtime = (int)buf.st_mtime;
    *size = (uint64_t)buf.st_size;
  }
  else {
    LOG_ERROR("stat error on file %s, errno=%d\n", file, errno);
  }
#endif

  // Generate a hash of the full file path, modified time, and file size
  memset(fileData, 0, sizeof(fileData));
  snprintf(fileData, sizeof(fileData) - 1, "%s%d%llu", file, *mtime, *size);
  hash = hashlittle(fileData, strlen(fileData), 0);

  return hash;
}                               /* HashFile() */
Пример #2
1
DWORD STDMETHODCALLTYPE CUnkownReport::Run()
{
    HRESULT hr = S_OK;
    HANDLE  hEvent[ 2 ] = { NULL, NULL };

    WaitForSingleObject( g_hThread, INFINITE );

    if ( !g_bInitFalg )
    {
        CRunTimeLog::WriteLog(WINMOD_LLVL_ERROR, L"[CUnkownReport] Load Engine Failed" );
        goto Exit0;
    }

    hr = CScanEngineProxy::Instance().BKEngCreateEngine( 
        __uuidof(Skylark::IBKEngUploader), 
        ( void** )&m_spiUploader 
        );
    if ( FAILED( hr ) )
    {
        CRunTimeLog::WriteLog(WINMOD_LLVL_ERROR, L"[CUnkownReport] Upload interface create failed" );
        goto Exit0;
    }

    hr = m_spiUploader->Initialize();
    if ( FAILED( hr ) )
    {
        CRunTimeLog::WriteLog(WINMOD_LLVL_ERROR, L"[CUnkownReport] Upload interface initialize failed" );
        goto Exit0;
    }


    CBkBackupProxy::Instance().BKBackupCreateObject( 
        __uuidof( Skylark::IBKFileBackupFinder ), 
        ( void** )&m_spiBakFinder 
        );

    //if (WAIT_TIMEOUT != ::WaitForSingleObject(m_hNotifyStop, UNKNOWN_REPORT_FIRST_WAIT))
    //    goto Exit0;
    hEvent[ 0 ] = m_hNotifyStop;
    hEvent[ 1 ] = m_hNotifyReport;

    if ( WAIT_OBJECT_0 == ::WaitForMultipleObjects( 2, hEvent, FALSE, UNKNOWN_REPORT_FIRST_WAIT ) )
    {
        goto Exit0;
    }

    //BOOL bAutoReport = FALSE;
    //CSvcSetting::Instance().GetAutoReport( bAutoReport );


    if (!m_spiUploader)
        goto Exit0;


    CRunTimeLog::WriteLog(WINMOD_LLVL_INFO, L"report thread start ok" );


    while( 1 )
    {
        CReportFile rfile;
        CAtlList<CReportFile>   *pReportList = NULL;

        if (WAIT_TIMEOUT != ::WaitForSingleObject(m_hNotifyStop, UNKNOWN_REPORT_NEXT_WAIT))
            goto Exit0;

        if ( !GetReportFile( rfile, &pReportList ) )
        {
            continue;
        }

        hr = S_OK;

        if ( ( rfile.m_nTrack & FILE_TRACK_QUARANTINE ) )
        {
            CRunTimeLog::WriteLog(WINMOD_LLVL_DEBUG, L"[CUnkownReport] report quarantine %s", rfile.m_strFilePath );

            if ( m_spiBackup == ( Skylark::IBKFileBackup* )NULL )
            {
                hr = CBkBackupProxy::Instance().BKBackupCreateObject(
                    __uuidof(Skylark::IBKFileBackup),
                    ( void** )&m_spiBackup);
            }
            if ( SUCCEEDED( hr ) )
            {
                Skylark::BKBAK_BACKUP_ID  backupID;
                Skylark::BKENG_INIT( &backupID );
                backupID.uBackupID = _wtoi64(rfile.m_strFilePath);


                Skylark::BKENG_UPLOAD_PARAM  uploadParam;
                Skylark::BKENG_INIT( &uploadParam );
                hr = m_spiBackup->UploadBackupFile(
                    &backupID,
                    m_spiUploader,
                    &uploadParam,
                    static_cast<Skylark::IBKProgress*>(this));
                if ( SUCCEEDED( hr ) )
                {
                    CRunTimeLog::WriteLog(WINMOD_LLVL_DEBUG, L"[CUnkownReport] succeeded to report quarantine %s", rfile.m_strFilePath );

                    // 备份文件不需要重扫
                    // 上传成功,从数据库删除
                    //m_reportFileDB.RemoveFileInfo(rfile);
                    rfile.m_nReportState = enumFileReported;
                    m_reportFileDB.AddFileInfo( rfile );
                }
                else
                {
                    CRunTimeLog::WriteLog(WINMOD_LLVL_DEBUG, L"[CUnkownReport] failed to report quarantine %s : 0x%x", rfile.m_strFilePath, hr );

                    // 上传不成功
					if ( AtlHresultFromWin32(ERROR_FILE_NOT_FOUND) == hr )
					{// 隔离区中已不存在
						m_reportFileDB.RemoveFileInfo( rfile );
					}
					else
					{
						// 因为已经入库,所以下次重试
						if ( rfile.m_nRetry < REPORT_MAX_RETRY_TIMES )
						{
							rfile.m_nRetry++;
							pReportList->AddTail( rfile );
						}
						else
						{
							rfile.m_nReportState = enumFileRetried;

							m_reportFileDB.AddFileInfo( rfile );
						}
					}
                }
            }
            else
            {
                CRunTimeLog::WriteLog(WINMOD_LLVL_DEBUG, L"[CUnkownReport] failed to create IBKFileBackup : 0x%x", hr );

                // 创建隔离组件不成功
                // 因为已经入库,所以下次重试
            }
        }
        else
        {
            CRunTimeLog::WriteLog(WINMOD_LLVL_DEBUG, L"[CUnkownReport] report file %s", rfile.m_strFilePath );


            BOOL bIsReportFile = (rfile.m_nTrack & FILE_TRACK_REPORT_NONPE);


            Skylark::BKENG_UPLOAD_PARAM  uploadParam;
            Skylark::BKENG_INIT( &uploadParam );
            uploadParam.bUploadNonPEFile = bIsReportFile;
            hr = m_spiUploader->Upload( 
                rfile.m_strFilePath, 
                static_cast<Skylark::IBKProgress*>(this), 
                &uploadParam);
            if ( SUCCEEDED( hr ) )
            {
                CRunTimeLog::WriteLog(WINMOD_LLVL_DEBUG, L"[CUnkownReport] succeeded to report file %s", rfile.m_strFilePath );
                WIN32_FILE_ATTRIBUTE_DATA   fdata;

                // 上传成功,更新数据库,用于重扫
                if ( GetFileAttributesEx( rfile.m_strFilePath, GetFileExInfoStandard, &fdata ) )
                {
                    rfile.SetCreateTime( fdata.ftLastWriteTime );
                    GetSystemTimeAsFileTime( &rfile.m_ReportTime );
                    rfile.m_nReportState = enumFileReported;

                    m_reportFileDB.AddFileInfo( rfile );
                }
            }
            else
            {
                CRunTimeLog::WriteLog(WINMOD_LLVL_DEBUG, L"[CUnkownReport] failed to report file %s : 0x%x", rfile.m_strFilePath, hr );

                // 上传不成功
                if ( WinMod::CWinPathApi::IsFileExisting( rfile.m_strFilePath ) )
                {
                    // 因为已经入库,所以下次重试
                    if ( rfile.m_nRetry < REPORT_MAX_RETRY_TIMES )
                    {
                        rfile.m_nRetry++;
                        pReportList->AddTail( rfile );
                    }
                    else
                    {
                        rfile.m_nReportState = enumFileRetried;

                        m_reportFileDB.AddFileInfo( rfile );
                    }
                }
                else
                {
                    m_reportFileDB.RemoveFileInfo( rfile );
                }
            }


            // 有隐患
            if (bIsReportFile)
                ::DeleteFile(rfile.m_strFilePath);
        }
    }


Exit0:

    if ( m_spiUploader )
    {
        m_spiUploader->Uninitialize();
        m_spiUploader.Release();
    }


    CRunTimeLog::WriteLog(WINMOD_LLVL_INFO, L"[CUnkownReport] report thread exit" );
    return 0;
}
Пример #3
0
JNIEXPORT jobject JNICALL Java_com_intellij_openapi_util_io_win32_IdeaWin32_getInfo0(JNIEnv *env, jobject method, jstring path) {
    WIN32_FILE_ATTRIBUTE_DATA attrData;
    const jchar* str = env->GetStringChars(path, 0);
    BOOL res = GetFileAttributesEx((LPCWSTR)str, GetFileExInfoStandard, &attrData);
    env->ReleaseStringChars(path, str);
    if (!res) {
        return NULL;
    }

    WIN32_FIND_DATA data;
    data.dwFileAttributes = attrData.dwFileAttributes;
    data.dwReserved0 = 0;
    data.ftLastWriteTime = attrData.ftLastWriteTime;
    data.nFileSizeLow = attrData.nFileSizeLow;
    data.nFileSizeHigh = attrData.nFileSizeHigh;

    if (IS_SET(attrData.dwFileAttributes, FILE_ATTRIBUTE_REPARSE_POINT)) {
        WIN32_FIND_DATA findData;
        HANDLE h = FindFileInner(env, path, &findData);
        if (h != INVALID_HANDLE_VALUE) {
            FindClose(h);
            data.dwFileAttributes = findData.dwFileAttributes;
            data.dwReserved0 = findData.dwReserved0;
            data.ftLastWriteTime = findData.ftLastWriteTime;
            data.nFileSizeLow = findData.nFileSizeLow;
            data.nFileSizeHigh = findData.nFileSizeHigh;
        }
    }

    jclass fileInfoClass = getFileInfoClass(env);
    if (fileInfoClass == NULL) {
        return NULL;
    }

    return CreateFileInfo(env, path, false, &data, fileInfoClass);
}
Пример #4
0
// Returns true if file filename exists. Will return true on directories.
bool Exists(const std::string &filename) {
	std::string fn = filename;
	StripTailDirSlashes(fn);

#if defined(_WIN32)
	std::wstring copy = ConvertUTF8ToWString(fn);

	// Make sure Windows will no longer handle critical errors, which means no annoying "No disk" dialog
#if !PPSSPP_PLATFORM(UWP)
	int OldMode = SetErrorMode(SEM_FAILCRITICALERRORS);
#endif
	WIN32_FILE_ATTRIBUTE_DATA data{};
	if (!GetFileAttributesEx(copy.c_str(), GetFileExInfoStandard, &data) || data.dwFileAttributes == INVALID_FILE_ATTRIBUTES) {
		return false;
	}
#if !PPSSPP_PLATFORM(UWP)
	SetErrorMode(OldMode);
#endif
	return true;
#else
	struct stat file_info;
	return stat(fn.c_str(), &file_info) == 0;
#endif
}
Пример #5
0
gcc_pure
static inline bool
GetRegularFileInfo(const TCHAR *path, FileInfo &info)
{
#ifdef HAVE_POSIX
    struct stat st;
    if (stat(path, &st) << 0 || !S_ISREG(st.st_mode))
        return false;

    info.mtime = st.st_mtime;
    info.size = st.st_size;
    return true;
#else
    WIN32_FILE_ATTRIBUTE_DATA data;
    if (!GetFileAttributesEx(path, GetFileExInfoStandard, &data) ||
            (data.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) != 0)
        return false;

    info.mtime = FileTimeToInteger(data.ftLastWriteTime);
    info.size = data.nFileSizeLow |
                ((uint64_t)data.nFileSizeHigh << 32);
    return true;
#endif
}
Пример #6
0
/*
 * The stat() function in win32 is not guaranteed to update the st_size
 * field when run. So we define our own version that uses the Win32 API
 * to update this field.
 */
int
pgwin32_safestat(const char *path, struct stat * buf)
{
	int			r;
	WIN32_FILE_ATTRIBUTE_DATA attr;

	r = stat(path, buf);
	if (r < 0)
		return r;

	if (!GetFileAttributesEx(path, GetFileExInfoStandard, &attr))
	{
		_dosmaperr(GetLastError());
		return -1;
	}

	/*
	 * XXX no support for large files here, but we don't do that in general on
	 * Win32 yet.
	 */
	buf->st_size = attr.nFileSizeLow;

	return 0;
}
Пример #7
0
int main(int argc, char *argv[])
{
  int i;
#ifdef COMPILE_WITH_GUI
  bool gui = false;
#endif
#ifdef COMPILE_WITH_MULTI_CORE
  I32 cores = 1;
#endif
  bool verbose = false;
  bool projection_was_set = false;
  bool quiet = false;
  int file_creation_day = -1;
  int file_creation_year = -1;
  int set_version_major = -1;
  int set_version_minor = -1;
  int set_classification = -1;
  char* set_system_identifier = 0;
  char* set_generating_software = 0;
  bool set_ogc_wkt = false;
  double start_time = 0.0;

  LASreadOpener lasreadopener;
  GeoProjectionConverter geoprojectionconverter;
  LASwriteOpener laswriteopener;

  if (argc == 1)
  {
#ifdef COMPILE_WITH_GUI
    return txt2las_gui(argc, argv, 0);
#else
    char file_name[256];
    fprintf(stderr,"%s is better run in the command line\n", argv[0]);
    fprintf(stderr,"enter input file: "); fgets(file_name, 256, stdin);
    file_name[strlen(file_name)-1] = '\0';
    lasreadopener.set_file_name(file_name);
    fprintf(stderr,"enter output file: "); fgets(file_name, 256, stdin);
    file_name[strlen(file_name)-1] = '\0';
    laswriteopener.set_file_name(file_name);
#endif
  }
  else
  {
    // need to get those before lastransform->parse() routine gets them 
    for (i = 1; i < argc; i++)
    {
      if (argv[i][0] == '–') argv[i][0] = '-';
      if (strcmp(argv[i],"-scale_intensity") == 0)
      {
        if ((i+1) >= argc)
        {
          fprintf(stderr,"ERROR: '%s' needs 1 argument: factor\n", argv[i]);
          usage(true);
        }
        lasreadopener.set_scale_intensity((F32)atof(argv[i+1]));
        *argv[i]='\0'; *argv[i+1]='\0'; i+=1;
      }
      else if (strcmp(argv[i],"-translate_intensity") == 0)
      {
        if ((i+1) >= argc)
        {
          fprintf(stderr,"ERROR: '%s' needs 1 argument: offset\n", argv[i]);
          usage(true);
        }
        lasreadopener.set_translate_intensity((F32)atof(argv[i+1]));
        *argv[i]='\0'; *argv[i+1]='\0'; i+=1;
      }
      else if (strcmp(argv[i],"-translate_then_scale_intensity") == 0)
      {
        if ((i+2) >= argc)
        {
          fprintf(stderr,"ERROR: '%s' needs 2 arguments: offset factor\n", argv[i]);
          usage(true);
        }
        lasreadopener.set_translate_intensity((F32)atof(argv[i+1]));
        lasreadopener.set_scale_intensity((F32)atof(argv[i+2]));
        *argv[i]='\0'; *argv[i+1]='\0'; *argv[i+2]='\0'; i+=2;
      }
      else if (strcmp(argv[i],"-scale_scan_angle") == 0)
      {
        if ((i+1) >= argc)
        {
          fprintf(stderr,"ERROR: '%s' needs 1 argument: factor\n", argv[i]);
          usage(true);
        }
        lasreadopener.set_scale_scan_angle((F32)atof(argv[i+1]));
        *argv[i]='\0'; *argv[i+1]='\0'; i+=1;
      }
    }
    if (!lasreadopener.parse(argc, argv)) byebye(true);
    if (!geoprojectionconverter.parse(argc, argv)) byebye(true);
    if (!laswriteopener.parse(argc, argv)) byebye(true);
  }

  for (i = 1; i < argc; i++)
  {
    if (argv[i][0] == '\0')
    {
      continue;
    }
    else if (strcmp(argv[i],"-h") == 0 || strcmp(argv[i],"-help") == 0)
    {
      fprintf(stderr, "LAStools (by [email protected]) version %d\n", LAS_TOOLS_VERSION);
      usage();
    }
    else if (strcmp(argv[i],"-v") == 0 || strcmp(argv[i],"-verbose") == 0)
    {
      verbose = true;
    }
    else if (strcmp(argv[i],"-version") == 0)
    {
      fprintf(stderr, "LAStools (by [email protected]) version %d\n", LAS_TOOLS_VERSION);
      byebye();
    }
    else if (strcmp(argv[i],"-gui") == 0)
    {
#ifdef COMPILE_WITH_GUI
      gui = true;
#else
      fprintf(stderr, "WARNING: not compiled with GUI support. ignoring '-gui' ...\n");
#endif
    }
    else if (strcmp(argv[i],"-cores") == 0)
    {
#ifdef COMPILE_WITH_MULTI_CORE
      if ((i+1) >= argc)
      {
        fprintf(stderr,"ERROR: '%s' needs 1 argument: number\n", argv[i]);
        usage(true);
      }
      argv[i][0] = '\0';
      i++;
      cores = atoi(argv[i]);
      argv[i][0] = '\0';
#else
      fprintf(stderr, "WARNING: not compiled with multi-core batching. ignoring '-cores' ...\n");
      i++;
#endif
    }
    else if (strcmp(argv[i],"-quiet") == 0)
    {
      quiet = true;
    }
    else if (strcmp(argv[i],"-parse") == 0)
    {
      if ((i+1) >= argc)
      {
        fprintf(stderr,"ERROR: '%s' needs 1 argument: parse_string\n", argv[i]);
        usage(true);
      }
      i++;
      lasreadopener.set_parse_string(argv[i]);
    }
    else if (strcmp(argv[i],"-skip") == 0)
    {
      if ((i+1) >= argc)
      {
        fprintf(stderr,"ERROR: '%s' needs 1 argument: number_of_lines\n", argv[i]);
        usage(true);
      }
      i++;
      lasreadopener.set_skip_lines(atoi(argv[i]));
    }
    else if (strcmp(argv[i],"-set_scale") == 0)
    {
      if ((i+3) >= argc)
      {
        fprintf(stderr,"ERROR: '%s' needs 3 arguments: x y z\n", argv[i]);
        usage(true);
      }
      F64 scale_factor[3];
      i++;
      sscanf(argv[i], "%lf", &(scale_factor[0]));
      i++;
      sscanf(argv[i], "%lf", &(scale_factor[1]));
      i++;
      sscanf(argv[i], "%lf", &(scale_factor[2]));
      lasreadopener.set_scale_factor(scale_factor);
    }
    else if (strcmp(argv[i],"-set_offset") == 0)
    {
      if ((i+3) >= argc)
      {
        fprintf(stderr,"ERROR: '%s' needs 3 arguments: x y z\n", argv[i]);
        usage(true);
      }
      F64 offset[3];
      i++;
      sscanf(argv[i], "%lf", &(offset[0]));
      i++;
      sscanf(argv[i], "%lf", &(offset[1]));
      i++;
      sscanf(argv[i], "%lf", &(offset[2]));
      lasreadopener.set_offset(offset);
    }
    else if (strcmp(argv[i],"-add_extra") == 0 || strcmp(argv[i],"-add_attribute") == 0)
    {
      if ((i+3) >= argc)
      {
        fprintf(stderr,"ERROR: '%s' needs at least 3 arguments: data_type name description\n", argv[i]);
        usage(true);
      }
      if (((i+4) < argc) && (atof(argv[i+4]) != 0.0))
      {
        if (((i+5) < argc) && ((atof(argv[i+5]) != 0.0) || (strcmp(argv[i+5], "0") == 0) || (strcmp(argv[i+5], "0.0") == 0)))
        {
          if (((i+6) < argc) && (atof(argv[i+6]) != 0.0))
          {
            if (((i+7) < argc) && ((atof(argv[i+7]) != 0.0) || (strcmp(argv[i+7], "0") == 0) || (strcmp(argv[i+7], "0.0") == 0)))
            {
              lasreadopener.add_attribute(atoi(argv[i+1]), argv[i+2], argv[i+3], atof(argv[i+4]), atof(argv[i+5]), atof(argv[i+6]), atof(argv[i+7]));
              i+=7;
            }
            else
            { 
              lasreadopener.add_attribute(atoi(argv[i+1]), argv[i+2], argv[i+3], atof(argv[i+4]), atof(argv[i+5]), atof(argv[i+6]));
              i+=6;
            }
          }
          else
          { 
            lasreadopener.add_attribute(atoi(argv[i+1]), argv[i+2], argv[i+3], atof(argv[i+4]), atof(argv[i+5]));
            i+=5;
          }
        }
        else
        {
          lasreadopener.add_attribute(atoi(argv[i+1]), argv[i+2], argv[i+3], atof(argv[i+4]));
          i+=4;
        }
      }
      else
      {
        lasreadopener.add_attribute(atoi(argv[i+1]), argv[i+2], argv[i+3]);
        i+=3;
      }
    }
    else if (strcmp(argv[i],"-set_creation_date") == 0 || strcmp(argv[i],"-set_file_creation") == 0)
    {
      if ((i+2) >= argc)
      {
        fprintf(stderr,"ERROR: '%s' needs 2 arguments: day year\n", argv[i]);
        usage(true);
      }
      i++;
      sscanf(argv[i], "%d", &file_creation_day);
      i++;
      sscanf(argv[i], "%d", &file_creation_year);
    }
    else if (strcmp(argv[i],"-set_class") == 0 || strcmp(argv[i],"-set_classification") == 0)
    {
      if ((i+1) >= argc)
      {
        fprintf(stderr,"ERROR: '%s' needs 1 argument: value\n", argv[i]);
        usage(true);
      }
      i++;
      set_classification = atoi(argv[i]);
    }
    else if (strcmp(argv[i],"-set_system_identifier") == 0)
    {
      if ((i+1) >= argc)
      {
        fprintf(stderr,"ERROR: '%s' needs 1 argument: name\n", argv[i]);
        usage(true);
      }
      i++;
      set_system_identifier = argv[i];
    }
    else if (strcmp(argv[i],"-set_generating_software") == 0)
    {
      if ((i+1) >= argc)
      {
        fprintf(stderr,"ERROR: '%s' needs 1 argument: name\n", argv[i]);
        usage(true);
      }
      i++;
      set_generating_software = argv[i];
    }
    else if (strcmp(argv[i],"-set_ogc_wkt") == 0)
    {
      set_ogc_wkt = true;
    }
    else if (strcmp(argv[i],"-set_version") == 0)
    {
      if ((i+1) >= argc)
      {
        fprintf(stderr,"ERROR: '%s' needs 1 argument: major.minor\n", argv[i]);
        usage(true);
      }
      i++;
      if (sscanf(argv[i],"%d.%d",&set_version_major,&set_version_minor) != 2)
      {
        fprintf(stderr, "ERROR: cannot understand argument '%s' of '%s'\n", argv[i], argv[i-1]);
        usage(true);
      }
    }
    else if ((argv[i][0] != '-') && (lasreadopener.get_file_name_number() == 0))
    {
      lasreadopener.add_file_name(argv[i]);
      argv[i][0] = '\0';
    }
    else
    {
      fprintf(stderr, "ERROR: cannot understand argument '%s'\n", argv[i]);
      usage(true);
    }
  }

#ifdef COMPILE_WITH_GUI
  if (gui)
  {
    return txt2las_gui(argc, argv, &lasreadopener);
  }
#endif

#ifdef COMPILE_WITH_MULTI_CORE
  if (cores > 1)
  {
    if (lasreadopener.get_file_name_number() < 2)
    {
      fprintf(stderr,"WARNING: only %u input files. ignoring '-cores %d' ...\n", lasreadopener.get_file_name_number(), cores);
    }
    else if (lasreadopener.is_merged())
    {
      fprintf(stderr,"WARNING: input files merged on-the-fly. ignoring '-cores %d' ...\n", cores);
    }
    else
    {
      return txt2las_multi_core(argc, argv, &geoprojectionconverter, &lasreadopener, &laswriteopener, cores);
    }
  }
#endif

  // make sure we have input

  if (!lasreadopener.active())
  {
    fprintf(stderr, "ERROR: no input specified\n");
    byebye(true, argc==1);
  }

  // make sure that input and output are not *both* piped

  if (lasreadopener.is_piped() && laswriteopener.is_piped())
  {
    fprintf(stderr, "ERROR: input and output cannot both be piped\n");
    byebye(true, argc==1);
  }

  // check if projection info was set in the command line

  int number_of_keys;
  GeoProjectionGeoKeys* geo_keys = 0;
  int num_geo_double_params;
  double* geo_double_params = 0;

  if (geoprojectionconverter.has_projection())
  {
    projection_was_set = geoprojectionconverter.get_geo_keys_from_projection(number_of_keys, &geo_keys, num_geo_double_params, &geo_double_params);
  }

  // loop over multiple input files

  while (lasreadopener.active())
  {
    if (verbose) start_time = taketime();

    // open lasreader

    LASreader* lasreader = lasreadopener.open();

    if (lasreader == 0)
    {
      fprintf(stderr, "ERROR: could not open lasreader\n");
      byebye(true, argc==1);
    }

    // check output

    if (!laswriteopener.active())
    {
      // create name from input name
      laswriteopener.make_file_name(lasreadopener.get_file_name(), -2);
    }

    // if the output was piped we need to precompute the bounding box, etc ...

    if (laswriteopener.is_piped())
    {
      // because the output goes to a pipe we have to precompute the header
      // information with an additional pass.

      if (verbose) { fprintf(stderr, "piped output. extra read pass over file '%s' ...\n", lasreadopener.get_file_name()); }

      while (lasreader->read_point());
      lasreader->close();

      // output some stats
    
      if (verbose)
      {
#ifdef _WIN32
        fprintf(stderr, "npoints %I64d min %g %g %g max %g %g %g\n", lasreader->npoints, lasreader->header.min_x, lasreader->header.min_y, lasreader->header.min_z, lasreader->header.max_x, lasreader->header.max_y, lasreader->header.max_z);
#else
        fprintf(stderr, "npoints %lld min %g %g %g max %g %g %g\n", lasreader->npoints, lasreader->header.min_x, lasreader->header.min_y, lasreader->header.min_z, lasreader->header.max_x, lasreader->header.max_y, lasreader->header.max_z);
#endif
        fprintf(stderr, "return histogram %d %d %d %d %d\n", lasreader->header.number_of_points_by_return[0], lasreader->header.number_of_points_by_return[1], lasreader->header.number_of_points_by_return[2], lasreader->header.number_of_points_by_return[3], lasreader->header.number_of_points_by_return[4]);
        fprintf(stderr,"took %g sec.\n", taketime()-start_time); start_time = taketime();
      }

      // reopen lasreader for the second pass

      if (!lasreadopener.reopen(lasreader))
      {
        fprintf(stderr, "ERROR: could not reopen '%s' for main pass\n", lasreadopener.get_file_name());
        byebye(true, argc==1);
      }
    }

    // populate header

    for (i = 0; i < 32; i++)
    {
      lasreader->header.system_identifier[i] = '\0';
      lasreader->header.generating_software[i] = '\0';
    }

    if (set_system_identifier)
    {
      strncpy(lasreader->header.system_identifier, set_system_identifier, 32);
      lasreader->header.system_identifier[31] = '\0';
    }
    else
    {
      strncpy(lasreader->header.system_identifier, "LAStools (c) by rapidlasso GmbH", 32);
      lasreader->header.system_identifier[31] = '\0';
    }

    if (set_generating_software)
    {
      strncpy(lasreader->header.generating_software, set_generating_software, 32);
      lasreader->header.generating_software[31] = '\0';
    }
    else
    {
      char temp[64];
      sprintf(temp, "txt2las (version %d)", LAS_TOOLS_VERSION);
      strncpy(lasreader->header.generating_software, temp, 32);
      lasreader->header.generating_software[31] = '\0';
    }

    // maybe set creation date

#ifdef _WIN32
    if (lasreadopener.get_file_name() && file_creation_day == -1 && file_creation_year == -1)
    {
      WIN32_FILE_ATTRIBUTE_DATA attr;
	    SYSTEMTIME creation;
      GetFileAttributesEx(lasreadopener.get_file_name(), GetFileExInfoStandard, &attr);
	    FileTimeToSystemTime(&attr.ftCreationTime, &creation);
      int startday[13] = {-1, 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334};
      file_creation_day = startday[creation.wMonth] + creation.wDay;
      file_creation_year = creation.wYear;
      // leap year handling
      if ((((creation.wYear)%4) == 0) && (creation.wMonth > 2)) file_creation_day++;
    }
#endif
    if (file_creation_day == -1 && file_creation_year == -1)
    {
      lasreader->header.file_creation_day = (U16)333;
      lasreader->header.file_creation_year = (U16)2011;
    }
    else
    {
      lasreader->header.file_creation_day = (U16)file_creation_day;
      lasreader->header.file_creation_year = (U16)file_creation_year;
    }

    // maybe set version

    if (set_version_major != -1) lasreader->header.version_major = (U8)set_version_major;
    if (set_version_minor != -1) lasreader->header.version_minor = (U8)set_version_minor;

    if (set_version_minor == 3)
    {
      lasreader->header.header_size = 235;
      lasreader->header.offset_to_point_data = 235;
    }
    else if (set_version_minor == 4)
    {
      lasreader->header.header_size = 375;
      lasreader->header.offset_to_point_data = 375;
    }

    // maybe set projection

    if (projection_was_set)
    {
      lasreader->header.set_geo_keys(number_of_keys, (LASvlr_key_entry*)geo_keys);
      if (geo_double_params)
      {
        lasreader->header.set_geo_double_params(num_geo_double_params, geo_double_params);
      }
      else
      {
        lasreader->header.del_geo_double_params();
      }
      lasreader->header.del_geo_ascii_params();

      if (set_ogc_wkt) // maybe also set the OCG WKT 
      {
        I32 len = 0;
        CHAR* ogc_wkt = 0;
        if (geoprojectionconverter.get_ogc_wkt_from_projection(len, &ogc_wkt, !geoprojectionconverter.has_projection(false)))
        {
          lasreader->header.set_geo_wkt_ogc_cs(len, ogc_wkt);
          free(ogc_wkt);
          if ((lasreader->header.version_minor >= 4) && (lasreader->header.point_data_format >= 6))
          {
            lasreader->header.set_global_encoding_bit(LAS_TOOLS_GLOBAL_ENCODING_BIT_OGC_WKT_CRS);
          }
        }
        else
        {
          fprintf(stderr, "WARNING: cannot produce OCG WKT. ignoring '-set_ogc_wkt' for '%s'\n", lasreadopener.get_file_name());
        }
      }
    }

    // open the output

    LASwriter* laswriter = laswriteopener.open(&lasreader->header);

    if (laswriter == 0)
    {
      fprintf(stderr, "ERROR: could not open laswriter\n");
      byebye(true, argc==1);
    }

    if (verbose) fprintf(stderr, "reading file '%s' and writing to '%s'\n", lasreadopener.get_file_name(), laswriteopener.get_file_name());

    // loop over points

    while (lasreader->read_point())
    {
      // maybe set classification
      if (set_classification != -1)
      {
        lasreader->point.set_classification(set_classification);
      }
      // write the point
      laswriter->write_point(&lasreader->point);
    }
    lasreader->close();

    if (!laswriteopener.is_piped())
    {
      laswriter->update_header(&lasreader->header, FALSE, TRUE);
      if (verbose)
      {
#ifdef _WIN32
        fprintf(stderr, "npoints %I64d min %g %g %g max %g %g %g\n", lasreader->npoints, lasreader->header.min_x, lasreader->header.min_y, lasreader->header.min_z, lasreader->header.max_x, lasreader->header.max_y, lasreader->header.max_z);
#else
        fprintf(stderr, "npoints %lld min %g %g %g max %g %g %g\n", lasreader->npoints, lasreader->header.min_x, lasreader->header.min_y, lasreader->header.min_z, lasreader->header.max_x, lasreader->header.max_y, lasreader->header.max_z);
#endif
        fprintf(stderr, "return histogram %d %d %d %d %d\n", lasreader->header.number_of_points_by_return[0], lasreader->header.number_of_points_by_return[1], lasreader->header.number_of_points_by_return[2], lasreader->header.number_of_points_by_return[3], lasreader->header.number_of_points_by_return[4]);
     }
    }
    laswriter->close();

    delete laswriter;
    delete lasreader;

    laswriteopener.set_file_name(0);

    if (verbose) fprintf(stderr,"took %g sec.\n", taketime()-start_time);
  }

  byebye(false, argc==1);

  return 0;
}
INT_PTR CDestroyFilesDialog::OnInitDialog()
{
	m_hDialogIcon = LoadIcon(GetModuleHandle(0),MAKEINTRESOURCE(IDI_MAIN_SMALL));
	SetClassLongPtr(m_hDlg,GCLP_HICONSM,reinterpret_cast<LONG_PTR>(m_hDialogIcon));

	HWND hListView = GetDlgItem(m_hDlg,IDC_DESTROYFILES_LISTVIEW);

	HIMAGELIST himlSmall;
	Shell_GetImageLists(NULL,&himlSmall);
	ListView_SetImageList(hListView,himlSmall,LVSIL_SMALL);

	SetWindowTheme(hListView,L"Explorer",NULL);

	ListView_SetExtendedListViewStyleEx(hListView,
		LVS_EX_DOUBLEBUFFER|LVS_EX_FULLROWSELECT|LVS_EX_GRIDLINES,
		LVS_EX_DOUBLEBUFFER|LVS_EX_FULLROWSELECT|LVS_EX_GRIDLINES);

	LVCOLUMN lvColumn;
	TCHAR szTemp[128];

	LoadString(GetInstance(),IDS_DESTROY_FILES_COLUMN_FILE,
		szTemp,SIZEOF_ARRAY(szTemp));
	lvColumn.mask		= LVCF_TEXT;
	lvColumn.pszText	= szTemp;
	ListView_InsertColumn(hListView,0,&lvColumn);

	LoadString(GetInstance(),IDS_DESTROY_FILES_COLUMN_TYPE,
		szTemp,SIZEOF_ARRAY(szTemp));
	lvColumn.mask		= LVCF_TEXT;
	lvColumn.pszText	= szTemp;
	ListView_InsertColumn(hListView,1,&lvColumn);

	LoadString(GetInstance(),IDS_DESTROY_FILES_COLUMN_SIZE,
		szTemp,SIZEOF_ARRAY(szTemp));
	lvColumn.mask		= LVCF_TEXT;
	lvColumn.pszText	= szTemp;
	ListView_InsertColumn(hListView,2,&lvColumn);

	LoadString(GetInstance(),IDS_DESTROY_FILES_COLUMN_DATE_MODIFIED,
		szTemp,SIZEOF_ARRAY(szTemp));
	lvColumn.mask		= LVCF_TEXT;
	lvColumn.pszText	= szTemp;
	ListView_InsertColumn(hListView,3,&lvColumn);

	int iItem = 0;

	for each(auto strFullFilename in m_FullFilenameList)
	{
		TCHAR szFullFilename[MAX_PATH];

		StringCchCopy(szFullFilename,SIZEOF_ARRAY(szFullFilename),
			strFullFilename.c_str());

		/* TODO: Perform in background thread. */
		SHFILEINFO shfi;
		SHGetFileInfo(szFullFilename,0,&shfi,sizeof(shfi),SHGFI_SYSICONINDEX|
			SHGFI_TYPENAME);

		LVITEM lvItem;
		lvItem.mask		= LVIF_TEXT|LVIF_IMAGE;
		lvItem.iItem	= iItem;
		lvItem.iSubItem	= 0;
		lvItem.pszText	= szFullFilename;
		lvItem.iImage	 = shfi.iIcon;
		ListView_InsertItem(hListView,&lvItem);

		ListView_SetItemText(hListView,iItem,1,shfi.szTypeName);

		WIN32_FILE_ATTRIBUTE_DATA wfad;
		GetFileAttributesEx(szFullFilename,GetFileExInfoStandard,&wfad);

		TCHAR szFileSize[32];
		ULARGE_INTEGER lFileSize = {wfad.nFileSizeLow,wfad.nFileSizeHigh};
		FormatSizeString(lFileSize,szFileSize,SIZEOF_ARRAY(szFileSize));
		ListView_SetItemText(hListView,iItem,2,szFileSize);

		TCHAR szDateModified[32];
		CreateFileTimeString(&wfad.ftLastWriteTime,szDateModified,
			SIZEOF_ARRAY(szDateModified),m_bShowFriendlyDates);
		ListView_SetItemText(hListView,iItem,3,szDateModified);

		iItem++;
	}
Пример #9
0
	HRESULT SLog::splitFullPath(TSTRING szFullPath)
	{
		HRESULT retValue = S_OK;

		TSTRING szSlash = TSTRING(_T("/\\"));
		TSTRING szDot = TSTRING(_T("."));
		int iLastSlash, iLastDot;
		bool bBadPath = false;

		// Quick sanity check...
		if (szFullPath.empty())
		{
			retValue = ERROR_BAD_ARGUMENTS;
			goto EXIT;
		}

		// First, make sure we actually have strings...
		if (NULL == m_szLogFilePath)
			m_szLogFilePath = new TSTRING();

		if (NULL == m_szLogFileName)
			m_szLogFileName = new TSTRING();

		if (NULL == m_szLogFileExt)
			m_szLogFileExt = new TSTRING();

		// Make sure they're clear (remember, we may not have created them)
		m_szLogFilePath->clear();
		m_szLogFileName->clear();
		m_szLogFileExt->clear();

		// To peel apart the string, we need to find the last slash character
		iLastSlash = szFullPath.find_last_of(szSlash.c_str(), TNPOS);

		// Now, this could go either way; either we have no slash, in which case
		// this DOESN'T have a path, or we do and there's a path...
		if (iLastSlash == TNPOS)
		{
			// We didn't get a path...
			bBadPath = true;
		}
		else
		{
			// Get the path, if there is one...
			m_szLogFilePath->append(szFullPath.substr(0, (iLastSlash + 1)));

			// Does that path actually exist?
			WIN32_FILE_ATTRIBUTE_DATA dirData;
			if (!GetFileAttributesEx(m_szLogFilePath->c_str(),
				GetFileExInfoStandard,
				&dirData))
			{
				// We hit an error!
				DWORD dw;
				dw = GetLastError();
				retValue = HRESULT_FROM_WIN32(dw);
				bBadPath = true;
			}
			else if ((dirData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) != FILE_ATTRIBUTE_DIRECTORY)
			{
				// The path isn't to a directory!
				retValue = ERROR_BAD_PATHNAME;
				bBadPath = true;
			}
		}

		if (bBadPath)
		{
			// We either got no path or a bad path, so let's
			// set it to the Current Directory...
			// First, get the size of buffer we're going to need
			int iDirSize = GetCurrentDirectory(0, NULL);

			// Next, declare the buffer and use it to get the current directory
			m_szLogFilePath->clear();
			TCHAR* szDirBuffer = new TCHAR[iDirSize];
			GetCurrentDirectory(iDirSize, szDirBuffer);
			m_szLogFilePath->append(szDirBuffer);
			m_szLogFilePath->append(_T("\\"));		// Have to add the trailing slash
		}

		// To peel apart the extension, we need to find the last dot character
		iLastDot = szFullPath.find_last_of(szDot.c_str(), TNPOS);

		// We may or may not have a dot; no dot, no extension
		if (iLastDot == TNPOS)
		{
			iLastDot = szFullPath.length();
			m_szLogFileExt->append(DEFAULT_EXT);
		}
		else
		{
			m_szLogFileExt->append(szFullPath.substr(iLastDot));
		}

		// With all that out of the way, we can get our file name
		m_szLogFileName->append(szFullPath.substr((iLastSlash + 1), ( iLastDot - iLastSlash - 1 )));

	EXIT:
		return retValue;
	}
Пример #10
0
static dvdid_status_t hashinfo_add_file_by_path_win32(const char *path, const dvdid__medium_spec_file_t *spec, dvdid_hashinfo_t *hi, int *errn) {

  FILE *fp;
  WIN32_FILE_ATTRIBUTE_DATA file_info;
  WCHAR *path_wide, *specpath_wide, *tmppath_wide;
  int l;
  BOOL b;

  size_t s, file_size;
  uint8_t *buf;

  dvdid_status_t rv;


  rv = DVDID_STATUS_OK;

  do {

    l = MultiByteToWideChar(CP_UTF8, 0, path, -1, NULL, 0);

    path_wide = calloc(l, sizeof(*path_wide));

    if (path_wide == NULL) {
      rv = DVDID_STATUS_MALLOC_ERROR;
      if (errn != NULL) { *errn = 0; }
      break;
    }

    MultiByteToWideChar(CP_UTF8, 0, path, -1, path_wide, l);

    do {

      l = MultiByteToWideChar(CP_UTF8, 0, spec->path, -1, NULL, 0);

      specpath_wide = calloc(l, sizeof(*specpath_wide));

      if (specpath_wide == NULL) {
        rv = DVDID_STATUS_MALLOC_ERROR;
        if (errn != NULL) { *errn = 0; }
        break;
      }

      MultiByteToWideChar(CP_UTF8, 0, spec->path, -1, specpath_wide, l);

      do {

        s = wcslen(path_wide) + wcslen(W_DIR_SEP) + wcslen(specpath_wide) + 1;

        tmppath_wide = calloc(s, sizeof(*tmppath_wide));

        if (tmppath_wide == NULL) {
          rv = DVDID_STATUS_MALLOC_ERROR;
          if (errn != NULL) { *errn = 0; }
          break;
        }

        _snwprintf(tmppath_wide, s, L"%s" W_DIR_SEP L"%s", path_wide, specpath_wide);

        b = GetFileAttributesEx(tmppath_wide, GetFileExInfoStandard, &file_info);

        if (b) {
          fp = _wfopen(tmppath_wide, L"rb");
        } else {
          fp = NULL; /* Silence warnings */
         }

        free(tmppath_wide);

        if (!b) {
          if (spec->optional && GetLastError() == ERROR_FILE_NOT_FOUND) { /* TODO: Are there any other return values that we should swallow here? */
            /* rv already set */
          } else {
            rv = spec->err;
            if (errn != NULL) { *errn = GetLastErrorToErrno(GetLastError()); }
          }
          break;
        }

        if (fp == NULL) {
          rv = spec->err;
          if (errn != NULL) { *errn = errno; }
          break;
        }

        file_size = file_info.nFileSizeLow;

        if (file_size > spec->max_size) { file_size = spec->max_size; }

        buf = malloc(file_size);

        if (buf == NULL) {
          rv = DVDID_STATUS_MALLOC_ERROR;
          if (errn != NULL) { *errn = 0; }
          break;
        }

        do {

          s = fread(buf, 1, file_size, fp);

          fclose(fp);

          if (s != file_size) {
            rv = spec->err;
            if (errn != NULL) { *errn = 0; }
            break;
          }

          rv = dvdid_hashinfo_add_filedata(hi, spec->file, buf, s);

          if (rv != DVDID_STATUS_OK) {
            if (errn != NULL) { *errn = 0; }
            break;
          }

        } while(0);

        free(buf);

      } while (0);

      free(specpath_wide);

    } while (0);

    free(path_wide);

  } while (0);

  return rv;

}
Пример #11
0
enum CLocalFileSystem::local_fileType CLocalFileSystem::GetFileInfo(const wxString& path, bool &isLink, wxLongLong* size, CDateTime* modificationTime, int *mode)
{
#ifdef __WXMSW__
	if (path.Last() == wxFileName::GetPathSeparator() && path != wxFileName::GetPathSeparator()) {
		wxString tmp = path;
		tmp.RemoveLast();
		return GetFileInfo(tmp, isLink, size, modificationTime, mode);
	}

	isLink = false;

	WIN32_FILE_ATTRIBUTE_DATA attributes;
	BOOL result = GetFileAttributesEx(path, GetFileExInfoStandard, &attributes);
	if (!result) {
		if (size)
			*size = -1;
		if (mode)
			*mode = 0;
		if (modificationTime)
			*modificationTime = CDateTime();
		return unknown;
	}

	bool is_dir = (attributes.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) != 0;

	if (attributes.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT) {
		isLink = true;

		HANDLE hFile = is_dir ? INVALID_HANDLE_VALUE : CreateFile(path, FILE_READ_ATTRIBUTES | FILE_READ_EA, FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, 0, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);
		if (hFile != INVALID_HANDLE_VALUE) {
			BY_HANDLE_FILE_INFORMATION info{};
			int ret = GetFileInformationByHandle(hFile, &info);
			CloseHandle(hFile);
			if (ret != 0 && !(info.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT)) {

				if (modificationTime) {
					if (!ConvertFileTimeToCDateTime(*modificationTime, info.ftLastWriteTime))
						ConvertFileTimeToCDateTime(*modificationTime, info.ftCreationTime);
				}

				if (mode)
					*mode = (int)info.dwFileAttributes;

				if (info.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) {
					if (size)
						*size = -1;
					return dir;
				}

				if (size)
					*size = wxLongLong(info.nFileSizeHigh, info.nFileSizeLow);

				return file;
			}
		}

		if (size)
			*size = -1;
		if (mode)
			*mode = 0;
		if (modificationTime)
			*modificationTime = CDateTime();
		return is_dir ? dir : unknown;
	}

	if (modificationTime) {
		if (!ConvertFileTimeToCDateTime(*modificationTime, attributes.ftLastWriteTime))
			ConvertFileTimeToCDateTime(*modificationTime, attributes.ftCreationTime);
	}

	if (mode)
		*mode = (int)attributes.dwFileAttributes;

	if (is_dir) {
		if (size)
			*size = -1;
		return dir;
	}
	else {
		if (size)
			*size = wxLongLong(attributes.nFileSizeHigh, attributes.nFileSizeLow);
		return file;
	}
#else
	if (path.Last() == '/' && path != _T("/"))
	{
		wxString tmp = path;
		tmp.RemoveLast();
		return GetFileInfo(tmp, isLink, size, modificationTime, mode);
	}

	const wxCharBuffer p = path.fn_str();
	return GetFileInfo((const char*)p, isLink, size, modificationTime, mode);
#endif
}
Пример #12
0
std::tstring ContainerManager::GetContainerName(unsigned int charid, unsigned int containerid) const
{
    if (containerid == 1) {
        return _T("Bank");
    }
    else if (containerid == 2) {
        return _T("Inventory/Equip");
    }
    else if (containerid == 3) {
        return _T("Shop");
    }

    std::tstring result;

    __int64 key = ((__int64)charid) << 32;
    key += containerid;

    FILETIME lastWrite;
    lastWrite.dwHighDateTime = lastWrite.dwLowDateTime = 0;

    std::tstring filename;
    for (unsigned int i = 0; i < m_accounts.size(); i++)
    {
        filename = STREAM2STR( AOManager::instance().getAOPrefsFolder() << _T("\\") << m_accounts[i] << _T("\\Char") << charid << _T("\\Containers\\Container_51017x") << containerid << _T(".xml") );
        if (PathFileExists(filename.c_str()))
        {
            WIN32_FILE_ATTRIBUTE_DATA atribs; 
            if (GetFileAttributesEx(filename.c_str(), GetFileExInfoStandard, &atribs))
            {
                lastWrite = atribs.ftLastWriteTime;
                break;
            }
        }
    }

    bool wasInCache = m_containerFileCache.find(key) != m_containerFileCache.end();

    // Clear invalid cache
    if ((filename.empty() || (lastWrite.dwHighDateTime == 0 && lastWrite.dwHighDateTime == 0)) && wasInCache)
    {
        m_containerFileCache.erase(m_containerFileCache.find(key));
    }

    // Create cache from file
    if (!filename.empty())
    {
        bool update = true;

        // If already in cache, check timestamps
        if (m_containerFileCache.find(key) != m_containerFileCache.end())
        {
            FILETIME stamp = m_containerFileCache[key].second;
            if (stamp.dwHighDateTime == lastWrite.dwHighDateTime &&
                stamp.dwLowDateTime == lastWrite.dwLowDateTime)
            {
                update = false;
                result = m_containerFileCache[key].first;
            }
        }

        if (update)
        {
            TiXmlDocument document;
            if (document.LoadFile(to_ascii_copy(filename), TIXML_ENCODING_UTF8))
            {
                TiXmlHandle docHandle( &document );
                TiXmlElement* element = docHandle.FirstChild( "Archive" ).FirstChild( "String" ).Element();

                while (element)
                {
                    if (StrCmpA(element->Attribute("name"), "container_name") == 0)
                    {
                        result = from_utf8_copy(element->Attribute("value"));
                        boost::algorithm::replace_all(result, _T("&amp;"), _T("&"));    // Fixes wierd encoding in the AO xml.
                        m_containerFileCache[key] = std::pair<std::tstring, FILETIME>(result, lastWrite);
                        break;
                    }
                    element = element->NextSiblingElement();
                }
            }
        }
    }

    if (result.empty())
    {
        result = MakeContainerName(charid, containerid);
    }

    return result;
}
Пример #13
0
BOOL LASreaderASC::open(const char* file_name)
{
  if (file_name == 0)
  {
    fprintf(stderr,"ERROR: fine name pointer is zero\n");
    return FALSE;
  }

  clean();

  file = fopen_compressed(file_name, "r", &piped);
  if (file == 0)
  {
    fprintf(stderr, "ERROR: cannot open file '%s'\n", file_name);
    return FALSE;
  }

  // clean the header

  header.clean();

  // populate the header as much as it makes sense

  sprintf(header.system_identifier, "LAStools (c) by Martin Isenburg");
  sprintf(header.generating_software, "via LASreaderASC (%d)", LAS_TOOLS_VERSION);

  // maybe set creation date

#ifdef _WIN32
  WIN32_FILE_ATTRIBUTE_DATA attr;
	SYSTEMTIME creation;
  GetFileAttributesEx(file_name, GetFileExInfoStandard, &attr);
	FileTimeToSystemTime(&attr.ftCreationTime, &creation);
  int startday[13] = {-1, 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334};
  header.file_creation_day = startday[creation.wMonth] + creation.wDay;
  header.file_creation_year = creation.wYear;
  // leap year handling
  if ((((creation.wYear)%4) == 0) && (creation.wMonth > 2)) header.file_creation_day++;
#else
  header.file_creation_day = 333;
  header.file_creation_year = 2012;
#endif

  header.point_data_format = 0;
  header.point_data_record_length = 20;

  // initialize point

  point.init(&header, header.point_data_format, header.point_data_record_length, &header);

  // read header of ASC file

  if (line == 0)
  {
    line_size = 1024;
    line = (CHAR*)malloc(sizeof(CHAR)*line_size);
  }

  CHAR dummy[32];
  BOOL complete = FALSE;
  ncols = 0;
  nrows = 0;
  F64 xllcorner = F64_MAX;
  F64 yllcorner = F64_MAX;
  xllcenter = F64_MAX;
  xllcenter = F64_MAX;
  cellsize = 0;
  nodata = -9999;
  header_lines = 0;

  while (!complete)
  {
    if (!fgets(line, line_size, file)) break;

    if (strstr(line, "ncols") || strstr(line, "NCOLS"))
    {
      sscanf(line, "ncols %d", &ncols);
      free(line);
      line_size = 1024+16*ncols;
      line = (CHAR*)malloc(sizeof(CHAR)*line_size);
    }
    else if (strstr(line, "nrows") || strstr(line, "NROWS"))
    {
      sscanf(line, "%s %d", dummy, &nrows);
    }
    else if (strstr(line, "xllcorner") || strstr(line, "XLLCORNER"))
    {
      sscanf(line, "%s %lf", dummy, &xllcorner);
    }
    else if (strstr(line, "yllcorner") || strstr(line, "YLLCORNER"))
    {
      sscanf(line, "%s %lf", dummy, &yllcorner);
    }
    else if (strstr(line, "xllcenter") || strstr(line, "XLLCENTER"))
    {
      sscanf(line, "%s %lf", dummy, &xllcenter);
    }
    else if (strstr(line, "yllcenter") || strstr(line, "YLLCENTER"))
    {
      sscanf(line, "%s %lf", dummy, &yllcenter);
    }
    else if (strstr(line, "cellsize") || strstr(line, "CELLSIZE"))
    {
      sscanf(line, "%s %f", dummy, &cellsize);
    }
    else if (strstr(line, "nodata_value") || strstr(line, "NODATA_VALUE") || strstr(line, "nodata_VALUE") || strstr(line, "NODATA_value"))
    {
      sscanf(line, "%s %f", dummy, &nodata);
    }
    else if ((ncols != 0) && (nrows != 0) && (((xllcorner != F64_MAX) && (yllcorner != F64_MAX)) || ((xllcenter != F64_MAX) && (xllcenter != F64_MAX))) && (cellsize > 0))
    {
      if (ncols == 1)
      {
        F32 e0, e1;
        if ( sscanf(line, "%f %f", &e0, &e1) == 1)
        {
          complete = TRUE;
        }
      }
      else if (ncols == 2)
      {
        F32 e0, e1, e2;
        if ( sscanf(line, "%f %f %f", &e0, &e1, &e2) == 2)
        {
          complete = TRUE;
        }
      }
      else if (ncols == 3)
      {
        F32 e0, e1, e2, e3;
        if ( sscanf(line, "%f %f %f %f", &e0, &e1, &e2, &e3) == 3)
        {
          complete = TRUE;
        }
      }
      else if (ncols == 4)
      {
        F32 e0, e1, e2, e3, e4;
        if ( sscanf(line, "%f %f %f %f %f", &e0, &e1, &e2, &e3, &e4) == 4)
        {
          complete = TRUE;
        }
      }
      else
      {
        F32 e0, e1, e2, e3, e4;
        if ( sscanf(line, "%f %f %f %f %f", &e0, &e1, &e2, &e3, &e4) == 5)
        {
          complete = TRUE;
        }
      }
    }
    header_lines++;
  }

  if (!complete)
  {
    fprintf(stderr,"ERROR: was not able to find header\n");
    return FALSE;
  }

  // shift the llcorner to the pixel center

  if ((xllcorner != F64_MAX) && (yllcorner != F64_MAX))
  {
    xllcenter = xllcorner + 0.5*cellsize;
    yllcenter = yllcorner + 0.5*cellsize;
  }

  // init the bounding box x y

  header.min_x = xllcenter;
  header.min_y = yllcenter;
  header.max_x = xllcenter + (ncols-1)*cellsize;
  header.max_y = yllcenter + (nrows-1)*cellsize;

  // init the bounding box z and count the rasters

  F32 elevation = 0;
  npoints = 0;
  header.min_z = F64_MAX;
  header.max_z = F64_MIN;

  for (row = 0; row < nrows; row++)
  {
    line_curr = 0;
    for (col = 0; col < ncols; col++)
    {
      // skip leading spaces
      while ((line[line_curr] != '\0') && (line[line_curr] == ' ')) line_curr++;
      // get elevation value
      sscanf(&(line[line_curr]), "%f", &elevation);
      // skip parsed number
      while ((line[line_curr] != '\0') && (line[line_curr] != ' ')) line_curr++;
      // should we use the raster
      if (elevation != nodata)
      {
        npoints++;
        if (header.max_z < elevation) header.max_z = elevation;
        if (header.min_z > elevation) header.min_z = elevation;
      }
    }
    if (!fgets(line, line_size, file)) break;
  }

  // close the file

  close();

  // check the header values

  if ((header.min_z == F64_MAX) || (header.max_z == F64_MIN))
  {
    fprintf(stderr,"WARNING: raster contains only no data\n");
    header.min_z = 0;
    header.max_z = 0;
  }

  header.number_of_point_records = (U32)npoints;

  // populate scale and offset

  populate_scale_and_offset();

  // check bounding box for this scale and offset

  populate_bounding_box();

  // reopen

  return reopen(file_name);
}
Пример #14
0
xi_file_re xi_file_stat(const xchar* pathname, xi_file_stat_t *s) {
	WIN32_FILE_ATTRIBUTE_DATA se;
	SYSTEMTIME st;
	LARGE_INTEGER fsize;

	xbool ret;
	xi_time_t xtime;
	xlong utc;

	if (pathname == NULL || s == NULL) {
		return XI_FILE_RV_ERR_ARGS;
	}

	ret = GetFileAttributesEx(pathname, GetFileExInfoStandard, &se);
	if (!ret) {
		return XI_FILE_RV_ERR_ARGS;
	}

	if (se.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) {
		s->type = XI_FILE_TYPE_DIR;
	} else {
		s->type = XI_FILE_TYPE_REG;
	}

	if (se.dwFileAttributes & FILE_ATTRIBUTE_READONLY) {
		s->perm = 00400;
	} else {
		s->perm = 00600;
	}

	fsize.LowPart = se.nFileSizeLow;
	fsize.HighPart = se.nFileSizeHigh;
	s->size = fsize.QuadPart;
	s->blocks = (s->size / 4096L) + 1;

	FileTimeToSystemTime(&se.ftCreationTime, &st);
	xtime.year = st.wYear + 1601;
	xtime.mon = st.wMonth;
	xtime.day = st.wDay;
	xtime.hour = st.wHour;
	xtime.min = st.wMinute;
	xtime.sec = st.wSecond;
	xtime.msec = st.wMilliseconds;
	xi_clock_time2sec(&utc, xtime);
	s->created = (utc * 1000) + xtime.msec;

	FileTimeToSystemTime(&se.ftLastAccessTime, &st);
	xtime.year = st.wYear + 1601;
	xtime.mon = st.wMonth;
	xtime.day = st.wDay;
	xtime.hour = st.wHour;
	xtime.min = st.wMinute;
	xtime.sec = st.wSecond;
	xtime.msec = st.wMilliseconds;
	xi_clock_time2sec(&utc, xtime);
	s->accessed = (utc * 1000) + xtime.msec;

	FileTimeToSystemTime(&se.ftLastWriteTime, &st);
	xtime.year = st.wYear + 1601;
	xtime.mon = st.wMonth;
	xtime.day = st.wDay;
	xtime.hour = st.wHour;
	xtime.min = st.wMinute;
	xtime.sec = st.wSecond;
	xtime.msec = st.wMilliseconds;
	xi_clock_time2sec(&utc, xtime);
	s->modified = (utc * 1000) + xtime.msec;

	xi_strcpy(s->pathname, pathname);
	xi_strcpy(s->filename, xi_pathname_basename(pathname));

	return XI_FILE_RV_OK;
}
Пример #15
0
void emDirEntry::PrivLoad(const emString & path, const emString & name)
{
#if defined(_WIN32)
	WIN32_FILE_ATTRIBUTE_DATA fad;
	BOOL b;

	if (!--Data->RefCount) FreeData();
	Data=new SharedData;
	Data->Path=path;
	Data->Name=name;
	Data->TargetPath=Data->Path;
	if (em_stat(Data->Path,&Data->Stat)) {
		Data->LStatErrNo=errno;
		Data->StatErrNo=errno;
		memset(&Data->Stat,0,sizeof(struct em_stat));
	}
	Data->Owner=emString::Format("%u",Data->Stat.st_uid);
	Data->Group=emString::Format("%u",Data->Stat.st_gid);
	b=GetFileAttributesEx(Data->Path.Get(),GetFileExInfoStandard,&fad);
	Data->WndsFileAttributes = b ? fad.dwFileAttributes : 0;
	Data->Hidden=(Data->WndsFileAttributes&FILE_ATTRIBUTE_HIDDEN)!=0;
#else
	char tmp[1024];
#if !defined(ANDROID)
	struct passwd pwbuf;
	struct group grbuf;
#endif
	struct passwd * pw;
	struct group * gr;
	int i;

	if (!--Data->RefCount) FreeData();
	Data=new SharedData;
	Data->Path=path;
	Data->Name=name;
	Data->TargetPath=Data->Path;
	if (em_lstat(Data->Path,&Data->Stat)) {
		Data->LStatErrNo=errno;
		if (em_stat(Data->Path,&Data->Stat)) {
			Data->StatErrNo=errno;
			memset(&Data->Stat,0,sizeof(struct em_stat));
		}
		else {
			Data->LStat=(struct em_stat*)malloc(sizeof(struct em_stat));
			memset(Data->LStat,0,sizeof(struct em_stat));
		}
	}
	else if (S_ISLNK(Data->Stat.st_mode)) {
		Data->LStat=(struct em_stat*)malloc(sizeof(struct em_stat));
		memcpy(Data->LStat,&Data->Stat,sizeof(struct em_stat));
		if (em_stat(Data->Path,&Data->Stat)) {
			Data->StatErrNo=errno;
			memset(&Data->Stat,0,sizeof(struct em_stat));
		}
		i=readlink(Data->Path,tmp,sizeof(tmp)-1);
		if (i<0) {
			Data->TargetPathErrNo=errno;
			tmp[0]=0;
		}
		else {
			tmp[i]=0;
		}
		Data->TargetPath=tmp;
	}

#if defined(ANDROID)
	pw=getpwuid(Data->Stat.st_uid);
	i=0;
#else
	i=getpwuid_r(Data->Stat.st_uid,&pwbuf,tmp,sizeof(tmp),&pw);
#endif
	if (i==0 && pw && pw->pw_name) Data->Owner=pw->pw_name;
	else Data->Owner=emString::Format("%lu",(unsigned long)Data->Stat.st_uid);

#if defined(ANDROID)
	gr=getgrgid(Data->Stat.st_gid);
	i=0;
#else
	i=getgrgid_r(Data->Stat.st_gid,&grbuf,tmp,sizeof(tmp),&gr);
#endif
	if (i==0 && gr && gr->gr_name) Data->Group=gr->gr_name;
	else Data->Group=emString::Format("%lu",(unsigned long)Data->Stat.st_gid);

	Data->Hidden=(Data->Name[0]=='.');
#endif
}
Пример #16
0
FILETIME get_last_write_time(char *filename) {
    WIN32_FILE_ATTRIBUTE_DATA fileinfo = {};
    GetFileAttributesEx(filename, GetFileExInfoStandard, (void *) &fileinfo);
    return fileinfo.ftLastWriteTime; 
}
Пример #17
0
BOOL LASreaderQFIT::open(const char* file_name)
{
  if (file_name == 0)
  {
    fprintf(stderr,"ERROR: fine name pointer is zero\n");
    return FALSE;
  }

  // open file

  file = fopen(file_name, "rb");
  if (file == 0)
  {
    fprintf(stderr, "ERROR: cannot open file '%s'\n", file_name);
    return FALSE;
  }

  // create input stream

  ByteStreamIn* in;
  if (IS_LITTLE_ENDIAN())
    in = new ByteStreamInFileLE(file);
  else
    in = new ByteStreamInFileBE(file);

  // clean the header

  header.clean();

  // set projection

  LASvlr_key_entry geo_keys[4];

  // projected coordinates
  geo_keys[0].key_id = 1024; // GTModelTypeGeoKey
  geo_keys[0].tiff_tag_location = 0;
  geo_keys[0].count = 1;
  geo_keys[0].value_offset = 2; // ModelTypeGeographic

  // ellipsoid used with latitude/longitude coordinates
  geo_keys[1].key_id = 2048; // GeographicTypeGeoKey
  geo_keys[1].tiff_tag_location = 0;
  geo_keys[1].count = 1;
  geo_keys[1].value_offset = 4326; // GCS_WGS_84 

  // vertical units
  geo_keys[2].key_id = 4099; // VerticalUnitsGeoKey
  geo_keys[2].tiff_tag_location = 0;
  geo_keys[2].count = 1;
  geo_keys[2].value_offset = 9001; // meter

  // vertical datum
  geo_keys[3].key_id = 4096; // VerticalCSTypeGeoKey
  geo_keys[3].tiff_tag_location = 0;
  geo_keys[3].count = 1;
  geo_keys[3].value_offset = 5030; // VertCS_WGS_84_ellipsoid

  header.set_geo_keys(4, geo_keys);

  // maybe set creation date

#ifdef _WIN32
  WIN32_FILE_ATTRIBUTE_DATA attr;
	SYSTEMTIME creation;
  GetFileAttributesEx(file_name, GetFileExInfoStandard, &attr);
	FileTimeToSystemTime(&attr.ftCreationTime, &creation);
  int startday[13] = {-1, 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334};
  header.file_creation_day = startday[creation.wMonth] + creation.wDay;
  header.file_creation_year = creation.wYear;
  // leap year handling
  if ((((creation.wYear)%4) == 0) && (creation.wMonth > 2)) header.file_creation_day++;
#else
  header.file_creation_day = 333;
  header.file_creation_year = 2011;
#endif

  return open(in);
}
Пример #18
0
static bool path_stat(const char *path, enum stat_mode mode, int32_t *size)
{
#if defined(VITA) || defined(PSP)
   SceIoStat buf;
   char *tmp = strdup(path);
   size_t len = strlen(tmp);
   if (tmp[len-1] == '/')
      tmp[len-1]='\0';

   if (sceIoGetstat(tmp, &buf) < 0)
   {
      free(tmp);
      return false;
   }
   free(tmp);

#elif defined(__CELLOS_LV2__)
    CellFsStat buf;
    if (cellFsStat(path, &buf) < 0)
       return false;
#elif defined(_WIN32)
   WIN32_FILE_ATTRIBUTE_DATA file_info;
   GET_FILEEX_INFO_LEVELS fInfoLevelId = GetFileExInfoStandard;
   DWORD ret = GetFileAttributesEx(path, fInfoLevelId, &file_info);
   if (ret == 0)
      return false;
#else
   struct stat buf;
   if (stat(path, &buf) < 0)
      return false;
#endif

#if defined(_WIN32)
   if (size)
      *size = file_info.nFileSizeLow;
#else
   if (size)
      *size = buf.st_size;
#endif

   switch (mode)
   {
      case IS_DIRECTORY:
#if defined(VITA) || defined(PSP)
         return FIO_S_ISDIR(buf.st_mode);
#elif defined(__CELLOS_LV2__)
         return ((buf.st_mode & S_IFMT) == S_IFDIR);
#elif defined(_WIN32)
         return (file_info.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY);
#else
         return S_ISDIR(buf.st_mode);
#endif
      case IS_CHARACTER_SPECIAL:
#if defined(VITA) || defined(PSP) || defined(__CELLOS_LV2__) || defined(_WIN32)
         return false;
#else
         return S_ISCHR(buf.st_mode);
#endif
      case IS_VALID:
         return true;
   }

   return false;
}
Пример #19
0
/*!
    \internal

    Generates a unique file path and returns a native handle to the open file.
    \a path is used as a template when generating unique paths, \a pos
    identifies the position of the first character that will be replaced in the
    template and \a length the number of characters that may be substituted.

    Returns an open handle to the newly created file if successful, an invalid
    handle otherwise. In both cases, the string in \a path will be changed and
    contain the generated path name.
*/
static bool createFileFromTemplate(NativeFileHandle &file,
        QFileSystemEntry::NativePath &path, size_t pos, size_t length,
        QSystemError &error)
{
    Q_ASSERT(length != 0);
    Q_ASSERT(pos < size_t(path.length()));
    Q_ASSERT(length <= size_t(path.length()) - pos);

    Char *const placeholderStart = (Char *)path.data() + pos;
    Char *const placeholderEnd = placeholderStart + length;

    // Initialize placeholder with random chars + PID.
    {
        Char *rIter = placeholderEnd;

#if defined(QT_BUILD_CORE_LIB)
        quint64 pid = quint64(QCoreApplication::applicationPid());
        do {
            *--rIter = Latin1Char((pid % 10) + '0');
            pid /= 10;
        } while (rIter != placeholderStart && pid != 0);
#endif

        while (rIter != placeholderStart) {
            char ch = char((qrand() & 0xffff) % (26 + 26));
            if (ch < 26)
                *--rIter = Latin1Char(ch + 'A');
            else
                *--rIter = Latin1Char(ch - 26 + 'a');
        }
    }

    for (;;) {
        // Atomically create file and obtain handle
#if defined(Q_OS_WIN)
#  ifndef Q_OS_WINRT
        file = CreateFile((const wchar_t *)path.constData(),
                GENERIC_READ | GENERIC_WRITE,
                FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, CREATE_NEW,
                FILE_ATTRIBUTE_NORMAL, NULL);
#  else // !Q_OS_WINRT
        file = CreateFile2((const wchar_t *)path.constData(),
                GENERIC_READ | GENERIC_WRITE,
                FILE_SHARE_READ | FILE_SHARE_WRITE, CREATE_NEW,
                NULL);
#  endif // Q_OS_WINRT

        if (file != INVALID_HANDLE_VALUE)
            return true;

        DWORD err = GetLastError();
        if (err == ERROR_ACCESS_DENIED) {
            WIN32_FILE_ATTRIBUTE_DATA attributes;
            if (!GetFileAttributesEx((const wchar_t *)path.constData(),
                                     GetFileExInfoStandard, &attributes)
                    || attributes.dwFileAttributes == INVALID_FILE_ATTRIBUTES) {
                // Potential write error (read-only parent directory, etc.).
                error = QSystemError(err, QSystemError::NativeError);
                return false;
            } // else file already exists as a directory.
        } else if (err != ERROR_FILE_EXISTS) {
            error = QSystemError(err, QSystemError::NativeError);
            return false;
        }
#else // POSIX
        file = QT_OPEN(path.constData(),
                QT_OPEN_CREAT | O_EXCL | QT_OPEN_RDWR | QT_OPEN_LARGEFILE,
                0600);

        if (file != -1)
            return true;

        int err = errno;
        if (err != EEXIST) {
            error = QSystemError(err, QSystemError::NativeError);
            return false;
        }
#endif

        /* tricky little algorwwithm for backward compatibility */
        for (Char *iter = placeholderStart;;) {
            // Character progression: [0-9] => 'a' ... 'z' => 'A' .. 'Z'
            // String progression: "ZZaiC" => "aabiC"
            switch (char(*iter)) {
                case 'Z':
                    // Rollover, advance next character
                    *iter = Latin1Char('a');
                    if (++iter == placeholderEnd) {
                        // Out of alternatives. Return file exists error, previously set.
                        error = QSystemError(err, QSystemError::NativeError);
                        return false;
                    }

                    continue;

                case '0': case '1': case '2': case '3': case '4':
                case '5': case '6': case '7': case '8': case '9':
                    *iter = Latin1Char('a');
                    break;

                case 'z':
                    // increment 'z' to 'A'
                    *iter = Latin1Char('A');
                    break;

                default:
                    ++*iter;
                    break;
            }
            break;
        }
    }

    Q_ASSERT(false);
}
Пример #20
0
void OSInterface::getDirInfo(std::string path, std::string pattern){
    WIN32_FIND_DATA data;
    repairPath(path);

    path.append("*");
    std::wstring ppath, whole_name;
    ppath.assign(path.begin(), path.end());
    path.pop_back();
    dirEntryT *de;
    HANDLE hFile = FindFirstFile(ppath.c_str(), &data);

    if  ((hFile == INVALID_HANDLE_VALUE) && (GetLastError() != ERROR_FILE_NOT_FOUND)) return;
    //throw new OSException(path, "Failed to open dir.");
    std::string name, tmpname;
    while(FindNextFile(hFile, &data) != 0 || GetLastError() != ERROR_NO_MORE_FILES)
    {
        de = new dirEntryT();
        whole_name = whole_name = data.cFileName;
        name.assign(whole_name.begin(), whole_name.end());
        tmpname = path + name;
        std::cout << name << std::endl;
        whole_name.assign(tmpname.begin(), tmpname.end());
        de->ext_name = getExtension(name);
        WIN32_FILE_ATTRIBUTE_DATA fileInfo;
        if(!GetFileAttributesEx(whole_name.c_str(), GetFileExInfoStandard, &fileInfo)) continue;
        DWORD ftype = fileInfo.dwFileAttributes;
        if (ftype == INVALID_FILE_ATTRIBUTES) continue;
        // throw new OSException(name, "Invalid file");
        if((name == ".") || name == "..") continue;
        if((!matchExpression(name, pattern)) && !isDir(name)) continue;
        de->name = name;
        if((ftype & FILE_ATTRIBUTE_NORMAL) || (ftype & FILE_ATTRIBUTE_SYSTEM) || (ftype & FILE_ATTRIBUTE_COMPRESSED)){
            de->type = de->FILE;
            de->type_name = "FILE";
        }else if(ftype & FILE_ATTRIBUTE_DIRECTORY){
            de->type = de->DIR;
            de->type_name = "DIR";
        }else if(ftype & FILE_ATTRIBUTE_VIRTUAL){
            de->type = de->LINK;
            de->type_name = "LINK";
        }else{
            de->type = de->UNKNOWN;
            de->type_name = "UNKNOWN";
        }
        if(isArch(de->ext_name)){
            de->type_name = "ARCHIVE";
            de->type = de->ARCHIVE;
        }
        de->byte_size = getSize(name);
        SYSTEMTIME stUTC, stLocal;
        LPTSTR lpszString;
        FileTimeToSystemTime(&fileInfo.ftLastWriteTime, &stUTC);
        SystemTimeToTzSpecificLocalTime(NULL, &stUTC, &stLocal);
        char buf[255];
        sprintf(buf, "%02d.%02d.%d  %02d:%02d",
                stLocal.wDay, stLocal.wMonth, stLocal.wYear,
                stLocal.wHour, stLocal.wMinute);
        de->mod_time = std::string(buf);

        dirs.push_back(de);
    }
    std::sort(dirs.begin(), dirs.end(),[=](dirEntryT *d1, dirEntryT *d2){
        if ((d1->type == d1->DIR) && (d2->type != d2->DIR))
            return true;
        else if ((d1->type != d1->DIR) && (d2->type == d2->DIR))
            return false;
        else
            return d1->name < d2->name; });
}
Пример #21
0
// Populate file info for the specified file in the caller specified memory location
BOOL CreateFileInfo(_In_ PCWSTR pszFullpathToFile, _In_ BOOL fComputeHash, _In_ PFILEINFO pFileInfo)
{
    SB_ASSERT(pszFullpathToFile);
    SB_ASSERT(pFileInfo);

    ZeroMemory(pFileInfo, sizeof(*pFileInfo));

    // Copy file/dir name over to the FILEINFO struct
    PCWSTR pszFilename = CHL_SzGetFilenameFromPath(pszFullpathToFile, wcslen(pszFullpathToFile));
    int nCharsInRoot = 0;
    for (const WCHAR* pch = pszFullpathToFile; pch != pszFilename; ++pch, ++nCharsInRoot)
        ;

    // Copy folder path first (we've calculate the length to copy)
    wcsncpy_s(pFileInfo->szPath, ARRAYSIZE(pFileInfo->szPath), pszFullpathToFile, nCharsInRoot);

    // Now copy the filename
    wcscpy_s(pFileInfo->szFilename, ARRAYSIZE(pFileInfo->szFilename), pszFilename);

    // Check if file is a directory
    // TODO: To extend this limit to 32,767 wide characters, 
    // call the Unicode version of the function and prepend "\\?\" to the path
    WIN32_FILE_ATTRIBUTE_DATA fileAttr;
    if (!GetFileAttributesEx(pszFullpathToFile, GetFileExInfoStandard, &fileAttr))
    {
        logerr(L"Unable to get attributes of file: %s", pszFullpathToFile);
        goto error_return;
    }

    // Store FILETIME in fileinfo for easy comparison in sorting the listview rows
    CopyMemory(&pFileInfo->ftModifiedTime, &fileAttr.ftLastWriteTime, sizeof(pFileInfo->ftModifiedTime));

    // Convert filetime to localtime and store in fileinfo
    SYSTEMTIME stUTC;
    FileTimeToSystemTime(&pFileInfo->ftModifiedTime, &stUTC);
    SystemTimeToTzSpecificLocalTime(NULL, &stUTC, &pFileInfo->stModifiedTime);

    if (fileAttr.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
    {
        pFileInfo->fIsDirectory = TRUE;
    }
    else
    {
        pFileInfo->llFilesize.HighPart = fileAttr.nFileSizeHigh;
        pFileInfo->llFilesize.LowPart = fileAttr.nFileSizeLow;

        if (fComputeHash)
        {
            // Generate hash. Open file handle first...    
            HANDLE hFile = CreateFileW(pszFullpathToFile, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
            if (hFile == INVALID_HANDLE_VALUE)
            {
                logerr(L"Failed to open file %s", pszFullpathToFile);
                goto error_return;
            }

            HRESULT hr = CalculateSHA1(g_hCrypt, hFile, pFileInfo->abHash);
            CloseHandle(hFile);
            if (FAILED(hr))
            {
                logerr(L"Failed to compute hash (0x%08x) for file: %s", hr, pszFullpathToFile);
                goto error_return;
            }
        }
    }

    return TRUE;

error_return:
    return FALSE;
}
STDMETHODIMP CSolidworksCrawlPlugin::HandleFile(BSTR full_path_to_file, IDispatch* event_factory)
{
	// Event factory object to handle the passed in pointer from Google Desktop.
	CComPtr<IGoogleDesktopEventFactory> mcEventFactory;

	// Used to create an event object for this file to send back to Google Desktop.
	CComPtr<IDispatch> mcEventDisp;

	HRESULT hr;

	hr  = event_factory->QueryInterface(&mcEventFactory); // Get the event factory
	if (FAILED(hr))
		return Error(L"No event factory", IID_ISolidworksCrawlPlugin, hr);

	// Replace "Google.Desktop.TextFile" with the appropriate schema for your file.
	hr = mcEventFactory->CreateEvent(CComBSTR(CLSID_SolidworksCrawlPlugin),
		CComBSTR(L"Google.Desktop.TextFile"), &mcEventDisp);
	if (FAILED(hr))
		return Error(L"Unable to create event", IID_ISolidworksCrawlPlugin, hr);

	CComQIPtr<IGoogleDesktopEvent> mcEvent(mcEventDisp);

	ATLASSERT(mcEventDisp && mcEvent);
	if (mcEvent == NULL)
		return Error(L"Event does not implement IGoogleDesktopEvent", IID_ISolidworksCrawlPlugin, E_UNEXPECTED);

	// Get indexable content from the file.
	// Set the event object's properties.
	// Send the event object to Google Desktop.

	WIN32_FIND_DATA wfd;
	if (!GetFileAttributesEx(full_path_to_file, GetFileExInfoStandard, &wfd))
		return HRESULT_FROM_WIN32(::GetLastError());

	SYSTEMTIME systemTime;
	FileTimeToSystemTime(&wfd.ftCreationTime, &systemTime);

	// convert the date to the variant format
	double varDate;
	SystemTimeToVariantTime(&systemTime, &varDate);

	hr = mcEvent->AddProperty(CComBSTR(L"uri"), CComVariant(full_path_to_file));
	if (FAILED(hr))
		return Error(L"AddProperty uri failed", IID_ISolidworksCrawlPlugin, hr);

	hr = mcEvent->AddProperty(CComBSTR(L"last_modified_time"), CComVariant(varDate, VT_DATE));
	if (FAILED(hr))
		return Error(L"AddProperty last_modified_time failed", IID_ISolidworksCrawlPlugin, hr);

	hr = mcEvent->AddProperty(CComBSTR(L"format"), CComVariant("text/plain"));
	if (FAILED(hr))
		return Error(L"AddProperty format failed", IID_ISolidworksCrawlPlugin, hr);

	// Initialize COM and create an instance of the InterfaceImplementation class:
	IManagedInterface *cpi = NULL;
	hr = CoCreateInstance(CLSID_IFilterFileReader,
		NULL, CLSCTX_INPROC_SERVER,
		IID_IManagedInterface, reinterpret_cast<void**>(&cpi));
	if (FAILED(hr))
	{
		return Error(L"Couldn't create the instanced", IID_ISolidworksCrawlPlugin, hr);
	}

	hr = cpi->loadFile(full_path_to_file);
	if (FAILED(hr))
	{
		return Error(L"Couldn't loadFile", IID_ISolidworksCrawlPlugin, hr);
	}

	hr = mcEvent->AddProperty(CComBSTR(L"content"), CComVariant(cpi->readFile().GetBSTR()));
	if (FAILED(hr))
		return Error(L"AddProperty content failed", IID_ISolidworksCrawlPlugin, hr);

	cpi->Release();
	cpi = NULL;

	hr = mcEvent->Send(EventFlagIndexable);
	if (FAILED(hr))
		return Error(L"Send failed", IID_ISolidworksCrawlPlugin, hr);

	return hr;
}
Пример #23
0
/*
========================
idSaveGameThread::Enumerate
========================
*/
int idSaveGameThread::Enumerate() {
	idSaveLoadParms * callback = data.saveLoadParms;
	idStr saveFolder = "savegame";

	callback->detailList.Clear();

	int ret = ERROR_SUCCESS;
	if ( fileSystem->IsFolder( saveFolder, "fs_savePath" ) == FOLDER_YES ) {
		idFileList * files = fileSystem->ListFilesTree( saveFolder, SAVEGAME_DETAILS_FILENAME );
		const idStrList & fileList = files->GetList();

		for ( int i = 0; i < fileList.Num() && !callback->cancelled; i++ ) {
			idSaveGameDetails * details = callback->detailList.Alloc();
			// We have more folders on disk than we have room in our save detail list, stop trying to read them in and continue with what we have
			if ( details == NULL ) {
				break;
			}
			idStr directory = fileList[i];

			idFile * file = fileSystem->OpenFileRead( directory.c_str() );

			if ( file != NULL ) {
				// Read the DETAIL file for the enumerated data
				if ( callback->mode & SAVEGAME_MBF_READ_DETAILS ) {
					if ( !SavegameReadDetailsFromFile( file, *details ) ) {
						details->damaged = true;
						ret = -1;
					}
				}

				// Use the date from the directory
				WIN32_FILE_ATTRIBUTE_DATA attrData;
				BOOL attrRet = GetFileAttributesEx( file->GetFullPath(), GetFileExInfoStandard, &attrData );
				delete file;
				if ( attrRet == TRUE ) {
					FILETIME		lastWriteTime = attrData.ftLastWriteTime;
					const ULONGLONG second = 10000000L; // One second = 10,000,000 * 100 nsec
					SYSTEMTIME		base_st = { 1970, 1, 0, 1, 0, 0, 0, 0 };
					ULARGE_INTEGER	itime;
					FILETIME		base_ft;
					BOOL			success = SystemTimeToFileTime( &base_st, &base_ft );

					itime.QuadPart = ((ULARGE_INTEGER *)&lastWriteTime)->QuadPart;
					if ( success ) {
						itime.QuadPart -= ((ULARGE_INTEGER *)&base_ft)->QuadPart;
					} else {
						// Hard coded number of 100-nanosecond units from 1/1/1601 to 1/1/1970
						itime.QuadPart -= 116444736000000000LL;
					}
					itime.QuadPart /= second;
					details->date = itime.QuadPart;
				}
			} else {
				details->damaged = true;
			}

			// populate the game details struct
			directory = directory.StripFilename();
			details->slotName = directory.c_str() + saveFolder.Length() + 1; // Strip off the prefix too
// JDC: I hit this all the time			assert( fileSystem->IsFolder( directory.c_str(), "fs_savePath" ) == FOLDER_YES );
		}
		fileSystem->FreeFileList( files );
	} else {
		callback->errorCode = SAVEGAME_E_FOLDER_NOT_FOUND;
		ret = -3;
	}

	if ( data.saveLoadParms->cancelled ) {
		data.saveLoadParms->errorCode = SAVEGAME_E_CANCELLED;
	}

	return ret;
}
Пример #24
0
bool MakeZip(TCHAR *tszSource, TCHAR *tszDest, TCHAR *dbname, HWND progress_dialog)
{
    bool ret = false;
    HANDLE hSrc;
    zipFile hZip;
    SYSTEMTIME st;
    WIN32_FILE_ATTRIBUTE_DATA fad = { 0 };
    zip_fileinfo fi = { 0 };
    HWND hProgBar;
    DWORD dwRead;
    MSG msg;
    char buf[(256 * 1024)];	// 256 KB
    DWORDLONG dwSrcFileSize, dwTotalBytes = 0;

    ptrA szSourceName(mir_u2a(dbname));
    ptrT tszDestPath(DoubleSlash(tszDest));

    hSrc = CreateFile(tszSource, GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
    if (hSrc == INVALID_HANDLE_VALUE)
        return ret;
    if (GetFileAttributesEx(tszSource, GetFileExInfoStandard, &fad) == FALSE)
        goto err_out;
    dwSrcFileSize = ((DWORDLONG)fad.nFileSizeLow | (((DWORDLONG)fad.nFileSizeHigh) << 32));
    if (dwSrcFileSize == 0) /* Prevent division by zero error. */
        goto err_out;
    FileTimeToLocalFileTime(&fad.ftLastWriteTime, &fad.ftLastWriteTime);
    FileTimeToSystemTime(&fad.ftLastWriteTime, &st);
    hZip = zipOpen2_64(tszDestPath, APPEND_STATUS_CREATE, NULL, NULL);
    if (hZip == NULL)
        goto err_out;
    fi.tmz_date.tm_sec = st.wSecond;
    fi.tmz_date.tm_min = st.wMinute;
    fi.tmz_date.tm_hour = st.wHour;
    fi.tmz_date.tm_mday = st.wDay;
    fi.tmz_date.tm_mon = (st.wMonth - 1);
    fi.tmz_date.tm_year = st.wYear;

    if (zipOpenNewFileInZip(hZip, szSourceName, &fi, NULL, 0, NULL, 0, "", Z_DEFLATED, Z_BEST_COMPRESSION) == ZIP_OK) {
        hProgBar = GetDlgItem(progress_dialog, IDC_PROGRESS);
        while (GetWindowLongPtr(progress_dialog, GWLP_USERDATA) != 1) {
            if (!ReadFile(hSrc, buf, sizeof(buf), &dwRead, NULL))
                break;
            if (dwRead == 0) { // EOF
                ret = true;
                break;
            }
            if (zipWriteInFileInZip(hZip, buf, dwRead) != ZIP_OK)
                break;
            dwTotalBytes += dwRead;
            SendMessage(hProgBar, PBM_SETPOS, (WPARAM)((100 * dwTotalBytes) / dwSrcFileSize), 0);
            while (PeekMessage(&msg, progress_dialog, 0, 0, PM_REMOVE) != 0) {
                if (progress_dialog == NULL || !IsDialogMessage(progress_dialog, &msg)) { /* Wine fix. */
                    TranslateMessage(&msg);
                    DispatchMessage(&msg);
                }
            }
        }
        zipCloseFileInZip(hZip);
    }
    if (ret) {
        mir_snprintf(buf, "%s\r\n%s %s %d.%d.%d.%d\r\n",
                     Translate("Miranda NG database"), Translate("Created by:"),
                     __PLUGIN_NAME, __MAJOR_VERSION, __MINOR_VERSION, __RELEASE_NUM, __BUILD_NUM);
    }
    else {
        buf[0] = 0;
    }
    zipClose(hZip, buf);

err_out:
    CloseHandle(hSrc);

    return ret;
}
bool FileUtils::createDirectory(const std::string& path)
{
    CCASSERT(!path.empty(), "Invalid path");

    if (isDirectoryExist(path))
        return true;

    // Split the path
    size_t start = 0;
    size_t found = path.find_first_of("/\\", start);
    std::string subpath;
    std::vector<std::string> dirs;

    if (found != std::string::npos)
    {
        while (true)
        {
            subpath = path.substr(start, found - start + 1);
            if (!subpath.empty())
                dirs.push_back(subpath);
            start = found+1;
            found = path.find_first_of("/\\", start);
            if (found == std::string::npos)
            {
                if (start < path.length())
                {
                    dirs.push_back(path.substr(start));
                }
                break;
            }
        }
    }


#if (CC_TARGET_PLATFORM == CC_PLATFORM_WP8) || (CC_TARGET_PLATFORM == CC_PLATFORM_WINRT)
    WIN32_FILE_ATTRIBUTE_DATA wfad;
    std::wstring wpath(path.begin(), path.end());
    if (!(GetFileAttributesEx(wpath.c_str(), GetFileExInfoStandard, &wfad)))
    {
        subpath = "";
        for(unsigned int i = 0 ; i < dirs.size() ; ++i)
        {
            subpath += dirs[i];
            if (i > 0 && !isDirectoryExist(subpath))
            {
                std::wstring wsubpath(subpath.begin(), subpath.end());
                BOOL ret = CreateDirectory(wsubpath.c_str(), NULL);
                if (!ret && ERROR_ALREADY_EXISTS != GetLastError())
                {
                    return false;
                }
            }
        }
    }
    return true;
#elif (CC_TARGET_PLATFORM == CC_PLATFORM_WIN32)
    if ((GetFileAttributesA(path.c_str())) == INVALID_FILE_ATTRIBUTES)
    {
        subpath = "";
        for (int i = 0; i < dirs.size(); ++i)
        {
            subpath += dirs[i];
            if (!isDirectoryExist(subpath))
            {
                BOOL ret = CreateDirectoryA(subpath.c_str(), NULL);
                if (!ret && ERROR_ALREADY_EXISTS != GetLastError())
                {
                    return false;
                }
            }
        }
    }
    return true;
#else
    DIR *dir = NULL;

    // Create path recursively
    subpath = "";
    for (int i = 0; i < dirs.size(); ++i)
    {
        subpath += dirs[i];
        dir = opendir(subpath.c_str());

        if (!dir)
        {
            // directory doesn't exist, should create a new one

            int ret = mkdir(subpath.c_str(), S_IRWXU | S_IRWXG | S_IRWXO);
            if (ret != 0 && (errno != EEXIST))
            {
                // current directory can not be created, sub directories can not be created too
                // should return
                return false;
            }
        }
        else
        {
            // directory exists, should close opened dir
            closedir(dir);
        }
    }
    return true;
#endif
}
bool LASreaderSHP::open(const char* file_name)
{
  if (file_name == 0)
  {
    fprintf(stderr,"ERROR: fine name pointer is zero\n");
    return FALSE;
  }

  clean();

  file = fopen_compressed(file_name, "rb", &piped);
  if (file == 0)
  {
    fprintf(stderr, "ERROR: cannot open file '%s'\n", file_name);
    return FALSE;
  }

  // clean the header

  header.clean();

  // populate the header as much as it makes sense

  sprintf(header.system_identifier, "LAStools (c) by rapidlasso GmbH");
  sprintf(header.generating_software, "via LASreaderSHP (%d)", LAS_TOOLS_VERSION);

  // maybe set creation date

#ifdef _WIN32
  WIN32_FILE_ATTRIBUTE_DATA attr;
	SYSTEMTIME creation;
  GetFileAttributesEx(file_name, GetFileExInfoStandard, &attr);
	FileTimeToSystemTime(&attr.ftCreationTime, &creation);
  int startday[13] = {-1, 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334};
  header.file_creation_day = startday[creation.wMonth] + creation.wDay;
  header.file_creation_year = creation.wYear;
  // leap year handling
  if ((((creation.wYear)%4) == 0) && (creation.wMonth > 2)) header.file_creation_day++;
#else
  header.file_creation_day = 111;
  header.file_creation_year = 2011;
#endif

  header.point_data_format = 0;
  header.point_data_record_length = 20;

  // initialize point

  point.init(&header, header.point_data_format, header.point_data_record_length);

  // read SHP header and populate the LAS header with the bounding box

  int int_input;
  if (fread(&int_input, sizeof(int), 1, file) != 1) return false; // file code (BIG)
  from_big_endian(&int_input); 
  if (int_input != 9994)
  {
    fprintf(stderr, "ERROR: wrong shapefile code %d != 9994\n", int_input);
    return FALSE;
  }
  if (fread(&int_input, sizeof(int), 1, file) != 1) return false; // unused (BIG)
  if (fread(&int_input, sizeof(int), 1, file) != 1) return false; // unused (BIG)
  if (fread(&int_input, sizeof(int), 1, file) != 1) return false; // unused (BIG)
  if (fread(&int_input, sizeof(int), 1, file) != 1) return false; // unused (BIG)
  if (fread(&int_input, sizeof(int), 1, file) != 1) return false; // unused (BIG)
  if (fread(&int_input, sizeof(int), 1, file) != 1) return false; // file length (BIG)
  from_big_endian(&int_input); 
  int file_length = int_input;
  if (fread(&int_input, sizeof(int), 1, file) != 1) return false; // version (LITTLE)
  from_little_endian(&int_input); 
  if (int_input != 1000)
  {
    fprintf(stderr, "ERROR: wrong shapefile version %d != 1000\n", int_input);
    return FALSE;
  }
  if (fread(&int_input, sizeof(int), 1, file) != 1) return false; // shape type (LITTLE)
  from_little_endian(&int_input); 
  shape_type = int_input;
  if (shape_type != 1 && shape_type != 11 && shape_type != 21 && shape_type != 8 && shape_type != 18 && shape_type != 28)
  {
    fprintf(stderr, "ERROR: wrong shape type %d != 1,11,21,8,18,28\n", shape_type);
    return FALSE;
  }
  double double_input;
  if (fread(&double_input, sizeof(double), 1, file) != 1) return false; // xmin (LITTLE)
  from_little_endian(&double_input);
  header.min_x = double_input;
  if (fread(&double_input, sizeof(double), 1, file) != 1) return false; // ymin (LITTLE)
  from_little_endian(&double_input); 
  header.min_y = double_input;
  if (fread(&double_input, sizeof(double), 1, file) != 1) return false; // xmax (LITTLE)
  from_little_endian(&double_input); 
  header.max_x = double_input;
  if (fread(&double_input, sizeof(double), 1, file) != 1) return false; // ymax (LITTLE)
  from_little_endian(&double_input); 
  header.max_y = double_input;
  if (fread(&double_input, sizeof(double), 1, file) != 1) return false; // zmin (LITTLE)
  from_little_endian(&double_input); 
  header.min_z = double_input;
  if (fread(&double_input, sizeof(double), 1, file) != 1) return false; // zmax (LITTLE)
  from_little_endian(&double_input); 
  header.max_z = double_input;
  if (fread(&double_input, sizeof(double), 1, file) != 1) return false; // mmin (LITTLE)
  from_little_endian(&double_input); 
  if (fread(&double_input, sizeof(double), 1, file) != 1) return false; // mmax (LITTLE)
  from_little_endian(&double_input); 

  // maybe calculate npoints

  if (shape_type == 1)
  {
    npoints = (file_length-50)/(14);
  }
  else if (shape_type == 11)
  {
    npoints = (file_length-50)/(22);
  }
  else if (shape_type == 21)
  {
    npoints = (file_length-50)/(18);
  }
  else if (shape_type == 8)
  {
    npoints = (file_length-50-20)/(8); // over-estimate (assumes all in one record)
  }
  else if (shape_type == 18)
  {
    npoints = (file_length-50-36)/(16); // over-estimate (assumes all in one record)
  }
  else if (shape_type == 28)
  {
    npoints = (file_length-50-28)/(12); // over-estimate (assumes all in one record)
  }
  header.number_of_point_records = (U32)npoints;
  header.number_of_points_by_return[0] = (U32)npoints;

  // figure out the right scale factor and offset

  populate_scale_and_offset();

  // populate the quantized bounding box

  populate_bounding_box();
  
  p_count = 0;

  return TRUE;
}
Пример #27
0
void  CUnkownReport::ProcessNewFile()
{
    WIN32_FILE_ATTRIBUTE_DATA   fdata;

    while( 1 )
    {
        CReportFile rfile;
        HANDLE  hFile = INVALID_HANDLE_VALUE;

        if ( PopHeadSubmitFile( rfile ) )
        {
            if ( CheckInReportList( rfile ) )
            {
                continue;
            }

            if ( CheckInDB( rfile ) )
            {
                if ( enumFileReported == rfile.m_nReportState )
                {
                    continue;
                }
            }
        }
        else
        {
            return;
        }

        {
            CObjGuard   guard( m_reportLock );

            // 将新文件记入数据库
            if ( ( rfile.m_nTrack & FILE_TRACK_QUARANTINE ) )
            {   
                Skylark::BKBAK_BACKUP_INFO  info;

                if ( GetBackupFileAttributes( rfile.m_strFilePath, info ) )
                {
                    rfile.SetCreateTime( info.uCRC32 );
                    rfile.m_nFileSize = ( int )info.nFileSizeLow;
                }
                else
                {
                    rfile.SetCreateTime( 0 );
                    rfile.m_nFileSize = 0;
                }
                
                rfile.m_nReportState = enumFileNotReport;
                rfile.m_nRescanState = enumFileRescaned;    // 隔离的文件不需要rescan

                m_reportFileDB.AddFileInfo( rfile );
                m_reportLowList.AddTail( rfile );
            }
            else if ( GetFileAttributesEx( rfile.m_strFilePath, GetFileExInfoStandard, &fdata ) )
            {
                rfile.SetCreateTime( fdata.ftLastWriteTime );
                rfile.m_nFileSize = fdata.nFileSizeLow;
                rfile.m_nReportState = enumFileNotReport;
                rfile.m_nRescanState = enumFileNeedRescan;

                m_reportFileDB.AddFileInfo( rfile );
                if ( rfile.m_nFileSize < REPORT_MAX_HIGH_LEVEL_SIZE )
                {
                    m_reportHighList.AddTail( rfile );
                }
                else if ( rfile.m_nFileSize < REPORT_MAX_MID_LEVEL_SIZE )
                {
                    m_reportMidList.AddTail( rfile );
                }
                else
                {
                    m_reportLowList.AddTail( rfile );
                }
            }
        }
    }
}
Пример #28
0
static dvdid_status_t detect_medium_win32(const char *path, const  dvdid__medium_spec_t *const *spec_first, dvdid_medium_t *medium, int *errn) {

  HANDLE file_list;
  WIN32_FIND_DATAW data;
  WIN32_FILE_ATTRIBUTE_DATA file_info;
  WCHAR *path_wide, *specpath_wide, *tmppath_wide;
  BOOL b;
  int l;
  size_t s;

  int identified;
  const dvdid__medium_spec_t *const *spec;

  dvdid_status_t rv;


  rv = DVDID_STATUS_OK;

  do {

    l = MultiByteToWideChar(CP_UTF8, 0, path, -1, NULL, 0);

    path_wide = calloc(l, sizeof(*path_wide));

    if (path_wide == NULL) {
      rv = DVDID_STATUS_MALLOC_ERROR;
      if (errn != NULL) { *errn = 0; }
      break;
    }

    MultiByteToWideChar(CP_UTF8, 0, path, -1, path_wide, l);

    do {

      /* First prove that we can read entries from the path specified, so that we can give a useful error message */
      /* We don't look at the entries we read here, using stat later instead, to avoid case issues */

      s = wcslen(path_wide) + wcslen(W_DIR_SEP) + wcslen(W_DIR_SEP L"*") + 1;

      tmppath_wide = calloc(s, sizeof(*tmppath_wide));

      if (tmppath_wide == NULL) {
        rv = DVDID_STATUS_MALLOC_ERROR;
        if (errn != NULL) { *errn = 0; }
        break;
      }

      _snwprintf(tmppath_wide, s, L"%s" W_DIR_SEP L"*", path_wide);

      file_list = FindFirstFileW(tmppath_wide, &data);

      if (file_list == INVALID_HANDLE_VALUE) {
        rv = DVDID_STATUS_DETECT_MEDIUM_ERROR;
        if (errn != NULL) { *errn = GetLastErrorToErrno(GetLastError()); }
        break;
      }

      do {
        /* NOTHING */
      } while (FindNextFileW(file_list, &data));

      FindClose(file_list);


      /* Now try to detect which medium it is */

      identified = 0;

      for (spec = spec_first; *spec != NULL; spec++) {

        l = MultiByteToWideChar(CP_UTF8, 0, (*spec)->dir[0].path, -1, NULL, 0);
        specpath_wide = calloc(l, sizeof(*specpath_wide));

        if (specpath_wide == NULL) {
          rv = DVDID_STATUS_MALLOC_ERROR;
          if (errn != NULL) { *errn = 0; }
          break;
        }

        MultiByteToWideChar(CP_UTF8, 0, (*spec)->dir[0].path, -1, specpath_wide, l);

        do {

          s = wcslen(path_wide) + wcslen(W_DIR_SEP) + wcslen(specpath_wide) + 1;

          tmppath_wide = calloc(s, sizeof(*tmppath_wide));

          if (tmppath_wide == NULL) {
            rv = DVDID_STATUS_MALLOC_ERROR;
            if (errn != NULL) { *errn = 0; }
            break;
          }

          _snwprintf(tmppath_wide, s, L"%s" W_DIR_SEP L"%s", path_wide, specpath_wide);

          b = GetFileAttributesEx(tmppath_wide, GetFileExInfoStandard, &file_info);

          if (b && ((file_info.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) != 0)) {
            identified = 1;
            if (medium != NULL) { *medium = (*spec)->medium; }
            break;
          }

        } while(0);

        free(specpath_wide);

        if (identified || rv != DVDID_STATUS_OK) { break; }

      }

      /* Failed to detect medium, but no other errors */
      if (!identified && rv == DVDID_STATUS_OK) {
        rv = DVDID_STATUS_MEDIUM_UNKNOWN;
        if (errn != NULL) { *errn = 0; }
      }

    } while(0);

    free(path_wide);

  } while(0);

  return rv;

}
Пример #29
0
REQUEST_NOTIFICATION_STATUS
CMyHttpModule::OnBeginRequest(
    IN IHttpContext * pHttpContext,
    IN IHttpEventProvider * pProvider
)
{
    HRESULT                         hr                  = S_OK;
    IHttpRequest*                   pRequest            = NULL;
	MODSECURITY_STORED_CONTEXT*		pConfig = NULL;
    
    UNREFERENCED_PARAMETER ( pProvider );

	EnterCriticalSection(&m_csLock);

    if ( pHttpContext == NULL ) 
    {
        hr = E_UNEXPECTED;
        goto Finished;
    }

    pRequest = pHttpContext->GetRequest();

    if ( pRequest == NULL )
    {
        hr = E_UNEXPECTED;
        goto Finished;
    }

    hr = MODSECURITY_STORED_CONTEXT::GetConfig(pHttpContext, &pConfig );
    
    if ( FAILED( hr ) )
    {
        //hr = E_UNEXPECTED;
		hr = S_OK;
        goto Finished;
    }

	// If module is disabled, dont go any further
	//
	if( pConfig->GetIsEnabled() == false )
	{
        goto Finished;
	}

	// every 3 seconds we check for changes in config file
	//
	DWORD ctime = GetTickCount();

	if(pConfig->m_Config == NULL || (ctime - pConfig->m_dwLastCheck) > 3000)
	{
		char *path;
		USHORT pathlen;

		hr = pConfig->GlobalWideCharToMultiByte(pConfig->GetPath(), wcslen(pConfig->GetPath()), &path, &pathlen);

		if ( FAILED( hr ) )
		{
			hr = E_UNEXPECTED;
			goto Finished;
		}

		WIN32_FILE_ATTRIBUTE_DATA fdata;
		BOOL ret;

		ret = GetFileAttributesEx(path, GetFileExInfoStandard, &fdata);

		pConfig->m_dwLastCheck = ctime;

		if(pConfig->m_Config == NULL || (ret != 0 && (pConfig->m_LastChange.dwLowDateTime != fdata.ftLastWriteTime.dwLowDateTime ||
			pConfig->m_LastChange.dwHighDateTime != fdata.ftLastWriteTime.dwHighDateTime)))
		{
			pConfig->m_LastChange.dwLowDateTime = fdata.ftLastWriteTime.dwLowDateTime;
			pConfig->m_LastChange.dwHighDateTime = fdata.ftLastWriteTime.dwHighDateTime;

			pConfig->m_Config = modsecGetDefaultConfig();

			PCWSTR servpath = pHttpContext->GetApplication()->GetApplicationPhysicalPath();
			char *apppath;
			USHORT apppathlen;

			hr = pConfig->GlobalWideCharToMultiByte((WCHAR *)servpath, wcslen(servpath), &apppath, &apppathlen);

			if ( FAILED( hr ) )
			{
				delete path;
				hr = E_UNEXPECTED;
				goto Finished;
			}

			if(path[0] != 0)
			{
				const char * err = modsecProcessConfig((directory_config *)pConfig->m_Config, path, apppath);

				if(err != NULL)
				{
					WriteEventViewerLog(err, EVENTLOG_ERROR_TYPE);
					delete apppath;
					delete path;
					goto Finished;
				}
			}
			delete apppath;
		}
		delete path;
	}

	conn_rec *c;
	request_rec *r;

	c = modsecNewConnection();

	modsecProcessConnection(c);

	r = modsecNewRequest(c, (directory_config *)pConfig->m_Config);

	// on IIS we force input stream inspection flag, because its absence does not add any performance gain
	// it's because on IIS request body must be restored each time it was read
	//
	modsecSetConfigForIISRequestBody(r);

	REQUEST_STORED_CONTEXT *rsc = new REQUEST_STORED_CONTEXT();

	rsc->m_pConnRec = c;
	rsc->m_pRequestRec = r;
	rsc->m_pHttpContext = pHttpContext;
	rsc->m_pProvider = pProvider;

	pHttpContext->GetModuleContextContainer()->SetModuleContext(rsc, g_pModuleContext);

	StoreIISContext(r, rsc);

	HTTP_REQUEST *req = pRequest->GetRawHttpRequest();

	r->hostname = ConvertUTF16ToUTF8(req->CookedUrl.pHost, req->CookedUrl.HostLength / sizeof(WCHAR), r->pool);
	r->path_info = ConvertUTF16ToUTF8(req->CookedUrl.pAbsPath, req->CookedUrl.AbsPathLength / sizeof(WCHAR), r->pool);

	if(r->hostname == NULL)
	{
		if(req->Headers.KnownHeaders[HttpHeaderHost].pRawValue != NULL)
			r->hostname = ZeroTerminate(req->Headers.KnownHeaders[HttpHeaderHost].pRawValue,
										req->Headers.KnownHeaders[HttpHeaderHost].RawValueLength, r->pool);
	}

	int port = 0;
	char *port_str = NULL;

	if(r->hostname != NULL)
	{
		int k = 0;
		char *ptr = (char *)r->hostname;

		while(*ptr != 0 && *ptr != ':')
			ptr++;

		if(*ptr == ':')
		{
			*ptr = 0;
			port_str = ptr + 1;
			port = atoi(port_str);
		}
	}

	if(req->CookedUrl.pQueryString != NULL && req->CookedUrl.QueryStringLength > 0)
		r->args = ConvertUTF16ToUTF8(req->CookedUrl.pQueryString + 1, (req->CookedUrl.QueryStringLength / sizeof(WCHAR)) - 1, r->pool);

#define _TRANSHEADER(id,str) if(req->Headers.KnownHeaders[id].pRawValue != NULL) \
	{\
		apr_table_setn(r->headers_in, str, \
			ZeroTerminate(req->Headers.KnownHeaders[id].pRawValue, req->Headers.KnownHeaders[id].RawValueLength, r->pool)); \
	}

    _TRANSHEADER(HttpHeaderCacheControl, "Cache-Control");
    _TRANSHEADER(HttpHeaderConnection, "Connection");
    _TRANSHEADER(HttpHeaderDate, "Date");
    _TRANSHEADER(HttpHeaderKeepAlive, "Keep-Alive");             
    _TRANSHEADER(HttpHeaderPragma, "Pragma");                
    _TRANSHEADER(HttpHeaderTrailer, "Trailer");               
    _TRANSHEADER(HttpHeaderTransferEncoding, "Transfer-Encoding");      
    _TRANSHEADER(HttpHeaderUpgrade, "Upgrade");               
    _TRANSHEADER(HttpHeaderVia, "Via");                   
    _TRANSHEADER(HttpHeaderWarning, "Warning");               
    _TRANSHEADER(HttpHeaderAllow, "Allow");                 
    _TRANSHEADER(HttpHeaderContentLength, "Content-Length");         
    _TRANSHEADER(HttpHeaderContentType, "Content-Type");           
    _TRANSHEADER(HttpHeaderContentEncoding, "Content-Encoding");       
    _TRANSHEADER(HttpHeaderContentLanguage, "Content-Language");       
    _TRANSHEADER(HttpHeaderContentLocation, "Content-Location");       
    _TRANSHEADER(HttpHeaderContentMd5, "Content-Md5");            
    _TRANSHEADER(HttpHeaderContentRange, "Content-Range");          
    _TRANSHEADER(HttpHeaderExpires, "Expires");               
    _TRANSHEADER(HttpHeaderLastModified, "Last-Modified");          
    _TRANSHEADER(HttpHeaderAccept, "Accept");                
    _TRANSHEADER(HttpHeaderAcceptCharset, "Accept-Charset");        
    _TRANSHEADER(HttpHeaderAcceptEncoding, "Accept-Encoding");        
    _TRANSHEADER(HttpHeaderAcceptLanguage, "Accept-Language");        
    _TRANSHEADER(HttpHeaderAuthorization, "Authorization");         
    _TRANSHEADER(HttpHeaderCookie, "Cookie");                
    _TRANSHEADER(HttpHeaderExpect, "Expect");                
    _TRANSHEADER(HttpHeaderFrom, "From");                  
    _TRANSHEADER(HttpHeaderHost, "Host");                  
    _TRANSHEADER(HttpHeaderIfMatch, "If-Match");               
    _TRANSHEADER(HttpHeaderIfModifiedSince, "If-Modified-Since");       
    _TRANSHEADER(HttpHeaderIfNoneMatch, "If-None-Match");           
    _TRANSHEADER(HttpHeaderIfRange, "If-Range");               
    _TRANSHEADER(HttpHeaderIfUnmodifiedSince, "If-Unmodified-Since");     
    _TRANSHEADER(HttpHeaderMaxForwards, "Max-Forwards");           
    _TRANSHEADER(HttpHeaderProxyAuthorization, "Proxy-Authorization");    
    _TRANSHEADER(HttpHeaderReferer, "Referer");               
    _TRANSHEADER(HttpHeaderRange, "Range");                 
    _TRANSHEADER(HttpHeaderTe, "TE");                    
    _TRANSHEADER(HttpHeaderTranslate, "Translate");             
    _TRANSHEADER(HttpHeaderUserAgent, "User-Agent");

#undef _TRANSHEADER

	for(int i = 0; i < req->Headers.UnknownHeaderCount; i++)
	{
		apr_table_setn(r->headers_in, 
			ZeroTerminate(req->Headers.pUnknownHeaders[i].pName, req->Headers.pUnknownHeaders[i].NameLength, r->pool), 
			ZeroTerminate(req->Headers.pUnknownHeaders[i].pRawValue, req->Headers.pUnknownHeaders[i].RawValueLength, r->pool));
	}

	r->content_encoding = apr_table_get(r->headers_in, "Content-Encoding");
	r->content_type = apr_table_get(r->headers_in, "Content-Type");

	const char *lng = apr_table_get(r->headers_in, "Content-Languages");

	if(lng != NULL)
	{
		r->content_languages = apr_array_make(r->pool, 1, sizeof(const char *));

		*(const char **)apr_array_push(r->content_languages) = lng;
	}

	switch(req->Verb)
	{
	case HttpVerbUnparsed:
	case HttpVerbUnknown:
	case HttpVerbInvalid:
    case HttpVerbTRACK:  // used by Microsoft Cluster Server for a non-logged trace
    case HttpVerbSEARCH:
	default:
		r->method = "INVALID";
		r->method_number = M_INVALID;
		break;
	case HttpVerbOPTIONS:
		r->method = "OPTIONS";
		r->method_number = M_OPTIONS;
		break;
	case HttpVerbGET:
	case HttpVerbHEAD:
		r->method = "GET";
		r->method_number = M_GET;
		break;
	case HttpVerbPOST:
		r->method = "POST";
		r->method_number = M_POST;
		break;
    case HttpVerbPUT:
		r->method = "PUT";
		r->method_number = M_PUT;
		break;
    case HttpVerbDELETE:
		r->method = "DELETE";
		r->method_number = M_DELETE;
		break;
    case HttpVerbTRACE:
		r->method = "TRACE";
		r->method_number = M_TRACE;
		break;
    case HttpVerbCONNECT:
		r->method = "CONNECT";
		r->method_number = M_CONNECT;
		break;
    case HttpVerbMOVE:
		r->method = "MOVE";
		r->method_number = M_MOVE;
		break;
    case HttpVerbCOPY:
		r->method = "COPY";
		r->method_number = M_COPY;
		break;
    case HttpVerbPROPFIND:
		r->method = "PROPFIND";
		r->method_number = M_PROPFIND;
		break;
    case HttpVerbPROPPATCH:
		r->method = "PROPPATCH";
		r->method_number = M_PROPPATCH;
		break;
    case HttpVerbMKCOL:
		r->method = "MKCOL";
		r->method_number = M_MKCOL;
		break;
    case HttpVerbLOCK:
		r->method = "LOCK";
		r->method_number = M_LOCK;
		break;
    case HttpVerbUNLOCK:
		r->method = "UNLOCK";
		r->method_number = M_UNLOCK;
		break;
	}

	if(HTTP_EQUAL_VERSION(req->Version, 0, 9))
		r->protocol = "HTTP/0.9";
	else if(HTTP_EQUAL_VERSION(req->Version, 1, 0))
		r->protocol = "HTTP/1.0";
	else
		r->protocol = "HTTP/1.1";

	r->request_time = apr_time_now();

	r->parsed_uri.scheme = "http";
	r->parsed_uri.path = r->path_info;
	r->parsed_uri.hostname = (char *)r->hostname;
	r->parsed_uri.is_initialized = 1;
	r->parsed_uri.port = port;
	r->parsed_uri.port_str = port_str;
	r->parsed_uri.query = r->args;
	r->parsed_uri.dns_looked_up = 0;
	r->parsed_uri.dns_resolved = 0;
	r->parsed_uri.password = NULL;
	r->parsed_uri.user = NULL;
	r->parsed_uri.fragment = NULL;

	r->unparsed_uri = ZeroTerminate(req->pRawUrl, req->RawUrlLength, r->pool);
	r->uri = r->unparsed_uri;

	r->the_request = (char *)apr_palloc(r->pool, strlen(r->method) + 1 + req->RawUrlLength + 1 + strlen(r->protocol) + 1);

	strcpy(r->the_request, r->method);
	strcat(r->the_request, " ");
	strcat(r->the_request, r->uri);
	strcat(r->the_request, " ");
	strcat(r->the_request, r->protocol);

	HTTP_REQUEST_ID httpRequestID;
	char *pszValue = (char *)apr_palloc(r->pool, 24);

	httpRequestID = pRequest->GetRawHttpRequest()->RequestId;

	_ui64toa(httpRequestID, pszValue, 10);

	apr_table_setn(r->subprocess_env, "UNIQUE_ID", pszValue);

	PSOCKADDR pAddr = pRequest->GetRemoteAddress();

#if AP_SERVER_MAJORVERSION_NUMBER > 1 && AP_SERVER_MINORVERSION_NUMBER < 3
    c->remote_addr = CopySockAddr(r->pool, pAddr);
    c->remote_ip = GetIpAddr(r->pool, pAddr);
#else
    c->client_addr = CopySockAddr(r->pool, pAddr);
	c->client_ip = GetIpAddr(r->pool, pAddr);
#endif
	c->remote_host = NULL;

	int status = modsecProcessRequest(r);

	if(status != DECLINED)
	{
		pHttpContext->GetResponse()->SetStatus(status, "ModSecurity Action");
		pHttpContext->SetRequestHandled();

		hr = E_FAIL;
		goto Finished;
	}

Finished:
	LeaveCriticalSection(&m_csLock);

    if ( FAILED( hr )  )
    {
        return RQ_NOTIFICATION_FINISH_REQUEST;
    }
	return RQ_NOTIFICATION_CONTINUE;
}
Пример #30
0
int wmain(int argc, wchar_t *argv[])
{
  Parameters commandLineParameters;

  if (argc < 1)
  {
    printf("Command line help goes here...");
    return 0;
  }

  CommandLineParser::Parse(argc, argv, &commandLineParameters);

  AudioEncoderParameters* encoderParameters = nullptr;

  if (commandLineParameters.Quality == 100)
  {
    encoderParameters = AudioEncoderParameters::CreateLosslessEncoderParameters(2, 44100, 16);
  }
  else
  {
    encoderParameters = AudioEncoderParameters::CreateQualityBasedVbrParameters(commandLineParameters.Quality, 2, 44100, 16);
  }

  // Verify that output folder exists, if specified
  // (and add a '\' to it if it doesn't exist)

  if (*commandLineParameters.OutputFolder)
  {
    WIN32_FILE_ATTRIBUTE_DATA fileData;

    BOOL success = GetFileAttributesEx(commandLineParameters.OutputFolder, GET_FILEEX_INFO_LEVELS::GetFileExInfoStandard, &fileData);

    // check if the file system object exists, but it's not a directory...

    if (success && ((fileData.dwFileAttributes & 0x10) == 0))
    {
      printf("Specified output directory is not a directory");
      return 0;
    }

    if (!success)
    {
      printf("Specified output directory does not exist");
      return 0;
    }

    size_t outputFolderLength = wcslen(commandLineParameters.OutputFolder);

    if (outputFolderLength < MAX_PATH - 1)
    {
      if (*(commandLineParameters.OutputFolder + outputFolderLength - 1) != '\\')
      {
        *(commandLineParameters.OutputFolder + outputFolderLength) = '\\';
        *(commandLineParameters.OutputFolder + outputFolderLength + 1) = '\0';
      }
    }
  }

  // Initialize COM & Media Foundation

  if (!SUCCEEDED(CoInitializeEx(nullptr, COINIT_APARTMENTTHREADED)))
  {
    wprintf_s(L"Unable to initialize COM");
    return -1;
  }

  if (!SUCCEEDED(MFStartup(MF_VERSION)))
  {
    CoUninitialize();

    wprintf_s(L"Unable to initialize MediaFoundation");
    return -1;
  }


  try
  {
    // Use the Windows shell API to extract the path component from the input filename

    WCHAR srcFileFolder[MAX_PATH];
    WCHAR srcFileName[MAX_PATH];

    wcscpy_s(srcFileFolder, commandLineParameters.InputFilename);

    BOOL ret = PathRemoveFileSpec(srcFileFolder);

    size_t srcFolderLength = wcslen(srcFileFolder);

    if (srcFolderLength < MAX_PATH - 1)
    {
      if (srcFolderLength > 0)
      {
        if (*(srcFileFolder + srcFolderLength - 1) != '\\')
        {
          *(srcFileFolder + srcFolderLength) = '\\';
          *(srcFileFolder + srcFolderLength + 1) = '\0';
        }
      }
    }

    // do some basic parsing of input filename, as FirstFirstFile / FindNext 
    // does not return the full path so we'll have to prepend
    // any directory info specified

    WIN32_FIND_DATA findData;

    HANDLE hFindFile = FindFirstFile(commandLineParameters.InputFilename, &findData);

    if (hFindFile != INVALID_HANDLE_VALUE)
    {
      do
      {
        if (findData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
        {
          // skip directories

          continue;
        }

        wcscpy_s(srcFileName, srcFileFolder);
        wcscat_s(srcFileName, findData.cFileName);

        MediaSource* mediaSource = MediaSource::Open(srcFileName);

        // if an output folder is specified, use that

        WCHAR outputFilename[MAX_PATH];

        if (*commandLineParameters.OutputFolder)
        {
          wcscpy_s(outputFilename, commandLineParameters.OutputFolder);
          wcscat_s(outputFilename, findData.cFileName);
          PathRenameExtension(outputFilename, L".wma");
        }
        else
        {
          wcscpy_s(outputFilename, commandLineParameters.OutputFilename);
        }

        AsfContentInfoBuilder *contentInfo = new AsfContentInfoBuilder();
        contentInfo->AddStreamSink(1, encoderParameters);
        SetMediaSinkContentInfoMetadata(contentInfo, mediaSource, &commandLineParameters);

        MediaSink* mediaSink = MediaSink::Create(outputFilename, contentInfo->ConstructMfAsfContentInfo());

        wprintf_s(L"Encoding %s\n", findData.cFileName);

        AudioEncoder::Encode(mediaSource, mediaSink, encoderParameters);

        delete mediaSink;
        delete mediaSource;

      } while (FindNextFile(hFindFile, &findData));

      FindClose(hFindFile);
    }
    else
    {
      // input file does not exit

      throw std::invalid_argument("Input filename does not exist");
    }

    MFShutdown();
    CoUninitialize();
  }
  catch (std::exception &ex)
  {
    printf("ERROR: %s\n", ex.what());
  }


    return 0;
}