ADDED CabTool.cpp Index: CabTool.cpp ================================================================== --- CabTool.cpp +++ CabTool.cpp @@ -0,0 +1,168 @@ + +#include "stdafx.h" +#include "CabTool.h" +#include "kiutil.h" +#include "fdi/fdi.h" +#include "kilib/kilib.h" + +// 無理矢理SFXも解凍 +static int seeker=0; +static int offhan=-1; +static int offhan2=-1; +static const char* sdll; +static kiPath* sdllr; + +// CallBack 定義 +static FNALLOC(mymalloc) +{ + return (void*)new BYTE[cb]; +} +static FNFREE(mymfree) +{ + delete [] (BYTE*)pv; +} +static FNOPEN(myfopen) +{ + int han=_open( pszFile, oflag, pmode ); + if( han!=-1 && seeker!=0 && !(oflag&_O_WRONLY) ) + { + _lseek( han,seeker,SEEK_SET ); + if( offhan==-1 )offhan=han; + else if( offhan2==-1 )offhan2=han; + } + return han; +} +static FNREAD(myfread) +{ + return _read( hf, pv, cb ); +} +static FNWRITE(myfwrite) +{ + return _write( hf, pv, cb ); +} +static FNCLOSE(myfclose) +{ + if( hf==offhan )offhan=-1; + else if( hf==offhan2 )offhan2=-1; + return _close(hf); +} +static FNSEEK(myfseek) +{ + if( hf==offhan || hf==offhan2 ) + { + if( seektype==SEEK_SET ) + return _lseek( hf, dist+seeker, SEEK_SET ) - seeker; + return _lseek( hf, dist, seektype ) - seeker; + } + return _lseek( hf, dist, seektype ); +} +static FNFDINOTIFY(mynotif) +{ + switch( fdint ) + { + case fdintCOPY_FILE: + { + char* name = kiutil::pathMake(pfdin->psz1); + if( 0==strcmpi( kiPath::name(name), sdll ) ) // DLLの位置を記憶 + *sdllr = name; + + return myfopen( name, + _O_BINARY|_O_CREAT|_O_TRUNC|_O_WRONLY|_O_SEQUENTIAL, + _S_IREAD|_S_IWRITE ); + } + + case fdintCLOSE_FILE_INFO: + myfclose( pfdin->hf ); + kiutil::timeSet( pfdin->psz1, pfdin->date, pfdin->time ); + SetFileAttributes( pfdin->psz1, + pfdin->attribs&(_A_RDONLY| _A_HIDDEN|_A_SYSTEM|_A_ARCH) ); + return TRUE; + } + return 0; +} + +int CCabTool::FindHeader( const char* fname, const BYTE* hdr, DWORD siz ) +{ + // FDI初期化 + FDICABINETINFO info; + ERF erf; + HFDI fdi=FDICreate( mymalloc,mymfree,myfopen,myfread, + myfwrite,myfclose,myfseek,cpuUNKNOWN,&erf ); + if( fdi==NULL ) + return false; + + // 開く + int ans=-1, han=myfopen( const_cast(fname), + _O_BINARY|_O_RDONLY|_O_SEQUENTIAL,0 ); + + // ヘッダ検索 + if( -1!=han ) + { + if( siz>10 && hdr[0]=='M' && hdr[1]=='Z' ) + { + for( DWORD i=2; iosver().dwPlatformId == VER_PLATFORM_WIN32_NT ) + { + // NT系では特権を取得しなくてはいけない + HANDLE hToken; + TOKEN_PRIVILEGES tkp; + ::OpenProcessToken( ::GetCurrentProcess(), + TOKEN_ADJUST_PRIVILEGES|TOKEN_QUERY, &hToken ); + ::LookupPrivilegeValue( + NULL, SE_SHUTDOWN_NAME, &tkp.Privileges[0].Luid ); + tkp.PrivilegeCount = 1; + tkp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED; + ::AdjustTokenPrivileges( hToken, FALSE, &tkp, 0, NULL, 0 ); + } + ::ExitWindowsEx( EWX_REBOOT, 0 ); +} + +static bool cancelShiteIidesuka() +{ + return IDYES == app()->msgBox( kiStr().loadRsrc( IDS_CANCELOK ), + "caldix", MB_ICONQUESTION|MB_YESNO|MB_DEFBUTTON2 ); +} + +template static inline bool show( const T& dlg ) +{ + (const_cast(dlg)).doModal(); + return IDOK == (const_cast(dlg)).getEndCode(); +} + + + +//---------------------------------------------------------------------------- +// 解凍関係 +//---------------------------------------------------------------------------- + +#include "kiutil.h" +#include "LzhTool.h" +#include "CabTool.h" +#include "ZipTool.h" +#define is_lzh(xx) (xx[2]=='-' && xx[3]=='l' && xx[4]=='h' && xx[6]=='-' && '0'<=xx[5] && xx[5]<='9') +#define is_zip(xx) (xx[2]=='P' && xx[3]=='K' && xx[4]==0x3 && xx[6]==0x4) +#define is_cab(xx) (xx[0]=='M' && xx[1]=='S' && xx[2]=='C' && xx[3]=='F') + +enum arctype{ e_lzh, e_zip, e_cab, unknown }; + +static arctype get_archive_type( const char* arcname ) +{ + // 手抜き判別 + arctype ans = unknown; + kiFile fp; + if( fp.open(arcname) ) + { + unsigned long asize = 128 << 10; + unsigned char *buf = new unsigned char[asize]; + unsigned char *p=buf, *end=buf+fp.read( buf, asize-6 ); + + while( p!=end ) + { + if( is_lzh(p) ) { ans=e_lzh; break; } + else if( is_zip(p) ) { ans=e_zip; break; } + else if( is_cab(p) ) { ans=e_cab; break; } + p++; + } + + delete [] buf; + } + return ans; +} + +static void melt_it( const char* arcname, const char* dllname, kiPath& dll_rel_path ) +{ + const char* ext = kiPath::ext( arcname ); + arctype type = unknown; + + // 判別 + if( 0==stricmp( ext, "lzh" ) ) type = e_lzh; + else if( 0==stricmp( ext, "zip" ) ) type = e_zip; + else if( 0==stricmp( ext, "cab" ) ) type = e_cab; + else type = get_archive_type(arcname); + + // 展開 + switch( type ) + { + case e_lzh:{ CLzhTool().Extract( arcname, dllname, dll_rel_path ); }break; + case e_zip:{ CZipTool().Extract( arcname, dllname, dll_rel_path ); }break; + case e_cab:{ CCabTool().Extract( arcname, dllname, dll_rel_path ); }break; + } +} + + + +//---------------------------------------------------------------------------- +// DLL情報管理:Meta-WWWC-Contentの解析など +//---------------------------------------------------------------------------- + +class DLLInfo +{ +public: + + DLLInfo( const char* _name, const char* _html, int _wwwc ) + : name( _name ), html( _html ), wwwc( _wwwc ), size( 0 ) {} + + bool ParseHTML( char* str ); + const kiStr& htmlName() const { return html; } + bool needToUpdate( kiPath& dlldir ); + const kiStr& getName() const { return name; } + const kiStr& getState() const { return stat; } + const int getSize() const { return size; } + const kiStr& getArchiveName() const { return arch; } + +private: + + char* Get_WWWC_Content( char* str ); + bool ParseWWWC( char* str ); + bool CheckDateTime( const char* localDLL ); + bool VersionCheckLogic( + const kiStr& dllName, const kiStr& htmlVer, int Ver, int subVer ); + +private: + + // 固定情報 + const kiStr name; // DLLの名前 + const kiStr html; // チェック先HTMLの名前 + const int wwwc; // 何番目のWWWCタグを利用するか + +private: + + // HTMLから取得する情報 + kiStr arch; // 書庫名 + kiStr vers; // バージョン + kiStr dttm; // 日付&時刻 + int size; // サイズ + + // バージョン照合の結果 + kiStr stat; // 更新状況 +}; + +char* DLLInfo::Get_WWWC_Content( char* x ) +{ + // もーれつに雑。 + while( *x==' ' || *x=='\t' || *x=='\r' || *x=='\n' ) x++; + if( (x[0]=='m' || x[0]=='M') + && (x[1]=='e' || x[1]=='E') + && (x[2]=='t' || x[2]=='T') + && (x[3]=='a' || x[3]=='A') ) + { + x+=4; + while( *x==' ' || *x=='\t' || *x=='\r' || *x=='\n' ) x++; + if( (x[0]=='n' || x[0]=='N') + && (x[1]=='a' || x[1]=='A') + && (x[2]=='m' || x[2]=='M') + && (x[3]=='e' || x[3]=='E') + && (x[4]=='=') + && (x[5]=='"') + && (x[6]=='w' || x[6]=='W') + && (x[7]=='w' || x[7]=='W') + && (x[8]=='w' || x[8]=='W') + && (x[9]=='c' || x[9]=='C') + && (x[10]=='"') ) + { + x+=11; + while( *x==' ' || *x=='\t' || *x=='\r' || *x=='\n' ) x++; + if( (x[0]=='c' || x[0]=='C') + && (x[1]=='o' || x[1]=='O') + && (x[2]=='n' || x[2]=='N') + && (x[3]=='t' || x[3]=='T') + && (x[4]=='e' || x[4]=='E') + && (x[5]=='n' || x[5]=='N') + && (x[6]=='t' || x[6]=='T') + && (x[7]=='=') + && (x[8]=='"') ) + { + x+=9; + char* p=x; + while( *p!='\0' && *p!='"' ) p++; + *p='\0'; + return x; + } + } + } + return NULL; +} + +bool DLLInfo::ParseHTML( char* str ) +{ + int ct = wwwc; + for( char* p=str; *p; ++p ) + if( *p == '<' ) + { + for( char* x=p+1; *x; ++x ) + if( *x == '>' ) + break; + *x = '\0'; + + char* w = Get_WWWC_Content( p+1 ); + if( w && (--ct)==0 ) + return ParseWWWC( w ); + + p = x; + } + return false; +} + +bool DLLInfo::ParseWWWC( char* str ) +{ + char *x,*k,*t,*p=str; + + // 2個目のスペースまでが更新日時 + for( int spc=2; *p; ++p ) + if( *p==' ' ) + if( (--spc)==0 ) + break; + if( *p=='\0' ) + return false; + *(p++) = '\0'; + dttm = str; + + // [xxx: ---] 部分 + while( true ) + { + while( *p!='\0' && *p!='[' ) ++p; + if( *p!='\0' ) ++p; + if( *p=='\0' )break; + + t=x=k=p; + while( *x!='\0' && *x!=']' ) x++; + while( *k!='\0' && *k!=':' ) k++; + if( *x=='\0' || *k=='\0' || k>=x )break; + *k=*x='\0'; + p=k+1; + + if( 0==lstrcmpi( t, "File" ) ) + arch = p; + else if( 0==lstrcmpi( t, "Ver" ) ) + { + while( *p && (*p<'0' || '9'<*p) ) + ++p; + vers = p; + } + else if( 0==lstrcmpi( t, "Size" ) ) + { + // atoi + for( int n=0; *p; p++ ) + if( '0'<=*p && *p<='9' ) + n = (10*n) + (*p - '0'); + size = n; + } + p=x+1; + } + + return ( size!=0 && arch.len()!=0 ); +} + +//---------------------------------------------------------------------------- +// caldixの設定項目管理 +//---------------------------------------------------------------------------- + +enum { + UNLHA, UNZIP, ZIP, CAB, TAR, UNRAR, UNGCA, + UNARJ, YZ1, BGA, JACK, AISH, ISH, UNBEL, SvZIP, + UNIMP, BH, YZ2, +DLLID_NUM }; + +struct CldxConfig +{ + kiStr UA; // ユーザーエージェント名 + + bool SuperAutoMode; // (利用しない) + bool AutoMode; // 全自動ならtrue, カスタムならfalse + + kiPath InstallTo; // インストール先 + int CheckServer; // 更新チェックに使うサーバ 窓辺=0, CSD=1, 惑星=2 + + int ProxyPort; // プロキシのポート番号 + kiStr ProxyServer; // プロキシサーバ名 + kiStr ProxyUser; // プロキシユーザ名(利用しない) + kiStr ProxyPwd; // プロキシパスワード(利用しない) + + bool George; // 常時接続モードならtrue, 汎用モードならfalse + bool UseCustomDir; // 全自動でも、カスタムと同じディレクトリを用いる + bool ShowReadMe; // 最後にcldxフォルダを開くか否か + +// 挿入caldixF + kiStr Filer; // フォルダを開くファイラー + kiStr F_Prefix; // ファイラに渡すオプション前 + kiStr F_Suffix; // ファイラに渡すオプション後ろ + +// 挿入ここまでcaldixF + + bool DoCheck[DLLID_NUM]; // 各DLLをチェック対象にするかどうか + int InstMode; // ダウンロードしたDLLの扱い + int Expire; // 日時チェックで更新対象とする範囲(単位:Day) + + kiArray List; // チェック対象DLLのリスト + + CldxConfig() + : UA( "caldix/1.21" ) + , SuperAutoMode( false ) + , AutoMode( true ) + , InstallTo( kiPath::Sys ) + { + kiIniFile ini; + ini.setFileName( "caldix.ini" ); + ini.setSection( "conf" ); + + InstallTo = ini.getStr ( "dll", InstallTo ); + CheckServer = ini.getInt ( "checkserv", 0 ) % 3; + ProxyServer = ini.getStr ( "proxy", "" ); + ProxyPort = ini.getInt ( "proxyport", -80 ); + George =!ini.getBool( "askhang", false ); // [1.21] デフォルトを false に変更。流石に今時… + UseCustomDir = ini.getBool( "custdir", false ); + ShowReadMe = ini.getBool( "readme", true ); + InstMode = ini.getInt ( "mode", 1 ); + Expire = ini.getInt ( "expire", 7 ); + int version = ini.getInt ( "ver", 110 ); + +// 挿入caldixF + Filer = ini.getStr ( "Filer","explorer"); + F_Prefix = ini.getStr ( "F_Prefix",""); + F_Suffix = ini.getStr ( "F_Suffix",""); + if( Filer=="" || Filer.isSame("explorer") ) + Filer = kiPath(kiPath::Win,true), Filer += "explorer.exe"; +// 挿入ここまでcaldixF + + for( int i=0; i StWeb.wYear) + || (StLocal.wYear==StWeb.wYear && StLocal.wMonth>StWeb.wMonth) + || (StLocal.wYear==StWeb.wYear && StLocal.wMonth==StWeb.wMonth && StLocal.wDay>=StWeb.wDay) ) + return false; // ローカルの方が新しいので更新しない + + if( StLocal.wYear+2 < StWeb.wYear ) + return true; // 確実に1年以上新しいので更新 + if( StLocal.wYear+1 == StWeb.wYear ) + StWeb.wMonth += 12; + + // cfg->Expire 日以上新しければ更新 + StWeb.wDay += 30 * (StWeb.wMonth - StLocal.wMonth); + return ( StLocal.wDay+cfg->Expire < StWeb.wDay ); +} + +//------------------------------------------------------------------------------- +// バージョンチェック for caldix/1.15 or older + caldixF fix +//------------------------------------------------------------------------------- +/* +bool DLLInfo::VersionCheckLogic( + const kiStr& dllName, + const kiStr& htmlVer, + int ver, int sub ) +{ + // 文字列に変換 + char verstr[100]; + if( dllName=="Unimp32.dll" ) + if( sub==0 ) + ::wsprintf( verstr, "%d.%02d", ver/100, ver%100 ); + else if( sub >= 100 ) + ::wsprintf( verstr, "%d.%02d%c", ver/100, ver%100, sub/100+'a'-1 ); + else + ::wsprintf( verstr, "%d.%02d%c", ver/100, ver%100, sub+'a'-1 ); + else if( dllName=="7-zip32.dll" ) // 7-zipだけは無条件でSubVersionも数値で入れる + ::wsprintf( verstr, "%d.%02d.%02d.%02d", ver/100, ver%100, sub/100,sub%100 ); + else if( sub < 100 ) + ::wsprintf( verstr, "%d.%02d", ver/100, ver%100 ); + else + ::wsprintf( verstr, "%d.%02d%c", ver/100, ver%100, sub/100+'a'-1 ); + + // 比較(htmlVerの方がVer.subVerより新しければtrue) + return + (CSTR_GREATER_THAN == ::CompareString(LOCALE_USER_DEFAULT,SORT_STRINGSORT,vers,-1,verstr,-1)); +} +*/ +//------------------------------------------------------------------------------- +// バージョンチェック for caldix/1.17 or newer +//------------------------------------------------------------------------------- + +const char* find_first_non_digit( const char* p ) +{ + while( '0'<=*p && *p<='9' ) ++p; + return p; +} + +bool DLLInfo::VersionCheckLogic( + const kiStr& dllName, // DLL名 + const kiStr& htmVerStr, // HTML上のバージョン文字列 + int locVer, int locSub ) // ローカルDLLのバージョン +{ + const char* vs = htmVerStr; + if( dllName == "Unimp32.dll" && locSub<100 ) + locSub *= 100; + + // バージョン文字列を解析。以下の4つの形式を認識する + //("%d.%d.%d.%d", ver/100, ver%100, sub/100, sub%100) + //("%d.%d", ver/100, ver%100) && sub<100 + //("%d.%d%c", ver/100, ver%100, sub/100+'a'-1) + //("%d.%d.%d", ver/100, ver%100, sub) + + int htmVer=0, htmSub=0; + { + // [%d][.] + const int d1 = atoi(vs); + vs = find_first_non_digit(vs); + if( *vs!='.' ) return false; ++vs; + // [%d] + const int d2 = atoi(vs); + const char* vs2 = find_first_non_digit(vs); + if( vs2-vs==1 && dllName=="Zip32.dll" ) // adhoc対処 + htmVer = d1*100 + d2*10; + else + htmVer = d1*100 + d2; + vs = vs2; + if( *vs=='.' ) // [.] + { + ++vs; + // [%d] + const int d3 = atoi(vs); + vs = find_first_non_digit(vs); + if( *vs=='.' ) // [.] + { + ++vs; + // [%d] + const int d4 = atoi(vs); + htmSub = d3*100 + d4; + } + else + htmSub = d3; + } + else if( 'a'<=*vs && *vs<='z' ) // [a-z] + htmSub = (*vs-'a'+1) * 100; + else if( 'A'<=*vs && *vs<='Z' ) // [A-Z] + htmSub = (*vs-'A'+1) * 100; + } + return (locVer < htmVer) || (locVer==htmVer && locSubsetMainWnd( this ); + UINT md = (cfg->AutoMode ? IDC_WORKTYPE1 : IDC_WORKTYPE2); + sendMsgToItem( md, BM_SETCHECK, BST_CHECKED ); + return FALSE; + } + + virtual bool onOK() + { + cfg->AutoMode = + (BST_CHECKED == sendMsgToItem( IDC_WORKTYPE1, BM_GETCHECK )); + return true; + } +}; + + + +//---------------------------------------------------------------------------- +// customDlg : 接続先/インストール先の選択 プロキシ|詳細への分岐 +//---------------------------------------------------------------------------- + +class customDlg : public kiDialog +{ +public: + customDlg() : kiDialog( IDD_CUSTOM1 ) {} + +private: + virtual BOOL onInit() + { + app()->setMainWnd( this ); + sendMsgToItem( IDC_DLLDIR, WM_SETTEXT, 0, (LPARAM)(const char*)(cfg->InstallTo) ); + sendMsgToItem( IDC_CONNECTTO1+cfg->CheckServer, BM_SETCHECK, BST_CHECKED ); + return FALSE; + } + + virtual BOOL CALLBACK proc( UINT msg, WPARAM wp, LPARAM lp ) + { + if( msg==WM_COMMAND ) + if( LOWORD(wp)==IDC_REF ) + { + kiSUtil::getFolderDlgOfEditBox( item(IDC_DLLDIR), hwnd(), NULL ); + return TRUE; + } + else if( LOWORD(wp)==IDC_PROXY ) + { + show( proxyDlg() ); + return TRUE; + } + else if( LOWORD(wp)==IDC_DETAIL ) + { + show( detailDlg() ); + return TRUE; + } + return FALSE; + } + + virtual bool onOK() + { + char str[MAX_PATH]; + sendMsgToItem( IDC_DLLDIR, WM_GETTEXT, sizeof(str)-1, (LPARAM)str ); + cfg->InstallTo=str, cfg->InstallTo.beBackSlash( true ); + for(int i=0; i<=2; ++i) + if( BST_CHECKED == sendMsgToItem( IDC_CONNECTTO1+i, BM_GETCHECK ) ) + cfg->CheckServer = i; + return true; + } + + virtual bool onCancel() + { + return cancelShiteIidesuka(); + } + +private: + class detailDlg : public kiDialog + { + public: + detailDlg() : kiDialog( IDD_DETAIL ) {} + private: + virtual BOOL onInit() + { + if( cfg->George ) + sendMsgToItem( IDC_CONNECT_ALWAYS, BM_SETCHECK, BST_CHECKED ); + if( cfg->ShowReadMe ) + sendMsgToItem( IDC_SHOW_README, BM_SETCHECK, BST_CHECKED ); + if( cfg->UseCustomDir ) + sendMsgToItem( IDC_SAVE_DESTDIR, BM_SETCHECK, BST_CHECKED ); + for( int i=0; iDoCheck[i] ) + sendMsgToItem( IDC_DLHA+i, BM_SETCHECK, BST_CHECKED ); +// 挿入caldixF + sendMsgToItem( IDC_FILERPATH, WM_SETTEXT, 0, (LPARAM)(const char*)(cfg->Filer) ); + sendMsgToItem( IDC_FILEROPT, WM_SETTEXT, 0, (LPARAM)(const char*)(cfg->F_Prefix) ); + sendMsgToItem( IDC_FILEROPT2, WM_SETTEXT, 0, (LPARAM)(const char*)(cfg->F_Suffix) ); + +// 挿入ここまでcaldixF + return FALSE; + } + +// 挿入caldixF + virtual BOOL CALLBACK proc( UINT msg, WPARAM wp, LPARAM lp ) + { + // 指定ボタン + if((msg==WM_COMMAND) && (LOWORD(wp)==IDC_REF )){ + kiSUtil::getOpenFileNameDlgOfEditBox(item(IDC_FILERPATH),hwnd()); + return TRUE; + } + return FALSE; + } +// 挿入ここまでcaldixF + + virtual bool onOK() + { + cfg->George = + (BST_CHECKED==sendMsgToItem( IDC_CONNECT_ALWAYS, BM_GETCHECK )); + cfg->ShowReadMe = + (BST_CHECKED==sendMsgToItem( IDC_SHOW_README, BM_GETCHECK )); + cfg->UseCustomDir = + (BST_CHECKED==sendMsgToItem( IDC_SAVE_DESTDIR, BM_GETCHECK )); + for( int i=0; iDoCheck[i] = + (BST_CHECKED==sendMsgToItem( IDC_DLHA+i, BM_GETCHECK )); +// 挿入caldixF + char str[500]; + + sendMsgToItem( IDC_FILERPATH, WM_GETTEXT, sizeof(str)-1, (LPARAM)str ); + cfg->Filer = str; + sendMsgToItem( IDC_FILEROPT, WM_GETTEXT, sizeof(str)-1, (LPARAM)str ); + cfg->F_Prefix = str; + sendMsgToItem( IDC_FILEROPT2, WM_GETTEXT, sizeof(str)-1, (LPARAM)str ); + cfg->F_Suffix = str; +// 挿入ここまでcaldixF + return true; + } + }; + + class proxyDlg : public kiDialog + { + public: + proxyDlg() : kiDialog( IDD_PROXY ) {} + private: + virtual BOOL onInit() + { + if( cfg->ProxyPort>0 ) + { + sendMsgToItem( IDC_USEPROXY, BM_SETCHECK, BST_CHECKED ); + ::EnableWindow( item(IDC_HOST_N), TRUE ); + ::EnableWindow( item(IDC_PORT_N), TRUE ); + ::EnableWindow( item(IDC_HOST), TRUE ); + ::EnableWindow( item(IDC_PORT), TRUE ); + ::SetDlgItemInt( hwnd(), IDC_PORT, cfg->ProxyPort, FALSE ); + } + else + ::SetDlgItemInt( hwnd(), IDC_PORT, -cfg->ProxyPort, FALSE ); + sendMsgToItem( IDC_HOST, WM_SETTEXT, 0, (LPARAM)(const char*)cfg->ProxyServer ); + return FALSE; + } + + virtual BOOL CALLBACK proc( UINT msg, WPARAM wp, LPARAM lp ) + { + if((msg==WM_COMMAND) && (LOWORD(wp)==IDC_USEPROXY)){ + BOOL x = ( BST_CHECKED==sendMsgToItem( IDC_USEPROXY, BM_GETCHECK ) ); + ::EnableWindow( item(IDC_HOST_N), x ); + ::EnableWindow( item(IDC_PORT_N), x ); + ::EnableWindow( item(IDC_HOST), x ); + ::EnableWindow( item(IDC_PORT), x ); + return TRUE; + } + return FALSE; + } + + virtual bool onOK() + { + char str[500]; + sendMsgToItem( IDC_HOST, WM_GETTEXT, sizeof(str)-1, (LPARAM)str ); + cfg->ProxyServer = str; + cfg->ProxyPort = ::GetDlgItemInt( hwnd(), IDC_PORT, NULL, FALSE ); + if( BST_CHECKED!=sendMsgToItem( IDC_USEPROXY, BM_GETCHECK ) ) + cfg->ProxyPort *= -1; + return true; + } + }; +}; + +//---------------------------------------------------------------------------- +// mirrorMan : バージョンチェック先サーバ情報管理 +//---------------------------------------------------------------------------- + +class mirrorInfo +{ +private: + enum { MAD, CSD, WAK, SERVER_NUM }; + static const char* c_serv[SERVER_NUM]; + static const char* c_path[SERVER_NUM]; + static const char* c_nick[SERVER_NUM]; + + int mirrors[SERVER_NUM+1]; + +public: + mirrorInfo() + { + for(int i=0; i!=SERVER_NUM+1; ++i) + mirrors[i] = -1; + } + + // どのサーバを先に見に行くか選択。 + void setPreferedServer( int p ) + { + switch( p ) + { + default: + case MAD: + mirrors[0] = MAD; + mirrors[1] = CSD; + mirrors[2] = WAK; + break; + case CSD: + mirrors[0] = CSD; + mirrors[1] = MAD; + mirrors[2] = WAK; + break; + case WAK: + mirrors[0] = WAK; + mirrors[1] = MAD; + mirrors[2] = CSD; + break; + } + } + + // m番目のミラーサーバがDownしてるっぽい場合、候補から消去 + void server_is_down( int m ) + { + for(int i=m; i!=SERVER_NUM; ++i) + mirrors[i] = mirrors[i+1]; + } + + // t番目のミラーサーバの情報を取得 + bool isMirrorLeft( int m ) const { return mirrors[m] >= 0; } + kiStr serverName ( int m ) const { return c_serv[mirrors[m]]; } + kiStr basePath ( int m ) const { return c_path[mirrors[m]]; } + kiStr nickname ( int m ) const { return c_nick[mirrors[m]]; } + kiStr baseURL ( int m ) const { + return (kiStr("http://")+=c_serv[mirrors[m]])+=c_path[mirrors[m]]; + } +}; + +// static constants + +const char* mirrorInfo::c_serv[mirrorInfo::SERVER_NUM] = { + "www.madobe.net", + "www.csdinc.co.jp", + "archiver.wakusei.ne.jp", +}; +const char* mirrorInfo::c_path[mirrorInfo::SERVER_NUM] = { + "/archiver/lib/", + "/archiver/lib/", + "/lib/", +}; +const char* mirrorInfo::c_nick[mirrorInfo::SERVER_NUM] = { + "Madobe", + "CSD", + "Wakusei", +}; +static mirrorInfo mirrorMan; + +//---------------------------------------------------------------------------- +// verDlg : 接続して実際のバージョンチェックを行う +//---------------------------------------------------------------------------- + +class verDlg : public kiDialog +{ +public: + verDlg( HINTERNET hi ) + : kiDialog( IDD_VERCHECK ), h(hi), ss(NULL), http(NULL) {} + + ~verDlg() + { + if( ss ) + ::InternetCloseHandle( ss ); + if( http ) + ::InternetCloseHandle( http ); + } + +private: + + HANDLE hT; + HINTERNET h, http, ss; + volatile bool m_endFlag; + + BOOL onInit() + { + app()->setMainWnd( this ); + sendMsgToItem( IDC_BAR, PBM_SETSTEP, 1 ); + sendMsgToItem( IDC_BAR, PBM_SETRANGE, 0, MAKELPARAM(0,cfg->List.len()*3) ); + + m_endFlag = false; + DWORD id; + if( !(hT = ::CreateThread( NULL, 0, threadEntry, this, 0, &id )) ) + end( IDCANCEL ); + return FALSE; + } + + bool onCancel() + { + m_endFlag = true; + DWORD ex; + while( ::GetExitCodeThread( hT, &ex ) && ex==STILL_ACTIVE ) + ::Sleep(0); + ::CloseHandle( hT ); + return true; + } + + static DWORD WINAPI threadEntry( void* prm ) + { + ((verDlg*)prm)->threadWorker(); + return 0; + } + +private: + + // 作業用マクロ + #define CHECK_CANCEL() if(m_endFlag) break + #define STEP_GRAPH() CHECK_CANCEL(); sendMsgToItem( IDC_BAR, PBM_STEPIT ) + #define RETRY_() ::InternetCloseHandle( http ); http=NULL; goto retry; + #define RETRY_error() do{ ++Mir; RETRY_() }while(0) + #define RETRY_serverdown() do{ mirrorMan.server_is_down(Mir); RETRY_() }while(0) + #define INET_CONNECT( __s ) ::InternetConnect( h, __s, INTERNET_DEFAULT_HTTP_PORT, NULL, NULL, INTERNET_SERVICE_HTTP, 0, 0 ) + #define HTTP_REQ( __n ) ::HttpOpenRequest( http, "GET", __n, "HTTP/1.0", NULL, NULL, 0, 0 ) + #define HTTP_SEND() status=0,::HttpSendRequest( ss, NULL, 0, NULL, 0 ), ::HttpQueryInfoA( ss, HTTP_QUERY_STATUS_CODE|HTTP_QUERY_FLAG_NUMBER,&status,&size,&dw),status; + + void threadWorker() + { + // 作業変数 + DWORD dw = 0, size = sizeof(DWORD), status; + kiStr name; + char buf[4000]; + + // メインループ + for( unsigned int i=0; iList.len(); ++i ) + { + if( !mirrorMan.isMirrorLeft(0) ) + break; // どのサーバにも繋げない場合、終了 + STEP_GRAPH(); + + // + // 未接続ならサーバへ繋ぐ + // + int Mir = 0; + retry: + if( !http ) + { + if( !mirrorMan.isMirrorLeft(Mir) ) + continue; // このDLLの情報取得は無理でした + http = INET_CONNECT( mirrorMan.serverName(Mir) ); + if( !http ) + RETRY_serverdown(); // 次のミラーを試す + } + + // + // HTTPリクエスト作成 + // + name = mirrorMan.basePath(Mir); + name+= cfg->List[i]->htmlName(); + ss = HTTP_REQ( name ); + if( !ss ) + RETRY_serverdown(); + CHECK_CANCEL(); + + // + // HTTPリクエスト送信 + // + bool succeeded = false; + int try_auth = 3; + while( !succeeded && (try_auth-->0) ) + { + status = HTTP_SEND(); + + if( status/100 == 2 ) // 200など。成功 + { + succeeded = true; + break; + } + else if( status == 0 ) // タイムアウト。別サーバをtry + { + ::InternetCloseHandle( ss ); + RETRY_serverdown(); + } + else if( status == 407 ) // 407 Proxy Authentication Required + { + // パスワードを打たせてもう一度 + DWORD dwRet = ::InternetErrorDlg( + hwnd(), ss, GetLastError(), + FLAGS_ERROR_UI_FILTER_FOR_ERRORS | + FLAGS_ERROR_UI_FLAGS_CHANGE_OPTIONS | + FLAGS_ERROR_UI_FLAGS_GENERATE_DATA, + NULL ); + // 認証失敗したら終了 + if( dwRet != ERROR_INTERNET_FORCE_RETRY ) + { + ::InternetCloseHandle( ss ); + end( IDOK ); return; + } + continue; + } + else // その他のエラー。あきらめて次のDLLに進む + { + ::InternetCloseHandle( ss ); + break; + } + } + + // + // 読込 + // + STEP_GRAPH(); + if( succeeded ) + { + DWORD read; + ::InternetReadFile( ss, buf, sizeof(buf)-1, &read ); + ::InternetCloseHandle( ss ); + buf[ read ] = '\0'; + } + + // + // 解析 + // + STEP_GRAPH(); + if( succeeded ) + cfg->List[i]->ParseHTML( buf ); + } + + if( !m_endFlag ) + end( IDOK ); + } +}; + + + +//---------------------------------------------------------------------------- +// dllDlg: ダウンロードするDLLの選択 +//---------------------------------------------------------------------------- + +class dllDlg : public kiDialog +{ +public: + dllDlg( kiArray& upd ) : kiDialog( IDD_CUSTOM2 ), m_upd(upd) {} + +private: + kiArray& m_upd; + + BOOL onInit() + { + app()->setMainWnd( this ); + + SHFILEINFO fi; + HIMAGELIST hI = (HIMAGELIST)::SHGetFileInfo( + kiPath(kiPath::Sys)+="KERNEL32.DLL", 0, &fi, sizeof(fi), + SHGFI_SYSICONINDEX | SHGFI_ICON | SHGFI_SMALLICON ); + int iDLL = fi.iIcon; + int iEXE = kiSUtil::getSysIcon( "exe" ); + + kiStr str; + kiListView list( this, IDC_UPDATELIST ); + list.setImageList( NULL, hI ); + list.insertColumn( 0, str.loadRsrc( IDS_LV_DLLNAME ), 120 ); + list.insertColumn( 1, str.loadRsrc( IDS_LV_STATE ), 110 ); + for( unsigned int i=0; igetName(), 0, strcmpi( "dll", kiPath::ext(m_upd[i]->getName()) ) ? iEXE : iDLL ); + list.setSubItem( i, 1, m_upd[i]->getState() ); + } + sendMsgToItem( IDC_UPDATELIST,LVM_SETEXTENDEDLISTVIEWSTYLE,LVS_EX_CHECKBOXES,LVS_EX_CHECKBOXES ); + for( i=0; i!=m_upd.len(); i++ ) + ListView_SetCheckState( item(IDC_UPDATELIST), i, TRUE ); + for( int j=0; j!=3; j++ ) + sendMsgToItem( IDC_INSTMODE1+j,BM_SETCHECK,j==cfg->InstMode ? BST_CHECKED : BST_UNCHECKED ); + return FALSE; + } + bool onCancel() + { + if( !cancelShiteIidesuka() ) + return false; + kiListView( this, IDC_UPDATELIST ).setImageList( NULL, NULL ); + return true; + } + bool onOK() + { + for( unsigned int i=0; i!=3; i++ ) + if( BST_CHECKED == sendMsgToItem( IDC_INSTMODE1+i, BM_GETCHECK ) ) + { + cfg->InstMode = i; + break; + } + + kiArray res; + res = m_upd, m_upd.empty(); + for( i=0; i& lst, const kiPath& pth ) + : kiDialog( IDD_VERCHECK ), m_lst( lst ), m_pth( pth ), m_cRef( 1 ){} + +private: + const kiArray& m_lst; + const kiPath& m_pth; + unsigned long m_cRef; + unsigned long m_total; + unsigned long m_step; + unsigned long m_startTime, m_lastTime; + bool m_stateCancel; + + BOOL onInit() + { + app()->setMainWnd( this ); + + m_startTime = m_lastTime = ::GetTickCount(); + m_stateCancel = false; + m_step = m_total = 0; + for( unsigned int i=0; igetSize(); + sendMsgToItem( IDC_BAR, PBM_SETRANGE,0, MAKELPARAM(0,32768) ); + setTimeInfo( 0 ); + ::ShowWindow( hwnd(), SW_SHOW ); + ::UpdateWindow( hwnd() ); + + kiPath url, fil; + + // メインループ + for( i=0; imsgBox( kiStr(1000).loadRsrc( IDS_DLERROR ), "caldix", MB_ICONINFORMATION|MB_SYSTEMMODAL ); + break; + } + + // "○○をダウンロード中..." のテキストを更新 + char msg[300]; + ::wsprintf( msg, kiStr().loadRsrc(IDS_DOWNLOADING), + (const char*)m_lst[i]->getName(), (const char*)mirrorMan.nickname(Mir) ); + sendMsgToItem( IDC_MSG, WM_SETTEXT, 0, (LPARAM)msg ); + ::EnableWindow( item(IDC_MSG), FALSE ); + ::EnableWindow( item(IDC_MSG), TRUE ); + + // ダウンロード元とダウンロード先 + url = mirrorMan.baseURL(Mir), url += m_lst[i]->getArchiveName(); + fil = m_pth, fil += m_lst[i]->getArchiveName(); + if( S_OK != ::URLDownloadToFile( NULL, url, fil, 0, this ) ) + { + ++Mir; + goto retry; + } + m_step += m_lst[i]->getSize(); + } + end( i==m_lst.len() ? IDOK : IDCANCEL ); + return FALSE; + } + bool onCancel() + { + if( cancelShiteIidesuka() ) + m_stateCancel = true; + return false; + } + +public: + void setTimeInfo( unsigned long bytesread ) + { + int sec = (bytesread==0 || m_lastTime==m_startTime) + ? (int)((double)(m_total) / 7000) + : (int)((double)((m_total-bytesread)) * (m_lastTime - m_startTime) / 1000 / bytesread); + + static char str[300]; + ::wsprintf( str, (const char*)(kiStr().loadRsrc(IDS_REST)), + (m_total-bytesread)/1000, sec/60, sec%60 ); + + sendMsgToItem( IDC_RESTTIME, WM_SETTEXT, 0, (LPARAM)str ); + } + + STDMETHODIMP_(ULONG) AddRef() { return (++m_cRef); } + STDMETHODIMP_(ULONG) Release() { return (m_cRef ? --m_cRef : 0L); } + STDMETHODIMP GetBindInfo( DWORD*, BINDINFO* ) { return E_NOTIMPL; } + STDMETHODIMP GetPriority( LONG* ) { return E_NOTIMPL; } + STDMETHODIMP OnLowResource( DWORD ) { return E_NOTIMPL; } + STDMETHODIMP OnDataAvailable( DWORD, DWORD, FORMATETC*, STGMEDIUM* ) { return E_NOTIMPL; } + STDMETHODIMP OnObjectAvailable( REFIID, IUnknown* ) { return E_NOTIMPL; } + STDMETHODIMP OnStartBinding( DWORD, IBinding* ) { return E_NOTIMPL; } + STDMETHODIMP OnStopBinding( HRESULT, LPCWSTR ) { return E_NOTIMPL; } + STDMETHODIMP QueryInterface( REFIID riid, void** ppv ) + { + *ppv = NULL; + AddRef(); + if( IsEqualIID( riid, IID_IUnknown ) || IsEqualIID( riid, IID_IBindStatusCallback ) ) + *ppv = (IBindStatusCallback*)this; + else + { + Release(); + return E_NOINTERFACE; + } + return NOERROR; + } + STDMETHODIMP OnProgress( ULONG cur, ULONG max, ULONG status, LPCWSTR txt ) + { + msgLoop( PEEK ); + + if( m_stateCancel ) + { + end( IDCANCEL ); + return E_ABORT; + } + + DWORD time = ::GetTickCount(); + if( time-m_lastTime >= 5000 ) + { + m_lastTime = time; + setTimeInfo( m_step+cur ); + } + + sendMsgToItem( IDC_BAR, PBM_SETPOS, (int)(((double)(m_step+cur))/m_total*32768) ); + return S_OK; + } +}; + + + +//---------------------------------------------------------------------------- +// instDlg : system等へインストール +//---------------------------------------------------------------------------- + +class instDlg : public kiDialog +{ +public: + instDlg( kiArray& upd, const kiPath& arcdir, const kiPath& work, const kiPath& to ) + : kiDialog( IDD_INSTALL ), m_upd( upd ), m_arcdir( arcdir ), m_workdir( work ), m_dlldir( to ) {} + +private: + kiArray& m_upd; + const kiPath& m_arcdir; + const kiPath& m_workdir; + const kiPath& m_dlldir; + bool onCancel() { return false; } + bool onOK() { return false; } + + BOOL onInit() + { + bool needreboot=false; + app()->setMainWnd( this ); + ::ShowWindow( hwnd(), SW_SHOW ); + ::UpdateWindow( hwnd() ); + //-- 解凍&インストール開始〜 --------------- + + char tmp[MAX_PATH]; + kiPath arc, dll, path; + for( unsigned int i=0; igetArchiveName(); + // ドキュメント保存先:フルパス + dll = m_workdir, ::lstrcpyn(tmp,m_upd[i]->getName(),m_upd[i]->getName().len()-3), dll += tmp, dll.remove(); + dll += "\\", dll.mkdir(), ::SetCurrentDirectory( dll ); + // 解凍( path=書庫内のDLLの相対パス ) + melt_it( arc, m_upd[i]->getName(), path ); + // インストール + if( !install_it( dll, path ) ) + { + needreboot = true; + } + if( path.isSame( "aish32.dll" ) ) + { + if( !install_it( dll, "Aishmv32.dll" ) ) + needreboot = true; + } + else if( path.isSame( "unrar32.dll" ) ) + { + if( !install_it( dll, "unrar.dll" ) ) + needreboot = true; + } + else if( path.isSame( "yz1.dll" ) ) + { + if( !install_it( dll, "yzdec.exe" ) ) + needreboot = true; + kiPath uyz( m_dlldir ); + if( !kiSUtil::exist( uyz+="UnYz1.dll" ) ) + if( !install_it( dll, "UnYz1.dll" ) ) + needreboot = true; + } + else if( path.isSame( "bh32.dll" ) ) + { + if( !install_it( dll, "bhsfx.exe" ) ) + needreboot = true; + } + // メッセージ処理 + msg(); + } + + //-- 解凍&インストール終了〜 --------------- + end( needreboot ? IDCANCEL : IDOK ); + return FALSE; + } + +private: + bool install_it( const char* position, const char* relpath ) + { + kiPath from( position ); from += relpath; + if( ::GetFileAttributes(from) != 0xffffffff ) + { + kiPath to( m_dlldir ); to += kiPath::name(relpath); + if( ::CopyFile( from, to, FALSE ) ) + ::DeleteFile( from ); + else + { + // 再起動後コピー準備 + move_later( from, to ); + return false; + } + } + return true; + } +}; + + + +//---------------------------------------------------------------------------- +// caldix : メインルーチン +//---------------------------------------------------------------------------- + +#include +#include + +class caldix : public kiApp +{ + caldix() + { + shellInit(); + kiutil::pathInit(); + + cfg = new CldxConfig; + } + + void run( kiCmdParser& cmd ) + { + // ダイアログ [全自動/カスタム] + if( !cfg->SuperAutoMode && !show( startDlg() ) ) + return; + + if( cfg->AutoMode ) + { + // 全自動なら、インストール先をシステムにするかもしれない + if( !cfg->UseCustomDir ) + cfg->InstallTo.beSpecialPath( kiPath::Sys ); + } + else + { + // ダイアログ [インストール先とか] + if( !show( customDlg() ) ) + return; + } + + // 設定の調整 + cfg->InstallTo.beBackSlash( true ); + cfg->GenerateDLLList(); + + // 常時接続モードでない場合、接続を確立 + if( !cfg->George ) + if( ERROR_SUCCESS != ::InternetAttemptConnect(0) ) + { + msgBox( kiStr().loadRsrc( IDS_NOINTERNET ) ); + return; + } + + // WinInet開始… + HINTERNET h = ::InternetOpen( cfg->UA, INTERNET_OPEN_TYPE_PRECONFIG, NULL, NULL, 0 ); + if( !h ) + { + msgBox( kiStr().loadRsrc( IDS_NOINTERNET ) ); + return; + } + + // プロクシの設定 + if( cfg->ProxyServer.len() && cfg->ProxyPort>0 ) + { + kiStr pr( "http=http://" ); + pr += cfg->ProxyServer; + pr += ':'; + pr += kiStr().setInt(cfg->ProxyPort); + INTERNET_PROXY_INFO pi = {INTERNET_OPEN_TYPE_PROXY,(const char*)pr,""}; + ::InternetSetOption( h, INTERNET_OPTION_PROXY, (void*)&pi, sizeof(pi) ); + ::UrlMkSetSessionOption( INTERNET_OPTION_PROXY, (void*)&pi, sizeof(pi), 0 ); + } + + // タイムアウトは5秒 + DWORD TimeOut = 5*1000; + ::InternetSetOption( h, INTERNET_OPTION_RECEIVE_TIMEOUT, &TimeOut, sizeof(TimeOut) ); + + // 接続先サーバ情報を設定から取得 + mirrorMan.setPreferedServer( cfg->CheckServer ); + + // ダイアログ [WWWC META CHECK] + if( !show( verDlg(h) ) ) + { + ::InternetCloseHandle( h ); + askRasHangUp(); + return; + } + + // バージョン比較 + kiStr tmp; + kiArray upd; + for( unsigned int i=0; iList.len(); ++i ) + if( cfg->List[i]->needToUpdate( cfg->InstallTo ) ) + upd.add( cfg->List[i] ); + + if( upd.len()==0 ) + { + ::InternetCloseHandle( h ); + msgBox( kiStr().loadRsrc( IDS_NONEED ), "caldix", MB_ICONINFORMATION ); + askRasHangUp(); + return; + } + + if( ! cfg->AutoMode ) + { + // ダイアログ [インストールするDLLとか] + if( !show(dllDlg(upd)) || upd.len()==0 ) + { + ::InternetCloseHandle( h ); + askRasHangUp(); + return; + } + } + + // ダウンロード + char buf[MAX_PATH]; + ::GetTempFileName( kiPath( kiPath::Tmp ), "cld", 0, buf ); + ::DeleteFile( buf ); + kiPath dlto( buf ); + dlto.beBackSlash( true ); + dlto.mkdir(); + + if( !show( downloadDlg(upd, dlto) ) ) + { + dlto.remove(); + ::InternetCloseHandle( h ); + askRasHangUp(); + return; + } + + // インストール準備 + bool needreboot = false; + cfg->InstallTo.mkdir(); + kiPath workDir( kiPath::Exe ); workDir.lower(); + UINT drv = workDir.getDriveType(); + if( strstr(workDir,"temporary internet files")!=NULL + || (drv!=DRIVE_FIXED && drv!=DRIVE_REMOTE && drv!=DRIVE_UNKNOWN) ) + workDir.beSpecialPath( kiPath::Dsk ), workDir.beBackSlash( true ); + workDir += "cldx\\"; + workDir.mkdir(); + + if( cfg->InstMode != 1 ) + { + // 書庫コピー + kiPath from, to; + for( unsigned int i=0; igetArchiveName(); + to = workDir, to += upd[i]->getArchiveName(); + ::CopyFile( from, to, FALSE ); + } + } + if( cfg->InstMode != 0 ) + { + // インストール + if( !show( instDlg( upd, dlto, workDir, cfg->InstallTo ) ) ) + needreboot = true; + } + + // 閉じ処理 + dlto.remove(); + ::InternetCloseHandle( h ); + + if( !needreboot ) + { + if( ! cfg->SuperAutoMode ) + msgBox( kiStr(500).loadRsrc( IDS_FINISHED ), "caldix", MB_ICONINFORMATION|MB_SYSTEMMODAL ); + askRasHangUp(); + } + else + if( IDYES!=msgBox( kiStr(1000).loadRsrc( IDS_REBOOT ), "caldix", MB_ICONINFORMATION|MB_YESNO|MB_SYSTEMMODAL ) ) + needreboot = false; + + // 簡易説明書出力 + if( ::GetACP() == 932 ) + { + kiFile fp; + if( fp.open( kiPath(workDir)+="読んでね.txt", false ) ) + { + static const char * text = +"このフォルダには、caldixでダウンロードされた\r\n" +"DLLの説明書を格納してあります。よくお読み下さい。\r\n" +"\r\n" +"★ UNZIP32.DLL を企業内等で利用する場合には、必ず\r\n" +"★ ライセンス契約が必要です。詳細は下記ページにて。\r\n" +"★ http://www.csdinc.co.jp/archiver/lib/unzip32.html\r\n" +"\r\n" +"それぞれのDLLの作者様のサイトは、\r\n" +" 『統合アーカイバプロジェクト』\r\n" +"   http://www.csdinc.co.jp/archiver/ \r\n" +"からリンクをたどって訪れることが出来ます。\r\n" +"是非一度は行ってみることをお勧めします。\r\n" +"\r\n" +"DLLのアンインストールは uncaldix が便利。\r\n" +" http://www6.plala.or.jp/amasoft/soft/uncaldix.html\r\n" +"\r\n" +"caldixに関するご質問等は( http://www.kmonos.net/ )へ\r\n" + ; fp.write( text, ki_strlen(text) ); + } + } + + // 出力先開く + if( cfg->ShowReadMe ) + { + char cmdline[1000]; +// コメントアウトcaldixF +/* + ::wsprintf( cmdline, "explorer \"%s\"", (const char*)workDir ); + ::WinExec( cmdline, SW_SHOWDEFAULT ); +*/ +// コメントアウトここまでcaldixF + +// 挿入caldixF + char wdir[MAX_PATH*3]; + + // caldixのパスを取得 + GetModuleFileName(NULL,wdir,MAX_PATH); + // caldix.exe→cldxにする + lstrcpy(GetFileName(wdir),"cldx"); + + // prefixとpostfixをつける( modified by k.inaba ) + bool bNeedQuote = false; + for(int i=0; i!=cfg->Filer.len(); ++i) + if(cfg->Filer[i]==' ') { bNeedQuote=true; break; } + ::wsprintf( cmdline, + bNeedQuote ? "\"%s\" %s\"%s\"%s" : "%s %s\"%s\"%s", + (const char*)cfg->Filer, + (const char*)cfg->F_Prefix, wdir, (const char*)cfg->F_Suffix); + + // ファイラ起動( modified by k.inaba ) + STARTUPINFO si = {sizeof(si)}; + PROCESS_INFORMATION pi; + { + kiPath original_cur(kiPath::Cur), sys(kiPath::Sys); // 大丈夫なはずだけど念のためのカレント移動 + ::SetCurrentDirectory(sys); + ::CreateProcess( NULL, cmdline, NULL, NULL, FALSE, 0, NULL, wdir, &si, &pi ); + ::SetCurrentDirectory(original_cur); + } + ::CloseHandle(pi.hProcess); + ::CloseHandle(pi.hThread); +// 挿入ここまでcaldixF + } + + if( needreboot ) + rebootWindows(); // 再起動でーす + } + + void askRasHangUp() + { + // 訊かないモード + if( cfg->George ) + return; + + // DLL,及び必要な関数をロード + HINSTANCE rasdll = kiutil::safepathLoadLibrary( "RASAPI32.DLL" ); + if( rasdll == NULL ) + return; + typedef DWORD (WINAPI * rE)( LPRASCONN,LPDWORD,LPDWORD ); + typedef DWORD (WINAPI * rH)( HRASCONN ); + typedef BOOL (WINAPI * rS)( HRASCONN,LPRASCONNSTATUS ); + rE RasEnumConnections = (rE)::GetProcAddress( rasdll, "RasEnumConnectionsA" ); + rH RasHangUp = (rH)::GetProcAddress( rasdll, "RasHangUpA" ); + rS RasGetConnectStatus= (rS)::GetProcAddress( rasdll, "RasGetConnectStatusA" ); + if( RasEnumConnections!=NULL && RasHangUp!=NULL && RasGetConnectStatus!=NULL ) + { + RASCONN* RasConn = new RASCONN[1]; + DWORD Num, Size = sizeof(RASCONN); + RasConn->dwSize = sizeof(RASCONN); + int Sts = RasEnumConnections( RasConn, &Size, &Num ); + if( (Sts==ERROR_BUFFER_TOO_SMALL) || (Sts==ERROR_NOT_ENOUGH_MEMORY) ) + { + delete [] RasConn; + RasConn = new RASCONN[Size/sizeof(RASCONN)]; + Sts = RasEnumConnections( RasConn, &Size, &Num ); + } + if( Sts==0 && Num>=1 ) + { + // 訊く。 + if( IDYES==msgBox( kiStr(1000).loadRsrc( IDS_RASHANGUP ), "caldix", MB_ICONINFORMATION|MB_YESNO|MB_SYSTEMMODAL ) ) + { + // 切る + RASCONNSTATUS RasSts; + RasSts.dwSize = sizeof(RASCONNSTATUS); + for( DWORD i=0; ihrasconn ); + while( RasGetConnectStatus( RasConn->hrasconn, &RasSts ) != ERROR_INVALID_HANDLE ) + ::Sleep( 10 ); + } + } + } + delete [] RasConn; + } + ::FreeLibrary( rasdll ); + } + + ~caldix() + { + delete cfg; + } + + friend void kilib_create_new_app(); +}; + +void kilib_create_new_app() +{ + new caldix; +} ADDED Caldix.dsp Index: Caldix.dsp ================================================================== --- Caldix.dsp +++ Caldix.dsp @@ -0,0 +1,396 @@ +# Microsoft Developer Studio Project File - Name="Caldix" - Package Owner=<4> +# Microsoft Developer Studio Generated Build File, Format Version 6.00 +# ** 編集しないでください ** + +# TARGTYPE "Win32 (x86) Application" 0x0101 + +CFG=Caldix - Win32 Debug +!MESSAGE これは有効なメイクファイルではありません。 このプロジェクトをビルドするためには NMAKE を使用してください。 +!MESSAGE [メイクファイルのエクスポート] コマンドを使用して実行してください +!MESSAGE +!MESSAGE NMAKE /f "Caldix.mak". +!MESSAGE +!MESSAGE NMAKE の実行時に構成を指定できます +!MESSAGE コマンド ライン上でマクロの設定を定義します。例: +!MESSAGE +!MESSAGE NMAKE /f "Caldix.mak" CFG="Caldix - Win32 Debug" +!MESSAGE +!MESSAGE 選択可能なビルド モード: +!MESSAGE +!MESSAGE "Caldix - Win32 Release" ("Win32 (x86) Application" 用) +!MESSAGE "Caldix - Win32 Debug" ("Win32 (x86) Application" 用) +!MESSAGE + +# Begin Project +# PROP AllowPerConfigDependencies 0 +# PROP Scc_ProjName "" +# PROP Scc_LocalPath "" +CPP=cl.exe +MTL=midl.exe +RSC=rc.exe + +!IF "$(CFG)" == "Caldix - Win32 Release" + +# PROP BASE Use_MFC 0 +# PROP BASE Use_Debug_Libraries 0 +# PROP BASE Output_Dir "Release" +# PROP BASE Intermediate_Dir "Release" +# PROP BASE Target_Dir "" +# PROP Use_MFC 0 +# PROP Use_Debug_Libraries 0 +# PROP Output_Dir "Release" +# PROP Intermediate_Dir "Release" +# PROP Ignore_Export_Lib 0 +# PROP Target_Dir "" +# ADD BASE CPP /nologo /W3 /GX /O2 /D "WIN32" /D "NDEBUG" /D "_WINDOWS" /D "_MBCS" /Yu"stdafx.h" /FD /c +# ADD CPP /nologo /W3 /O1 /Oy /Ob2 /D "WIN32" /D "NDEBUG" /D "_WINDOWS" /D "_MBCS" /Yu"stdafx.h" /FD /c +# ADD BASE MTL /nologo /D "NDEBUG" /mktyplib203 /win32 +# ADD MTL /nologo /D "NDEBUG" /mktyplib203 /win32 +# ADD BASE RSC /l 0x411 /d "NDEBUG" +# ADD RSC /l 0x411 /d "NDEBUG" +BSC32=bscmake.exe +# ADD BASE BSC32 /nologo +# ADD BSC32 /nologo +LINK32=link.exe +# ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:windows /machine:I386 +# ADD LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib comctl32.lib ws2_32.lib wininet.lib fdi/fdi.lib urlmon.lib /nologo /subsystem:windows /machine:I386 /opt:"nowin98" +# SUBTRACT LINK32 /pdb:none + +!ELSEIF "$(CFG)" == "Caldix - Win32 Debug" + +# PROP BASE Use_MFC 0 +# PROP BASE Use_Debug_Libraries 1 +# PROP BASE Output_Dir "Debug" +# PROP BASE Intermediate_Dir "Debug" +# PROP BASE Target_Dir "" +# PROP Use_MFC 0 +# PROP Use_Debug_Libraries 1 +# PROP Output_Dir "Debug" +# PROP Intermediate_Dir "Debug" +# PROP Ignore_Export_Lib 0 +# PROP Target_Dir "" +# ADD BASE CPP /nologo /W3 /Gm /GX /ZI /Od /D "WIN32" /D "_DEBUG" /D "_WINDOWS" /D "_MBCS" /Yu"stdafx.h" /FD /GZ /c +# ADD CPP /nologo /W3 /Gm /GX /ZI /Od /D "WIN32" /D "_DEBUG" /D "_WINDOWS" /D "_MBCS" /Yu"stdafx.h" /FD /GZ /c +# ADD BASE MTL /nologo /D "_DEBUG" /mktyplib203 /win32 +# ADD MTL /nologo /D "_DEBUG" /mktyplib203 /win32 +# ADD BASE RSC /l 0x411 /d "_DEBUG" +# ADD RSC /l 0x411 /d "_DEBUG" +BSC32=bscmake.exe +# ADD BASE BSC32 /nologo +# ADD BSC32 /nologo +LINK32=link.exe +# ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:windows /debug /machine:I386 /pdbtype:sept +# ADD LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib comctl32.lib ws2_32.lib wininet.lib fdi/fdi.lib urlmon.lib /nologo /subsystem:windows /debug /machine:I386 /pdbtype:sept + +!ENDIF + +# Begin Target + +# Name "Caldix - Win32 Release" +# Name "Caldix - Win32 Debug" +# Begin Group "Source Files" + +# PROP Default_Filter "cpp;c;cxx;rc;def;r;odl;idl;hpj;bat" +# Begin Source File + +SOURCE=.\CabTool.cpp +# End Source File +# Begin Source File + +SOURCE=.\Caldix.cpp +# End Source File +# Begin Source File + +SOURCE=.\kiutil.cpp +# End Source File +# Begin Source File + +SOURCE=.\LzhDecoder2.cpp +# End Source File +# Begin Source File + +SOURCE=.\LzhTool.cpp +# End Source File +# Begin Source File + +SOURCE=.\StdAfx.cpp +# ADD CPP /Yc"stdafx.h" +# End Source File +# Begin Source File + +SOURCE=.\ZipTool.cpp +# End Source File +# End Group +# Begin Group "Header Files" + +# PROP Default_Filter "h;hpp;hxx;hm;inl" +# Begin Source File + +SOURCE=.\CabTool.h +# End Source File +# Begin Source File + +SOURCE=.\kiutil.h +# End Source File +# Begin Source File + +SOURCE=.\LzhDecoder2.h +# End Source File +# Begin Source File + +SOURCE=.\LzhTool.h +# End Source File +# Begin Source File + +SOURCE=.\StdAfx.h +# End Source File +# Begin Source File + +SOURCE=.\ZipTool.h +# End Source File +# End Group +# Begin Group "Resource Files" + +# PROP Default_Filter "ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe" +# Begin Source File + +SOURCE=.\caldix.ico +# End Source File +# Begin Source File + +SOURCE=.\Caldix.rc +# End Source File +# Begin Source File + +SOURCE=.\manifest.xml +# End Source File +# Begin Source File + +SOURCE=.\resource.h +# End Source File +# End Group +# Begin Group "K.I.LIB" + +# PROP Default_Filter "" +# Begin Source File + +SOURCE=.\kilib\kilib.h +# End Source File +# Begin Source File + +SOURCE=.\kilib\kilibext.h +# End Source File +# Begin Source File + +SOURCE=.\kilib\kl_app.cpp +# End Source File +# Begin Source File + +SOURCE=.\kilib\kl_app.h +# End Source File +# Begin Source File + +SOURCE=.\kilib\kl_carc.cpp +# End Source File +# Begin Source File + +SOURCE=.\kilib\kl_carc.h +# End Source File +# Begin Source File + +SOURCE=.\kilib\kl_cmd.cpp +# End Source File +# Begin Source File + +SOURCE=.\kilib\kl_cmd.h +# End Source File +# Begin Source File + +SOURCE=.\kilib\kl_dnd.cpp +# End Source File +# Begin Source File + +SOURCE=.\kilib\kl_dnd.h +# End Source File +# Begin Source File + +SOURCE=.\kilib\kl_file.cpp +# End Source File +# Begin Source File + +SOURCE=.\kilib\kl_file.h +# End Source File +# Begin Source File + +SOURCE=.\kilib\kl_find.cpp +# End Source File +# Begin Source File + +SOURCE=.\kilib\kl_find.h +# End Source File +# Begin Source File + +SOURCE=.\kilib\kl_misc.h +# End Source File +# Begin Source File + +SOURCE=.\kilib\kl_reg.cpp +# End Source File +# Begin Source File + +SOURCE=.\kilib\kl_reg.h +# End Source File +# Begin Source File + +SOURCE=.\kilib\kl_str.cpp +# End Source File +# Begin Source File + +SOURCE=.\kilib\kl_str.h +# End Source File +# Begin Source File + +SOURCE=.\kilib\kl_wcmn.cpp +# End Source File +# Begin Source File + +SOURCE=.\kilib\kl_wcmn.h +# End Source File +# Begin Source File + +SOURCE=.\kilib\kl_wnd.cpp +# End Source File +# Begin Source File + +SOURCE=.\kilib\kl_wnd.h +# End Source File +# End Group +# Begin Group "zlib" + +# PROP Default_Filter "" +# Begin Source File + +SOURCE=.\zlib\adler32.c +# SUBTRACT CPP /YX /Yc /Yu +# End Source File +# Begin Source File + +SOURCE=.\zlib\compress.c +# SUBTRACT CPP /YX /Yc /Yu +# End Source File +# Begin Source File + +SOURCE=.\zlib\crc32.c +# SUBTRACT CPP /YX /Yc /Yu +# End Source File +# Begin Source File + +SOURCE=.\zlib\deflate.c +# SUBTRACT CPP /YX /Yc /Yu +# End Source File +# Begin Source File + +SOURCE=.\zlib\deflate.h +# End Source File +# Begin Source File + +SOURCE=.\zlib\gzio.c +# SUBTRACT CPP /YX /Yc /Yu +# End Source File +# Begin Source File + +SOURCE=.\zlib\infblock.c +# SUBTRACT CPP /YX /Yc /Yu +# End Source File +# Begin Source File + +SOURCE=.\zlib\infblock.h +# End Source File +# Begin Source File + +SOURCE=.\zlib\infcodes.c +# SUBTRACT CPP /YX /Yc /Yu +# End Source File +# Begin Source File + +SOURCE=.\zlib\infcodes.h +# End Source File +# Begin Source File + +SOURCE=.\zlib\inffast.c +# SUBTRACT CPP /YX /Yc /Yu +# End Source File +# Begin Source File + +SOURCE=.\zlib\inffast.h +# End Source File +# Begin Source File + +SOURCE=.\zlib\inffixed.h +# End Source File +# Begin Source File + +SOURCE=.\zlib\inflate.c +# SUBTRACT CPP /YX /Yc /Yu +# End Source File +# Begin Source File + +SOURCE=.\zlib\inftrees.c +# SUBTRACT CPP /YX /Yc /Yu +# End Source File +# Begin Source File + +SOURCE=.\zlib\inftrees.h +# End Source File +# Begin Source File + +SOURCE=.\zlib\infutil.c +# SUBTRACT CPP /YX /Yc /Yu +# End Source File +# Begin Source File + +SOURCE=.\zlib\infutil.h +# End Source File +# Begin Source File + +SOURCE=.\zlib\maketree.c +# SUBTRACT CPP /YX /Yc /Yu +# End Source File +# Begin Source File + +SOURCE=.\zlib\trees.c +# SUBTRACT CPP /YX /Yc /Yu +# End Source File +# Begin Source File + +SOURCE=.\zlib\trees.h +# End Source File +# Begin Source File + +SOURCE=.\zlib\uncompr.c +# SUBTRACT CPP /YX /Yc /Yu +# End Source File +# Begin Source File + +SOURCE=.\zlib\zconf.h +# End Source File +# Begin Source File + +SOURCE=.\zlib\zlib.h +# End Source File +# Begin Source File + +SOURCE=.\zlib\zutil.c +# SUBTRACT CPP /YX /Yc /Yu +# End Source File +# Begin Source File + +SOURCE=.\zlib\zutil.h +# End Source File +# End Group +# Begin Source File + +SOURCE=.\ReadMe.txt +# End Source File +# End Target +# End Project ADDED Caldix.dsw Index: Caldix.dsw ================================================================== --- Caldix.dsw +++ Caldix.dsw @@ -0,0 +1,29 @@ +Microsoft Developer Studio Workspace File, Format Version 6.00 +# 警告: このワークスペース ファイル を編集または削除しないでください! + +############################################################################### + +Project: "Caldix"=.\Caldix.dsp - Package Owner=<4> + +Package=<5> +{{{ +}}} + +Package=<4> +{{{ +}}} + +############################################################################### + +Global: + +Package=<5> +{{{ +}}} + +Package=<3> +{{{ +}}} + +############################################################################### + ADDED Caldix.rc Index: Caldix.rc ================================================================== --- Caldix.rc +++ Caldix.rc @@ -0,0 +1,583 @@ +//Microsoft Developer Studio generated resource script. +// +#include "resource.h" + +#define APSTUDIO_READONLY_SYMBOLS +///////////////////////////////////////////////////////////////////////////// +// +// Generated from the TEXTINCLUDE 2 resource. +// +#include "afxres.h" + +///////////////////////////////////////////////////////////////////////////// +#undef APSTUDIO_READONLY_SYMBOLS + +///////////////////////////////////////////////////////////////////////////// +// 日本語 resources + +#if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_JPN) +#ifdef _WIN32 +LANGUAGE LANG_JAPANESE, SUBLANG_DEFAULT +#pragma code_page(932) +#endif //_WIN32 + +#ifndef _MAC +///////////////////////////////////////////////////////////////////////////// +// +// Version +// + +VS_VERSION_INFO VERSIONINFO + FILEVERSION 1,2,1,0 + PRODUCTVERSION 1,2,1,0 + FILEFLAGSMASK 0x3fL +#ifdef _DEBUG + FILEFLAGS 0x1L +#else + FILEFLAGS 0x0L +#endif + FILEOS 0x4L + FILETYPE 0x1L + FILESUBTYPE 0x0L +BEGIN + BLOCK "StringFileInfo" + BEGIN + BLOCK "041104b0" + BEGIN + VALUE "Comments", "http://www.kmonos.net/\0" + VALUE "CompanyName", "\0" + VALUE "FileDescription", "Common Archivers Library DLL Installer X\0" + VALUE "FileVersion", "1.21\0" + VALUE "InternalName", "caldix\0" + VALUE "LegalCopyright", "proposed by k.inaba\0" + VALUE "LegalTrademarks", "\0" + VALUE "OriginalFilename", "caldix.exe\0" + VALUE "PrivateBuild", "\0" + VALUE "ProductName", "K.I.Lib caldix\0" + VALUE "ProductVersion", "1.21\0" + VALUE "SpecialBuild", "\0" + END + END + BLOCK "VarFileInfo" + BEGIN + VALUE "Translation", 0x411, 1200 + END +END + +#endif // !_MAC + + +#ifdef APSTUDIO_INVOKED +///////////////////////////////////////////////////////////////////////////// +// +// TEXTINCLUDE +// + +1 TEXTINCLUDE DISCARDABLE +BEGIN + "resource.h\0" +END + +2 TEXTINCLUDE DISCARDABLE +BEGIN + "#include ""afxres.h""\r\n" + "\0" +END + +3 TEXTINCLUDE DISCARDABLE +BEGIN + "\r\n" + "\0" +END + +#endif // APSTUDIO_INVOKED + + +///////////////////////////////////////////////////////////////////////////// +// +// 24 +// + +1 24 MOVEABLE PURE "manifest.xml" + +///////////////////////////////////////////////////////////////////////////// +// +// Dialog +// + +IDD_START DIALOG DISCARDABLE 0, 0, 263, 99 +STYLE DS_ABSALIGN | DS_MODALFRAME | DS_CENTER | WS_POPUP | WS_CAPTION | + WS_SYSMENU +CAPTION "統合アーカイバDLL自動インストーラ" +FONT 9, "MS Pゴシック" +BEGIN + LTEXT "このソフトは、「統合アーカイバDLL」をインターネットから自動で入手し、貴方のパソコンで使用できるように設定を整えるためのソフトです。\r\n\r\n開始ボタンを押すと作業を始めます。\r\n\r\n注意!DCさくらやFlashGet等のソフトでブラウザ監視をしている方は、監視機能を一時的にOFFにして下さい。", + IDC_STATIC,7,7,138,85,SS_SUNKEN + GROUPBOX "実行方法",IDC_STATIC,153,9,102,49 + CONTROL "全自動(入門者向け)(&A)",IDC_WORKTYPE1,"Button", + BS_AUTORADIOBUTTON | WS_GROUP | WS_TABSTOP,160,23,86,10 + CONTROL "カスタム(上級者向け)(&C)",IDC_WORKTYPE2,"Button", + BS_AUTORADIOBUTTON,160,38,90,10 + DEFPUSHBUTTON "開始",IDOK,156,71,49,21,WS_GROUP + PUSHBUTTON "中止",IDCANCEL,208,71,47,21 +END + +IDD_VERCHECK DIALOG DISCARDABLE 0, 0, 183, 65 +STYLE DS_ABSALIGN | DS_MODALFRAME | DS_CENTER | WS_POPUP | WS_CAPTION | + WS_SYSMENU +CAPTION "統合アーカイバDLL自動インストーラ" +FONT 9, "MS Pゴシック" +BEGIN + DEFPUSHBUTTON "中止",IDCANCEL,66,44,50,14 + LTEXT "最新バージョンの情報を集めています…",IDC_MSG,7,10,169, + 8 + CONTROL "Progress1",IDC_BAR,"msctls_progress32",PBS_SMOOTH | + WS_BORDER,7,31,169,9 + RTEXT "",IDC_RESTTIME,73,19,103,9 +END + +IDD_CUSTOM1 DIALOG DISCARDABLE 0, 0, 263, 97 +STYLE DS_ABSALIGN | DS_MODALFRAME | DS_CENTER | WS_POPUP | WS_CAPTION | + WS_SYSMENU +CAPTION "統合アーカイバDLL自動インストーラ" +FONT 9, "MS Pゴシック" +BEGIN + GROUPBOX "&DLLをインストールするディレクトリ",IDC_STATIC,7,7,249, + 35,WS_GROUP + EDITTEXT IDC_DLLDIR,16,22,200,12,ES_AUTOHSCROLL + PUSHBUTTON "指定(&R)...",IDC_REF,221,21,31,14 + GROUPBOX "接続先サーバ",IDC_STATIC,7,45,69,45 + CONTROL "&Madobe",IDC_CONNECTTO1,"Button",BS_AUTORADIOBUTTON | + WS_GROUP | WS_TABSTOP,14,55,38,10 + CONTROL "C&SD Inc.",IDC_CONNECTTO2,"Button",BS_AUTORADIOBUTTON, + 14,65,41,10 + CONTROL "&Wakusei",IDC_CONNECTTO3,"Button",BS_AUTORADIOBUTTON,14, + 75,40,10 + PUSHBUTTON "&Proxy設定...",IDC_PROXY,82,54,57,14,WS_GROUP + PUSHBUTTON "その他の設定(&E)...",IDC_DETAIL,82,73,57,14 + DEFPUSHBUTTON "次へ",IDOK,156,69,49,21,WS_GROUP + PUSHBUTTON "中止",IDCANCEL,208,69,47,21 +END + +IDD_CUSTOM2 DIALOG DISCARDABLE 0, 0, 263, 99 +STYLE DS_ABSALIGN | DS_MODALFRAME | DS_CENTER | WS_POPUP | WS_CAPTION | + WS_SYSMENU +CAPTION "統合アーカイバDLL自動インストーラ" +FONT 9, "MS Pゴシック" +BEGIN + CONTROL "List1",IDC_UPDATELIST,"SysListView32",LVS_REPORT | + LVS_SINGLESEL | LVS_NOSORTHEADER | WS_BORDER | + WS_TABSTOP,7,7,144,85 + CONTROL "ダウンロードのみ(&D)",IDC_INSTMODE1,"Button", + BS_AUTORADIOBUTTON,156,20,70,12 + CONTROL "インストール(書庫残さない)(&R)",IDC_INSTMODE2,"Button", + BS_AUTORADIOBUTTON,156,33,99,10 + CONTROL "インストール(書庫残す)(&I)",IDC_INSTMODE3,"Button", + BS_AUTORADIOBUTTON,156,46,90,10 + DEFPUSHBUTTON "実行",IDOK,156,71,49,21,WS_GROUP + PUSHBUTTON "中止",IDCANCEL,208,71,47,21 +END + +IDD_INSTALL DIALOG DISCARDABLE 0, 0, 183, 65 +STYLE DS_ABSALIGN | DS_MODALFRAME | DS_CENTER | WS_POPUP | WS_CAPTION | + WS_SYSMENU +CAPTION "統合アーカイバDLL自動インストーラ" +FONT 9, "MS Pゴシック" +BEGIN + LTEXT "DLLをインストールしています…",IDC_STATIC,44,28,92,8 +END + +IDD_PROXY DIALOG DISCARDABLE 0, 0, 187, 79 +STYLE DS_MODALFRAME | DS_CENTER | WS_POPUP | WS_CAPTION | WS_SYSMENU +CAPTION "プロキシの設定" +FONT 9, "MS Pゴシック" +BEGIN + CONTROL "プロキシを指定する(&P)",IDC_USEPROXY,"Button", + BS_AUTOCHECKBOX | WS_TABSTOP,7,7,82,10 + LTEXT "ホスト名(&H)",IDC_HOST_N,23,24,34,8,WS_DISABLED + EDITTEXT IDC_HOST,60,21,113,12,ES_AUTOHSCROLL | WS_DISABLED + LTEXT "ポート番号(&T)",IDC_PORT_N,16,38,41,8,WS_DISABLED + EDITTEXT IDC_PORT,60,36,41,12,ES_AUTOHSCROLL | ES_NUMBER | + WS_DISABLED + DEFPUSHBUTTON "OK",IDOK,73,58,50,14 + PUSHBUTTON "キャンセル",IDCANCEL,130,58,50,14 +END + +IDD_DETAIL DIALOG DISCARDABLE 0, 0, 251, 187 +STYLE DS_ABSALIGN | DS_MODALFRAME | DS_CENTER | WS_POPUP | WS_CAPTION | + WS_SYSMENU +CAPTION "caldix詳細設定" +FONT 9, "MS Pゴシック" +BEGIN + CONTROL "常時接続環境で利用(&F)",IDC_CONNECT_ALWAYS,"Button", + BS_AUTOCHECKBOX | WS_GROUP | WS_TABSTOP,7,9,86,10 + CONTROL "「カスタム」で指定したディレクトリを「全自動」でも使用する(&U)", + IDC_SAVE_DESTDIR,"Button",BS_AUTOCHECKBOX | WS_TABSTOP,7, + 20,191,10 + CONTROL "終了時にcldxフォルダを開く(&O)",IDC_SHOW_README,"Button", + BS_AUTOCHECKBOX | WS_TABSTOP,7,31,105,10 + GROUPBOX "フォルダを開くファイラー",IDC_STATIC,7,43,237,47 + EDITTEXT IDC_FILERPATH,12,55,194,12,ES_AUTOHSCROLL + PUSHBUTTON "指定(&Q)...",IDC_REF,211,54,31,14 + LTEXT "オプション",IDC_STATIC,14,74,30,8 + LTEXT "前(&P):",IDC_STATIC,53,73,18,8 + EDITTEXT IDC_FILEROPT,79,71,40,12,ES_AUTOHSCROLL + LTEXT "後ろ(&S):",IDC_STATIC,137,74,23,8 + EDITTEXT IDC_FILEROPT2,166,71,40,12,ES_AUTOHSCROLL + GROUPBOX "チェック対象にするDLL",IDC_STATIC,7,93,234,62,WS_GROUP + CONTROL "Un&lha32",IDC_DLHA,"Button",BS_AUTOCHECKBOX | + WS_TABSTOP,14,104,35,10 + CONTROL "Un&Zip32",IDC_DUZP,"Button",BS_AUTOCHECKBOX | + WS_TABSTOP,14,116,35,10 + CONTROL "Zi&p圧縮系",IDC_DZIP,"Button",BS_AUTOCHECKBOX | + WS_TABSTOP,14,128,43,10 + CONTROL "&Cab32",IDC_DCAB,"Button",BS_AUTOCHECKBOX | WS_TABSTOP, + 14,140,31,10 + CONTROL "&Tar32",IDC_DTAR,"Button",BS_AUTOCHECKBOX | WS_TABSTOP, + 61,104,33,10 + CONTROL "&Rar解凍系",IDC_DRAR,"Button",BS_AUTOCHECKBOX | + WS_TABSTOP,61,116,45,10 + CONTROL "Un&GCA32",IDC_DGCA,"Button",BS_AUTOCHECKBOX | + WS_TABSTOP,61,128,45,10 + CONTROL "Un&arj32j",IDC_DARJ,"Button",BS_AUTOCHECKBOX | + WS_TABSTOP,61,140,35,10 + CONTROL "&Yz1系",IDC_DYZ1,"Button",BS_AUTOCHECKBOX | WS_TABSTOP, + 109,104,35,10 + CONTROL "&Bga32",IDC_DBGA,"Button",BS_AUTOCHECKBOX | WS_TABSTOP, + 109,116,35,10 + CONTROL "&Jack32",IDC_DJCK,"Button",BS_AUTOCHECKBOX | WS_TABSTOP, + 109,128,35,10 + CONTROL "Ais&h32",IDC_DAIS,"Button",BS_AUTOCHECKBOX | WS_TABSTOP, + 109,140,35,10 + CONTROL "&Ish32",IDC_DISH,"Button",BS_AUTOCHECKBOX | WS_TABSTOP, + 151,103,35,10 + CONTROL "Unb&el32",IDC_DBEL,"Button",BS_AUTOCHECKBOX | + WS_TABSTOP,151,115,35,10 + CONTROL "&7-zip32",IDC_D7ZP,"Button",BS_AUTOCHECKBOX | + WS_TABSTOP,151,127,35,10 + CONTROL "UnI&mp32",IDC_DIMP,"Button",BS_AUTOCHECKBOX | + WS_TABSTOP,151,140,35,10 + CONTROL "Bh&32",IDC_DBH,"Button",BS_AUTOCHECKBOX | WS_TABSTOP, + 195,103,35,10 + DEFPUSHBUTTON "OK",IDOK,140,159,49,21,WS_GROUP + PUSHBUTTON "キャンセル",IDCANCEL,195,159,47,21 +END + + +///////////////////////////////////////////////////////////////////////////// +// +// DESIGNINFO +// + +#ifdef APSTUDIO_INVOKED +GUIDELINES DESIGNINFO DISCARDABLE +BEGIN + IDD_START, DIALOG + BEGIN + LEFTMARGIN, 7 + RIGHTMARGIN, 256 + TOPMARGIN, 7 + BOTTOMMARGIN, 92 + END + + IDD_VERCHECK, DIALOG + BEGIN + LEFTMARGIN, 7 + RIGHTMARGIN, 176 + TOPMARGIN, 7 + BOTTOMMARGIN, 58 + END + + IDD_CUSTOM1, DIALOG + BEGIN + LEFTMARGIN, 7 + RIGHTMARGIN, 256 + TOPMARGIN, 7 + BOTTOMMARGIN, 90 + END + + IDD_CUSTOM2, DIALOG + BEGIN + LEFTMARGIN, 7 + RIGHTMARGIN, 255 + TOPMARGIN, 7 + BOTTOMMARGIN, 92 + END + + IDD_INSTALL, DIALOG + BEGIN + LEFTMARGIN, 7 + RIGHTMARGIN, 176 + TOPMARGIN, 7 + BOTTOMMARGIN, 58 + END + + IDD_PROXY, DIALOG + BEGIN + LEFTMARGIN, 7 + RIGHTMARGIN, 180 + TOPMARGIN, 7 + BOTTOMMARGIN, 72 + END + + IDD_DETAIL, DIALOG + BEGIN + LEFTMARGIN, 7 + RIGHTMARGIN, 244 + TOPMARGIN, 7 + BOTTOMMARGIN, 180 + END +END +#endif // APSTUDIO_INVOKED + + +///////////////////////////////////////////////////////////////////////////// +// +// Icon +// + +// Icon with lowest ID value placed first to ensure application icon +// remains consistent on all systems. +IDI_MAIN ICON DISCARDABLE "caldix.ico" + +///////////////////////////////////////////////////////////////////////////// +// +// String Table +// + +STRINGTABLE DISCARDABLE +BEGIN + IDS_NOINTERNET "インターネットに接続できませんでした。終了します。" + IDS_LV_DLLNAME "DLL名" + IDS_LV_STATE "作業の種類" + IDS_NONEED "全て最新版が入っています。バージョンアップの必要はありません。" + IDS_FINISHED "インストールは無事終了しました。\n\nDLLの説明書は ""cldx"" フォルダに保存してあります。" + IDS_NEWINST "新規導入" + IDS_UPDINST "%sに更新" + IDS_DOWNLOADING "%sをダウンロード中です。[%s]" + IDS_REBOOT "作業を完了するために、Windowsを再起動する必要があります。今すぐ再起動してよろしいですか?(起動中のアプリケーションは保存終了して下さい。)" + IDS_CANCELOK "DLLのインストールを中止してよろしいですか?" + IDS_RASHANGUP "インターネットへの接続回線を切断しますか?" + IDS_REST "残り %dKB (約%d分%02d秒)" +END + +STRINGTABLE DISCARDABLE +BEGIN + IDS_DLERROR "ダウンロードに失敗しました。日をおいてからもう一度実行してみて下さい。" +END + +#endif // 日本語 resources +///////////////////////////////////////////////////////////////////////////// + + +///////////////////////////////////////////////////////////////////////////// +// 英語 (アメリカ) resources + +#if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_ENU) +#ifdef _WIN32 +LANGUAGE LANG_ENGLISH, SUBLANG_ENGLISH_US +#pragma code_page(1252) +#endif //_WIN32 + +///////////////////////////////////////////////////////////////////////////// +// +// Dialog +// + +IDD_CUSTOM1 DIALOG DISCARDABLE 0, 0, 263, 97 +STYLE DS_ABSALIGN | DS_MODALFRAME | DS_CENTER | WS_POPUP | WS_CAPTION | + WS_SYSMENU +CAPTION "Common Archivers Library DLL Installer X" +FONT 9, "MS Sans Serif" +BEGIN + GROUPBOX "&Directory to install DLL",IDC_STATIC,7,7,249,35, + WS_GROUP + EDITTEXT IDC_DLLDIR,16,22,205,12,ES_AUTOHSCROLL + PUSHBUTTON "&Ref...",IDC_REF,226,21,24,14 + GROUPBOX "Update Info Server",IDC_STATIC,7,45,84,45 + CONTROL "&Madobe",IDC_CONNECTTO1,"Button",BS_AUTORADIOBUTTON | + WS_GROUP | WS_TABSTOP,14,56,38,10 + CONTROL "C&SD Inc.",IDC_CONNECTTO2,"Button",BS_AUTORADIOBUTTON, + 14,66,41,10 + CONTROL "&Wakusei",IDC_CONNECTTO3,"Button",BS_AUTORADIOBUTTON,14, + 76,40,10 + PUSHBUTTON "&Proxy...",IDC_PROXY,100,75,49,14 + DEFPUSHBUTTON "Next",IDOK,156,69,49,21,WS_GROUP + PUSHBUTTON "Cancel",IDCANCEL,208,69,47,21 +END + +IDD_CUSTOM2 DIALOG DISCARDABLE 0, 0, 263, 99 +STYLE DS_ABSALIGN | DS_MODALFRAME | DS_CENTER | WS_POPUP | WS_CAPTION | + WS_SYSMENU +CAPTION "Common Archivers Library DLL Installer X" +FONT 9, "MS Sans Serif" +BEGIN + CONTROL "List1",IDC_UPDATELIST,"SysListView32",LVS_REPORT | + LVS_SINGLESEL | LVS_NOSORTHEADER | WS_BORDER | + WS_TABSTOP,7,7,144,85 + DEFPUSHBUTTON "Start",IDOK,156,71,49,21,WS_GROUP + PUSHBUTTON "Cancel",IDCANCEL,208,71,47,21 + CONTROL "&Download Only",IDC_INSTMODE1,"Button", + BS_AUTORADIOBUTTON,159,18,93,10 + CONTROL "Install(&Remove Archive)",IDC_INSTMODE2,"Button", + BS_AUTORADIOBUTTON,159,30,96,10 + CONTROL "&Install",IDC_INSTMODE3,"Button",BS_AUTORADIOBUTTON,159, + 42,96,10 +END + +IDD_START DIALOG DISCARDABLE 0, 0, 263, 99 +STYLE DS_ABSALIGN | DS_MODALFRAME | DS_CENTER | WS_POPUP | WS_CAPTION | + WS_SYSMENU +CAPTION "Common Archivers Library DLL Installer X" +FONT 9, "MS Sans Serif" +BEGIN + LTEXT "You can automatically download and install ""Common Archiver DLLs"" from Internet by this software.\r\n\r\nPush 'Start' button to begin installation.", + IDC_STATIC,7,7,138,85,SS_SUNKEN + GROUPBOX "Install Type",IDC_STATIC,153,7,102,52 + CONTROL "Full &Automatic",IDC_WORKTYPE1,"Button", + BS_AUTORADIOBUTTON | WS_GROUP | WS_TABSTOP,161,22,86,10 + CONTROL "&Custom",IDC_WORKTYPE2,"Button",BS_AUTORADIOBUTTON,161, + 36,90,10 + DEFPUSHBUTTON "Start",IDOK,156,71,49,21,WS_GROUP + PUSHBUTTON "Cancel",IDCANCEL,208,71,47,21 +END + +IDD_VERCHECK DIALOG DISCARDABLE 0, 0, 183, 65 +STYLE DS_ABSALIGN | DS_MODALFRAME | DS_CENTER | WS_POPUP | WS_CAPTION | + WS_SYSMENU +CAPTION "Common Archivers Library DLL Installer X" +FONT 9, "MS Sans Serif" +BEGIN + DEFPUSHBUTTON "Cancel",IDCANCEL,66,44,50,14 + LTEXT "Collecting the latest information...",IDC_MSG,7,10,162, + 8 + CONTROL "Progress1",IDC_BAR,"msctls_progress32",PBS_SMOOTH | + WS_BORDER,7,26,169,9 +END + +IDD_INSTALL DIALOG DISCARDABLE 0, 0, 183, 65 +STYLE DS_ABSALIGN | DS_MODALFRAME | DS_CENTER | WS_POPUP | WS_CAPTION | + WS_SYSMENU +CAPTION "Common Archivers Library DLL Installer X" +FONT 9, "MS Sans Serif" +BEGIN + CTEXT "Installing DLLs...",IDC_STATIC,27,28,124,8 +END + +IDD_PROXY DIALOG DISCARDABLE 0, 0, 187, 79 +STYLE DS_MODALFRAME | DS_CENTER | WS_POPUP | WS_CAPTION | WS_SYSMENU +CAPTION "Proxy" +FONT 9, "MS Sans Serif" +BEGIN + CONTROL "Use &Proxy",IDC_USEPROXY,"Button",BS_AUTOCHECKBOX | + WS_TABSTOP,7,7,165,10 + LTEXT "&Host",IDC_HOST_N,23,24,15,8,WS_DISABLED + EDITTEXT IDC_HOST,42,21,129,12,ES_AUTOHSCROLL | WS_DISABLED + LTEXT "Por&t",IDC_PORT_N,24,38,13,8,WS_DISABLED + EDITTEXT IDC_PORT,42,36,41,12,ES_AUTOHSCROLL | ES_NUMBER | + WS_DISABLED + DEFPUSHBUTTON "OK",IDOK,73,58,50,14 + PUSHBUTTON "Cancel",IDCANCEL,130,58,50,14 +END + + +///////////////////////////////////////////////////////////////////////////// +// +// DESIGNINFO +// + +#ifdef APSTUDIO_INVOKED +GUIDELINES DESIGNINFO DISCARDABLE +BEGIN + IDD_CUSTOM1, DIALOG + BEGIN + LEFTMARGIN, 7 + RIGHTMARGIN, 256 + TOPMARGIN, 7 + BOTTOMMARGIN, 90 + END + + IDD_CUSTOM2, DIALOG + BEGIN + LEFTMARGIN, 7 + RIGHTMARGIN, 256 + TOPMARGIN, 7 + BOTTOMMARGIN, 92 + END + + IDD_START, DIALOG + BEGIN + LEFTMARGIN, 7 + RIGHTMARGIN, 256 + TOPMARGIN, 7 + BOTTOMMARGIN, 92 + END + + IDD_VERCHECK, DIALOG + BEGIN + LEFTMARGIN, 7 + RIGHTMARGIN, 176 + TOPMARGIN, 7 + BOTTOMMARGIN, 58 + END + + IDD_INSTALL, DIALOG + BEGIN + LEFTMARGIN, 7 + RIGHTMARGIN, 176 + TOPMARGIN, 7 + BOTTOMMARGIN, 58 + END + + IDD_PROXY, DIALOG + BEGIN + LEFTMARGIN, 7 + RIGHTMARGIN, 180 + TOPMARGIN, 7 + BOTTOMMARGIN, 72 + END +END +#endif // APSTUDIO_INVOKED + + +///////////////////////////////////////////////////////////////////////////// +// +// String Table +// + +STRINGTABLE DISCARDABLE +BEGIN + IDS_NOINTERNET "Couldn't connect to network." + IDS_LV_DLLNAME "Name" + IDS_LV_STATE "State" + IDS_NONEED "You already have the latest version DLLs. No need to update." + IDS_FINISHED "Installation finished. Document of each DLL is in 'cldx' folder." + IDS_NEWINST "New" + IDS_UPDINST "%s is avail." + IDS_DOWNLOADING "Downloading %s ... [%s]" + IDS_REBOOT "You should reboot Windows to finish installation. Are you ready to reboot ?" + IDS_CANCELOK "Do you want to abort the installation ?" + IDS_RASHANGUP "Do you want to Hang up the dial-up connection ?" + IDS_REST "Rest %d KB (%d'%02d)" +END + +STRINGTABLE DISCARDABLE +BEGIN + IDS_DLERROR "Download error !" +END + +#endif // 英語 (アメリカ) resources +///////////////////////////////////////////////////////////////////////////// + + + +#ifndef APSTUDIO_INVOKED +///////////////////////////////////////////////////////////////////////////// +// +// Generated from the TEXTINCLUDE 3 resource. +// + + +///////////////////////////////////////////////////////////////////////////// +#endif // not APSTUDIO_INVOKED + ADDED LzhDecoder2.cpp Index: LzhDecoder2.cpp ================================================================== --- LzhDecoder2.cpp +++ LzhDecoder2.cpp @@ -0,0 +1,357 @@ + +#include "stdafx.h" +#include "LzhDecoder2.h" + +void CLzhDecoder2::Unstore() +{ +#define UNS_BUFSIZE (32768) + int how_much; + char buf[UNS_BUFSIZE]; + + if( cmpsize==-1 ) + { + while( (how_much=fread(buf,1,UNS_BUFSIZE,in))!=0 ) + { + if( how_much==-1 ) + break; + fwrite(buf,1,how_much,out); + } + return; + } + + while( cmpsize>0 ) + { + how_much = cmpsize>UNS_BUFSIZE?UNS_BUFSIZE:cmpsize; + if( 0>=(how_much=fread( buf,1,how_much,in )) ) + break; + fwrite( buf,1,how_much,out ); + cmpsize -= how_much; + } +} + +void CLzhDecoder2::Decode( lzh_method mhd,FILE* infile,DWORD insize, + FILE* outfile,DWORD outsize ) +{ + in = infile; + cmpsize = insize; + out = outfile; + orisize = outsize; + + DWORD dicsiz,dicbit; + + // メソッドによっていろいろ切り替え + switch( mhd ) + { + case LH0:Unstore(); return; + default: return; + + case LH4: np=14,pbit=4,dicbit=12,dicsiz=(1<=dicsiz ) + { + fwrite( text,1,dicsiz,out ); + loc = 0; + } + if( ++i>=(int)dicsiz ) + i = 0; + } + } + } + + if( loc!=0 ) + fwrite( text,1,loc,out ); + + delete [] text; +} + +/**************** LH4-7,ARJ,ZOO ************************/ + +void CLzhDecoder2::make_table(WORD nchar,BYTE* bitlen, + WORD tablebits,WORD* table) +{ + WORD count[17],weight[17],start[17],total,*p; + unsigned int i; + int j,k,l,m,n,avail; + + avail = nchar; + + for( i=1; i<=16; i++ ) + { + count[i] = 0; + weight[i] = 1 << (16 - i); + } + + for( i=0; i>= m; + weight[i] >>= m; + } + + j = start[tablebits + 1] >> m; + k = 1 << tablebits; + if( j!=0 ) + for( i=j; i<(unsigned)k; i++ ) + table[i] = 0; + + for( j=0; j> m]; + i <<= tablebits; + n = k - tablebits; + while (--n >= 0) + { + if (*p == 0) + { + right[avail] = left[avail] = 0; + *p = avail++; + } + if (i & 0x8000) + p = &right[*p]; + else + p = &left[*p]; + i <<= 1; + } + *p = j; + } + start[k] = l; + } +} + +void CLzhDecoder2::read_pt_len(short nn,short nbit,short i_special) +{ + short i, c, n=getbits((BYTE)nbit); + + if( n==0 ) + { + c = getbits((BYTE)nbit); + for( i=0; i> (16-3); + if( c==7 ) + { + WORD mask = 1<<(16-4); + while( mask&bitbuf ) + { + mask >>= 1; + c++; + } + } + fillbuf( (c<7) ? 3 : c-3 ); + pt_len[i++] = (BYTE)c; + if( i==i_special ) + { + c = getbits(2); + while( --c>=0 ) + pt_len[i++] = 0; + } + } + while( i>(16-8) ]; + if( c>=NT ) + { + WORD mask = 1<<(16-9); + do + { + if( bitbuf&mask )c = right[c]; + else c = left[c]; + mask >>= 1; + }while( c>=NT ); + } + fillbuf(pt_len[c]); + if( c<=2 ) + { + if( c==0 ) c = 1; + else if( c==1 ) c = getbits(4) + 3; + else c = getbits(CBIT) + 20; + while( --c>=0 ) + c_len[i++] = 0; + } + else + c_len[i++] = c-2; + } + while( i>4 ]; + if( j>= 1; + }while( j>=NC ); + fillbuf( c_len[j]-12 ); + } + return j; +} + +WORD CLzhDecoder2::decode_p_st1() +{ + WORD j, mask; + + j = pt_table[ bitbuf>>(16-8) ]; + if( j>= 1; + }while( j>=np ); + fillbuf(pt_len[j] - 8); + } + if( j!=0 ) + j = (1<<(j-1)) + getbits(j-1); + return j; +} + + +/******************** bit単位のread&write ************************/ + +void CLzhDecoder2::init_getbits() +{ + bitbuf = 0; + subbitbuf = 0; + bitcount = 0; + fillbuf(16); +} + +void CLzhDecoder2::fillbuf(BYTE n) +{ + while( n>bitcount ) + { + n -= bitcount; + bitbuf = (bitbuf<>(8-bitcount)); + if( cmpsize!=0 ) + { + cmpsize--; + subbitbuf = (BYTE)getc(in); + } + else + subbitbuf = 0; + bitcount = 8; + } + bitcount -= n; + bitbuf = (bitbuf<>(8-n)); + subbitbuf <<= n; +} + +WORD CLzhDecoder2::getbits(BYTE n) +{ + WORD x = bitbuf>>(16-n); + fillbuf(n); + return x; +} ADDED LzhDecoder2.h Index: LzhDecoder2.h ================================================================== --- LzhDecoder2.h +++ LzhDecoder2.h @@ -0,0 +1,74 @@ +#ifndef AFX_LZHDECODER2_H__31F8AA04_3F84_11D4_8D96_8AB5A6462337__INCLUDED_ +#define AFX_LZHDECODER2_H__31F8AA04_3F84_11D4_8D96_8AB5A6462337__INCLUDED_ + +#define MAXMATCH 256 +#define THRESHOLD 3 + +#define NT (16+3) +#define TBIT 5 +#define CBIT 9 +#define NC (255+MAXMATCH+2-THRESHOLD) +#define NPT 0x80 + +#define N_CHAR (256+60-THRESHOLD+1) +#define TREESIZE_C (N_CHAR*2) +#define TREESIZE_P (128*2) +#define TREESIZE (TREESIZE_C+TREESIZE_P) +#define ROOT_C 0 +#define ROOT_P TREESIZE_C + +enum lzh_method{ LH0,LH4,LH5,LH6,LH7,UNKNOWN }; + +class CLzhDecoder2 +{ +public: + void Decode( lzh_method mhd,FILE* infile,DWORD insize, + FILE* outfile,DWORD outsize ); + +private: + void Unstore(); + WORD Decode_C(lzh_method mhd) + {switch( mhd ){ + case LH4: + case LH5: + case LH6: + case LH7:return decode_c_st1(); + }return 0;}; + WORD Decode_P(lzh_method mhd) + {switch( mhd ){ + case LH4: + case LH5: + case LH6: + case LH7:return decode_p_st1(); + }return 0;}; + +private: + // 全般的に + FILE *in,*out; + DWORD cmpsize,orisize; + + DWORD loc; + + // lh4-lh7 + void make_table(WORD nchar,BYTE* bitlen,WORD tablebits,WORD* table); + void read_pt_len(short nn,short nbit,short i_special); + void read_c_len(); + WORD decode_c_st1(); + WORD decode_p_st1(); + + WORD left[ 2*NC-1 ], right[ 2*NC-1 ]; + BYTE c_len[NC], pt_len[NPT]; + WORD c_table[4096],pt_table[256]; + + WORD blocksize; + int pbit; + int np; + + // bit単位のread&write + void init_getbits(); + void fillbuf(BYTE n); + WORD getbits(BYTE n); + WORD bitbuf;BYTE subbitbuf,bitcount; +}; + +#endif ADDED LzhTool.cpp Index: LzhTool.cpp ================================================================== --- LzhTool.cpp +++ LzhTool.cpp @@ -0,0 +1,257 @@ + +#include "stdafx.h" +#include "LzhTool.h" +#include "LzhDecoder2.h" +#include "kiutil.h" +#include "kilib/kilib.h" + +bool CLzhTool::crcinit; +unsigned short CLzhTool::crctable[256]; + +bool CLzhTool::Extract( const char* aname, const char* dll, kiPath& dll_rel_path ) +{ + // 先頭の方を読み込み + FILE* fp = fopen( aname,"rb" ); + if( !fp ) + return false; + unsigned char* buff = new unsigned char[65536]; + DWORD siz = fread( buff, 1, 65536, fp ); + fclose( fp ); + // ヘッダを探す + int ps = FindHeader( aname,buff,siz ); + // 書庫を開く + if( ps==-1 || !(lzh = fopen( aname,"rb" )) ) + { + delete [] buff; + return false; + } + + fseek( lzh,ps,SEEK_SET ); + + // 格納ファイル毎に処理 + while( ReadHeader( buff ) ) + { + long base = ftell( lzh ); + char* name; + + if( h_FileName[0]!='!' && h_FileName[0]!='$' && h_FileName[0]!='%' ) + if( out=fopen( name=kiutil::pathMake(h_FileName),"wb" ) ) + { + if( 0==strcmpi( kiPath::name(name), dll ) ) // DLLの位置を記憶 + dll_rel_path = name; + + // デコード + CLzhDecoder2 dec; + lzh_method mhd = UNKNOWN; + if( 0==strcmp(h_Method,"-lh0-") )mhd=LH0; + else if( 0==strcmp(h_Method,"-lh5-") )mhd=LH5; + else if( 0==strcmp(h_Method,"-lh6-") )mhd=LH6; + else if( 0==strcmp(h_Method,"-lh7-") )mhd=LH7; + dec.Decode( mhd, lzh, h_CompSize, out, h_OrigSize ); + + // 属性など設定 + fclose( out ); + + SetFileAttributes( name,h_Attrib ); + if( h_Level<2 ) + kiutil::timeSet( name, (WORD)(h_Update>>16),(WORD)h_Update ); + else + kiutil::timeSet( name, h_Update ); + } + + fseek( lzh, base+h_CompSize, SEEK_SET ); + } + + delete [] buff; + fclose( lzh ); + return true; +} + +int CLzhTool::FindHeader( const char* fname, const BYTE* hdr, DWORD siz ) +{ + bool bopen = false; + BYTE* temp; + int ans=-1; + + for( DWORD i=0; i2 ) // LV3以上未対応 + return false; + + BYTE bshdr = (h_Level==2)?26:buf[0]+2; + if( bshdr<21 || buf[0]==0 ) + return false; + BYTE hdrsum= buf[1]; + for( int i=0; i!=5; i++ ) + h_Method[i]=(char)buf[2+i];h_Method[5]=0; + h_CompSize = (buf[ 7])+(buf[ 8]<<8)+(buf[ 9]<<16)+(buf[10]<<24); + h_OrigSize = (buf[11])+(buf[12]<<8)+(buf[13]<<16)+(buf[14]<<24); + h_Update = (buf[15])+(buf[16]<<8)+(buf[17]<<16)+(buf[18]<<24); + h_Attrib = buf[19]; + if( h_Method[0]!='-' || h_Method[1]!='l' ) + return false; + +// レベル共通じゃない基本ヘッダ部分 +// +// 21: file_name_length +// 22- n: file_name ( with path info ) +// WORD: crc16_of_file +// : and some extension part +// +//

+// 21: file_name_length +// 22- n: file_name ( with no path info ) +// WORD: crc16_of_file +// BYTE: os_flag +// : and some extension part +// +//

+// WORD: crc16_of_file +// BYTE: os_flag +// +// + if( (bshdr-21)!=fread_crc(buf+21,(bshdr-21)) ) + return false; + if( h_Level!=2 ) + { + if( sum!=hdrsum || 21+1+buf[21]+2>bshdr ) + return false; + memcpy( h_FileName,buf+22,buf[21] ); + h_FileName[buf[21]]=0; + } + +// 拡張ヘッダ( h1/h2 ) +// repeating of such blocks. +//------------------------------------------------------ +// WORD: size_of_this_block ( if 0 then end_of_header ) +// BYTE: type_flag +// : data ( (blocksize-3) bytes ) +//------------------------------------------------------ + + char PathName[MAX_PATH*2]={0}; + if( h_Level!=0 ) + { + DWORD hdrcrc=0xffffffff; + WORD tmpcrc; + + // ここでループって拡張ヘッダ読み込み + WORD ehs; + ehs = ((buf[bshdr-2])|(buf[bshdr-1]<<8)); + + while( ehs>2 ) + { + tmpcrc=crc;//CRC自身を読み込んだときに直すため + if( ehs!=fread_crc(buf,ehs) ) + return false; + if( h_Level==1 ) + h_CompSize-=ehs; + + switch( *buf ) + { + case 0x00://共通 + if( ehs>=5 && hdrcrc==0xffffffff ) + { + hdrcrc=((buf[1])|(buf[2]<<8)); + + crc=tmpcrc; + buf[1]=buf[2]=0; + UpdateCRC(buf,ehs); + } + break; + case 0x01://ファイル名 + memcpy(h_FileName,buf+1,ehs-3>MAX_PATH?MAX_PATH:ehs-3); + h_FileName[ehs-3>MAX_PATH?MAX_PATH:ehs-3]=0; + break; + case 0x02://パス名 + memcpy(PathName,buf+1,ehs-3>MAX_PATH?MAX_PATH:ehs-3); + PathName[ehs-3>MAX_PATH?MAX_PATH:ehs-3]=0; + break; + case 0xff://新属性 + break; + case 0x40://属性(DOS依存) + if( ehs>=5 ) + h_Attrib=((buf[1])|(buf[2]<<8)); + break; + case 0x41://タイムスタンプ(UNLHA32.DLL) + //は、なんだかうまくいかないので無視する。 + break; + } + + ehs = ((buf[ehs-2])|(buf[ehs-1]<<8)); + } + + if( hdrcrc!=0xffffffff && crc!=hdrcrc ) + return false; + } + + // ff -> \\ 変換 + char* x; + for( x=h_FileName; *x!=0; x=CharNext(x) ) + if( (BYTE)*x==0xff ) + *x='\\'; + for( x=PathName; *x!=0; x=CharNext(x) ) + if( (BYTE)*x==0xff ) + *x='\\'; + strcat( PathName,h_FileName ); + strcpy( h_FileName,PathName ); + return true; + +// lha header MEMO +// (h0/h1) +// 1 byte 目は、「1byte目自身を除いた基本ヘッダのサイズ」 +// チェックサムは、「1,2byte目自身を除いた基本ヘッダの合計」 +// (h1) +// offset_to_next_hdr は、基本ヘッダ末端から次のヘッダへの距離 +// (h1/h2) +// crcは自分自身は0000として他全部から算出 +} ADDED LzhTool.h Index: LzhTool.h ================================================================== --- LzhTool.h +++ LzhTool.h @@ -0,0 +1,55 @@ +#ifndef AFX_LZHTOOL_H__31F8AA01_3F84_11D4_8D96_8AB5A6462337__INCLUDED_ +#define AFX_LZHTOOL_H__31F8AA01_3F84_11D4_8D96_8AB5A6462337__INCLUDED_ + +// Lzh Archive Extraction ... ( XacRett #39 SubSet ) + +class CLzhTool +{ +public: + //-- 外向きインターフェイス -------------- + bool Extract( const char* aname, const char* dll, kiPath& dll_rel_path ); + +public: + //-- CRC 計算 --------------------------- + static bool crcinit; + static unsigned short crctable[256]; + static void init_crc_table(){ + if( !crcinit ) + for( unsigned short i=0,j,r; i!=256; i++ ) + { + r = i; + for( j=0; j!=8; j++ ) + { + if( r&1 ) r = ((r>>1)^0xA001); + else r>>=1; + } + crctable[i] = r; + }} + CLzhTool() { init_crc_table(); } + +private: + //-- 内部処理 + int FindHeader( const char* fname, const BYTE* hdr, DWORD siz ); + bool ReadHeader( unsigned char* buf ); + + WORD crc; + BYTE sum; + void UpdateCRC( BYTE *p,int n ) + {while( n-- )crc = crctable[(crc^(*p++))&0xff] ^ (crc >> 8);} + void UpdateSum( BYTE *p,int n ) + {while( n-- )sum+=*(p++);} + int fread_crc( BYTE* p,int n) + {n=fread(p,1,n,lzh);if(n==-1)n=0; + UpdateCRC(p,n);UpdateSum(p,n);return n;} + + FILE *lzh,*out; + BYTE h_Level; // ヘッダレベル + char h_FileName[MAX_PATH*2]; // ファイル名(パス付き) + char h_Method[6]; // 圧縮法 "-lh5-" など。 + DWORD h_CompSize; // 圧縮されたサイズ + DWORD h_OrigSize; // 元のサイズ + WORD h_Attrib; // 属性 + DWORD h_Update; // 更新日時(h0,h1:ftime h2:time_t) +}; + +#endif ADDED ReadMe.txt Index: ReadMe.txt ================================================================== --- ReadMe.txt +++ ReadMe.txt @@ -0,0 +1,113 @@ + +★ caldix 1.21 について色々 +★ 2010/11/25 + + + +【ダウンロード対象とするDLLを減らす方法】 + +  caldix.iniファイルを用意し、以下のような3行を書いてください。 + + [conf] + Ver=121 + DLLList=LZzCTARBJGbaIY7iH + +  DLLList= の右側の各文字が、対象とするDLLを表しています。 +   L : Unlha32 +   Z : UnZip32 +   z : Zip32j Zip32 sfx32gui.dat (zip圧縮系) +   C : Cab32 +   T : Tar32 +   A : Unarj32j +   R : Unrar32 Unrar (rar解凍系) +   B : Bga32 +   J : Jack32 +   G : UnGCA32 +   b : Unbel32 +   a : Aish32 +   I : Ish32 +   Y : Yz1 +   7 : 7-zip32 +   i : Unimp32 +   H : Bh32 +  以上の通りです。例えばUnlhaとUnzipだけで十分なら、 + + [conf] + Ver=121 + DLLList=LZ + +  と書けばよいわけです。 +  使わないDLLは無視するようにして作業時間を短縮したい方や、 +  他のソフトのバンドル用として使うために、非対応DLLは +  落とさなくても良い、という場合にご利用下さい。 + +  1.10までのバージョンと比べて、Ver= という行が増えていることに +  注意して下さい。古いバージョンのcaldixから自動生成されたcaldix.iniには +  新しいDLLである7-zip32.dll対応用の"7"が含まれていないため、そのまま +  1.11に移行しても7-zipを認識しないという悲しい状況になってしまうため、 +  急遽付け足したフラグがこの Ver= です。えーと要するに私K.INABAの +  設計ミスとも言います。 + +  動作としては、Ver=111 (以上)が入っていないと、"7" が無くても +  7-zip32.dllをダウンロードしてしまう、という違いになります。 + + + +【ソースについて】 + +  Visual C++ 6.0 用です。笑っちゃうような適当なコードが +  散見されますので、参考にしようと思った方はたぶん失望します。 + +   Special Thanks! + + T.Matsumoto 氏による caldixF Version 1.16 の改善点を + caldix/1.17 へ取り込みました。感謝します。 + -- http://tmsoft.webhop.net/caldix/ + +  caldix::askRasHangUp() は、曽田氏作の FFFTP を参考にしています。 + -- http://www2.biglobe.ne.jp/~sota/ + +  認証の必要なProxyに対応できるようになるソースを、 +  ユーザーの川崎氏にご教授いただきました。ありがとうございます。 + +  zip展開部分に zlib 1.1.3 を使用しています。 +  (C) 1995-1998 Jean-loup Gailly and Mark Adler + -- http://www.info-zip.org/pub/infozip/zlib/ + +  lzh展開部分に LHa for unix のソースを利用しています。 + -- http://www2m.biglobe.ne.jp/~dolphin/lha/lha-unix.htm + +  cab展開部分に Microsoft社 の CabinetSDK を使用しています。 + +  ! caldixをビルドするには、fdi ディレクトリに fdi.lib と fdi.h を +  ! 入れておいてください。Platform SDK から入手できます。 + -- http://www.microsoft.com/msdownload/platformsdk/sdkupdate/ + + + +【利用条件】 + +  caldix の「zlib/* LzhDecoder2.* を除くソース全て」及び +  配布バイナリ「caldix.exe」は以下のライセンスの下に公開されています。 + + + --- NYSL ver 0.9982 ( http://nysl.kinaba.cjb.net )--- + + A. 本ソフトウェアは Everyone'sWare です。このソフトを手にした一人一人が、 + ご自分の作ったものを扱うのと同じように、自由に利用することが出来ます。 + + A-1. フリーウェアです。作者からは使用料等を要求しません。 + A-2. 有料無料や媒体の如何を問わず、自由に転載・再配布できます。 + A-3. いかなる種類の 改変・他プログラムでの利用 を行っても構いません。 + A-4. 変更したものや部分的に使用したものは、あなたのものになります。 + 公開する場合は、あなたの名前の下で行って下さい。 + + B. このソフトを利用することによって生じた損害等について、作者は + 責任を負わないものとします。各自の責任においてご利用下さい。 + + C. 著作者人格権は K.INABA に帰属します。著作権は放棄します。 + + D. 以上の3項は、ソース・実行バイナリの双方に適用されます。 + +-------------------------------------------------------- +by k.inaba( http://www.kmonos.net/ ) ADDED StdAfx.cpp Index: StdAfx.cpp ================================================================== --- StdAfx.cpp +++ StdAfx.cpp @@ -0,0 +1,8 @@ +// stdafx.cpp : 標準インクルードファイルを含むソース ファイル +// Caldix.pch 生成されるプリコンパイル済ヘッダー +// stdafx.obj 生成されるプリコンパイル済タイプ情報 + +#include "stdafx.h" + +// TODO: STDAFX.H に含まれていて、このファイルに記述されていない +// ヘッダーファイルを追加してください。 ADDED StdAfx.h Index: StdAfx.h ================================================================== --- StdAfx.h +++ StdAfx.h @@ -0,0 +1,18 @@ +#ifndef FX_STDAFX_H__A9DB83DB_A9FD_11D0_BFD1_444553540000__INCLUDED_ +#define AFX_STDAFX_H__A9DB83DB_A9FD_11D0_BFD1_444553540000__INCLUDED_ + +#undef WINVER +#define WINVER 0x0400 +#include + +#include +#include + +#include "kilib/kilibext.h" +#include +#include +#include +#include +#include + +#endif ADDED ZipTool.cpp Index: ZipTool.cpp ================================================================== --- ZipTool.cpp +++ ZipTool.cpp @@ -0,0 +1,277 @@ + +#include "stdafx.h" +#include "ZipTool.h" +#include "zlib/zlib.h" +#include "kiutil.h" +#include "kilib/kilib.h" + +bool CZipTool::Extract( const char* aname, const char* dll, kiPath& dll_rel_path ) +{ + ZipLocalHeader hdr; + + if( !(zip=fopen(aname,"rb")) ) + return false; + + while( doHeader( &hdr ) ) + { + unsigned long posnext = ftell( zip ) + hdr.csz; + char* name; + + if( out=fopen( name=kiutil::pathMake(hdr.fnm),"wb") ) + { + if( 0==strcmpi( kiPath::name(name), dll ) ) // DLLの位置を記憶 + dll_rel_path = name; + + // 展開! + switch( hdr.mhd ) + { + case Stored: Unstore( hdr.usz, hdr.csz ); break; + case Deflated: Inflate( hdr.usz, hdr.csz ); break; + } + + // 事後処理 + fclose( out ); + + kiutil::timeSet( name, + (WORD)(hdr.dat),(WORD)(hdr.tim)); + } + + fseek( zip, posnext, SEEK_SET ); + } + + fclose( zip ); + return true; +} + +//---- CRC 関係 --------------------- + +// make crc table +//static void zip_make_crc_table() +//{ +// for( DWORD c,n=0; n!=256; n++ ) +// { +// c = n; +// for( DWORD k=8; k; k-- ) +// c = (c&1) ? ((0xedb88320L)^(c>>1)) : (c>>1); +// crc_table[n] = c; +// } +//} + +// the result +static DWORD crc_table[256] = { +0x00000000, 0x77073096, 0xee0e612c, 0x990951ba, 0x076dc419, 0x706af48f, 0xe963a535, 0x9e6495a3, +0x0edb8832, 0x79dcb8a4, 0xe0d5e91e, 0x97d2d988, 0x09b64c2b, 0x7eb17cbd, 0xe7b82d07, 0x90bf1d91, +0x1db71064, 0x6ab020f2, 0xf3b97148, 0x84be41de, 0x1adad47d, 0x6ddde4eb, 0xf4d4b551, 0x83d385c7, +0x136c9856, 0x646ba8c0, 0xfd62f97a, 0x8a65c9ec, 0x14015c4f, 0x63066cd9, 0xfa0f3d63, 0x8d080df5, +0x3b6e20c8, 0x4c69105e, 0xd56041e4, 0xa2677172, 0x3c03e4d1, 0x4b04d447, 0xd20d85fd, 0xa50ab56b, +0x35b5a8fa, 0x42b2986c, 0xdbbbc9d6, 0xacbcf940, 0x32d86ce3, 0x45df5c75, 0xdcd60dcf, 0xabd13d59, +0x26d930ac, 0x51de003a, 0xc8d75180, 0xbfd06116, 0x21b4f4b5, 0x56b3c423, 0xcfba9599, 0xb8bda50f, +0x2802b89e, 0x5f058808, 0xc60cd9b2, 0xb10be924, 0x2f6f7c87, 0x58684c11, 0xc1611dab, 0xb6662d3d, +0x76dc4190, 0x01db7106, 0x98d220bc, 0xefd5102a, 0x71b18589, 0x06b6b51f, 0x9fbfe4a5, 0xe8b8d433, +0x7807c9a2, 0x0f00f934, 0x9609a88e, 0xe10e9818, 0x7f6a0dbb, 0x086d3d2d, 0x91646c97, 0xe6635c01, +0x6b6b51f4, 0x1c6c6162, 0x856530d8, 0xf262004e, 0x6c0695ed, 0x1b01a57b, 0x8208f4c1, 0xf50fc457, +0x65b0d9c6, 0x12b7e950, 0x8bbeb8ea, 0xfcb9887c, 0x62dd1ddf, 0x15da2d49, 0x8cd37cf3, 0xfbd44c65, +0x4db26158, 0x3ab551ce, 0xa3bc0074, 0xd4bb30e2, 0x4adfa541, 0x3dd895d7, 0xa4d1c46d, 0xd3d6f4fb, +0x4369e96a, 0x346ed9fc, 0xad678846, 0xda60b8d0, 0x44042d73, 0x33031de5, 0xaa0a4c5f, 0xdd0d7cc9, +0x5005713c, 0x270241aa, 0xbe0b1010, 0xc90c2086, 0x5768b525, 0x206f85b3, 0xb966d409, 0xce61e49f, +0x5edef90e, 0x29d9c998, 0xb0d09822, 0xc7d7a8b4, 0x59b33d17, 0x2eb40d81, 0xb7bd5c3b, 0xc0ba6cad, +0xedb88320, 0x9abfb3b6, 0x03b6e20c, 0x74b1d29a, 0xead54739, 0x9dd277af, 0x04db2615, 0x73dc1683, +0xe3630b12, 0x94643b84, 0x0d6d6a3e, 0x7a6a5aa8, 0xe40ecf0b, 0x9309ff9d, 0x0a00ae27, 0x7d079eb1, +0xf00f9344, 0x8708a3d2, 0x1e01f268, 0x6906c2fe, 0xf762575d, 0x806567cb, 0x196c3671, 0x6e6b06e7, +0xfed41b76, 0x89d32be0, 0x10da7a5a, 0x67dd4acc, 0xf9b9df6f, 0x8ebeeff9, 0x17b7be43, 0x60b08ed5, +0xd6d6a3e8, 0xa1d1937e, 0x38d8c2c4, 0x4fdff252, 0xd1bb67f1, 0xa6bc5767, 0x3fb506dd, 0x48b2364b, +0xd80d2bda, 0xaf0a1b4c, 0x36034af6, 0x41047a60, 0xdf60efc3, 0xa867df55, 0x316e8eef, 0x4669be79, +0xcb61b38c, 0xbc66831a, 0x256fd2a0, 0x5268e236, 0xcc0c7795, 0xbb0b4703, 0x220216b9, 0x5505262f, +0xc5ba3bbe, 0xb2bd0b28, 0x2bb45a92, 0x5cb36a04, 0xc2d7ffa7, 0xb5d0cf31, 0x2cd99e8b, 0x5bdeae1d, +0x9b64c2b0, 0xec63f226, 0x756aa39c, 0x026d930a, 0x9c0906a9, 0xeb0e363f, 0x72076785, 0x05005713, +0x95bf4a82, 0xe2b87a14, 0x7bb12bae, 0x0cb61b38, 0x92d28e9b, 0xe5d5be0d, 0x7cdcefb7, 0x0bdbdf21, +0x86d3d2d4, 0xf1d4e242, 0x68ddb3f8, 0x1fda836e, 0x81be16cd, 0xf6b9265b, 0x6fb077e1, 0x18b74777, +0x88085ae6, 0xff0f6a70, 0x66063bca, 0x11010b5c, 0x8f659eff, 0xf862ae69, 0x616bffd3, 0x166ccf45, +0xa00ae278, 0xd70dd2ee, 0x4e048354, 0x3903b3c2, 0xa7672661, 0xd06016f7, 0x4969474d, 0x3e6e77db, +0xaed16a4a, 0xd9d65adc, 0x40df0b66, 0x37d83bf0, 0xa9bcae53, 0xdebb9ec5, 0x47b2cf7f, 0x30b5ffe9, +0xbdbdf21c, 0xcabac28a, 0x53b39330, 0x24b4a3a6, 0xbad03605, 0xcdd70693, 0x54de5729, 0x23d967bf, +0xb3667a2e, 0xc4614ab8, 0x5d681b02, 0x2a6f2b94, 0xb40bbe37, 0xc30c8ea1, 0x5a05df1b, 0x2d02ef8d +}; + +// update crc +#define calc_crc(c,b) (crc_table[(c&0xff)^(b&0xff)]^((c)>>8)) + +DWORD CZipTool::crc32( DWORD crc, const BYTE* dat, int len ) +{ + crc ^= 0xffffffffL; + while( len-- ) + crc = calc_crc( crc,*dat++ ); + return (crc^0xffffffffL); +} + +//-- ヘッダ処理 ----------------------------------- + +bool CZipTool::read_header( ZipLocalHeader* hdr ) +{ + unsigned char* buf = new unsigned char[65536]; + + if( 26 != fread(buf,1,26,zip) ) + { delete [] buf; return false; } + + hdr->ver = ((buf[ 0])|(buf[ 1]<<8)); + hdr->flg = ((buf[ 2])|(buf[ 3]<<8)); + hdr->mhd = ((buf[ 4])|(buf[ 5]<<8)); + hdr->tim = ((buf[ 6])|(buf[ 7]<<8)); + hdr->dat = ((buf[ 8])|(buf[ 9]<<8)); + hdr->crc = ((buf[10])|(buf[11]<<8)|(buf[12]<<16)|(buf[13]<<24)); + hdr->csz = ((buf[14])|(buf[15]<<8)|(buf[16]<<16)|(buf[17]<<24)); + hdr->usz = ((buf[18])|(buf[19]<<8)|(buf[20]<<16)|(buf[21]<<24)); + hdr->fnl = ((buf[22])|(buf[23]<<8)); + hdr->exl = ((buf[24])|(buf[25]<<8)); + + if( hdr->fnl!=fread(buf,1,hdr->fnl,zip) ) + { delete [] buf; return false; } + + int l = (hdr->fnl>MAX_PATH-1)?(MAX_PATH-1):(hdr->fnl); + memcpy( hdr->fnm, buf, l ); + hdr->fnm[l]='\0'; + char* pp; + for( pp=hdr->fnm; *pp!=0; pp++ ); + + if( hdr->mhd > Deflated || hdr->mhd==Tokenized ) + { delete [] buf; return false; } + if( pp-hdr->fnm != l ) + { delete [] buf; return false; } + if( hdr->exl != fread(buf,1,hdr->exl,zip) ) + { delete [] buf; return false; } + + delete [] buf; + return true; +} + +bool CZipTool::doHeader( ZipLocalHeader* hdr ) +{ + int c, stage=0; + while( EOF != (c=fgetc(zip)) ) + { + if( c=='P' ) stage++; + else if( c=='K' && stage==1 ) stage++; + else if( c==0x03 && stage==2 ) stage++; + else if( c==0x04 && stage==3 ) + { + stage++; + int x=ftell(zip); + if( read_header( hdr ) ) + return true; + fseek( zip,x,SEEK_SET ); + } + else stage=0; + } + + return false; +} + +//////////////////////////////////////////////////////////////// +// Store : 無圧縮格納 +//////////////////////////////////////////////////////////////// + +void CZipTool::Unstore( DWORD usz, DWORD csz ) +{ + unsigned char* buf = new unsigned char[65536]; +//--------------------------------------------------------------------// + + int how_much; + while( csz ) + { + how_much = csz > 65536 ? 65536 : csz; + if( 0>=(how_much=zipread( buf, how_much )) ) + break; + zipwrite( buf, how_much ); + csz -= how_much; + } + + delete [] buf; +} + +//////////////////////////////////////////////////////////////// +// Deflate : lzss+huffman。現在のpkzipのメソッド +//////////////////////////////////////////////////////////////// + +static void* my_zalloc(void* prm,UINT num,UINT siz) + {return (void*)new char[num*siz];} +static void my_zfree(void* prm,void* ptr) + {delete [] (char*)ptr;} +void CZipTool::Inflate( DWORD usz, DWORD csz ) +{ + unsigned char* outbuf = new unsigned char[65536]; + unsigned char* inbuf = outbuf + 32768; +//--------------------------------------------------------------------// + + // zlib準備 + z_stream_s zs; + zs.zalloc = my_zalloc; + zs.zfree = my_zfree; + + // 出力バッファ + int outsiz = 32768; + zs.next_out = outbuf; + zs.avail_out= outsiz; + + // 入力バッファ + int insiz = zipread( inbuf, + 32768 > csz ? csz : 32768 ); + if( insiz<=0 ) + return; + csz -= insiz; + zs.next_in = inbuf; + zs.avail_in = insiz; + + // スタート + inflateInit2( &zs, -15 ); + + // 書庫から入力し終わるまでループ + int err = Z_OK; + while( csz ) + { + while( zs.avail_out > 0 ) + { + err = inflate( &zs,Z_PARTIAL_FLUSH ); + if( err!=Z_STREAM_END && err!=Z_OK ) + csz=0; + if( !csz ) + break; + + if( zs.avail_in<=0 ) + { + int insiz = zipread( inbuf, 32768 > csz ? + csz : 32768 ); + if( insiz<=0 ) + { + err = Z_STREAM_END; + csz = 0; + break; + } + + csz -= insiz; + zs.next_in = inbuf; + zs.avail_in = insiz; + } + } + + zipwrite( outbuf, outsiz-zs.avail_out ); + zs.next_out = outbuf; + zs.avail_out = outsiz; + } + + // 出力残しを無くす。 + while( err!=Z_STREAM_END ) + { + err = inflate(&zs,Z_PARTIAL_FLUSH); + if( err!=Z_STREAM_END && err!=Z_OK ) + break; + + zipwrite( outbuf, outsiz-zs.avail_out ); + zs.next_out = outbuf; + zs.avail_out = outsiz; + } + + // 終了 + inflateEnd(&zs); + + delete [] outbuf; +} ADDED ZipTool.h Index: ZipTool.h ================================================================== --- ZipTool.h +++ ZipTool.h @@ -0,0 +1,117 @@ +#ifndef AFX_ZIPTOOL_H__4C5F3720_4483_11D4_8D96_88668194683D__INCLUDED_ +#define AFX_ZIPTOOL_H__4C5F3720_4483_11D4_8D96_88668194683D__INCLUDED_ + +// Zip Archive Extraction ... ( XacRett #39 SubSet ) + +// ローカルヘッダ +struct ZipLocalHeader +{ + // 'P' 'K' 03 04 + WORD ver; // version_needed_to_extract + WORD flg; // general_purpose_bit_flag + WORD mhd; // compression_method + WORD tim; // last_modified_file_time + WORD dat; // last_modified_file_date + DWORD crc; // crc32 + DWORD csz; // compressed-size + DWORD usz; // uncompressed-size + WORD fnl; // filename-len + WORD exl; // extra_field_length + + char fnm[MAX_PATH]; +// BYTE ext[]; +}; + +// 圧縮メソッドの種類 +enum ZipMethod +{ + Stored, // 0 + Shrunk, // 1 + Reduced1, // 2-5 + Reduced2, + Reduced3, + Reduced4, + Imploded, // 6 + Tokenized, // 7 ( not supported ) + Deflated, // 8 + EnhDeflated,// 9 ( not supported ) + DclImploded,//10 ( not supported ) + + Err=178 // this value is used by xacrett (^^; +}; + +class CZipTool +{ + +public: + //-- 外向きインターフェイス -------------- + bool Extract( const char* aname, const char* dll, kiPath& dll_rel_path ); + +private: //-- Zip内部処理用 ----------------------- + +// CRC + DWORD crc32( DWORD crc, const BYTE* dat, int len ); +// ファイルIO + FILE *zip,*out; + void zipwrite( BYTE* dat, int len ) + { fwrite( dat, 1, len, out ); } + int zipread( BYTE* dat, int len ) + { return fread( dat, 1, len, zip ); } +// bit-reader + unsigned long bitbuf; + int bits_left; + bool bits_eof; + + void initbits() + { + bits_eof=false, bits_left=0, bitbuf=0; + } + int getbits( int n ) + { + if( n <= bits_left ) + { + int c = (int)(bitbuf & ((1<>= n; + bits_left -= n; + return c; + } + return fillbits( n ); + } + int fillbits( int n ) + { + BYTE next; + + if( !zipread( &next,1 ) ) + bits_eof = true; + else + { + bitbuf |= (next<>= n; + bits_left -= n; + return c; + } + +// 展開アルゴリズム + void Unstore( DWORD usz, DWORD csz ); + void Inflate( DWORD usz, DWORD csz ); + +// ヘッダ処理 +// 面倒なのでCentralDirectory系は一切無視! + + // 現在のファイル位置からヘッダとして読む + bool read_header( ZipLocalHeader* hdr ); + // ヘッダ位置を探し出して読む + bool doHeader( ZipLocalHeader* hdr ); +}; + +#endif ADDED caldix.ico Index: caldix.ico ================================================================== --- caldix.ico +++ caldix.ico cannot compute difference between binary files ADDED fdi/FDI.H Index: fdi/FDI.H ================================================================== --- fdi/FDI.H +++ fdi/FDI.H @@ -0,0 +1,1070 @@ +/* + * FDI.H -- File Decompression Interface + * + * Copyright (C) Microsoft Corporation 1993-1997 + * All Rights Reserved. + */ + +#ifdef __cplusplus +extern "C" { +#endif + +#ifndef INCLUDED_TYPES_FCI_FDI +#define INCLUDED_TYPES_FCI_FDI 1 + +#ifndef HUGE +#define HUGE +#endif + +#ifndef FAR +#define FAR +#endif + +#ifndef DIAMONDAPI +#define DIAMONDAPI __cdecl +#endif + + +//** Specify structure packing explicitly for clients of FDI +#pragma pack(4) + +//** Don't redefine types defined in Win16 WINDOWS.H (_INC_WINDOWS) +// or Win32 WINDOWS.H (_WINDOWS_) +// +#if !defined(_INC_WINDOWS) && !defined(_WINDOWS_) +typedef int BOOL; /* f */ +typedef unsigned char BYTE; /* b */ +typedef unsigned int UINT; /* ui */ +typedef unsigned short USHORT; /* us */ +typedef unsigned long ULONG; /* ul */ +#endif // _INC_WINDOWS + +typedef unsigned long CHECKSUM; /* csum */ + +typedef unsigned long UOFF; /* uoff - uncompressed offset */ +typedef unsigned long COFF; /* coff - cabinet file offset */ + + +#ifndef TRUE +#define TRUE 1 +#endif + +#ifndef FALSE +#define FALSE 0 +#endif + +#ifndef NULL +#define NULL 0 +#endif + + +/*** ERF - Error structure + * + * This structure returns error information from FCI/FDI. The caller should + * not modify this structure. + */ +typedef struct { + int erfOper; // FCI/FDI error code -- see FDIERROR_XXX + // and FCIERR_XXX equates for details. + + int erfType; // Optional error value filled in by FCI/FDI. + // For FCI, this is usually the C run-time + // *errno* value. + + BOOL fError; // TRUE => error present +} ERF; /* erf */ +typedef ERF FAR *PERF; /* perf */ + +#ifdef _DEBUG +// don't hide statics from map during debugging +#define STATIC +#else // !DEBUG +#define STATIC static +#endif // !DEBUG + +#define CB_MAX_CHUNK 32768U +#define CB_MAX_DISK 0x7fffffffL +#define CB_MAX_FILENAME 256 +#define CB_MAX_CABINET_NAME 256 +#define CB_MAX_CAB_PATH 256 +#define CB_MAX_DISK_NAME 256 + +/*** tcompXXX - Compression types + * + * These are passed to FCIAddFile(), and are also stored in the CFFOLDER + * structures in cabinet files. + * + * NOTE: We reserve bits for the TYPE, QUANTUM_LEVEL, and QUANTUM_MEM + * to provide room for future expansion. Since this value is stored + * in the CFDATA records in the cabinet file, we don't want to + * have to change the format for existing compression configurations + * if we add new ones in the future. This will allows us to read + * old cabinet files in the future. + */ + +typedef unsigned short TCOMP; /* tcomp */ + +#define tcompMASK_TYPE 0x000F // Mask for compression type +#define tcompTYPE_NONE 0x0000 // No compression +#define tcompTYPE_MSZIP 0x0001 // MSZIP +#define tcompTYPE_QUANTUM 0x0002 // Quantum +#define tcompTYPE_LZX 0x0003 // LZX +#define tcompBAD 0x000F // Unspecified compression type + +#define tcompMASK_LZX_WINDOW 0x1F00 // Mask for LZX Compression Memory +#define tcompLZX_WINDOW_LO 0x0F00 // Lowest LZX Memory (15) +#define tcompLZX_WINDOW_HI 0x1500 // Highest LZX Memory (21) +#define tcompSHIFT_LZX_WINDOW 8 // Amount to shift over to get int + +#define tcompMASK_QUANTUM_LEVEL 0x00F0 // Mask for Quantum Compression Level +#define tcompQUANTUM_LEVEL_LO 0x0010 // Lowest Quantum Level (1) +#define tcompQUANTUM_LEVEL_HI 0x0070 // Highest Quantum Level (7) +#define tcompSHIFT_QUANTUM_LEVEL 4 // Amount to shift over to get int + +#define tcompMASK_QUANTUM_MEM 0x1F00 // Mask for Quantum Compression Memory +#define tcompQUANTUM_MEM_LO 0x0A00 // Lowest Quantum Memory (10) +#define tcompQUANTUM_MEM_HI 0x1500 // Highest Quantum Memory (21) +#define tcompSHIFT_QUANTUM_MEM 8 // Amount to shift over to get int + +#define tcompMASK_RESERVED 0xE000 // Reserved bits (high 3 bits) + + + +#define CompressionTypeFromTCOMP(tc) \ + ((tc) & tcompMASK_TYPE) + +#define CompressionLevelFromTCOMP(tc) \ + (((tc) & tcompMASK_QUANTUM_LEVEL) >> tcompSHIFT_QUANTUM_LEVEL) + +#define CompressionMemoryFromTCOMP(tc) \ + (((tc) & tcompMASK_QUANTUM_MEM) >> tcompSHIFT_QUANTUM_MEM) + +#define TCOMPfromTypeLevelMemory(t,l,m) \ + (((m) << tcompSHIFT_QUANTUM_MEM ) | \ + ((l) << tcompSHIFT_QUANTUM_LEVEL) | \ + ( t )) + +#define LZXCompressionWindowFromTCOMP(tc) \ + (((tc) & tcompMASK_LZX_WINDOW) >> tcompSHIFT_LZX_WINDOW) + +#define TCOMPfromLZXWindow(w) \ + (((w) << tcompSHIFT_LZX_WINDOW ) | \ + ( tcompTYPE_LZX )) + + +//** Revert to default structure packing +#pragma pack() + +#endif // !INCLUDED_TYPES_FCI_FDI + +/* + * Concepts: + * A *cabinet* file contains one or more *folders*. A folder contains + * one or more (pieces of) *files*. A folder is by definition a + * decompression unit, i.e., to extract a file from a folder, all of + * the data from the start of the folder up through and including the + * desired file must be read and decompressed. + * + * A folder can span one (or more) cabinet boundaries, and by implication + * a file can also span one (or more) cabinet boundaries. Indeed, more + * than one file can span a cabinet boundary, since FCI concatenates + * files together into a single data stream before compressing (actually, + * at most one file will span any one cabinet boundary, but FCI does + * not know which file this is, since the mapping from uncompressed bytes + * to compressed bytes is pretty obscure. Also, since FCI compresses + * in blocks of 32K (at present), any files with data in a 32K block that + * spans a cabinet boundary require FDI to read both cabinet files + * to get the two halves of the compressed block). + * + * Overview: + * The File Decompression Interface is used to simplify the reading of + * cabinet files. A setup program will proceed in a manner very + * similar to the pseudo code below. An FDI context is created, the + * setup program calls FDICopy() for each cabinet to be processed. For + * each file in the cabinet, FDICopy() calls a notification callback + * routine, asking the setup program if the file should be copied. + * This call-back approach is great because it allows the cabinet file + * to be read and decompressed in an optimal manner, and also makes FDI + * independent of the run-time environment -- FDI makes *no* C run-time + * calls whatsoever. All memory allocation and file I/O functions are + * passed into FDI by the client. + * + * main(...) + * { + * // Read INF file to construct list of desired files. + * // Ideally, these would be sorted in the same order as the + * // files appear in the cabinets, so that you can just walk + * // down the list in response to fdintCOPY_FILE notifications. + * + * // Construct list of required cabinets. + * + * hfdi = FDICreate(...); // Create FDI context + * For (cabinet in List of Cabinets) { + * FDICopy(hfdi,cabinet,fdiNotify,...); // Process each cabinet + * } + * FDIDestroy(hfdi); + * ... + * } + * + * // Notification callback function + * fdiNotify(fdint,...) + * { + * If (User Aborted) // Permit cancellation + * if (fdint == fdintCLOSE_FILE_INFO) + * close open file + * return -1; + * switch (fdint) { + * case fdintCOPY_FILE: // File to copy, maybe + * // Check file against list of desired files + * if want to copy file + * open destination file and return handle + * else + * return NULL; // Skip file + * case fdintCLOSE_FILE_INFO: + * close file + * set date, time, and attributes + * + * case fdintNEXT_CABINET: + * if not an error callback + * Tell FDI to use suggested directory name + * else + * Tell user what the problem was, and prompt + * for a new disk and/or path. + * if user aborts + * Tell FDI to abort + * else + * return to FDI to try another cabinet + * + * default: + * return 0; // more messages may be defined + * ... + * } + * + * Error Handling Suggestions: + * Since you the client have passed in *all* of the functions that + * FDI uses to interact with the "outside" world, you are in prime + * position to understand and deal with errors. + * + * The general philosophy of FDI is to pass all errors back up to + * the client. FDI returns fairly generic error codes in the case + * where one of the callback functions (PFNOPEN, PFNREAD, etc.) fail, + * since it assumes that the callback function will save enough + * information in a static/global so that when FDICopy() returns + * fail, the client can examine this information and report enough + * detail about the problem that the user can take corrective action. + * + * For very specific errors (CORRUPT_CABINET, for example), FDI returns + * very specific error codes. + * + * THE BEST POLICY IS FOR YOUR CALLBACK ROUTINES TO AVOID RETURNING + * ERRORS TO FDI! + * + * Examples: + * (1) If the disk is getting full, instead of returning an error + * from your PFNWRITE function, you should -- inside your + * PFNWRITE function -- put up a dialog telling the user to free + * some disk space. + * (2) When you get the fdintNEXT_CABINET notification, you should + * verify that the cabinet you return is the correct one (call + * FDIIsCabinet(), and make sure the setID matches the one for + * the current cabinet specified in the fdintCABINET_INFO, and + * that the disk number is one greater. + * + * NOTE: FDI will continue to call fdintNEXT_CABINET until it + * gets the cabinet it wants, or until you return -1 + * to abort the FDICopy() call. + * + * The documentation below on the FDI error codes provides explicit + * guidance on how to avoid each error. + * + * If you find you must return a failure to FDI from one of your + * callback functions, then FDICopy() frees all resources it allocated + * and closes all files. If you can figure out how to overcome the + * problem, you can call FDICopy() again on the last cabinet, and + * skip any files that you already copied. But, note that FDI does + * *not* maintain any state between FDICopy() calls, other than possibly + * memory allocated for the decompressor. + * + * See FDIERROR for details on FDI error codes and recommended actions. + * + * + * Progress Indicator Suggestions: + * As above, all of the file I/O functions are supplied by you. So, + * updating a progress indicator is very simple. You keep track of + * the target files handles you have opened, along with the uncompressed + * size of the target file. When you see writes to the handle of a + * target file, you use the write count to update your status! + * Since this method is available, there is no separate callback from + * FDI just for progess indication. + */ + +#ifndef INCLUDED_FDI +#define INCLUDED_FDI 1 + +//** Specify structure packing explicitly for clients of FDI +#pragma pack(4) + + +/*** FDIERROR - Error codes returned in erf.erfOper field + * + * In general, FDI will only fail if one of the passed in memory or + * file I/O functions fails. Other errors are pretty unlikely, and are + * caused by corrupted cabinet files, passing in a file which is not a + * cabinet file, or cabinet files out of order. + * + * Description: Summary of error. + * Cause: List of possible causes of this error. + * Response: How client might respond to this error, or avoid it in + * the first place. + */ +typedef enum { + FDIERROR_NONE, + // Description: No error + // Cause: Function was successfull. + // Response: Keep going! + + FDIERROR_CABINET_NOT_FOUND, + // Description: Cabinet not found + // Cause: Bad file name or path passed to FDICopy(), or returned + // to fdintNEXT_CABINET. + // Response: To prevent this error, validate the existence of the + // the cabinet *before* passing the path to FDI. + + FDIERROR_NOT_A_CABINET, + // Description: Cabinet file does not have the correct format + // Cause: File passed to to FDICopy(), or returned to + // fdintNEXT_CABINET, is too small to be a cabinet file, + // or does not have the cabinet signature in its first + // four bytes. + // Response: To prevent this error, call FDIIsCabinet() to check a + // cabinet before calling FDICopy() or returning the + // cabinet path to fdintNEXT_CABINET. + + FDIERROR_UNKNOWN_CABINET_VERSION, + // Description: Cabinet file has an unknown version number. + // Cause: File passed to to FDICopy(), or returned to + // fdintNEXT_CABINET, has what looks like a cabinet file + // header, but the version of the cabinet file format + // is not one understood by this version of FDI. The + // erf.erfType field is filled in with the version number + // found in the cabinet file. + // Response: To prevent this error, call FDIIsCabinet() to check a + // cabinet before calling FDICopy() or returning the + // cabinet path to fdintNEXT_CABINET. + + FDIERROR_CORRUPT_CABINET, + // Description: Cabinet file is corrupt + // Cause: FDI returns this error any time it finds a problem + // with the logical format of a cabinet file, and any + // time one of the passed-in file I/O calls fails when + // operating on a cabinet (PFNOPEN, PFNSEEK, PFNREAD, + // or PFNCLOSE). The client can distinguish these two + // cases based upon whether the last file I/O call + // failed or not. + // Response: Assuming this is not a real corruption problem in + // a cabinet file, the file I/O functions could attempt + // to do retries on failure (for example, if there is a + // temporary network connection problem). If this does + // not work, and the file I/O call has to fail, then the + // FDI client will have to clean up and call the + // FDICopy() function again. + + FDIERROR_ALLOC_FAIL, + // Description: Could not allocate enough memory + // Cause: FDI tried to allocate memory with the PFNALLOC + // function, but it failed. + // Response: If possible, PFNALLOC should take whatever steps + // are possible to allocate the memory requested. If + // memory is not immediately available, it might post a + // dialog asking the user to free memory, for example. + // Note that the bulk of FDI's memory allocations are + // made at FDICreate() time and when the first cabinet + // file is opened during FDICopy(). + + FDIERROR_BAD_COMPR_TYPE, + // Description: Unknown compression type in a cabinet folder + // Cause: [Should never happen.] A folder in a cabinet has an + // unknown compression type. This is probably caused by + // a mismatch between the version of FCI.LIB used to + // create the cabinet and the FDI.LIB used to read the + // cabinet. + // Response: Abort. + + FDIERROR_MDI_FAIL, + // Description: Failure decompressing data from a cabinet file + // Cause: The decompressor found an error in the data coming + // from the file cabinet. The cabinet file was corrupted. + // [11-Apr-1994 bens When checksuming is turned on, this + // error should never occur.] + // Response: Probably should abort; only other choice is to cleanup + // and call FDICopy() again, and hope there was some + // intermittent data error that will not reoccur. + + FDIERROR_TARGET_FILE, + // Description: Failure writing to target file + // Cause: FDI returns this error any time it gets an error back + // from one of the passed-in file I/O calls fails when + // writing to a file being extracted from a cabinet. + // Response: To avoid or minimize this error, the file I/O functions + // could attempt to avoid failing. A common cause might + // be disk full -- in this case, the PFNWRITE function + // could have a check for free space, and put up a dialog + // asking the user to free some disk space. + + FDIERROR_RESERVE_MISMATCH, + // Description: Cabinets in a set do not have the same RESERVE sizes + // Cause: [Should never happen]. FDI requires that the sizes of + // the per-cabinet, per-folder, and per-data block + // RESERVE sections be consistent across all the cabinets + // in a set. + // Response: Abort. + + FDIERROR_WRONG_CABINET, + // Description: Cabinet returned on fdintNEXT_CABINET is incorrect + // Cause: NOTE: THIS ERROR IS NEVER RETURNED BY FDICopy()! + // Rather, FDICopy() keeps calling the fdintNEXT_CABINET + // callback until either the correct cabinet is specified, + // or you return ABORT. + // When FDICopy() is extracting a file that crosses a + // cabinet boundary, it calls fdintNEXT_CABINET to ask + // for the path to the next cabinet. Not being very + // trusting, FDI then checks to make sure that the + // correct continuation cabinet was supplied! It does + // this by checking the "setID" and "iCabinet" fields + // in the cabinet. When MAKECAB.EXE creates a set of + // cabinets, it constructs the "setID" using the sum + // of the bytes of all the destination file names in + // the cabinet set. FDI makes sure that the 16-bit + // setID of the continuation cabinet matches the + // cabinet file just processed. FDI then checks that + // the cabinet number (iCabinet) is one more than the + // cabinet number for the cabinet just processed. + // Response: You need code in your fdintNEXT_CABINET (see below) + // handler to do retries if you get recalled with this + // error. See the sample code (EXTRACT.C) to see how + // this should be handled. + + FDIERROR_USER_ABORT, + // Description: FDI aborted. + // Cause: An FDI callback returnd -1 (usually). + // Response: Up to client. + +} FDIERROR; + + +/* + * FAT file attribute flag used by FCI/FDI to indicate that + * the filename in the CAB is a UTF string + */ +#ifndef _A_NAME_IS_UTF +#define _A_NAME_IS_UTF 0x80 +#endif + +/* + * FAT file attribute flag used by FCI/FDI to indicate that + * the file should be executed after extraction + */ +#ifndef _A_EXEC +#define _A_EXEC 0x40 +#endif + + +/*** HFDI - Handle to an FDI context + * + * FDICreate() creates this, and it must be passed to all other FDI + * functions. + */ +typedef void FAR *HFDI; /* hfdi */ + + +/*** FDICABINETINFO - Information about a cabinet + * + */ +typedef struct { + long cbCabinet; // Total length of cabinet file + USHORT cFolders; // Count of folders in cabinet + USHORT cFiles; // Count of files in cabinet + USHORT setID; // Cabinet set ID + USHORT iCabinet; // Cabinet number in set (0 based) + BOOL fReserve; // TRUE => RESERVE present in cabinet + BOOL hasprev; // TRUE => Cabinet is chained prev + BOOL hasnext; // TRUE => Cabinet is chained next +} FDICABINETINFO; /* fdici */ +typedef FDICABINETINFO FAR *PFDICABINETINFO; /* pfdici */ + + +/*** FDIDECRYPTTYPE - PFNFDIDECRYPT command types + * + */ +typedef enum { + fdidtNEW_CABINET, // New cabinet + fdidtNEW_FOLDER, // New folder + fdidtDECRYPT, // Decrypt a data block +} FDIDECRYPTTYPE; /* fdidt */ + + +/*** FDIDECRYPT - Data for PFNFDIDECRYPT function + * + */ +typedef struct { + FDIDECRYPTTYPE fdidt; // Command type (selects union below) + void FAR *pvUser; // Decryption context + union { + struct { // fdidtNEW_CABINET + void FAR *pHeaderReserve; // RESERVE section from CFHEADER + USHORT cbHeaderReserve; // Size of pHeaderReserve + USHORT setID; // Cabinet set ID + int iCabinet; // Cabinet number in set (0 based) + } cabinet; + + struct { // fdidtNEW_FOLDER + void FAR *pFolderReserve; // RESERVE section from CFFOLDER + USHORT cbFolderReserve; // Size of pFolderReserve + USHORT iFolder; // Folder number in cabinet (0 based) + } folder; + + struct { // fdidtDECRYPT + void FAR *pDataReserve; // RESERVE section from CFDATA + USHORT cbDataReserve; // Size of pDataReserve + void FAR *pbData; // Data buffer + USHORT cbData; // Size of data buffer + BOOL fSplit; // TRUE if this is a split data block + USHORT cbPartial; // 0 if this is not a split block, or + // the first piece of a split block; + // Greater than 0 if this is the + // second piece of a split block. + } decrypt; + }; +} FDIDECRYPT; /* fdid */ +typedef FDIDECRYPT FAR *PFDIDECRYPT; /* pfdid */ + + +/*** FNALLOC - Memory Allocation + * FNFREE - Memory Free + * + * These are modeled after the C run-time routines malloc() and free() + * FDI expects error handling to be identical to these C run-time routines. + * + * As long as you faithfully copy the semantics of malloc() and free(), + * you can supply any functions you like! + * + * WARNING: You should never assume anything about the sequence of + * PFNALLOC and PFNFREE calls -- incremental releases of + * FDI may have radically different numbers of + * PFNALLOC calls and allocation sizes! + */ +//** Memory functions for FDI +typedef void HUGE * (FAR DIAMONDAPI *PFNALLOC)(ULONG cb); /* pfna */ +#define FNALLOC(fn) void HUGE * FAR DIAMONDAPI fn(ULONG cb) + +typedef void (FAR DIAMONDAPI *PFNFREE)(void HUGE *pv); /* pfnf */ +#define FNFREE(fn) void FAR DIAMONDAPI fn(void HUGE *pv) + + +/*** PFNOPEN - File I/O callbacks for FDI + * PFNREAD + * PFNWRITE + * PFNCLOSE + * PFNSEEK + * + * These are modeled after the C run-time routines _open, _read, + * _write, _close, and _lseek. The values for the PFNOPEN oflag + * and pmode calls are those defined for _open. FDI expects error + * handling to be identical to these C run-time routines. + * + * As long as you faithfully copy these aspects, you can supply + * any functions you like! + * + * WARNING: You should never assume you know what file is being + * opened at any one point in time! FDI will usually + * stick to opening cabinet files, but it is possible + * that in a future implementation it may open temporary + * files or open cabinet files in a different order. + * + * Notes for Memory Mapped File fans: + * You can write wrapper routines to allow FDI to work on memory + * mapped files. You'll have to create your own "handle" type so that + * you can store the base memory address of the file and the current + * seek position, and then you'll allocate and fill in one of these + * structures and return a pointer to it in response to the PFNOPEN + * call and the fdintCOPY_FILE call. Your PFNREAD and PFNWRITE + * functions will do memcopy(), and update the seek position in your + * "handle" structure. PFNSEEK will just change the seek position + * in your "handle" structure. + */ +//** File I/O functions for FDI +typedef int (FAR DIAMONDAPI *PFNOPEN) (char FAR *pszFile, int oflag, int pmode); +typedef UINT (FAR DIAMONDAPI *PFNREAD) (int hf, void FAR *pv, UINT cb); +typedef UINT (FAR DIAMONDAPI *PFNWRITE)(int hf, void FAR *pv, UINT cb); +typedef int (FAR DIAMONDAPI *PFNCLOSE)(int hf); +typedef long (FAR DIAMONDAPI *PFNSEEK) (int hf, long dist, int seektype); + +#define FNOPEN(fn) int FAR DIAMONDAPI fn(char FAR *pszFile, int oflag, int pmode) +#define FNREAD(fn) UINT FAR DIAMONDAPI fn(int hf, void FAR *pv, UINT cb) +#define FNWRITE(fn) UINT FAR DIAMONDAPI fn(int hf, void FAR *pv, UINT cb) +#define FNCLOSE(fn) int FAR DIAMONDAPI fn(int hf) +#define FNSEEK(fn) long FAR DIAMONDAPI fn(int hf, long dist, int seektype) + + + +/*** PFNFDIDECRYPT - FDI Decryption callback + * + * If this function is passed on the FDICopy() call, then FDI calls it + * at various times to update the decryption state and to decrypt FCDATA + * blocks. + * + * Common Entry Conditions: + * pfdid->fdidt - Command type + * pfdid->pvUser - pvUser value from FDICopy() call + * + * fdidtNEW_CABINET: //** Notification of a new cabinet + * Entry: + * pfdid->cabinet. + * pHeaderReserve - RESERVE section from CFHEADER + * cbHeaderReserve - Size of pHeaderReserve + * setID - Cabinet set ID + * iCabinet - Cabinet number in set (0 based) + * Exit-Success: + * returns anything but -1; + * Exit-Failure: + * returns -1; FDICopy() is aborted. + * Notes: + * (1) This call allows the decryption code to pick out any information + * from the cabinet header reserved area (placed there by DIACRYPT) + * needed to perform decryption. If there is no such information, + * this call would presumably be ignored. + * (2) This call is made very soon after fdintCABINET_INFO. + * + * fdidtNEW_FOLDER: //** Notification of a new folder + * Entry: + * pfdid->folder. + * pFolderReserve - RESERVE section from CFFOLDER + * cbFolderReserve - Size of pFolderReserve + * iFolder - Folder number in cabinet (0 based) + * Exit-Success: + * returns anything but -1; + * Exit-Failure: + * returns -1; FDICopy() is aborted. + * Notes: + * This call allows the decryption code to pick out any information + * from the folder reserved area (placed there by DIACRYPT) needed + * to perform decryption. If there is no such information, this + * call would presumably be ignored. + * + * fdidtDECRYPT: //** Decrypt a data buffer + * Entry: + * pfdid->folder. + * pDataReserve - RESERVE section for this CFDATA block + * cbDataReserve - Size of pDataReserve + * pbData - Data buffer + * cbData - Size of data buffer + * fSplit - TRUE if this is a split data block + * cbPartial - 0 if this is not a split block, or the first + * piece of a split block; Greater than 0 if + * this is the second piece of a split block. + * Exit-Success: + * returns TRUE; + * Exit-Failure: + * returns FALSE; error during decrypt + * returns -1; FDICopy() is aborted. + * Notes: + * FCI will split CFDATA blocks across cabinet boundaries if + * necessary. To provide maximum flexibility, FDI will call the + * fdidtDECRYPT function twice on such split blocks, once when + * the first portion is read, and again when the second portion + * is read. And, of course, most data blocks will not be split. + * So, there are three cases: + * + * 1) fSplit == FALSE + * You have the entire data block, so decrypt it. + * + * 2) fSplit == TRUE, cbPartial == 0 + * This is the first portion of a split data block, so cbData + * is the size of this portion. You can either choose to decrypt + * this piece, or ignore this call and decrypt the full CFDATA + * block on the next (second) fdidtDECRYPT call. + * + * 3) fSplit == TRUE, cbPartial > 0 + * This is the second portion of a split data block (indeed, + * cbPartial will have the same value as cbData did on the + * immediately preceeding fdidtDECRYPT call!). If you decrypted + * the first portion on the first call, then you can decrypt the + * second portion now. If you ignored the first call, then you + * can decrypt the entire buffer. + * NOTE: pbData points to the second portion of the split data + * block in this case, *not* the entire data block. If + * you want to wait until the second piece to decrypt the + * *entire* block, pbData-cbPartial is the address of the + * start of the whole block, and cbData+cbPartial is its + * size. + */ +typedef int (FAR DIAMONDAPI *PFNFDIDECRYPT)(PFDIDECRYPT pfdid); /* pfnfdid */ +#define FNFDIDECRYPT(fn) int FAR DIAMONDAPI fn(PFDIDECRYPT pfdid) + + +/*** FDINOTIFICATION - Notification structure for PFNFDINOTIFY + * + * See the FDINOTIFICATIONTYPE definition for information on usage and + * meaning of these fields. + */ +typedef struct { +// long fields + long cb; + char FAR *psz1; + char FAR *psz2; + char FAR *psz3; // Points to a 256 character buffer + void FAR *pv; // Value for client + +// int fields + int hf; + +// short fields + USHORT date; + USHORT time; + USHORT attribs; + + USHORT setID; // Cabinet set ID + USHORT iCabinet; // Cabinet number (0-based) + USHORT iFolder; // Folder number (0-based) + + FDIERROR fdie; +} FDINOTIFICATION, FAR *PFDINOTIFICATION; /* fdin, pfdin */ + + +/*** FDINOTIFICATIONTYPE - FDICopy notification types + * + * The notification function for FDICopy can be called with the following + * values for the fdint parameter. In all cases, the pfdin->pv field is + * filled in with the value of the pvUser argument passed in to FDICopy(). + * + * A typical sequence of calls will be something like this: + * fdintCABINET_INFO // Info about the cabinet + * fdintENUMERATE // Starting enumeration + * fdintPARTIAL_FILE // Only if this is not the first cabinet, and + * // one or more files were continued from the + * // previous cabinet. + * ... + * fdintPARTIAL_FILE + * fdintCOPY_FILE // The first file that starts in this cabinet + * ... + * fdintCOPY_FILE // Now let's assume you want this file... + * // PFNWRITE called multiple times to write to this file. + * fdintCLOSE_FILE_INFO // File done, set date/time/attributes + * + * fdintCOPY_FILE // Now let's assume you want this file... + * // PFNWRITE called multiple times to write to this file. + * fdintNEXT_CABINET // File was continued to next cabinet! + * fdintCABINET_INFO // Info about the new cabinet + * // PFNWRITE called multiple times to write to this file. + * fdintCLOSE_FILE_INFO // File done, set date/time/attributes + * ... + * fdintENUMERATE // Ending enumeration + * + * fdintCABINET_INFO: + * Called exactly once for each cabinet opened by FDICopy(), including + * continuation cabinets opened due to file(s) spanning cabinet + * boundaries. Primarily intended to permit EXTRACT.EXE to + * automatically select the next cabinet in a cabinet sequence even if + * not copying files that span cabinet boundaries. + * Entry: + * pfdin->psz1 = name of next cabinet + * pfdin->psz2 = name of next disk + * pfdin->psz3 = cabinet path name + * pfdin->setID = cabinet set ID (a random 16-bit number) + * pfdin->iCabinet = Cabinet number within cabinet set (0-based) + * Exit-Success: + * Return anything but -1 + * Exit-Failure: + * Returns -1 => Abort FDICopy() call + * Notes: + * This call is made *every* time a new cabinet is examined by + * FDICopy(). So if "foo2.cab" is examined because a file is + * continued from "foo1.cab", and then you call FDICopy() again + * on "foo2.cab", you will get *two* fdintCABINET_INFO calls all + * told. + * + * fdintCOPY_FILE: + * Called for each file that *starts* in the current cabinet, giving + * the client the opportunity to request that the file be copied or + * skipped. + * Entry: + * pfdin->psz1 = file name in cabinet + * pfdin->cb = uncompressed size of file + * pfdin->date = file date + * pfdin->time = file time + * pfdin->attribs = file attributes + * pfdin->iFolder = file's folder index + * Exit-Success: + * Return non-zero file handle for destination file; FDI writes + * data to this file use the PFNWRITE function supplied to FDICreate, + * and then calls fdintCLOSE_FILE_INFO to close the file and set + * the date, time, and attributes. NOTE: This file handle returned + * must also be closeable by the PFNCLOSE function supplied to + * FDICreate, since if an error occurs while writing to this handle, + * FDI will use the PFNCLOSE function to close the file so that the + * client may delete it. + * Exit-Failure: + * Returns 0 => Skip file, do not copy + * Returns -1 => Abort FDICopy() call + * + * fdintCLOSE_FILE_INFO: + * Called after all of the data has been written to a target file. + * This function must close the file and set the file date, time, + * and attributes. + * Entry: + * pfdin->psz1 = file name in cabinet + * pfdin->hf = file handle + * pfdin->date = file date + * pfdin->time = file time + * pfdin->attribs = file attributes + * pfdin->iFolder = file's folder index + * pfdin->cb = Run After Extract (0 - don't run, 1 Run) + * Exit-Success: + * Returns TRUE + * Exit-Failure: + * Returns FALSE, or -1 to abort; + * + * IMPORTANT NOTE IMPORTANT: + * pfdin->cb is overloaded to no longer be the size of + * the file but to be a binary indicated run or not + * + * IMPORTANT NOTE: + * FDI assumes that the target file was closed, even if this + * callback returns failure. FDI will NOT attempt to use + * the PFNCLOSE function supplied on FDICreate() to close + * the file! + * + * fdintPARTIAL_FILE: + * Called for files at the front of the cabinet that are CONTINUED + * from a previous cabinet. This callback occurs only when FDICopy is + * started on second or subsequent cabinet in a series that has files + * continued from a previous cabinet. + * Entry: + * pfdin->psz1 = file name of file CONTINUED from a PREVIOUS cabinet + * pfdin->psz2 = name of cabinet where file starts + * pfdin->psz3 = name of disk where file starts + * Exit-Success: + * Return anything other than -1; enumeration continues + * Exit-Failure: + * Returns -1 => Abort FDICopy() call + * + * fdintENUMERATE: + * Called once after a call to FDICopy() starts scanning a CAB's + * CFFILE entries, and again when there are no more CFFILE entries. + * If CAB spanning occurs, an additional call will occur after the + * first spanned file is completed. If the pfdin->iFolder value is + * changed from zero, additional calls will occur next time it reaches + * zero. If iFolder is changed to zero, FDICopy will terminate, as if + * there were no more CFFILE entries. Primarily intended to allow an + * application with it's own file list to help FDI advance quickly to + * a CFFILE entry of interest. Can also be used to allow an + * application to determine the cb values for each file in the CAB. + * Entry: + * pfdin->cb = current CFFILE position + * pfdin->iFolder = number of files remaining + * pfdin->setID = current CAB's setID value + * Exit-Don't Care: + * Don't change anything. + * Return anything but -1. + * Exit-Forcing a skip: + * pfdin->cb = desired CFFILE position + * pfdin->iFolder = desired # of files remaining + * Return anything but -1. + * Exit-Stop: + * pfdin->iFolder = set to 0 + * Return anything but -1. + * Exit-Failure: + * Return -1 => Abort FDICopy call ("user aborted".) + * Notes: + * This call can be ignored by applications which want normal file + * searching. The application can adjust the supplied values to + * force FDICopy() to continue it's search at another location, or + * to force FDICopy() to terminate the search, by setting iFolder to 0. + * (FDICopy() will report no error when terminated this way.) + * FDI has no means to verify the supplied cb or iFolder values. + * Arbitrary values are likely to cause undesirable results. An + * application should cross-check pfdin->setID to be certain the + * external database is in sync with the CAB. Reverse-skips are OK + * (but may be inefficient) unless fdintNEXT_CABINET has been called. + * + * fdintNEXT_CABINET: + * This function is *only* called when fdintCOPY_FILE was told to copy + * a file in the current cabinet that is continued to a subsequent + * cabinet file. It is important that the cabinet path name (psz3) + * be validated before returning! This function should ensure that + * the cabinet exists and is readable before returning. So, this + * is the function that should, for example, issue a disk change + * prompt and make sure the cabinet file exists. + * + * When this function returns to FDI, FDI will check that the setID + * and iCabinet match the expected values for the next cabinet. + * If not, FDI will continue to call this function until the correct + * cabinet file is specified, or until this function returns -1 to + * abort the FDICopy() function. pfdin->fdie is set to + * FDIERROR_WRONG_CABINET to indicate this case. + * + * If you *haven't* ensured that the cabinet file is present and + * readable, or the cabinet file has been damaged, pfdin->fdie will + * receive other appropriate error codes: + * + * FDIERROR_CABINET_NOT_FOUND + * FDIERROR_NOT_A_CABINET + * FDIERROR_UNKNOWN_CABINET_VERSION + * FDIERROR_CORRUPT_CABINET + * FDIERROR_BAD_COMPR_TYPE + * FDIERROR_RESERVE_MISMATCH + * FDIERROR_WRONG_CABINET + * + * Entry: + * pfdin->psz1 = name of next cabinet where current file is continued + * pfdin->psz2 = name of next disk where current file is continued + * pfdin->psz3 = cabinet path name; FDI concatenates psz3 with psz1 + * to produce the fully-qualified path for the cabinet + * file. The 256-byte buffer pointed at by psz3 may + * be modified, but psz1 may not! + * pfdin->fdie = FDIERROR_WRONG_CABINET if the previous call to + * fdintNEXT_CABINET specified a cabinet file that + * did not match the setID/iCabinet that was expected. + * Exit-Success: + * Return anything but -1 + * Exit-Failure: + * Returns -1 => Abort FDICopy() call + * Notes: + * This call is almost always made when a target file is open and + * being written to, and the next cabinet is needed to get more + * data for the file. + */ +typedef enum { + fdintCABINET_INFO, // General information about cabinet + fdintPARTIAL_FILE, // First file in cabinet is continuation + fdintCOPY_FILE, // File to be copied + fdintCLOSE_FILE_INFO, // close the file, set relevant info + fdintNEXT_CABINET, // File continued to next cabinet + fdintENUMERATE, // Enumeration status +} FDINOTIFICATIONTYPE; /* fdint */ + +typedef int (FAR DIAMONDAPI *PFNFDINOTIFY)(FDINOTIFICATIONTYPE fdint, + PFDINOTIFICATION pfdin); /* pfnfdin */ + +#define FNFDINOTIFY(fn) int FAR DIAMONDAPI fn(FDINOTIFICATIONTYPE fdint, \ + PFDINOTIFICATION pfdin) + + +/*** cpuType values for FDICreate() + * + * (Ignored by 32-bit FDI.) + */ +#define cpuUNKNOWN (-1) /* FDI does detection */ +#define cpu80286 (0) /* '286 opcodes only */ +#define cpu80386 (1) /* '386 opcodes used */ + + +/*** FDICreate - Create an FDI context + * + * Entry: + * pfnalloc + * pfnfree + * pfnopen + * pfnread + * pfnwrite + * pfnclose + * pfnlseek + * cpuType - Select CPU type (auto-detect, 286, or 386+) + * NOTE: For the 32-bit FDI.LIB, this parameter is ignored! + * perf + * + * Exit-Success: + * Returns non-NULL FDI context handle. + * + * Exit-Failure: + * Returns NULL; perf filled in with error code + * + */ +HFDI FAR DIAMONDAPI FDICreate(PFNALLOC pfnalloc, + PFNFREE pfnfree, + PFNOPEN pfnopen, + PFNREAD pfnread, + PFNWRITE pfnwrite, + PFNCLOSE pfnclose, + PFNSEEK pfnseek, + int cpuType, + PERF perf); + + +/*** FDIIsCabinet - Determines if file is a cabinet, returns info if it is + * + * Entry: + * hfdi - Handle to FDI context (created by FDICreate()) + * hf - File handle suitable for PFNREAD/PFNSEEK, positioned + * at offset 0 in the file to test. + * pfdici - Buffer to receive info about cabinet if it is one. + * + * Exit-Success: + * Returns TRUE; file is a cabinet, pfdici filled in. + * + * Exit-Failure: + * Returns FALSE, file is not a cabinet; If an error occurred, + * perf (passed on FDICreate call!) filled in with error. + */ +BOOL FAR DIAMONDAPI FDIIsCabinet(HFDI hfdi, + int hf, + PFDICABINETINFO pfdici); + + +/*** FDICopy - extracts files from a cabinet + * + * Entry: + * hfdi - handle to FDI context (created by FDICreate()) + * pszCabinet - main name of cabinet file + * pszCabPath - Path to cabinet file(s) + * flags - Flags to modify behavior + * pfnfdin - Notification function + * pfnfdid - Decryption function (pass NULL if not used) + * pvUser - User specified value to pass to notification function + * + * Exit-Success: + * Returns TRUE; + * + * Exit-Failure: + * Returns FALSE, perf (passed on FDICreate call!) filled in with + * error. + * + * Notes: + * (1) If FDICopy() fails while a target file is being written out, then + * FDI will use the PFNCLOSE function to close the file handle for that + * target file that was returned from the fdintCOPY_FILE notification. + * The client application is then free to delete the target file, since + * it will not be in a valid state (since there was an error while + * writing it out). + */ +BOOL FAR DIAMONDAPI FDICopy(HFDI hfdi, + char FAR *pszCabinet, + char FAR *pszCabPath, + int flags, + PFNFDINOTIFY pfnfdin, + PFNFDIDECRYPT pfnfdid, + void FAR *pvUser); + + +/*** FDIDestroy - Destroy an FDI context + * + * Entry: + * hfdi - handle to FDI context (created by FDICreate()) + * + * Exit-Success: + * Returns TRUE; + * + * Exit-Failure: + * Returns FALSE; + */ +BOOL FAR DIAMONDAPI FDIDestroy(HFDI hfdi); + + +//** Revert to default structure packing +#pragma pack() + +#endif // !INCLUDED_FDI + +#ifdef __cplusplus +} +#endif ADDED fdi/FDI.LIB Index: fdi/FDI.LIB ================================================================== --- fdi/FDI.LIB +++ fdi/FDI.LIB cannot compute difference between binary files ADDED fdi/readme.txt Index: fdi/readme.txt ================================================================== --- fdi/readme.txt +++ fdi/readme.txt @@ -0,0 +1,1 @@ +The files are copied from old Cabinet SDK so that the whole project compiles with VC6. ADDED kilib/kilib.h Index: kilib/kilib.h ================================================================== --- kilib/kilib.h +++ kilib/kilib.h @@ -0,0 +1,27 @@ +//--- K.I.LIB --- +// kilib.h : main-header of K.I.LIB + +#ifndef AFX_KILIB_H__89998F34_A9FE_4A27_A159_671F85AA9383__INCLUDED_ +#define AFX_KILIB_H__89998F34_A9FE_4A27_A159_671F85AA9383__INCLUDED_ + +#include "kl_misc.h" +#include "kl_cmd.h" +#include "kl_str.h" +#include "kl_wnd.h" +#include "kl_file.h" +#include "kl_app.h" +#include "kl_reg.h" +#include "kl_find.h" +#include "kl_wcmn.h" +#include "kl_dnd.h" + +extern kiApp* app(); +extern void kilib_create_new_app(); + +#ifdef KILIB_LOG +#define Log(_s_) app()->log((const char*)(_s_)) +#else +#define Log(_s_) +#endif + +#endif ADDED kilib/kilibext.h Index: kilib/kilibext.h ================================================================== --- kilib/kilibext.h +++ kilib/kilibext.h @@ -0,0 +1,11 @@ +//--- K.I.LIB --- +// kilibext.h : extra-classes of K.I.LIB + +#ifndef AFX_KILIBEXT_H__89998F34_A9FE_4A27_A159_671F85AA9383__INCLUDED_ +#define AFX_KILIBEXT_H__89998F34_A9FE_4A27_A159_671F85AA9383__INCLUDED_ + +#include "kilib.h" +#include "kl_carc.h" +#include "kl_rythp.h" + +#endif ADDED kilib/kl_app.cpp Index: kilib/kl_app.cpp ================================================================== --- kilib/kl_app.cpp +++ kilib/kl_app.cpp @@ -0,0 +1,74 @@ +//--- K.I.LIB --- +// kl_app.h : application class for K.I.LIB + +#include "stdafx.h" +#include "kilib.h" + +//------------ 唯一のアプリケーションオブジェクトの管理 ------------// + +kiApp* kiApp::st_pApp = NULL; + +kiApp* app() +{ + return kiApp::st_pApp; +} + +//-------------------- スタートアップコード ------------------------// + +void kilib_startUp() +{ + //-- K.I.LIB 初期化 + kiStr::init(); + kiWindow::init(); + + //-- キーボード状態クリア + ::GetAsyncKeyState( VK_SHIFT ); + + //-- アプリケーションインスタンスを作成 + kilib_create_new_app(); + if( app() ) + { + // コマンドライン分割 + kiCmdParser cmd( ::GetCommandLine(), true ); + + // 実行 + app()->run( cmd ); + } + + //-- K.I.LIB 終了 + kiWindow::finish(); + + delete app(); + ::ExitProcess( 0 ); +} + +//--------------- C-Runtime初期化コード削除周りの処理 ---------------// + +#if 1 + +int APIENTRY WinMain( HINSTANCE, HINSTANCE, char*, int ) +{ + kilib_startUp(); + return 0; +} + +#else + +void* operator new( size_t siz ) +{ + return (void*)::GlobalAlloc( GMEM_FIXED, siz ); +} + +void operator delete( void* ptr ) +{ + ::GlobalFree( (HGLOBAL)ptr ); +} + +void main() +{ + // main がないと何故か libc.lib がリンクエラーになるのでダミー +} + +#endif + +//--------------------------------------------------------------// ADDED kilib/kl_app.h Index: kilib/kl_app.h ================================================================== --- kilib/kl_app.h +++ kilib/kl_app.h @@ -0,0 +1,125 @@ +//--- K.I.LIB --- +// kl_app.h : application class for K.I.LIB + +#ifndef AFX_KIAPP_H__AC24C8AF_2187_4873_83E8_AB4F2325017B__INCLUDED_ +#define AFX_KIAPP_H__AC24C8AF_2187_4873_83E8_AB4F2325017B__INCLUDED_ + +/*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*/ +// 汎用アプリケーションクラス + +class kiApp +{ +friend kiApp* app(); +friend void kilib_startUp(); + +public: //-- 外向きインターフェイス -------------------------- + + // インスタンス + HINSTANCE inst() const + { + return m_hInst; + } + + // メインウインドウ + HWND mainhwnd() const + { + return m_pMainWnd ? m_pMainWnd->hwnd() : NULL; + } + kiWindow* mainwnd() const + { + return m_pMainWnd; + } + void setMainWnd( kiWindow* wnd ) + { + m_pMainWnd = wnd; + } + + // OSバージョン + const OSVERSIONINFO& osver() const + { + return m_OsVer; + } + + // メッセージボックス + int msgBox( const char* msg, const char* caption=NULL, UINT type=MB_OK ) + { + return ::MessageBox( mainhwnd(), msg, caption, type ); + } + + // シェルのアロケータでメモリ解放 + void shellFree( void* ptr ) const + { + m_pShellAlloc->Free( ptr ); + } + + // 仮想コード vKey のキーは押されているか? + static bool keyPushed( int vKey ) + { + return( 0!=(::GetAsyncKeyState( vKey )>>15) ); + } + + // CommonControl / OLE 初期化 + void shellInit() + { + if( !m_bShellInit ) + { + ::InitCommonControls(); + ::OleInitialize( NULL ); + m_bShellInit = true; + } + } + +#ifdef KILIB_LOG + void log( const char* str ) + { + if( !m_log.isOpened() ) + { + kiPath logtxt( kiPath::Exe ); logtxt += "log.txt"; + m_log.open( logtxt, false ); + } + m_log.write( str, ki_strlen(str) ); + m_log.write( "\r\n", 2 ); + } +#endif + +protected: //-- 派生クラス向け ----------------------------- + + // 起動時に呼ばれる関数。必須。 + virtual void run( kiCmdParser& cmd ) = 0; + +protected: //-- 内部処理 ----------------------------------- + + kiApp() + { + st_pApp = this; + m_hInst = ::GetModuleHandle( NULL ); + m_pMainWnd = NULL; + m_bShellInit = false; + m_OsVer.dwOSVersionInfoSize = sizeof( m_OsVer ); + ::GetVersionEx( &m_OsVer ); + ::SHGetMalloc( &m_pShellAlloc ); + } + +protected: + + virtual ~kiApp() + { + m_pShellAlloc->Release(); + if( m_bShellInit ) + ::OleUninitialize(); + } + +private: + + HINSTANCE m_hInst; + IMalloc* m_pShellAlloc; + bool m_bShellInit; + OSVERSIONINFO m_OsVer; + kiWindow* m_pMainWnd; + static kiApp* st_pApp; +#ifdef KILIB_LOG + kiFile m_log; +#endif +}; + +#endif ADDED kilib/kl_carc.cpp Index: kilib/kl_carc.cpp ================================================================== --- kilib/kl_carc.cpp +++ kilib/kl_carc.cpp @@ -0,0 +1,242 @@ +//--- K.I.LIB --- +// kl_carc.cpp : handling "common archivers' dll" + +#include "stdafx.h" +#include "kilibext.h" +#include "../kiutil.h" + +//------------------------ load/unload 制御 ----------------------// + + +kiArcDLLRaw::kiArcDLLRaw( const char* dllname ) + : m_DllPath( dllname ), not_loaded_yet( true ) +{ + ki_memzero( m_Proc, ISARC_FUNCTION_END*sizeof(FARPROC) ); + f_VSb = NULL; +} + +kiArcDLLRaw::~kiArcDLLRaw() +{ + unload(); +} + +bool kiArcDLLRaw::load() +{ + not_loaded_yet = false; + + m_hDLL = kiutil::safepathLoadLibrary( m_DllPath ); + if( !m_hDLL ) + return false; + + // DLLの名前部分を切り出し + char str[MAX_PATH], *p; + const char *x, *y, *z; + for( x=y=m_DllPath; *x!='\0'; x=kiStr::next(x) ) + if( *x=='\\' || *x=='/' ) + y = x + 1; + for( p=str, z=y; (*z!='.' && *z!='3' && *z!='\0'); p++, z++ ) + *p = *z; + *p = '\0'; + + // コマンド送りAPIを取得。ccで始まるAPI名かも? + f_Cmd = ::GetProcAddress( m_hDLL, str ); + if( f_Cmd ) + m_DllNameBody = str; + else + { + f_Cmd = ::GetProcAddress( m_hDLL, "ccCommand" ); + if( f_Cmd ) + m_DllNameBody = "cc"; + else + { + if( str[0]=='7' && (f_Cmd=::GetProcAddress(m_hDLL,"SevenZip")) ) + m_DllNameBody = "SevenZip"; + else + return false; + } + } + + return true; +} + +void kiArcDLLRaw::unload() +{ + if( !not_loaded_yet && m_hDLL ) + { + ki_memzero( m_Proc, ISARC_FUNCTION_END*sizeof(FARPROC) ); + ::FreeLibrary( m_hDLL ); + not_loaded_yet = true; + } +} + +bool kiArcDLLRaw::isAlive() +{ + if( not_loaded_yet ) + load(); + + return (m_hDLL != NULL); +} + +FARPROC kiArcDLLRaw::getProc( const char* procname ) +{ + kiStr funcName = (const char*)m_DllNameBody; + funcName += procname; + return ::GetProcAddress( m_hDLL, funcName ); +} + +//----------------------------- APIのラッパ群 --------------------------// + + +int kiArcDLLRaw::command( const HWND wnd, LPCSTR cmd, LPSTR buf, const DWORD siz ) +{ + if( not_loaded_yet ) + if( !load() ) + return ERROR_NOT_SUPPORT; + + // コマンド関数は必ずロードされている + + typedef int (WINAPI * CARC_CMD)(const HWND,const char*,char*,const DWORD); + return ((CARC_CMD)f_Cmd)( wnd, cmd, buf, siz ); +} + +WORD kiArcDLLRaw::getVer() +{ + if( not_loaded_yet ) + if( !load() ) + return 0; + + if( !f_Ver ) + f_Ver = getProc( "GetVersion" ); + + typedef WORD (WINAPI * CARC_VER)(void); + return f_Ver ? ((CARC_VER)f_Ver)() : 0; +} + +WORD kiArcDLLRaw::getVerSub() +{ + if( not_loaded_yet ) + if( !load() ) + return 0; + + if( !f_VSb ) + f_VSb = getProc( "GetSubVersion" ); + + typedef WORD (WINAPI * CARC_VER)(void); + return f_VSb ? ((CARC_VER)f_VSb)() : 0; +} + +bool kiArcDLLRaw::isVerSubAvail() +{ + if( not_loaded_yet ) + if( !load() ) + return 0; + if( !f_VSb ) + f_VSb = getProc( "GetSubVersion" ); + return f_VSb != 0; +} + +BOOL kiArcDLLRaw::check( LPCSTR filename, const int mode ) +{ + if( not_loaded_yet ) + if( !load() ) + return FALSE; + + if( !f_Chk ) + f_Chk = getProc( "CheckArchive" ); + + typedef BOOL (WINAPI * CARC_CHK)(const char*,const int); + return f_Chk ? ((CARC_CHK)f_Chk)( filename, mode ) : FALSE; +} + +HARC kiArcDLLRaw::openArc( const HWND wnd, LPCSTR arcname, const DWORD flag ) +{ + if( not_loaded_yet ) + if( !load() ) + return NULL; + + if( !f_Opn ) + f_Opn = getProc( "OpenArchive" ); + + typedef HARC (WINAPI * CARC_OPN)(const HWND,LPCSTR,const DWORD); + return f_Opn ? ((CARC_OPN)f_Opn)( wnd, arcname, flag ) : NULL; +} + +void kiArcDLLRaw::closeArc( HARC arc ) +{ + if( not_loaded_yet ) + if( !load() ) + return; + + if( !f_Cls ) + f_Cls = getProc( "CloseArchive" ); + + typedef int (WINAPI * CARC_CLS)(HARC); + if( f_Cls ) + ((CARC_CLS)f_Cls)( arc ); +} + +int kiArcDLLRaw::findfirst( HARC arc, LPCSTR wildname, INDIVIDUALINFO* inf ) +{ + if( not_loaded_yet ) + if( !load() ) + return ERROR_NOT_SUPPORT; + + if( !f_Ffs ) + f_Ffs = getProc( "FindFirst" ); + + typedef int (WINAPI * CARC_FFS)(HARC,LPCSTR,INDIVIDUALINFO FAR *); + return f_Ffs ? ((CARC_FFS)f_Ffs)( arc, wildname, inf ) : ERROR_NOT_SUPPORT; +} + +int kiArcDLLRaw::findnext( HARC arc, INDIVIDUALINFO* inf ) +{ + if( not_loaded_yet ) + if( !load() ) + return ERROR_NOT_SUPPORT; + + if( !f_Fnx ) + f_Fnx = getProc( "FindNext" ); + + typedef int (WINAPI * CARC_FNX)(HARC,INDIVIDUALINFO FAR *); + return f_Fnx ? ((CARC_FNX)f_Fnx)( arc, inf ) : ERROR_NOT_SUPPORT; +} + +int kiArcDLLRaw::getAttr( HARC arc ) +{ + if( not_loaded_yet ) + if( !load() ) + return ERROR_NOT_SUPPORT; + + if( !f_GAr ) + f_GAr = getProc( "GetAttribute" ); + + typedef int (WINAPI * CARC_GAR)(HARC); + return f_GAr ? ((CARC_GAR)f_GAr)( arc ) : 0; +} + +BOOL kiArcDLLRaw::setOwner( HWND wnd ) +{ + if( not_loaded_yet ) + if( !load() ) + return ERROR_NOT_SUPPORT; + + if( !f_SOw ) + f_SOw = getProc( "SetOwnerWindow" ); + + typedef BOOL (WINAPI * CARC_SOW)(HWND); + return f_SOw ? ((CARC_SOW)f_SOw)( wnd ) : FALSE; +} + +BOOL kiArcDLLRaw::clearOwner() +{ + if( not_loaded_yet ) + if( !load() ) + return ERROR_NOT_SUPPORT; + + if( !f_COw ) + f_COw = getProc( "ClearOwnerWindow" ); + + typedef BOOL (WINAPI * CARC_COW)(); + return f_COw ? ((CARC_COW)f_COw)() : FALSE; +} + ADDED kilib/kl_carc.h Index: kilib/kl_carc.h ================================================================== --- kilib/kl_carc.h +++ kilib/kl_carc.h @@ -0,0 +1,371 @@ +//--- K.I.LIB --- +// kl_carc.h : handling "common archivers' dll" + +#ifndef AFX_KIARCDLLRAW_H__C94DE2A0_4292_49CE_8471_2CAA1340D216__INCLUDED_ +#define AFX_KIARCDLLRAW_H__C94DE2A0_4292_49CE_8471_2CAA1340D216__INCLUDED_ + +/*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*/ +// 統合アーカイバDLL共通の定義 + +// FNAME_MAX +#if !defined(FNAME_MAX32) +#define FNAME_MAX32 512 +#define FNAME_MAX FNAME_MAX32 +#else +#if !defined(FNAME_MAX) +#define FNAME_MAX 128 +#endif +#endif + +// CHECKARCHIVE +#if !defined(CHECKARCHIVE_RAPID) +#define CHECKARCHIVE_RAPID 0 +#define CHECKARCHIVE_BASIC 1 +#define CHECKARCHIVE_FULLCRC 2 +#endif + +// ISARC +#if !defined(ISARC_FUNCTION_START) +#define ISARC_FUNCTION_START 0 +#define ISARC 0 +#define ISARC_GET_VERSION 1 +#define ISARC_GET_CURSOR_INTERVAL 2 +#define ISARC_SET_CURSOR_INTERVAL 3 +#define ISARC_GET_BACK_GROUND_MODE 4 +#define ISARC_SET_BACK_GROUND_MODE 5 +#define ISARC_GET_CURSOR_MODE 6 +#define ISARC_SET_CURSOR_MODE 7 +#define ISARC_GET_RUNNING 8 + +#define ISARC_CHECK_ARCHIVE 16 +#define ISARC_CONFIG_DIALOG 17 +#define ISARC_GET_FILE_COUNT 18 +#define ISARC_QUERY_FUNCTION_LIST 19 +#define ISARC_HOUT 20 +#define ISARC_STRUCTOUT 21 +#define ISARC_GET_ARC_FILE_INFO 22 + +#define ISARC_OPEN_ARCHIVE 23 +#define ISARC_CLOSE_ARCHIVE 24 +#define ISARC_FIND_FIRST 25 +#define ISARC_FIND_NEXT 26 +#define ISARC_EXTRACT 27 +#define ISARC_ADD 28 +#define ISARC_MOVE 29 +#define ISARC_DELETE 30 +#define ISARC_SETOWNERWINDOW 31 +#define ISARC_CLEAROWNERWINDOW 32 +#define ISARC_SETOWNERWINDOWEX 33 +#define ISARC_KILLOWNERWINDOWEX 34 + +#define ISARC_GET_ARC_FILE_NAME 40 +#define ISARC_GET_ARC_FILE_SIZE 41 +#define ISARC_GET_ARC_ORIGINAL_SIZE 42 +#define ISARC_GET_ARC_COMPRESSED_SIZE 43 +#define ISARC_GET_ARC_RATIO 44 +#define ISARC_GET_ARC_DATE 45 +#define ISARC_GET_ARC_TIME 46 +#define ISARC_GET_ARC_OS_TYPE 47 +#define ISARC_GET_ARC_IS_SFX_FILE 48 +#define ISARC_GET_ARC_WRITE_TIME_EX 49 +#define ISARC_GET_ARC_CREATE_TIME_EX 50 +#define ISARC_GET_ARC_ACCESS_TIME_EX 51 +#define ISARC_GET_ARC_CREATE_TIME_EX2 52 +#define ISARC_GET_ARC_WRITE_TIME_EX2 53 +#define ISARC_GET_FILE_NAME 57 +#define ISARC_GET_ORIGINAL_SIZE 58 +#define ISARC_GET_COMPRESSED_SIZE 59 +#define ISARC_GET_RATIO 60 +#define ISARC_GET_DATE 61 +#define ISARC_GET_TIME 62 +#define ISARC_GET_CRC 63 +#define ISARC_GET_ATTRIBUTE 64 +#define ISARC_GET_OS_TYPE 65 +#define ISARC_GET_METHOD 66 +#define ISARC_GET_WRITE_TIME 67 +#define ISARC_GET_CREATE_TIME 68 +#define ISARC_GET_ACCESS_TIME 69 +#define ISARC_GET_WRITE_TIME_EX 70 +#define ISARC_GET_CREATE_TIME_EX 71 +#define ISARC_GET_ACCESS_TIME_EX 72 +#define ISARC_SET_ENUM_MEMBERS_PROC 80 +#define ISARC_CLEAR_ENUM_MEMBERS_PROC 81 + +#define ISARC_FUNCTION_END 81 +#endif + +// ERROR +#if !defined(ERROR_START) +#define ERROR_START 0x8000 + // warning +#define ERROR_DISK_SPACE 0x8005 +#define ERROR_READ_ONLY 0x8006 +#define ERROR_USER_SKIP 0x8007 +#define ERROR_UNKNOWN_TYPE 0x8008 +#define ERROR_METHOD 0x8009 +#define ERROR_PASSWORD_FILE 0x800A +#define ERROR_VERSION 0x800B +#define ERROR_FILE_CRC 0x800C +#define ERROR_FILE_OPEN 0x800D +#define ERROR_MORE_FRESH 0x800E +#define ERROR_NOT_EXIST 0x800F +#define ERROR_ALREADY_EXIST 0x8010 + +#define ERROR_TOO_MANY_FILES 0x8011 + // error +#define ERROR_MAKEDIRECTORY 0x8012 +#define ERROR_CANNOT_WRITE 0x8013 +#define ERROR_HUFFMAN_CODE 0x8014 +#define ERROR_COMMENT_HEADER 0x8015 +#define ERROR_HEADER_CRC 0x8016 +#define ERROR_HEADER_BROKEN 0x8017 +#define ERROR_ARC_FILE_OPEN 0x8018 +#define ERROR_NOT_ARC_FILE 0x8019 +#define ERROR_CANNOT_READ 0x801A +#define ERROR_FILE_STYLE 0x801B +#define ERROR_COMMAND_NAME 0x801C +#define ERROR_MORE_HEAP_MEMORY 0x801D +#define ERROR_ENOUGH_MEMORY 0x801E +#if !defined(ERROR_ALREADY_RUNNING) +#define ERROR_ALREADY_RUNNING 0x801F +#endif +#define ERROR_USER_CANCEL 0x8020 +#define ERROR_HARC_ISNOT_OPENED 0x8021 +#define ERROR_NOT_SEARCH_MODE 0x8022 +#define ERROR_NOT_SUPPORT 0x8023 +#define ERROR_TIME_STAMP 0x8024 +#define ERROR_TMP_OPEN 0x8025 +#define ERROR_LONG_FILE_NAME 0x8026 +#define ERROR_ARC_READ_ONLY 0x8027 +#define ERROR_SAME_NAME_FILE 0x8028 +#define ERROR_NOT_FIND_ARC_FILE 0x8029 +#define ERROR_RESPONSE_READ 0x802A +#define ERROR_NOT_FILENAME 0x802B +#define ERROR_TMP_COPY 0x802C +#define ERROR_EOF 0x802D +#define ERROR_ADD_TO_LARC 0x802E +#define ERROR_TMP_BACK_SPACE 0x802F +#define ERROR_SHARING 0x8030 +#define ERROR_NOT_FIND_FILE 0x8031 +#define ERROR_LOG_FILE 0x8032 +#define ERROR_NO_DEVICE 0x8033 +#define ERROR_GET_ATTRIBUTES 0x8034 +#define ERROR_SET_ATTRIBUTES 0x8035 +#define ERROR_GET_INFORMATION 0x8036 +#define ERROR_GET_POINT 0x8037 +#define ERROR_SET_POINT 0x8038 +#define ERROR_CONVERT_TIME 0x8039 +#define ERROR_GET_TIME 0x803a +#define ERROR_SET_TIME 0x803b +#define ERROR_CLOSE_FILE 0x803c +#define ERROR_HEAP_MEMORY 0x803d +#define ERROR_HANDLE 0x803e +#define ERROR_TIME_STAMP_RANGE 0x803f +#define ERROR_MAKE_ARCHIVE 0x8040 + +#define ERROR_END ERROR_MAKE_ARCHIVE +#define ERROR_BUF_TOO_SMALL 0x8041 /**/ +#endif + +// CONFIG +#if !defined(UNPACK_CONFIG_MODE) +#define UNPACK_CONFIG_MODE 1 +#define PACK_CONFIG_MODE 2 +#endif + +// OPENARCHIVE +#if !defined(EXTRACT_FOUND_FILE) +#define M_INIT_FILE_USE 0x00000001L +#define M_REGARDLESS_INIT_FILE 0x00000002L +#define M_NO_BACKGROUND_MODE 0x00000004L +#define M_NOT_USE_TIME_STAMP 0x00000008L +#define M_EXTRACT_REPLACE_FILE 0x00000010L +#define M_EXTRACT_NEW_FILE 0x00000020L +#define M_EXTRACT_UPDATE_FILE 0x00000040L +#define M_CHECK_ALL_PATH 0x00000100L +#define M_CHECK_FILENAME_ONLY 0x00000200L +#define M_CHECK_DISK_SIZE 0x00000400L +#define M_REGARDLESS_DISK_SIZE 0x00000800L +#define M_USE_DRIVE_LETTER 0x00001000L +#define M_NOT_USE_DRIVE_LETTER 0x00002000L +#define M_INQUIRE_DIRECTORY 0x00004000L +#define M_NOT_INQUIRE_DIRECTORY 0x00008000L +#define M_INQUIRE_WRITE 0x00010000L +#define M_NOT_INQUIRE_WRITE 0x00020000L +#define M_CHECK_READONLY 0x00040000L +#define M_REGARDLESS_READONLY 0x00080000L +#define M_REGARD_E_COMMAND 0x00100000L +#define M_REGARD_X_COMMAND 0x00200000L +#define M_ERROR_MESSAGE_ON 0x00400000L +#define M_ERROR_MESSAGE_OFF 0x00800000L +#define M_BAR_WINDOW_ON 0x01000000L +#define M_BAR_WINDOW_OFF 0x02000000L +#define M_CHECK_PATH 0x04000000L +#define M_RECOVERY_ON 0x08000000L + +#define M_MAKE_INDEX_FILE 0x10000000L +#define M_NOT_MAKE_INDEX_FILE 0x20000000L +#define EXTRACT_FOUND_FILE 0x40000000L +#define EXTRACT_NAMED_FILE 0x80000000L +#endif + +// ATTRIBUTE +#ifndef FA_RDONLY +#define FA_RDONLY 0x01 +#define FA_HIDDEN 0x02 +#define FA_SYSTEM 0x04 +#define FA_LABEL 0x08 +#define FA_DIREC 0x10 +#define FA_ARCH 0x20 +#endif +#ifndef FA_ENCRYPTED +#define FA_ENCRYPTED 0x40 +#endif + +// STRUCTURES +#if defined(__BORLANDC__) +#pragma option -a- +#else +#pragma pack(1) +#endif + +typedef HGLOBAL HARCHIVE; + +#ifndef ARC_DECSTRACT +#define ARC_DECSTRACT +typedef HGLOBAL HARC; + +typedef struct { + DWORD dwOriginalSize; + DWORD dwCompressedSize; + DWORD dwCRC; + UINT uFlag; + UINT uOSType; + WORD wRatio; + WORD wDate; + WORD wTime; + char szFileName[FNAME_MAX32 + 1]; + char dummy1[3]; + char szAttribute[8]; + char szMode[8]; +} INDIVIDUALINFO, FAR *LPINDIVIDUALINFO; + +typedef struct { + DWORD dwFileSize; + DWORD dwWriteSize; + char szSourceFileName[FNAME_MAX32 + 1]; + char dummy1[3]; + char szDestFileName[FNAME_MAX32 + 1]; + char dummy[3]; +} EXTRACTINGINFO, FAR *LPEXTRACTINGINFO; + +typedef struct { + EXTRACTINGINFO exinfo; + DWORD dwCompressedSize; + DWORD dwCRC; + UINT uOSType; + WORD wRatio; + WORD wDate; + WORD wTime; + char szAttribute[8]; + char szMode[8]; +} EXTRACTINGINFOEX, *LPEXTRACTINGINFOEX; +#endif + +#if !defined(__BORLANDC__) +#pragma pack() +#else +#pragma option -a. +#endif + +#if !defined(__BORLANDC__) +#define _export +#endif + +// WindowsMessage +#ifndef WM_ARCEXTRACT +#define WM_ARCEXTRACT "wm_arcextract" +#define ARCEXTRACT_BEGIN 0 +#define ARCEXTRACT_INPROCESS 1 +#define ARCEXTRACT_END 2 +#define ARCEXTRACT_OPEN 3 +#define ARCEXTRACT_COPY 4 +typedef BOOL CALLBACK ARCHIVERPROC(HWND,UINT,UINT,LPEXTRACTINGINFOEX); +typedef ARCHIVERPROC *LPARCHIVERPROC; +#endif + +/*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*/ +// 統合アーカイバDLLを非常に薄く覆うレイヤ + +class kiArcDLLRaw +{ +public: //-- 外向きインターフェイス -------------------------- + + // DLL名で初期化。 + kiArcDLLRaw( const char* dllname ); + kiPath& name() + { return m_DllPath; } + + // DLLが生きているかどうか。 + bool isAlive(); + + // API のラッパ [ DLLやAPIが無いときの返値 ] + + // バージョンx100 [ 0 ] + WORD getVer(); + // バージョンサブx100 [ 0 ] + WORD getVerSub(); + // バージョンサブが取れるかどうか? + bool isVerSubAvail(); + // コマンド送り [ ERROR_NOT_SUPPORT ] + int command( const HWND wnd, LPCSTR cmd, LPSTR buf, const DWORD siz ); + // 書庫チェック [ FALSE ] + BOOL check( LPCSTR filename, const int mode ); + + // 開く [ NULL ] + HARC openArc( const HWND wnd, LPCSTR arcname, const DWORD flag ); + // 閉じる + void closeArc( HARC arc ); + // 一つ目を検索 [ ERROR_NOT_SUPPORT ] + int findfirst( HARC arc, LPCSTR wildname, INDIVIDUALINFO* inf ); + // 二つ目以降を検索 [ ERROR_NOT_SUPPORT ] + int findnext( HARC arc, INDIVIDUALINFO* inf ); + // 属性取得 [ 0 ] + int getAttr( HARC arc ); + + // オーナー指定 [ FALSE ] + BOOL setOwner( HWND wnd ); + // オーナー解除 [ FALSE ] + BOOL clearOwner(); + + // ※load系は呼ばなくても内部で何とかするのでできれば使わないこと。 + bool load(); + void unload(); + +private: //-- 内部処理 ----------------------------------- + + HINSTANCE m_hDLL; + bool not_loaded_yet; + + kiPath m_DllPath; + kiStr m_DllNameBody; + FARPROC getProc( const char* procname ); + + FARPROC m_Proc[ ISARC_FUNCTION_END ]; + FARPROC f_VSb; +#define f_Cmd m_Proc[ ISARC ] +#define f_Chk m_Proc[ ISARC_GET_VERSION ] +#define f_Ver m_Proc[ ISARC_CHECK_ARCHIVE ] +#define f_Opn m_Proc[ ISARC_OPEN_ARCHIVE ] +#define f_Cls m_Proc[ ISARC_CLOSE_ARCHIVE ] +#define f_Ffs m_Proc[ ISARC_FIND_FIRST ] +#define f_Fnx m_Proc[ ISARC_FIND_NEXT ] +#define f_GAr m_Proc[ ISARC_GET_ATTRIBUTE ] +#define f_SOw m_Proc[ ISARC_SETOWNERWINDOW ] +#define f_COw m_Proc[ ISARC_CLEAROWNERWINDOW ] + +public: + virtual ~kiArcDLLRaw(); +}; + +#endif ADDED kilib/kl_cmd.cpp Index: kilib/kl_cmd.cpp ================================================================== --- kilib/kl_cmd.cpp +++ kilib/kl_cmd.cpp @@ -0,0 +1,79 @@ +//--- K.I.LIB --- +// kl_cmd.h : commandline parser + +#include "stdafx.h" +#include "kilib.h" + + +//------------------------ 文字列のメモリ処理など -----------------------// + + +kiCmdParser::kiCmdParser( char* cmd, bool ignoreFirst ) +{ + m_Buffer = NULL; + if( cmd ) + doit( cmd, ignoreFirst ); +} + +kiCmdParser::kiCmdParser( const char* cmd, bool ignoreFirst ) +{ + m_Buffer=NULL; + if( cmd ) + { + m_Buffer = new char[ ki_strlen(cmd)+1 ]; + ki_strcpy( m_Buffer, cmd ); + doit( m_Buffer, ignoreFirst ); + } +} + +kiCmdParser::~kiCmdParser() +{ + delete [] m_Buffer; +} + + +//---------------------------- 分割の処理 -----------------------------// + + +void kiCmdParser::doit( char* start, bool ignoreFirst ) +{ + char* p=start; + char endc; + bool first = true; + + while( *p!='\0' ) + { + // 余分な空白はスキップ + while( *p==' ' ) //|| *p=='\t' || *p=='\r' || *p=='\n' ) + p++; + + // " だったら、その旨記録してさらに一個進める + if( *p=='"' ) + endc='"', p++; + else + endc=' '; + + // end-of-text なら終了 + if( *p=='\0' ) + break; + + if( first && ignoreFirst ) + first = false; + else + { + // 引数を保存 + if( *p=='-' ) + m_Switch.add( p ); + else + m_Param.add( p ); + } + + // 引数の終わりへ… + while( *p!=endc && *p!='\0' ) + p++; + + // 終わりは'\0'にすることによって、引数を区切る + if( *p!='\0' ) + *(p++) = '\0'; + } +} ADDED kilib/kl_cmd.h Index: kilib/kl_cmd.h ================================================================== --- kilib/kl_cmd.h +++ kilib/kl_cmd.h @@ -0,0 +1,38 @@ +//--- K.I.LIB --- +// kl_cmd.h : commandline parser + +#ifndef AFX_KICMDPARSER_H__843A27E0_5DBF_48AF_A748_FA7F111F699A__INCLUDED_ +#define AFX_KICMDPARSER_H__843A27E0_5DBF_48AF_A748_FA7F111F699A__INCLUDED_ + +/*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*/ +// kiCmdParser : コマンド文字列をchar*の配列に分割 + +class kiCmdParser +{ +public: //-- 外向きインターフェイス -------------------------- + + // 文字列で初期化 + kiCmdParser( char* cmd, bool ignoreFirst=false ); + kiCmdParser( const char* cmd, bool ignoreFirst=false ); + + // スイッチ文字列の配列 + cCharArray& option() + { return m_Switch; } + + // スイッチ以外の文字列の配列 + cCharArray& param() + { return m_Param; } + +private: //-- 内部処理 ----------------------------------- + + void doit( char* start, bool ignoreFirst ); + cCharArray m_Param; + cCharArray m_Switch; + char* m_Buffer; + +public: + + virtual ~kiCmdParser(); +}; + +#endif ADDED kilib/kl_dnd.cpp Index: kilib/kl_dnd.cpp ================================================================== --- kilib/kl_dnd.cpp +++ kilib/kl_dnd.cpp @@ -0,0 +1,217 @@ +//--- K.I.LIB --- +// kl_dnd.h : drag and drop operation + +#include "stdafx.h" +#include "kilib.h" + +//--------------------------------------------------------------------// + +bool kiDropSource::DnD( kiDataObject* pObj, DWORD efct, DWORD* pefct ) +{ + kiDropSource* pDrpSrc = new kiDropSource; + pDrpSrc->AddRef(); + pObj->begin(); + + DWORD d, *p=(pefct==NULL ? &d : pefct); + HRESULT hr = ::DoDragDrop( pObj, pDrpSrc, efct, p ); + + pDrpSrc->Release(); + return (hr == DRAGDROP_S_DROP); +} + +//------------------------ IUnknown Implement -------------------------// + +kiDropSource::kiDropSource() : m_cRef( 0L ) +{ + app()->shellInit(); // OleInitialize() +} + +STDMETHODIMP_(ULONG) kiDropSource::AddRef() +{ + return ++m_cRef; +} + +STDMETHODIMP_(ULONG) kiDropSource::Release() +{ + if( --m_cRef ) + return m_cRef; + + delete this; + return 0L; +} + +STDMETHODIMP kiDropSource::QueryInterface( REFIID riid, void** ppObj ) +{ + if( ::IsEqualIID( riid, IID_IUnknown ) + || ::IsEqualIID( riid, IID_IDropSource ) ) + { + *ppObj = (void*)this; + AddRef(); + return S_OK; + } + + *ppObj = NULL; + return E_NOINTERFACE; +} + +//------------------------ IDropSource Implement -------------------------// + +STDMETHODIMP kiDropSource::GiveFeedback( DWORD dwEffect ) +{ + return DRAGDROP_S_USEDEFAULTCURSORS; +} + +STDMETHODIMP kiDropSource::QueryContinueDrag( BOOL keyESC, DWORD keyOther ) +{ + if( keyESC ) + return DRAGDROP_S_CANCEL; + if( !(keyOther&MK_LBUTTON) && !(keyOther&MK_RBUTTON) ) + return DRAGDROP_S_DROP; + return S_OK; +} + +//------------------------ IUnknown Implement -------------------------// + +kiDataObject::kiDataObject() : m_cRef( 0L ), m_FormatList( 2 ) +{ +} + +STDMETHODIMP_(ULONG) kiDataObject::AddRef() +{ + return ++m_cRef; +} + +STDMETHODIMP_(ULONG) kiDataObject::Release() +{ + if( --m_cRef ) + return m_cRef; + + delete this; + return 0L; +} + +STDMETHODIMP kiDataObject::QueryInterface( REFIID riid, void** ppObj ) +{ + if( ::IsEqualIID( riid, IID_IUnknown ) + || ::IsEqualIID( riid, IID_IDataObject ) ) + { + *ppObj = (void*)this; + AddRef(); + return S_OK; + } + + *ppObj = NULL; + return E_NOINTERFACE; +} + +//------------------------ IDataObject Implement -------------------------// + + +STDMETHODIMP kiDataObject::GetData( FORMATETC* fmtc, STGMEDIUM* stg ) +{ + HRESULT hr = QueryGetData( fmtc ); + if( FAILED(hr) ) + return hr; + bool res = giveData( *fmtc, stg, m_bFirst ); + m_bFirst = false; + return res ? S_OK : STG_E_MEDIUMFULL; +} + +STDMETHODIMP kiDataObject::QueryGetData( FORMATETC* fmtc ) +{ + for( unsigned int i=0; i!=m_FormatList.len(); i++ ) + if( m_FormatList[i].cfFormat == fmtc->cfFormat ) +// if(fmtc & TYMED_HGLOBAL) + return S_OK; + return DV_E_FORMATETC; +} + +//---------- Enumrator ---------// + +class kiDataObject_Enum : public IEnumFORMATETC +{ +public: + kiDataObject_Enum( kiDataObject* p ) + : m_cRef( 0L ), m_pObj( p ), m_nCur( 0L ) + { + m_pObj->AddRef(); + } + ~kiDataObject_Enum() + { + m_pObj->Release(); + } + STDMETHODIMP_(ULONG) AddRef() + { + return ++m_cRef; + } + STDMETHODIMP_(ULONG) Release() + { + if( --m_cRef ) + return m_cRef; + delete this; + return 0L; + } + STDMETHODIMP QueryInterface( REFIID riid, void** ppObj ) + { + if( ::IsEqualIID( riid, IID_IUnknown ) + || ::IsEqualIID( riid, IID_IEnumFORMATETC ) ) + { + *ppObj = (void*)this; + AddRef(); + return S_OK; + } + *ppObj = NULL; + return E_NOINTERFACE; + } + STDMETHODIMP Clone( IEnumFORMATETC** ppNew ) + { + *ppNew = new kiDataObject_Enum( m_pObj ); + ((kiDataObject_Enum*)(*ppNew))->m_nCur = m_nCur; + (*ppNew)->AddRef(); + return S_OK; + } + STDMETHODIMP Reset() + { + m_nCur = 0; + return S_OK; + } + STDMETHODIMP Skip( ULONG celt ) + { + m_nCur += celt; + if( m_pObj->m_FormatList.len() <= m_nCur ) + { + m_nCur = m_pObj->m_FormatList.len() - 1; + return S_FALSE; + } + return S_OK; + } + STDMETHODIMP Next( ULONG celt, FORMATETC* pFmt, ULONG* fetched ) + { + if( fetched ) + *fetched = 0L; + if( !pFmt ) + return E_POINTER; + ULONG i; + for( i=0; i < celt && m_nCur < m_pObj->m_FormatList.len(); i++,m_nCur++ ) + *pFmt++ = m_pObj->m_FormatList[m_nCur]; + if( fetched ) + *fetched = i; + return i==celt ? S_OK : S_FALSE; + } +private: + ULONG m_cRef; + ULONG m_nCur; + kiDataObject* m_pObj; +}; + +STDMETHODIMP kiDataObject::EnumFormatEtc( DWORD drctn, IEnumFORMATETC** ppEnm ) +{ + if( !ppEnm ) + return E_INVALIDARG; + *ppEnm = NULL; + if( drctn!=DATADIR_GET ) + return E_NOTIMPL; + + (*ppEnm = new kiDataObject_Enum( this ))->AddRef(); + return S_OK; +} ADDED kilib/kl_dnd.h Index: kilib/kl_dnd.h ================================================================== --- kilib/kl_dnd.h +++ kilib/kl_dnd.h @@ -0,0 +1,95 @@ +//--- K.I.LIB --- +// kl_dnd.h : drag and drop operation + +#ifndef AFX_KIDROPSOURCE_H__141BEF0D_0DA2_4156_93E4_313535916A23__INCLUDED_ +#define AFX_KIDROPSOURCE_H__141BEF0D_0DA2_4156_93E4_313535916A23__INCLUDED_ + +/*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*/ +// kiDataObject : ドロップデータとしての標準処理 + +class kiDataObject : public IDataObject +{ +protected: // 派生クラス向け処理 + + virtual bool giveData( const FORMATETC& fmt, STGMEDIUM* stg, bool firstcall ) = 0; + void addFormat( const FORMATETC& frm ) + { + m_FormatList.add( frm ); + } + +protected: //-- IUnknown ----------- + + kiDataObject(); + STDMETHODIMP QueryInterface( REFIID, void** ); + STDMETHODIMP_(ULONG) AddRef(); + STDMETHODIMP_(ULONG) Release(); +private: + ULONG m_cRef; + +private: //-- IDataObject ------------ + + STDMETHODIMP GetData( FORMATETC*, STGMEDIUM* ); + STDMETHODIMP QueryGetData( FORMATETC* ); + STDMETHODIMP EnumFormatEtc( DWORD, IEnumFORMATETC** ); + STDMETHODIMP GetDataHere( FORMATETC*, STGMEDIUM* ) + { + return E_NOTIMPL; + } + STDMETHODIMP GetCanonicalFormatEtc( FORMATETC*, FORMATETC* ) + { + return E_NOTIMPL; + } + STDMETHODIMP SetData( FORMATETC*, STGMEDIUM*, BOOL ) + { + return E_NOTIMPL; + } + STDMETHODIMP DAdvise( FORMATETC*, DWORD, IAdviseSink*, DWORD* ) + { + return OLE_E_ADVISENOTSUPPORTED; + } + STDMETHODIMP DUnadvise( DWORD ) + { + return OLE_E_NOCONNECTION; + } + STDMETHODIMP EnumDAdvise( IEnumSTATDATA** ) + { + return OLE_E_ADVISENOTSUPPORTED; + } + +private: //-- 内部処理 ----------------- + + kiArray m_FormatList; + bool m_bFirst; + friend class kiDataObject_Enum; + +public: + void begin() + { + m_bFirst = true; + } +}; + +/*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*/ +// kiDropSource : ドロップ元としての標準処理 + +class kiDropSource : public IDropSource +{ +public: //-- ドラッグ&ドロップ実行! + + static bool DnD( kiDataObject* pObj, DWORD efct, DWORD* pefct=NULL ); + +private: //-- IUnknown + + kiDropSource(); + STDMETHODIMP QueryInterface( REFIID, void** ); + STDMETHODIMP_(ULONG) AddRef(); + STDMETHODIMP_(ULONG) Release(); + ULONG m_cRef; + +private: //-- IDropSource + + STDMETHODIMP QueryContinueDrag( BOOL, DWORD ); + STDMETHODIMP GiveFeedback( DWORD ); +}; + +#endif ADDED kilib/kl_file.cpp Index: kilib/kl_file.cpp ================================================================== --- kilib/kl_file.cpp +++ kilib/kl_file.cpp @@ -0,0 +1,150 @@ +//--- K.I.LIB --- +// kl_file.cpp : file operations + +#include "stdafx.h" +#include "kilib.h" + +//--------------------------- static --------------------------// + +unsigned long kiFile::getSize( const char* fname, unsigned long err ) +{ + HANDLE h = ::CreateFile( fname, + GENERIC_READ, FILE_SHARE_WRITE|FILE_SHARE_READ, + NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL|FILE_FLAG_SEQUENTIAL_SCAN, NULL ); + if( h==INVALID_HANDLE_VALUE ) + return err; + + unsigned long ans = ::GetFileSize( h, NULL ); + ::CloseHandle( h ); + + return ans==0xffffffff ? err : ans; +} + +//--------------------------- 結んで開いて --------------------------// + + +bool kiFile::open( const char* filename, bool read, bool create ) +{ + close(); + + if( m_bReadMode = read ) + m_hFile = ::CreateFile( filename, + GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, + FILE_ATTRIBUTE_NORMAL | FILE_FLAG_SEQUENTIAL_SCAN, NULL ); + else + m_hFile = ::CreateFile( filename, + GENERIC_WRITE, FILE_SHARE_READ, NULL, + create ? CREATE_ALWAYS : OPEN_EXISTING, + FILE_ATTRIBUTE_NORMAL | FILE_FLAG_SEQUENTIAL_SCAN, NULL ); + if( m_hFile == INVALID_HANDLE_VALUE ) + return false; + + m_nBufPos = 0; + if( m_bReadMode ) + flush(); + + return true; +} + +void kiFile::close() +{ + if( m_hFile != INVALID_HANDLE_VALUE ) + { + if( !m_bReadMode ) + flush(); + + ::CloseHandle( m_hFile ); + m_hFile = INVALID_HANDLE_VALUE; + } +} + + +//-------------------------- 読み書き ----------------------------// + + +unsigned long kiFile::read( unsigned char* buf, unsigned long len ) +{ + unsigned long ans = 0; + if( m_nBufSize!=0 && m_hFile!=INVALID_HANDLE_VALUE && m_bReadMode ) + { + while( (m_nBufSize-m_nBufPos) <= len ) + { + ans += (m_nBufSize-m_nBufPos); + ki_memcpy( buf, m_pBuf+m_nBufPos, m_nBufSize-m_nBufPos ); + len -= (m_nBufSize-m_nBufPos); + buf += (m_nBufSize-m_nBufPos); + + flush(); + if( m_nBufSize == 0 ) + return ans; + } + ans += len; + ki_memcpy( buf, m_pBuf+m_nBufPos, len ); + m_nBufPos += len; + } + return ans; +} + +void kiFile::write( const void* buf, unsigned long len ) +{ + if( m_hFile==INVALID_HANDLE_VALUE || m_bReadMode ) + return; + const unsigned char* ubuf = (const unsigned char*)buf; + + while( (kifile_bufsize-m_nBufPos) <= len ) + { + ki_memcpy( m_pBuf+m_nBufPos, buf, (kifile_bufsize-m_nBufPos) ); + len -= (kifile_bufsize-m_nBufPos); + ubuf += (kifile_bufsize-m_nBufPos); + m_nBufPos = kifile_bufsize; + flush(); + } + ki_memcpy( m_pBuf+m_nBufPos, ubuf, len ); + m_nBufPos += len; +} + +#undef putc +void kiFile::putc( unsigned char c ) +{ + if( m_hFile==INVALID_HANDLE_VALUE || m_bReadMode ) + return; + if( (kifile_bufsize-m_nBufPos) <= 1 ) + flush(); + m_pBuf[ m_nBufPos++ ] = c; +} + +#undef getc +int kiFile::getc() +{ + if( m_nBufSize==0 || m_hFile==INVALID_HANDLE_VALUE || !m_bReadMode ) + return -1; + + if( 0==(m_nBufSize-m_nBufPos) ) + { + flush(); + if( m_nBufSize==0 ) + return -1; + } + if( 1==(m_nBufSize-m_nBufPos) ) + { + int ans = m_pBuf[ m_nBufPos++ ]; + flush(); + return ans; + } + + return m_pBuf[ m_nBufPos++ ]; +} + +void kiFile::flush() +{ + if( m_bReadMode ) + { + ::ReadFile( m_hFile, m_pBuf, kifile_bufsize, &m_nBufSize, NULL ); + m_nBufPos = 0; + } + else + { + ::WriteFile( m_hFile, m_pBuf, m_nBufPos, &m_nBufSize, NULL ); + m_nBufSize = m_nBufPos = 0; + } +} ADDED kilib/kl_file.h Index: kilib/kl_file.h ================================================================== --- kilib/kl_file.h +++ kilib/kl_file.h @@ -0,0 +1,88 @@ +//--- K.I.LIB --- +// kl_file.h : file operations + +#ifndef AFX_KIFILE_H__7D126C1E_3E5C_476E_9A4E_81CA8055621D__INCLUDED_ +#define AFX_KIFILE_H__7D126C1E_3E5C_476E_9A4E_81CA8055621D__INCLUDED_ + +/*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*/ +// バイナリファイル操作 + +class kiFile +{ +public: //-- static ---------------------------------------- + + // ファイルサイズ取得( 名前, エラー時に返したい値 ) + static unsigned long getSize( const char* fname, unsigned long err=0xffffffff ); + +public: //-- 外向きインターフェイス -------------------------- + + // 開いて閉じて + bool open( const char* filename, bool read=true, bool create=true ); + void close(); + + // 読んで書いて + unsigned long read( unsigned char* buf, unsigned long len ); + void write( const void* buf, unsigned long len ); + int getc(); + void putc( unsigned char c ); + + // シーク + void seekTo( unsigned long pos ) + { + if( !m_bReadMode ) flush(); + ::SetFilePointer( m_hFile, pos, NULL, FILE_BEGIN ); + if( m_bReadMode ) flush(); + } + void seek( long pos ) + { + if( !m_bReadMode ) flush(); + ::SetFilePointer( m_hFile, + pos-(signed)m_nBufSize+(signed)m_nBufPos, NULL, + FILE_CURRENT ); + if( m_bReadMode ) flush(); + } + unsigned long tell() + { + return ::SetFilePointer( m_hFile, 0, NULL, FILE_CURRENT ) + - m_nBufSize + m_nBufPos; + } + + // 情報取得 + bool isOpened() + { + return m_hFile != INVALID_HANDLE_VALUE; + } + unsigned long getSize( unsigned long* higher=NULL ) + { + return ::GetFileSize( m_hFile, higher ); + } + bool isEOF() + { + return (m_nBufPos==0 && m_nBufSize==0); + } + +public: //-- 内部処理 ----------------------------------- + + kiFile() : kifile_bufsize( 65536 ) + { + m_hFile= INVALID_HANDLE_VALUE; + m_pBuf = new unsigned char[kifile_bufsize]; + } + + virtual ~kiFile() + { + close(); + delete [] m_pBuf; + } + +private: + const int kifile_bufsize; + void flush(); + + HANDLE m_hFile; + bool m_bReadMode; + unsigned char* m_pBuf; + unsigned long m_nBufSize, m_nBufPos; +}; + +#endif ADDED kilib/kl_find.cpp Index: kilib/kl_find.cpp ================================================================== --- kilib/kl_find.cpp +++ kilib/kl_find.cpp @@ -0,0 +1,67 @@ +//--- K.I.LIB --- +// kl_find.h : FindFirstFile wrapper + +#include "stdafx.h" +#include "kilib.h" + +#define isDots(p) (*p=='.' && (p[1]=='\0' || (p[1]=='.' && p[2]=='\0'))) + +bool kiFindFile::findfirst( const char* wild, WIN32_FIND_DATA* pfd ) +{ + HANDLE xh = ::FindFirstFile( wild, pfd ); + if( xh==INVALID_HANDLE_VALUE ) + return false; + while( isDots(pfd->cFileName) ) + if( !::FindNextFile( xh, pfd ) ) + { + ::FindClose( xh ); + return false; + } + ::FindClose( xh ); + return true; +} + +void kiFindFile::close() +{ + first=true; + if( h!=INVALID_HANDLE_VALUE ) + { + ::FindClose( h ), h=INVALID_HANDLE_VALUE; + } +} + +bool kiFindFile::begin( const char* wild ) +{ + close(); + + h = ::FindFirstFile( wild, &fd ); + if( h==INVALID_HANDLE_VALUE ) + return false; + while( isDots(fd.cFileName) ) + if( !::FindNextFile( h, &fd ) ) + { + close(); + return false; + } + return true; +} + +bool kiFindFile::next( WIN32_FIND_DATA* pfd ) +{ + if( h==INVALID_HANDLE_VALUE ) + return false; + if( first ) + { + first = false; + ki_memcpy( pfd, &fd, sizeof(fd) ); + return true; + } + if( !::FindNextFile( h, pfd ) ) + return false; + while( isDots(fd.cFileName) ) + if( !::FindNextFile( h, pfd ) ) + return false; + return true; +} + +#undef isDots ADDED kilib/kl_find.h Index: kilib/kl_find.h ================================================================== --- kilib/kl_find.h +++ kilib/kl_find.h @@ -0,0 +1,32 @@ +//--- K.I.LIB --- +// kl_find.h : FindFirstFile wrapper + +#ifndef AFX_KIFINDFILE_H__86462791_815C_4F44_9F16_802B54B411BA__INCLUDED_ +#define AFX_KIFINDFILE_H__86462791_815C_4F44_9F16_802B54B411BA__INCLUDED_ + +/*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*/ +// ファイル検索 + +class kiFindFile +{ +public: //-- 外向きインターフェイス -------------------------- + + static bool findfirst( const char* wild, WIN32_FIND_DATA* pfd ); + bool begin( const char* wild ); + bool next( WIN32_FIND_DATA* pfd ); + +public: //-- 内部処理 ----------------------------------- + + kiFindFile() + { h = INVALID_HANDLE_VALUE; } + virtual ~kiFindFile() + { close(); } + void close(); + +private: + HANDLE h; + bool first; + WIN32_FIND_DATA fd; +}; + +#endif ADDED kilib/kl_misc.h Index: kilib/kl_misc.h ================================================================== --- kilib/kl_misc.h +++ kilib/kl_misc.h @@ -0,0 +1,124 @@ +//--- K.I.LIB --- +// kl_misc.h : common-classes for K.I.LIB + +#ifndef AFX_KILIBBASE_H__89998F34_A9FE_4A27_A159_671F85AA9383__INCLUDED_ +#define AFX_KILIBBASE_H__89998F34_A9FE_4A27_A159_671F85AA9383__INCLUDED_ + +/*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*/ +// 使用する外部関数を何となくマクロ化しておく +// 追記:何でこんなことやったんだ…? > 昔の自分(^^; + +#define ki_strlen(p) ::lstrlen(p) +#define ki_strcpy(p,s) ::lstrcpy(p,s) +#define ki_strcat(p,s) ::lstrcat(p,s) +#define ki_strcmp(p,s) ::lstrcmp(p,s) +#define ki_strcmpi(p,s) ::lstrcmpi(p,s) +#define ki_memzero(p,l) ::ZeroMemory(p,l) +#define ki_memcpy(p,s,l) ::CopyMemory(p,s,l) +#define ki_memmov(p,s,l) ::MoveMemory(p,s,l) +#define ki_memset(p,c,l) ::FillMemory(p,l,c) +inline bool ki_memcmp( const char* x, const char* y, int l ) +{ + while( *x++==*y++ && --l ); + return l==0; +} + +/*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*/ +// kiArray : 配列のようなキューのような代物 + +template class kiArray +{ +public: //-- 外向きインターフェイス -------------------------- + + // 初期サイズ( 10〜255 )で初期化 + kiArray( unsigned char start_size=10 ) + { + m_pArray = new T[ m_ALen=start_size ]; + m_Len = 0; + } + + // 配列を空にする + void empty() + { + m_Len = 0; + } + + // 要素数を取得 + unsigned long len() const + { + return m_Len; + } + + // 末尾に一個追加 + void add( const T& obj ) + { + if( m_Len>=m_ALen ) + { + T* p = new T[ m_ALen<<=1 ]; + for( unsigned long i=0; i!=m_Len; i++ ) + p[i] = m_pArray[i]; + delete [] m_pArray; + m_pArray = p; + } + m_pArray[ m_Len++ ] = obj; + } + + // 要素にアクセス + T& operator []( unsigned long i ) + { + return m_pArray[i]; + } + const T& operator []( unsigned long i ) const + { + return m_pArray[i]; + } + + // 配列コピー + kiArray& operator = ( const kiArray& o ) + { + if( &o != this ) + { + empty(); + for( unsigned int i=0; i!=o.len(); i++ ) + add( o[i] ); + } + return *this; + } + + //-- ちょっと危険なメソッド群 + void alloc( unsigned long x ) + { + if( x > m_ALen ) + { + T* p = new T[ m_ALen=(m_ALen<<1)>x?(m_ALen<<1):x ]; + for( unsigned long i=0; i!=m_Len; i++ ) + p[i] = m_pArray[i]; + delete [] m_pArray; + m_pArray = p; + } + } + void forcelen( unsigned long x ) + { + alloc( x ); + m_Len = x; + } + +private: //-- 内部処理 ----------------------------------- + + T* m_pArray; + unsigned long m_Len, m_ALen; + +public: + + virtual ~kiArray() + { + delete [] m_pArray; + } +}; + +#define BoolArray kiArray +#define CharArray kiArray +#define cCharArray kiArray +#define StrArray kiArray + +#endif ADDED kilib/kl_reg.cpp Index: kilib/kl_reg.cpp ================================================================== --- kilib/kl_reg.cpp +++ kilib/kl_reg.cpp @@ -0,0 +1,169 @@ +//--- K.I.LIB --- +// kl_reg.h : registry and ini-file operation + +#include "stdafx.h" +#include "kilib.h" + + +//---------------------------- open系 ----------------------------// + + +bool kiRegKey::open( HKEY parent, LPCTSTR keyname, REGSAM access ) +{ + return (ERROR_SUCCESS == RegOpenKeyEx( parent, + keyname, 0, access, &m_hKey )); +} + +bool kiRegKey::create( HKEY parent, LPCTSTR keyname, REGSAM access ) +{ + DWORD x; + return (ERROR_SUCCESS == RegCreateKeyEx( parent, + keyname, 0, REG_NONE, REG_OPTION_NON_VOLATILE, access, NULL, &m_hKey, &x )); +} + + +//------------------------- query/set系 ----------------------------// + + +bool kiRegKey::get( LPCTSTR valname, DWORD* val ) +{ + DWORD x=4; + return (ERROR_SUCCESS == RegQueryValueEx( m_hKey, + valname, NULL, NULL, (BYTE*)val, &x )); +} + +bool kiRegKey::get( LPCTSTR valname, BYTE* val, DWORD siz ) +{ + return (ERROR_SUCCESS == RegQueryValueEx( m_hKey, + valname, NULL, NULL, val, &siz )); +} + +bool kiRegKey::get( LPCTSTR valname, kiStr* val ) +{ + static char dat[2048]; + DWORD x = 2048; + if( ERROR_SUCCESS == RegQueryValueEx( m_hKey, + valname, NULL, NULL, (BYTE*)dat, &x )) + { + *val = dat; + return true; + } + return false; +} + +bool kiRegKey::set( LPCTSTR valname, DWORD val ) +{ + return (ERROR_SUCCESS == RegSetValueEx( m_hKey, + valname, 0, REG_DWORD, (BYTE*)&val, 4 )); +} + +bool kiRegKey::set( LPCTSTR valname, BYTE* val, DWORD siz ) +{ + return (ERROR_SUCCESS == RegSetValueEx( m_hKey, + valname, 0, REG_BINARY, (BYTE*)val, siz )); +} + +bool kiRegKey::set( LPCTSTR valname, LPCTSTR val ) +{ + return (ERROR_SUCCESS == RegSetValueEx( m_hKey, + valname, 0, REG_SZ, (BYTE*)val, ki_strlen(val)+1 )); +} + + +//--------------------------- delete系 ----------------------------// + + +bool kiRegKey::del( LPCTSTR valname ) +{ + return (ERROR_SUCCESS == RegDeleteValue( m_hKey, valname )); +} + +bool kiRegKey::delSubKey( LPCTSTR keyname ) +{ + if( app()->osver().dwPlatformId == VER_PLATFORM_WIN32_NT ) + return delSubKeyRecursive( m_hKey, keyname ); + else + return (ERROR_SUCCESS == RegDeleteKey( m_hKey, keyname )); +} + +bool kiRegKey::delSubKeyRecursive( HKEY k, LPCTSTR n ) +{ + HKEY k2; + if( ERROR_SUCCESS!=RegOpenKeyEx( k,n,0,KEY_READ,&k2 ) ) + return false; + + bool ans = true; + static char buf[2048]; + DWORD bs = sizeof(buf); + + for( int i=0; + ERROR_SUCCESS==RegEnumKeyEx( k2,i,buf,&bs,NULL,NULL,NULL,NULL ); + i++ ) + { + if( !delSubKeyRecursive( k2,buf ) ) + ans = false; + bs = sizeof(buf); + } + + RegCloseKey( k2 ); + RegDeleteKey( k,n ); + return ans; +} + +//--------------------------- ini:初期化 ----------------------------// + + +void kiIniFile::setFileName( const char* ini, bool exepath ) +{ + if( !exepath ) + m_FileName = ""; + else + { + m_FileName.beSpecialPath( kiPath.Exe ); + m_FileName.beBackSlash( true ); + } + m_FileName += ini; +} + + +//--------------------------- ini:read系 ----------------------------// + + +int kiIniFile::getInt( const char* key, int defval ) +{ + return ::GetPrivateProfileInt( m_CurSec, key, defval, m_FileName ); +} + +bool kiIniFile::getBool( const char* key, bool defval ) +{ + return (0 != ::GetPrivateProfileInt( m_CurSec, + key, defval?1:0, m_FileName ) ); +} + +const char* kiIniFile::getStr( const char* key, const char* defval ) +{ + ::GetPrivateProfileString( m_CurSec, key, defval, + m_StrBuf, sizeof(m_StrBuf), m_FileName ); + return m_StrBuf; +} + + +//--------------------------- ini:write系 ----------------------------// + + +bool kiIniFile::putStr( const char* key, const char* val ) +{ + return (FALSE != ::WritePrivateProfileString( + m_CurSec, key, val, m_FileName ) ); +} + +bool kiIniFile::putInt( const char* key, int val ) +{ + ::wsprintf( m_StrBuf, "%d", val ); + return putStr( key, m_StrBuf ); +} + +bool kiIniFile::putBool( const char* key, bool val ) +{ + return putStr( key, val ? "1" : "0" ); +} ADDED kilib/kl_reg.h Index: kilib/kl_reg.h ================================================================== --- kilib/kl_reg.h +++ kilib/kl_reg.h @@ -0,0 +1,100 @@ +//--- K.I.LIB --- +// kl_reg.h : registry and ini-file operation + +#ifndef AFX_KIREGKEY_H__4FD5E1B3_B8FE_45B3_B19E_3D30407C94BA__INCLUDED_ +#define AFX_KIREGKEY_H__4FD5E1B3_B8FE_45B3_B19E_3D30407C94BA__INCLUDED_ + +/*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*/ +// レジストリ操作&ini操作 + +class kiRegKey +{ +public: //-- 外向きインターフェイス -------------------------- + + // 開く&閉じる + bool open( HKEY parent, LPCTSTR keyname, REGSAM access = KEY_ALL_ACCESS ); + bool create( HKEY parent, LPCTSTR keyname, REGSAM access = KEY_ALL_ACCESS ); + void close() + { + if( m_hKey ) + RegCloseKey( m_hKey ); + } + + // サブキーが存在するや否や + bool exist( LPCTSTR keyname ) + { + HKEY k; + if( ERROR_SUCCESS==RegOpenKeyEx( m_hKey,keyname,0,KEY_READ,&k ) ) + { + RegCloseKey( k ); + return true; + } + return false; + } + // HKEYへキャスト + operator HKEY() const + { + return m_hKey; + } + + // 値を得る + bool get( LPCTSTR valname, DWORD* val ); + bool get( LPCTSTR valname, BYTE* val, DWORD siz ); + bool get( LPCTSTR valname, kiStr* val ); + + // 値を設定 + bool set( LPCTSTR valname, DWORD val ); + bool set( LPCTSTR valname, BYTE* val, DWORD siz ); + bool set( LPCTSTR valname, LPCTSTR val ); + + // 削除 + bool del( LPCTSTR valname ); + bool delSubKey( LPCTSTR keyname ); + +public: //-- 内部処理 ----------------------------------- + + kiRegKey() + { + m_hKey = NULL; + } + + virtual ~kiRegKey() + { + close(); + } + +private: + + HKEY m_hKey; + static bool delSubKeyRecursive( HKEY k, LPCTSTR n ); +}; + +class kiIniFile +{ +public: //-- 外向きインターフェイス -------------------------- + + // iniファイル名を設定 + void setFileName( const char* ini, bool exepath=true ); + void setSection( const char* section ) + { m_CurSec = section; } + + // 読み込み + // ※ 注意!getStrの返値は内部バッファな為、 + // ※    呼び出し直後以外は内容を保証しない。 + int getInt( const char* key, int defval ); + bool getBool( const char* key, bool defval ); + const char* getStr( const char* key, const char* defval ); + + // 書き込み + bool putStr( const char* key, const char* val ); + bool putInt( const char* key, int val ); + bool putBool( const char* key, bool val ); + +private: //-- 内部処理 ----------------------------------- + + kiPath m_FileName; + kiStr m_CurSec; + char m_StrBuf[256]; +}; + +#endif ADDED kilib/kl_rythp.cpp Index: kilib/kl_rythp.cpp ================================================================== --- kilib/kl_rythp.cpp +++ kilib/kl_rythp.cpp @@ -0,0 +1,323 @@ +//--- K.I.LIB --- +// kl_rythp.cpp : interpretor for simple script langauage 'Rythp' + +#include "stdafx.h" +#include "kilibext.h" + +//-------------------- Variant 型変数 --------------------------// + +int kiVar::getInt() +{ + int n=0; + bool minus = (*m_pBuf=='-'); + for( char* p = minus ? m_pBuf+1 : m_pBuf; *p; p=next(p) ) + { + if( '0'>*p || *p>'9' ) + return 0; + n = (10*n) + (*p-'0'); + } + return minus ? -n : n; +} + +void kiVar::quote() +{ + if( m_pBuf[0]=='\"' ) + return; + for( const char* p=m_pBuf; *p; p=next(p) ) + if( *p==' ' ) + break; + if( !(*p) ) + return; + + int ln=len()+1; + if( m_ALen=0 ) + { + if( *p=='(' && !(dqc&1) ) + kkc++; + else if( *p==')' && !(dqc&1) ) + kkc--; + else if( *p=='\"' ) + dqc++; + else if( *p=='%' ) + p++; + else if( (*p=='\t' || *p==' ' || *p=='\r' || *p=='\n') && kkc==0 && !(dqc&1) ) + return p; + p++; + } + return (kkc==0 && !(dqc&1)) ? p : NULL; +} + +bool kiRythpVM::split( char* buf, kiArray& argv, kiArray& argb, int& argc ) +{ + argv.empty(), argb.empty(), argc=0; + + for( char* p=buf; p=split_tonext(p); p++,argc++ ) + { + argv.add( p ); + argb.add( *p=='(' ); + + if( !(p=split_toend(p)) ) + return false; + + if( argv[argc][0]=='(' || argv[argc][0]=='"' ) + argv[argc]++, *(p-1)='\0'; + if( *p=='\0' ) + { + argc++; + break; + } + *p='\0'; + } + return true; +} + +//------------------------- 実行 -------------------------// + +void kiRythpVM::eval( char* str, kiVar* ans ) +{ + // 返値をクリアしておく + kiVar tmp,*aaa=&tmp; + if(ans) + *ans="",aaa=ans; + + // "function param1 param2 ..." 形式の文字列をパラメータに分割 + kiArray av; + kiArray ab; + int ac; + if( split( str,av,ab,ac ) && ac ) + { + // function名取得 + kiVar name; + getarg( av[0],ab[0],&name ); + + // function実行! + exec_function( name, av, ab, ac, aaa ); + } +} + +void kiRythpVM::getarg( char* a, bool b, kiVar* arg ) +{ + kiVar t; + const char* p; + + // (...) なら eval する。 + if( b ) + eval( a,&t ), p = t; + else + p = a; + + // 変数置き換え + *arg=""; + for( ; *p; *p && p++ ) + if( *p!='%' ) + { + *arg += *p; + } + else + { + p++, *arg+=ele[(*p)&0xff]; + } +} + +//------------------------- Minimum-Rythp環境 -------------------------// + +bool kiRythpVM::exec_function( const kiVar& name, + const kiArray& a, const kiArray& b,int c, kiVar* r ) +{ +// Minimum-Rythp で利用できる function は以下の通り。 +// exec, while, if, let, +, -, *, /, =, !, between, mod + + kiVar t; + int i,A,B,C; + +//----- ---- --- -- - - - +//-- (exec 実行文 実行文 ...) returns last-result +//----- ---- --- -- - - - + if( name=="exec" ) + { + for( i=1; i=3 ) + { + // (特殊処理)複数回呼ぶコードなのでコピらなきゃ駄目。 + int L1=ki_strlen(a[1]), L2=ki_strlen(a[2]); + char* tmp = new char[ 1 + (L1>L2 ? L1 : L2) ]; + while( getarg( ki_strcpy(tmp,a[1]), b[1], &t ), t.len() ) + getarg( ki_strcpy(tmp,a[2]), b[2], r ); + delete [] tmp; + } + } +//----- ---- --- -- - - - +//-- (if 条件 真なら [偽なら]) returns executed-result +//----- ---- --- -- - - - + else if( name=="if" ) + { + if( c>=3 ) + { + if( getarg( a[1],b[1],&t ), t.len() ) + getarg( a[2],b[2],r ); + else if( c>=4 ) + getarg( a[3],b[3],r ); + } + } +//----- ---- --- -- - - - +//-- (let 変数名 値 値 ...) returns new-value +//----- ---- --- -- - - - + else if( name=="let" ) + { + if( c>=2 ) + { + *r = ""; + for( i=2; i=3 ) + { + getarg(a[1],b[1],&t), A=t.getInt(); + getarg(a[2],b[2],&t), B=t.getInt(); + *r = A==B ? "1" : ""; + } + } +//----- ---- --- -- - - - +//-- (between 値A 値B 値C) returns A <= B <= C ? +//----- ---- --- -- - - - + else if( name=="between" ) + { + if( c>=4 ) + { + getarg(a[1],b[1],&t), A=t.getInt(); + getarg(a[2],b[2],&t), B=t.getInt(); + getarg(a[3],b[3],&t), C=t.getInt(); + *r = (A<=B && B<=C) ? "1" : ""; + } + } +//----- ---- --- -- - - - +//-- (! 値A [値B]) returns A!=B ? or !A +//----- ---- --- -- - - - + else if( name=="!" ) + { + if( c>=2 ) + { + getarg(a[1],b[1],&t), A=t.getInt(); + if( c==2 ) + *r = A==0 ? "1" : ""; + else + { + getarg(a[2],b[2],&t), B=t.getInt(); + *r = A!=B ? "1" : ""; + } + } + } +//----- ---- --- -- - - - +//-- (+ 値A 値B) returns A+B +//----- ---- --- -- - - - + else if( name=="+" ) + { + if( c>=3 ) + { + getarg(a[1],b[1],&t), A=t.getInt(); + getarg(a[2],b[2],&t), B=t.getInt(); + r->setInt( A+B ); + } + } +//----- ---- --- -- - - - +//-- (- 値A 値B) returns A-B +//----- ---- --- -- - - - + else if( name=="-" ) + { + if( c>=3 ) + { + getarg(a[1],b[1],&t), A=t.getInt(); + getarg(a[2],b[2],&t), B=t.getInt(); + r->setInt( A-B ); + } + } +//----- ---- --- -- - - - +//-- (* 値A 値B) returns A*B +//----- ---- --- -- - - - + else if( name=="*" ) + { + if( c>=3 ) + { + getarg(a[1],b[1],&t), A=t.getInt(); + getarg(a[2],b[2],&t), B=t.getInt(); + r->setInt( A*B ); + } + } +//----- ---- --- -- - - - +//-- (/ 値A 値B) returns A/B +//----- ---- --- -- - - - + else if( name=="/" ) + { + if( c>=3 ) + { + getarg(a[1],b[1],&t), A=t.getInt(); + getarg(a[2],b[2],&t), B=t.getInt(); + r->setInt( A/B ); + } + } +//----- ---- --- -- - - - +//-- (mod 値A 値B) returns A%B +//----- ---- --- -- - - - + else if( name=="mod" ) + { + if( c>=3 ) + { + getarg(a[1],b[1],&t), A=t.getInt(); + getarg(a[2],b[2],&t), B=t.getInt(); + r->setInt( A%B ); + } + } + else + return false; + return true; +} + ADDED kilib/kl_rythp.h Index: kilib/kl_rythp.h ================================================================== --- kilib/kl_rythp.h +++ kilib/kl_rythp.h @@ -0,0 +1,54 @@ +//--- K.I.LIB --- +// kl_rythp.h : interpretor for simple script langauage 'Rythp' + +#ifndef AFX_KIRYTHPVM_H__4F3C28A9_7EFE_4605_A149_2C0B9A9236E5__INCLUDED_ +#define AFX_KIRYTHPVM_H__4F3C28A9_7EFE_4605_A149_2C0B9A9236E5__INCLUDED_ + +/*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*/ +// kiVar : Rythp用のVariant変数型。ほとんどただのkiStr。 + +class kiVar : public kiStr +{ +public: + kiVar() : kiStr(20) {} + explicit kiVar( const char* s ) : kiStr( s, 20 ){} + explicit kiVar( const kiStr& s ) : kiStr( s, 20 ){} + explicit kiVar( const kiVar& s ) : kiStr( s, 20 ){} + void operator = ( const char* s ){ kiStr::operator =(s); } + + int getInt(); + void quote(); +}; + +/*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*/ +// kiRythpVM : 最小限Rythp。実用には、派生して独自の exec_function を実装すべし + +class kiRythpVM +{ +public: + kiRythpVM(); + virtual ~kiRythpVM() {} + +public: + // eval + void eval( char* str, kiVar* ans=NULL ); + +protected: + // 引数を適当にevalや変数置き換えをした形で取得 + void getarg( char* a, bool b, kiVar* arg ); + + // function実行。[ bool=処理したか?、 name=function名、 a,b,c=引数、 r=返値 ] + virtual bool exec_function( const kiVar& name, + const CharArray& a, const BoolArray& b,int c, kiVar* r ); + +private: + // 変数 + kiVar ele[256]; + + // パラメータ分割 + static char* split_tonext( char* p ); + static char* split_toend( char* p ); + static bool split( char* buf, CharArray& argv, BoolArray& argb, int& argc ); +}; + +#endif ADDED kilib/kl_str.cpp Index: kilib/kl_str.cpp ================================================================== --- kilib/kl_str.cpp +++ kilib/kl_str.cpp @@ -0,0 +1,344 @@ +//--- K.I.LIB --- +// kl_str.cpp : string classes for K.I.LIB + +#include "stdafx.h" +#include "kilib.h" + + +//------------------------ 2byte文字処理用 ----------------------// + + +char kiStr::st_lb[256]; + +void kiStr::init() +{ + st_lb[0] = 0; + for( int c=1; c!=256; c++ ) + st_lb[c] = (::IsDBCSLeadByte(c) ? 2 : 1); +} + + +//-------------------------- コピー系色々 ------------------------// + + +kiStr::kiStr( int start_size ) +{ + (m_pBuf = new char[ m_ALen = start_size ])[0] = '\0'; +} + +kiStr::kiStr( const char* s, int min_size ) +{ + int slen = ki_strlen(s) + 1; + m_ALen = ( slen < min_size ) ? min_size : slen; + ki_memcpy( m_pBuf=new char[m_ALen], s, slen ); +} + +kiStr::kiStr( const kiStr& s ) +{ + ki_memcpy( m_pBuf=new char[m_ALen=s.m_ALen], s.m_pBuf, m_ALen=s.m_ALen ); +} + +kiStr& kiStr::operator = ( const kiStr& s ) +{ + if( this != &s ) + *this = (const char*)s; + return *this; +} + +kiStr& kiStr::operator = ( const char* s ) +{ + int slen = ki_strlen( s ) + 1; + int len = this->len(); + + if( m_ALen < slen || s <= m_pBuf+len || m_pBuf <= s+slen ) + { + char* tmp = new char[ m_ALen = ( m_ALen>slen ? m_ALen : slen) ]; + ki_memcpy( tmp, s, slen ); + delete [] m_pBuf; + m_pBuf = tmp; + } + else + ki_memcpy( m_pBuf, s, slen ); + return *this; +} + +kiStr& kiStr::operator += ( const char* s ) +{ + int slen = ki_strlen( s ) + 1; + int len = this->len(); + + if( m_ALen < len+slen+1 + || ( s <= m_pBuf && m_pBuf <= s+len ) + || ( m_pBuf <= s && s <= m_pBuf+slen ) ) + { + char* tmp = new char[ m_ALen = ( m_ALen>slen+len+1 ? m_ALen : slen+len+1) ]; + ki_memcpy( tmp, m_pBuf, len ); + delete [] m_pBuf; + m_pBuf = tmp; + } + + ki_memcpy( m_pBuf+len, s, slen+1 ); + return *this; +} + +kiStr& kiStr::operator += ( char c ) +{ + int len = this->len(); + + if( m_ALen < len+2 ) + { + char* tmp = new char[ m_ALen=len+20 ]; + ki_memcpy( tmp, m_pBuf, len ); + delete [] m_pBuf; + m_pBuf = tmp; + } + + m_pBuf[len]=c, m_pBuf[len+1]='\0'; + return *this; +} + +kiStr& kiStr::setInt( int n, bool cm ) +{ + if( n==0 ) + m_pBuf[0] = '0', m_pBuf[1] = '\0'; + else + { + bool minus = (n<0); + if( minus ) + n= -n; + + char tmp[30]; + tmp[29]='\0'; + int i; + + for( i=28; i>=0; i-- ) + { + if( cm && (29-i)%4==0 ) + tmp[i--] = ','; + tmp[i] = '0' + n%10; + n /= 10; + if( n==0 ) + break; + } + + if( minus ) + tmp[--i] = '-'; + + (*this) = tmp+i; + } + return (*this); +} + +//-------------------------- 文字列処理全般 ------------------------// + + +kiStr::~kiStr() +{ + delete [] m_pBuf; +} + +kiStr::operator const char*() const +{ + return m_pBuf; +} + +bool kiStr::operator == ( const char* s ) const +{ + return 0==ki_strcmp( m_pBuf, s ); +} + +bool kiStr::isSame( const char* s ) const +{ + return 0==ki_strcmpi( m_pBuf, s ); +} + +int kiStr::len() const +{ + return ki_strlen( m_pBuf ); +} + + +//-------------------------- ユーティリティー ------------------------// + + +kiStr& kiStr::loadRsrc( UINT id ) +{ + ::LoadString( GetModuleHandle(NULL), id, m_pBuf, m_ALen ); + return *this; +} + +void kiPath::beSpecialPath( int nPATH ) +{ + switch( nPATH ) + { + case Win: ::GetWindowsDirectory( m_pBuf, m_ALen ); break; + case Sys: ::GetSystemDirectory( m_pBuf, m_ALen ); break; + case Tmp: ::GetTempPath( m_ALen, m_pBuf ); break; + case Cur: ::GetCurrentDirectory( m_ALen, m_pBuf ); break; + case Exe_name: + ::GetModuleFileName( NULL, m_pBuf, m_ALen );break; + case Exe: + { + ::GetModuleFileName( NULL, m_pBuf, m_ALen ); + + char* m=NULL; + for( char *p=m_pBuf; *p!='\0'; p=next(p) ) + if( *p=='\\' ) + m = p; + if( m ) + *m='\0'; + break; + } + default: + { + *m_pBuf = '\0'; + + LPITEMIDLIST il; + if( NOERROR!=::SHGetSpecialFolderLocation( NULL, nPATH, &il ) ) + return; + ::SHGetPathFromIDList( il, m_pBuf ); + app()->shellFree( il ); + } + } +} + +void kiPath::beBackSlash( bool add ) +{ + char* last = m_pBuf; + for( char* p=m_pBuf; *p!='\0'; p=next(p) ) + last=p; + if( *last=='\\' || *last=='/' ) + { + if( !add ) + *last = '\0'; + } + else if( add && last!=m_pBuf ) + *this += '\\'; +} + +bool kiPath::beDirOnly() +{ + char* lastslash = m_pBuf-1; + for( char* p=m_pBuf; *p; p=next(p) ) + if( *p=='\\' || *p=='/' ) + lastslash = p; + + *(lastslash+1) = '\0'; + + return (lastslash+1 != m_pBuf); +} + +void kiPath::beShortPath() +{ + ::GetShortPathName( m_pBuf, m_pBuf, m_ALen ); +} + +void kiPath::mkdir() +{ + for( char *p=m_pBuf; *p; p=kiStr::next(p) ) + { + if( (*p!='\\' && *p!='/') || (p-m_pBuf<=4) ) + continue; + *p = '\0'; + if( !kiSUtil::exist(m_pBuf) ) + if( ::CreateDirectory( m_pBuf, NULL ) ) + ::SHChangeNotify( SHCNE_MKDIR,SHCNF_PATH,(const void*)m_pBuf,NULL ); + *p = '\\'; + } +} + +void kiPath::remove() +{ + if( !kiSUtil::exist(*this) ) + return; + if( !kiSUtil::isdir(*this) ) + { + ::DeleteFile(*this); + return; + } + + // buf == filename with no last '\\' + kiPath buf(*this); + buf.beBackSlash(false); + + kiPath tmp(buf); + WIN32_FIND_DATA fd; + kiFindFile find; + find.begin( tmp += "\\*" ); + while( find.next( &fd ) ) + { + tmp = buf; + tmp += '\\'; + tmp += fd.cFileName; + tmp.remove(); + } + find.close(); + + ::RemoveDirectory( buf ); +} + +void kiPath::getBody( kiStr& str ) const +{ + char *p=const_cast(name()),*x,c; + for( x=p; *x; x=next(x) ) + if( *x=='.' ) + break; + c=*x, *x='\0'; + str=p; + *x=c; +} + +const char* kiPath::name( const char* str ) +{ + const char* ans = str - 1; + for( const char* p=str; *p; p=next(p) ) + if( *p=='\\' || *p=='/' ) + ans = p; + return (ans+1); +} + +const char* kiPath::ext( const char* str ) +{ + const char *ans = NULL, *p; + for( p=name(str); *p; p=next(p) ) + if( *p=='.' ) + ans = p; + return ans ? (ans+1) : p; +} + +const char* kiPath::ext_all( const char* str ) +{ + const char* p; + for( p=name(str); *p; p=next(p) ) + if( *p=='.' ) + return (p+1); + return p; +} + +void kiPath::body( const char* str, char* buf ) +{ + char *n=const_cast(kiPath::name(str)),*x; + for( x=n; *x; x=next(x) ) + if( *x=='.' ) + break; + memcpy( buf, str, x-n ); + buf[x-n]='\0'; +} + +UINT kiPath::getDriveType() const +{ + char* p; + for( p=m_pBuf; *p=='\\'; p=next(p) ); + for( p=m_pBuf; *p && *p!='\\'; p=next(p) ); + char c=*(++p);*p='\0'; + UINT ans=::GetDriveType( m_pBuf ); + *p=c; return ans; +} + +bool kiPath::endwithyen( const char* str ) +{ + for( const char *p=str,*last=str; *p; p=next(p) ) + last=p; + return ( *last=='\\' || *last=='/' ); +} + ADDED kilib/kl_str.h Index: kilib/kl_str.h ================================================================== --- kilib/kl_str.h +++ kilib/kl_str.h @@ -0,0 +1,133 @@ +//--- K.I.LIB --- +// kl_str.h : string classes for K.I.LIB + +#ifndef AFX_KISTR_H__1932CA2C_ACA6_4606_B57A_ACD0B7D1D35B__INCLUDED_ +#define AFX_KISTR_H__1932CA2C_ACA6_4606_B57A_ACD0B7D1D35B__INCLUDED_ + +/*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*/ +// kiStr : 単純文字列 + +class kiStr +{ +friend void kilib_startUp(); + +private: //-- グローバルな初期化処理など --------------------- + + static void init(); + +public: //-- 外向きインターフェイス -------------------------- + + // 2byte文字の処理を高速化(したような気分) + static char* next( char* p ) + { return p+st_lb[(*p)&0xff]; } + static const char* next( const char* p ) + { return p+st_lb[(*p)&0xff]; } + static bool isLeadByte( char c ) + { return st_lb[c&0xff]==2; } + + // 初期化 + kiStr( int start_size = 100 ); + kiStr( const char* s, int min_size = 100 ); + explicit kiStr( const kiStr& s ); + + // 演算子 + kiStr& operator = ( const kiStr& ); + kiStr& operator = ( const char* s ); + kiStr& operator += ( const char* s ); + kiStr& operator += ( char c ); + bool operator == ( const char* s ) const; + bool isSame( const char* s ) const; + operator const char*() const; + int len() const; + char operator[]( int i ) const + { return m_pBuf[i]; } + void lower() + { ::CharLower(m_pBuf); } + void upper() + { ::CharUpper(m_pBuf); } + kiStr& setInt( int n, bool cm=false ); + + // リソースからロード + kiStr& loadRsrc( UINT id ); + +protected: //-- 派生クラス向け ----------------------------- + + char* m_pBuf; + int m_ALen; + +private: //-- 内部処理 ------------------------------------- + + static char st_lb[256]; + +public: + + virtual ~kiStr(); +}; + +/*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*/ +// kiPath : パス特有の処理用関数付き文字列 + +class kiPath : public kiStr +{ +public: //-- 外向きインターフェイス -------------------------- + + // 初期化 + kiPath() : kiStr( MAX_PATH ){} + explicit kiPath( const char* s ) : kiStr( s, MAX_PATH ){} + explicit kiPath( const kiStr& s ) : kiStr( s, MAX_PATH ){} + explicit kiPath( const kiPath& s ) : kiStr( s, MAX_PATH ){} + kiPath( int nPATH, bool bs = true ) : kiStr( MAX_PATH ) + { + beSpecialPath( nPATH ); + if( nPATH != Exe_name ) + beBackSlash( bs ); + } + + // operator + void operator = ( const char* s ){ kiStr::operator =(s); } + + // 特殊パス取得 + void beSpecialPath( int nPATH ); + enum { Win=0x1787, Sys, Tmp, Prg, Exe, Cur, Exe_name, + Snd=CSIDL_SENDTO, Dsk=CSIDL_DESKTOP, Doc=CSIDL_PERSONAL }; + + // 短いパス + void beShortPath(); + + // 最後のバックスラッシュ制御 + void beBackSlash( bool add ); + + // ディレクトリ名のみ + bool beDirOnly(); + // ファイル名except拡張子のみ + void getBody( kiStr& str ) const; + + // 複数階層mkdir + void mkdir(); + // 複数階層rmdir + void remove(); + + // ドライブタイプ + UINT getDriveType() const; + + // [static] ディレクトリ情報を含まない、ファイル名のみ抽出 + static const char* name( const char* str ); + // [static] 最後の拡張子。無ければNULL + static const char* ext( const char* str ); + // [static] 拡張子全部。無ければNULL + static const char* ext_all( const char* str ); + // [static] body部分抽出。 + static void body( const char* str, char* buf ); + // [static] \ / で終わるか否か + static bool endwithyen( const char* str ); + + // non-static-ver + const char* name() const + { return name(m_pBuf); } + const char* ext() const + { return ext(m_pBuf); } + const char* ext_all() const + { return ext_all(m_pBuf); } +}; + +#endif ADDED kilib/kl_wcmn.cpp Index: kilib/kl_wcmn.cpp ================================================================== --- kilib/kl_wcmn.cpp +++ kilib/kl_wcmn.cpp @@ -0,0 +1,136 @@ +//--- K.I.LIB --- +// kl_wcmn.h : windows-common-interface operatin + +#include "stdafx.h" +#include "kilib.h" + +static int CALLBACK __ki__ofp( HWND w, UINT m, LPARAM l, LPARAM d ) +{ + if( m==BFFM_INITIALIZED && d ) + ::SendMessage( w, BFFM_SETSELECTION, TRUE, d ); + return 0; +} + +bool kiSUtil::getFolderDlg( char* buf, HWND par, const char* title, const char* def ) +{ + // 情報セット + BROWSEINFO bi; + ki_memzero( &bi, sizeof(bi) ); + bi.hwndOwner = par; + bi.pszDisplayName = buf; + bi.lpszTitle = title; + bi.ulFlags = BIF_RETURNONLYFSDIRS | BIF_DONTGOBELOWDOMAIN; + bi.lpfn = __ki__ofp; + bi.lParam = (long)def; + + // ダイアログ表示 + ITEMIDLIST* id = SHBrowseForFolder( &bi ); + if( id==NULL ) + return false; + SHGetPathFromIDList( id, buf ); + app()->shellFree( id ); + + // 終了 + return true; +} + +void kiSUtil::getFolderDlgOfEditBox( HWND wnd, HWND par, const char* title ) +{ + char str[MAX_PATH]; + ::SendMessage( wnd, WM_GETTEXT, MAX_PATH, (LPARAM)str ); + for( char* x=str,*l=str; *x; x=kiStr::next(x) ) + l=x; + if( *l=='\\' || *l=='/' ) + *l='\0'; + if( getFolderDlg( str, par, title, str ) ) + ::SendMessage( wnd, WM_SETTEXT, 0, (LPARAM)str ); +} + +int kiSUtil::getSysIcon( const char* ext ) +{ + SHFILEINFO fi; + ::SHGetFileInfo( + kiPath("test.")+=ext, 0, &fi, sizeof(fi), + SHGFI_USEFILEATTRIBUTES | SHGFI_SYSICONINDEX | SHGFI_ICON | SHGFI_SMALLICON ); + return fi.iIcon; +} + +void kiSUtil::msgLastError() +{ + char* pMsg; + ::FormatMessage( + FORMAT_MESSAGE_ALLOCATE_BUFFER|FORMAT_MESSAGE_FROM_SYSTEM|FORMAT_MESSAGE_IGNORE_INSERTS, + NULL,::GetLastError(),MAKELANGID(LANG_NEUTRAL,SUBLANG_DEFAULT),(LPTSTR)&pMsg,0,NULL ); + app()->msgBox( pMsg ); + ::LocalFree( pMsg ); +} + +void kiSUtil::createShortCut( const kiPath& at, const char* name ) +{ + ::CoInitialize(NULL); + + IShellLink* psl; + if( SUCCEEDED(::CoCreateInstance(CLSID_ShellLink, NULL, CLSCTX_INPROC_SERVER,IID_IShellLink,(void**)&psl)) ) + { + psl->SetPath( kiPath(kiPath::Exe_name) ); + psl->SetWorkingDirectory( kiPath(kiPath::Exe,false) ); + + IPersistFile* ppf; + if( SUCCEEDED(psl->QueryInterface(IID_IPersistFile,(void**)&ppf)) ) + { + WORD wsz[MAX_PATH]; + kiPath lnkfile( at ); + lnkfile += name, lnkfile += ".lnk"; + ::MultiByteToWideChar(CP_ACP,0,lnkfile,-1,wsz,MAX_PATH); + ppf->Save(wsz,TRUE); + ppf->Release(); + } + psl->Release(); + } + ::CoUninitialize(); +} + +bool kiSUtil::exist( const char* fname ) +{ + return 0xffffffff != ::GetFileAttributes( fname ); +} + +bool kiSUtil::isdir( const char* fname ) +{ + DWORD attr = ::GetFileAttributes( fname ); + return attr!=0xffffffff && (attr&FILE_ATTRIBUTE_DIRECTORY); +} + +// 挿入caldixF +// ファイル参照ダイアログ手抜き版 +bool kiSUtil::getOpenFileNameDlg(HWND hwnd,char *rfn) +{ + OPENFILENAME ofn; + + ZeroMemory((LPVOID)&ofn, sizeof(OPENFILENAME)); + ofn.lStructSize = sizeof(OPENFILENAME); + ofn.hwndOwner = hwnd; + ofn.lpstrFilter = "アプリケーション(*.exe)\0*.exe\0全てのファイル(*.*)\0*.*\0\0"; + ofn.lpstrFile = rfn; + ofn.nMaxFile = MAX_PATH; + ofn.Flags = OFN_FILEMUSTEXIST|OFN_HIDEREADONLY|OFN_EXPLORER; + ofn.lpfnHook = NULL; + // なんか持ってれば + if (GetOpenFileName(&ofn)){ + lstrcpy(rfn,ofn.lpstrFile); + return TRUE; + } + + return FALSE; +} + +void kiSUtil::getOpenFileNameDlgOfEditBox(HWND wnd,HWND par) +{ + char str[MAX_PATH]; + + str[0] = '\0'; + ::SendMessage( wnd, WM_GETTEXT, MAX_PATH, (LPARAM)str ); + if( getOpenFileNameDlg(par,str) ) + ::SendMessage( wnd, WM_SETTEXT, 0, (LPARAM)str ); +} +// 挿入ここまでcaldixF ADDED kilib/kl_wcmn.h Index: kilib/kl_wcmn.h ================================================================== --- kilib/kl_wcmn.h +++ kilib/kl_wcmn.h @@ -0,0 +1,37 @@ +//--- K.I.LIB --- +// kl_wcmn.h : windows-common-interface operatin + +#ifndef AFX_KIWINCOMMON_H__0686721C_CAFB_4C2C_9FE5_0F482EA6A60B__INCLUDED_ +#define AFX_KIWINCOMMON_H__0686721C_CAFB_4C2C_9FE5_0F482EA6A60B__INCLUDED_ + +/*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*/ +// シェルユーティリティークラス + +class kiSUtil +{ +public: + // 「フォルダの選択」ダイアログ + static bool getFolderDlg( char* buf, HWND par, const char* title, const char* def ); + static void getFolderDlgOfEditBox( HWND wnd, HWND par, const char* title ); + + // 対応する拡張子用アイコンの、システムイメージリストのインデックスを返す。 + static int getSysIcon( const char* ext ); + + // 最後のエラーを表示 + static void msgLastError(); + + // 自分へのショートカット作成 + static void createShortCut( const kiPath& at, const char* name ); + + // ファイルが存在する? + static bool exist( const char* fname ); + static bool isdir( const char* fname ); + +// 挿入caldixF + // ファイル参照ダイアログ手抜き版 + static bool getOpenFileNameDlg(HWND, char*); + static void getOpenFileNameDlgOfEditBox(HWND, HWND); +// 挿入ここまでcaldixF +}; + +#endif ADDED kilib/kl_wnd.cpp Index: kilib/kl_wnd.cpp ================================================================== --- kilib/kl_wnd.cpp +++ kilib/kl_wnd.cpp @@ -0,0 +1,450 @@ +//--- K.I.LIB --- +// kl_wnd.cpp : window information manager + +#include "stdafx.h" +#include "kilib.h" + + +//-------- Windowを作成時に HWND に kiWindow* をセットするための処理 -------// + + +kiWindow* kiWindow::st_pCurInit = NULL; + HHOOK kiWindow::st_hHook = NULL; + +void kiWindow::init() +{ + // CreateWindow 用フック設置 + st_hHook = ::SetWindowsHookEx( WH_CBT, &CBTProc, NULL, ::GetCurrentThreadId() ); +} + +void kiWindow::finish() +{ + // CreateWindow 用フック解除 + ::UnhookWindowsHookEx( st_hHook ); +} + +LRESULT CALLBACK kiWindow::CBTProc( int code, WPARAM wp, LPARAM lp ) +{ + if( code == HCBT_CREATEWND ) + { + if( st_pCurInit ) + { + // k.i.lib のウインドウが CreateWindow された場合 + st_pCurInit->setHwnd( (HWND)wp ); + ::SetWindowLong( (HWND)wp, GWL_USERDATA, (LONG)st_pCurInit ); + st_pCurInit = NULL; + } + else + ::SetWindowLong( (HWND)wp, GWL_USERDATA, 0 ); + } + + return ::CallNextHookEx( st_hHook, code, wp, lp ); +} + +void kiWindow::detachHwnd() +{ + ::SetWindowLong( hwnd(), GWL_USERDATA, 0 ); + if( this == app()->mainwnd() ) + app()->setMainWnd( NULL ); + setHwnd( NULL ); +} + + +//------------ Window にまつわるエトセトラな処理 (static) ---------------// + + +bool kiWindow::loopbreaker = false; + +void kiWindow::msg() +{ + for( MSG msg; ::PeekMessage( &msg,NULL,0,0,PM_REMOVE ); ) + ::TranslateMessage( &msg ), ::DispatchMessage( &msg ); +} + +void kiWindow::msgLoop( msglooptype type ) +{ + kiWindow* wnd; + MSG msg; + while( !loopbreaker && + type==GET ? ::GetMessage( &msg,NULL,0,0 ) + : ::PeekMessage( &msg,NULL,0,0,PM_REMOVE ) ) + { + if( wnd = app()->mainwnd() ) + { + if( wnd->m_hAccel ) + if( ::TranslateAccelerator( wnd->hwnd(), wnd->m_hAccel, &msg ) ) + continue; + if( wnd->isDlgMsg( &msg ) ) + continue; + } + ::TranslateMessage( &msg ), ::DispatchMessage( &msg ); + } + loopbreaker = false; +} + +void kiWindow::setFront( HWND wnd ) +{ + const OSVERSIONINFO& v = app()->osver(); + + // Win2000 以上 or Win98 以上 + if( ( v.dwPlatformId==VER_PLATFORM_WIN32_NT && v.dwMajorVersion>=5 ) + || ( v.dwPlatformId==VER_PLATFORM_WIN32_WINDOWS && + v.dwMajorVersion*100+v.dwMinorVersion>=410 ) ) + { + DWORD pid; + DWORD th1 = ::GetWindowThreadProcessId( ::GetForegroundWindow(), &pid ); + DWORD th2 = ::GetCurrentThreadId(); + ::AttachThreadInput( th2, th1, TRUE ); + ::SetForegroundWindow( wnd ); + ::AttachThreadInput( th2, th1, FALSE ); + ::BringWindowToTop( wnd ); + } + else // 古いWin + ::SetForegroundWindow( wnd ); + + // Special Thanks To kazubon !! ( the author of TClock ) +} + +void kiWindow::setCenter( HWND wnd, HWND rel ) +{ + RECT rc,pr; + ::GetWindowRect( wnd, &rc ); + + if( rel ) + ::GetWindowRect( rel, &pr ); + else + ::SystemParametersInfo( SPI_GETWORKAREA, 0, &pr, 0 ); + + ::SetWindowPos( wnd, 0, + pr.left + ( (pr.right-pr.left)-(rc.right-rc.left) )/2, + pr.top + ( (pr.bottom-pr.top)-(rc.bottom-rc.top) )/2, + 0, 0, SWP_NOSIZE|SWP_NOZORDER ); +} + + +//------------------ Windowベースクラスとしての処理 ----------------------// + + +kiWindow::kiWindow() +{ + m_hWnd = NULL; + m_hAccel = NULL; + app()->shellInit(); +} + +kiWindow::~kiWindow() +{ + if( m_hWnd && ::IsWindow( m_hWnd ) ) + { + ::SetWindowLong( m_hWnd, GWL_USERDATA, 0 ); + ::DestroyWindow( m_hWnd ); + } +} + +void kiWindow::loadAccel( UINT id ) +{ + m_hAccel = ::LoadAccelerators( app()->inst(), MAKEINTRESOURCE(id) ); +} + + +//---------------- スタンドアロンのWindowの処理 ---------------------// + +// …未完成… + +//---------------------------- Dialog -----------------------------// + + +kiDialog::kiDialog( UINT id ) +{ + m_Rsrc = id; +} + +void kiDialog::doModal( HWND parent ) +{ + setState( true ); + preCreate( this ); + + ::DialogBoxParam( app()->inst(), MAKEINTRESOURCE(m_Rsrc), + parent, commonDlg, (LPARAM)this ); +} + +void kiDialog::createModeless( HWND parent ) +{ + setState( false ); + preCreate( this ); + + ::CreateDialogParam( app()->inst(), MAKEINTRESOURCE(m_Rsrc), + parent, commonDlg, (LPARAM)this ); + + ::ShowWindow( hwnd(), SW_SHOW ); + ::UpdateWindow( hwnd() ); +} + +void kiDialog::end( UINT endcode ) +{ + setEndCode( endcode ); + + if( isModal() ) + ::EndDialog( hwnd(), getEndCode() ); + else + ::DestroyWindow( hwnd() ); +} + +BOOL kiDialog::commonDlg( HWND dlg, UINT msg, WPARAM wp, LPARAM lp ) +{ + // kiDialog インターフェイスへのポインタを取得 + kiDialog* ptr = (kiDialog*)::GetWindowLong( dlg, GWL_USERDATA ); + if( !ptr ) return FALSE; + + // WM_INITDIALOG なら onInit を呼ぶ + if( msg == WM_INITDIALOG ) + return ptr->onInit(); + + // OK / Cancel 処理 + else if( msg == WM_COMMAND ) + { + switch( LOWORD(wp) ) + { + case IDOK: + if( ptr->onOK() ) + ptr->end( IDOK ); + return TRUE; + case IDCANCEL: + if( ptr->onCancel() ) + ptr->end( IDCANCEL ); + return TRUE; + } + } + + // 普通のメッセージ + BOOL ans = ptr->proc( msg, wp, lp ); + + // WM_DESTORY ならウインドウハンドル切り離し + if( msg == WM_DESTROY ) + ptr->detachHwnd(); + + return ans; +} + + +//------------------------ PropertySheet -------------------------// + + +kiPropSheet* kiPropSheet::st_CurInitPS = NULL; + +kiPropSheet::kiPropSheet() : kiDialog( 0 ) +{ + ki_memzero( &m_Header, sizeof(m_Header) ); + m_Header.dwSize = sizeof(m_Header); + m_Header.dwFlags |=PSH_USECALLBACK | PSH_PROPSHEETPAGE; + m_Header.pfnCallback = main_initProc; + m_Header.hInstance = app()->inst(); + m_Header.nStartPage = 0; +} + +void kiPropSheet::begin() +{ + int l = m_Pages.len(); + PROPSHEETPAGE* ppsp = new PROPSHEETPAGE[ l ]; + ki_memzero( ppsp, sizeof(PROPSHEETPAGE)*l ); + + for( int i=0; iinst(); + ppsp[i].pfnCallback = page_initProc; + ppsp[i].pfnDlgProc = page_cmmnProc; + ppsp[i].dwFlags = PSP_USECALLBACK | PSP_HASHELP; + m_Pages[i]->setInfo( ppsp+i ); + } + + m_Header.ppsp = ppsp; + m_Header.nPages = l; + + st_CurInitPS = this; + PropertySheet( &m_Header ); + delete [] ppsp; +} + +void kiPropSheet::doModal( HWND parent ) +{ + m_Header.dwFlags &= (~PSH_MODELESS); + setState( true ); + begin(); +} + +void kiPropSheet::createModeless( HWND parent ) +{ + m_Header.dwFlags |= PSH_MODELESS; + setState( false ); + begin(); +} + +void kiPropSheet::end( UINT endcode ) +{ + // 終了コードセット + setEndCode( endcode ); + + // サブクラス化解除 + ::SetWindowLong( hwnd(), GWL_WNDPROC, (LONG)m_DefProc ); + + // 終了 + if( isModal() ) // サブクラス化解除してるので、再度 end が呼ばれることはないはず。 + ::PostMessage( hwnd(), WM_COMMAND, IDCANCEL, 0 ); + else + ::DestroyWindow( hwnd() ); + + // WM_DESTROY時相当の動作 + detachHwnd(); +} + +LRESULT CALLBACK kiPropSheet::main_cmmnProc( HWND dlg, UINT msg, WPARAM wp, LPARAM lp ) +{ + kiPropSheet* ptr = (kiPropSheet*)::GetWindowLong( dlg, GWL_USERDATA ); + if( !ptr ) + return 0; + + // まずデフォルトの処理 + LRESULT result = ::CallWindowProc( ptr->m_DefProc, dlg, msg, wp, lp ); + + // ×ボタンはキャンセル扱い + if( msg==WM_SYSCOMMAND && wp==SC_CLOSE ) + ::PostMessage( dlg, WM_COMMAND, IDCANCEL, 0 ); + + // コマンド処理 + else if( msg==WM_COMMAND ) + { + switch( LOWORD(wp) ) + { + case IDOK: + if( ptr->onOK() ) + ptr->end( IDOK ); + return TRUE; + case IDCANCEL: + if( ptr->onCancel() ) + ptr->end( IDCANCEL ); + return TRUE; + case IDAPPLY: + ptr->onApply(); + break; + case ID_KIPS_HELP: + ptr->onHelp(); + break; + default: + ptr->onCommand( LOWORD(wp) ); + break; + } + } + + // ドラッグ&ドロップ + else if( msg==WM_DROPFILES ) + ptr->onDrop( (HDROP)wp ); + + return result; +} + +struct DLGTEMPLATEEX +{ + WORD dlgVer; + WORD signature; + DWORD helpID; + DWORD exStyle; + DWORD style; + WORD cDlgItems; + short x; + short y; + short cx; + short cy; +}; + +int CALLBACK kiPropSheet::main_initProc( HWND dlg, UINT msg, LPARAM lp ) +{ + if( msg == PSCB_PRECREATE ) + { + // スタイルを指すDWORDのアドレスを取得 + DWORD* pst = ( 0xffff==((DLGTEMPLATEEX*)lp)->signature ) ? + &(((DLGTEMPLATEEX*)lp)->style) : &(((DLGTEMPLATE*)lp)->style); + // ヘルプボタンを消して最小化ボタンを付ける + (*pst) &= ~DS_CONTEXTHELP; + (*pst) |= WS_MINIMIZEBOX; + + preCreate( st_CurInitPS ); + } + else if( msg == PSCB_INITIALIZED ) + { + // 何故か出来てしまう余計なメニューを削除 + HMENU sysm = ::GetSystemMenu( dlg, FALSE ); + ::DeleteMenu( sysm, SC_SIZE, MF_BYCOMMAND ); + ::DeleteMenu( sysm, SC_MAXIMIZE, MF_BYCOMMAND ); + + // 起動時はウインドウを必ず前面へ + setFront( dlg ); + + //サブクラス化する + st_CurInitPS->m_DefProc = (WNDPROC)::SetWindowLong( dlg, GWL_WNDPROC, (LONG)main_cmmnProc ); + st_CurInitPS->onInit(); + } + return 0; +} + +BOOL kiPropSheet::page_cmmnProc( HWND dlg, UINT msg, WPARAM wp, LPARAM lp ) +{ + kiPropSheetPage* ptr = (kiPropSheetPage*)::GetWindowLong( dlg, GWL_USERDATA ); + if( !ptr ) + return FALSE; + + // ここで、共通処理 + switch( msg ) + { + case WM_INITDIALOG: + return ptr->onInit(); + + case WM_NOTIFY: + switch( ((NMHDR*)lp)->code ) + { + case PSN_APPLY: + ptr->onOK(); + return TRUE; + } + break; + + case WM_COMMAND: + if( lp ) + switch( HIWORD(wp) ) + { + case BN_CLICKED: + if((HWND)lp==::GetFocus()) + case EN_CHANGE: + case CBN_SELCHANGE: + PropSheet_Changed( ptr->parent()->hwnd(), dlg ); + } + break; + + case WM_DESTROY: + BOOL ans=ptr->proc( msg, wp, lp ); + ptr->detachHwnd(); + return ans; + } + + return ptr->proc( msg, wp, lp ); +} + +UINT CALLBACK kiPropSheet::page_initProc( HWND dlg, UINT msg, LPPROPSHEETPAGE ppsp ) +{ + if( msg == PSPCB_CREATE ) + preCreate( (kiWindow*)(ppsp->lParam) ); + return TRUE; +} + +void kiPropSheetPage::setInfo( PROPSHEETPAGE* p ) +{ + p->pszTemplate = MAKEINTRESOURCE( getRsrcID() ); + p->lParam = (LPARAM)this; + + if( m_hIcon ) + { + p->dwFlags|= PSP_USEHICON; + p->hIcon = m_hIcon; + } +} + ADDED kilib/kl_wnd.h Index: kilib/kl_wnd.h ================================================================== --- kilib/kl_wnd.h +++ kilib/kl_wnd.h @@ -0,0 +1,348 @@ +//--- K.I.LIB --- +// kl_wnd.h : window information manager + +#ifndef AFX_KIWINDOW_H__26105B94_1E36_42FA_8916_C2F7FB9EF994__INCLUDED_ +#define AFX_KIWINDOW_H__26105B94_1E36_42FA_8916_C2F7FB9EF994__INCLUDED_ + +/*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*/ +// kiWindow : Windowの簡単な管理 + +class kiWindow +{ +friend void kilib_startUp(); + +private: //-- グローバルな初期化処理など --------------------- + + static void init(); + static void finish(); + +public: //-- 外向きインターフェイス -------------------------- + + // 関連付けられているHWND + HWND hwnd() + { + return m_hWnd; + } + + // そのWindow用にアクセラレータをロード + void loadAccel( UINT id ); + + // ウインドウがまだ残っているかどうかチェック + bool isAlive() + { + if( !m_hWnd ) + return false; + if( ::IsWindow(m_hWnd) ) + return true; + m_hWnd = NULL; + return false; + } + + // 親 + kiWindow* parent() + { + return kiwnd( ::GetParent( hwnd() ) ); + } + + // メッセージ送信 + int sendMsg( UINT msg, WPARAM wp=0, LPARAM lp=0 ) + { + return ::SendMessage( hwnd(), msg, wp, lp ); + } + + // [static] キューにあるメッセージを全て処理 + static void msg(); + + // [static] メッセージループをまわす。 + enum msglooptype {PEEK, GET}; + static void msgLoop( msglooptype type = GET ); + + // [static] Windowを強制的に front へ + static void setFront( HWND wnd ); + + // [static] Windowを中央へ + static void setCenter( HWND wnd, HWND rel=NULL ); + + // [static] HWND -> kiWindow ( もしあれば ) + static kiWindow* kiwnd( HWND wnd ) + { + kiWindow* ptr = (kiWindow*)::GetWindowLong( wnd, GWL_USERDATA ); + if( !ptr ) return NULL; + if( ::IsBadCodePtr((FARPROC)&ptr) ) return NULL; + return ptr; + } + +protected: //-- 派生クラス向け ----------------------------- + + // 派生クラスは、作成直前にコレを呼ぶこと。 + static void preCreate( kiWindow* wnd ) + { st_pCurInit = wnd; } + // 破棄直前にコレを呼ぶこと。 + void detachHwnd(); + // いったんGET/POSTメッセージループを停止 + static void loopbreak() + { + loopbreaker = true; + } + +private: //-- 内部処理 ------------------------------------- + + // ウインドウハンドル設定 + static LRESULT CALLBACK CBTProc( int code, WPARAM wp, LPARAM lp ); + static HHOOK st_hHook; + static kiWindow* st_pCurInit; + void setHwnd( HWND wnd ) + { + m_hWnd = wnd; + } + + // ウインドウ情報保持用変数 + HWND m_hWnd; + HACCEL m_hAccel; + // ダイアログメッセージ + virtual bool isDlgMsg( MSG* msg ) + { return false; } + // GETループ一時抜けだし + static bool loopbreaker; + +protected: + kiWindow(); +public: + virtual ~kiWindow(); +}; + +/*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*/ +// kiDialog : DialogをkiWindowとして管理する + +class kiDialog : public kiWindow +{ +public: //-- 外向きインターフェイス -------------------------- + + // モーダルダイアログとして実行 + virtual void doModal( HWND parent=NULL ); + + // モードレスダイアログとして作成 + virtual void createModeless( HWND parent=NULL ); + + // 終了コード取得 + UINT getEndCode() + { + return m_EndCode; + } + + // モーダルか否か + bool isModal() + { + return m_bStateModal; + } + + // ダイアログアイテム + int sendMsgToItem( UINT id, UINT msg, WPARAM wp=0, LPARAM lp=0 ) + { + return ::SendDlgItemMessage( hwnd(), id, msg, wp, lp ); + } + HWND item( UINT id ) + { + return ::GetDlgItem( hwnd(), id ); + } + +protected: //-- 派生クラス向け ----------------------------- + + // リソースIDで初期化 + kiDialog( UINT id ); + + // リソースID取得 + UINT getRsrcID() + { + return m_Rsrc; + } + + // 終了コードをセット + void setEndCode( UINT endcode ) + { + m_EndCode = endcode; + } + + // モーダルか否かのフラグ"のみ"を切替 + void setState( bool modal ) + { + m_bStateModal = modal; + } + + // 終了コードをセットして、終了する( IDOK を渡しても onOK() は呼ばれないことに注意! ) + virtual void end( UINT endcode ); + + // コマンド・メッセージ発生時に呼ばれる + + // OK -> onOK -> if true end(IDOK) + virtual bool onOK() {return true;} + // 取消 -> onCancel -> if true end(IDCANCEL) + virtual bool onCancel() {return true;} + // WM_INITDIALOG -> onInit + virtual BOOL onInit() {return FALSE;} + // WM_???? -> proc + virtual BOOL CALLBACK proc( UINT msg, WPARAM wp, LPARAM lp ) {return FALSE;} + +private: //-- 内部処理 ------------------------------------- + + UINT m_EndCode; + UINT m_Rsrc; + bool m_bStateModal; + bool isDlgMsg( MSG* msg ) + { + return (FALSE!=::IsDialogMessage( hwnd(), msg )); + } + static BOOL CALLBACK commonDlg( HWND dlg, UINT msg, WPARAM wp, LPARAM lp ); +}; + +/*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*/ +// kiPropSheet : PropertySheetをkiWindowとして管理する。 + +#define IDAPPLY (0x3021) +#define ID_KIPS_HELP (0x0009) + +class kiPropSheetPage : public kiDialog +{ +friend class kiPropSheet; + +protected: //-- 派生クラス向け ---------------------------- + + // ダイアログやアイコンのIDで初期化 + kiPropSheetPage( UINT dlgid ) + : kiDialog( dlgid ), m_hIcon( NULL ) {} + void setIcon( HICON h ) + { m_hIcon = h; } + + // OK/適用 -> page::onOK -> sheet::onOK -> (if ok 終了) + // virtual bool onOK() + // WM_INITDIALOG + // virtual BOOL onInit() + // その他 + // virtual BOOL CALLBACK proc( UINT msg, WPARAM wp, LPARAM lp ) + +private: //-- 内部処理 ------------------------------------- + + void end( UINT endcode ) {} + void setInfo( PROPSHEETPAGE* p ); + HICON m_hIcon; +}; + +class kiPropSheet : public kiDialog +{ +friend class kiPropSheetPage; + +public: //-- 外向きインターフェイス -------------------------- + + // モーダルダイアログとして実行 + void doModal( HWND parent ); + + // モードレスダイアログとして作成 + void createModeless( HWND parent ); + +protected: //-- 派生クラス向け ---------------------------- + + // コンストラクタ辺りで↓これをいじるべし + PROPSHEETHEADER m_Header; + kiArray m_Pages; + + // 終了 + void end( UINT endcode ); + // + void sendOK2All() + { + for( unsigned int i=0;i!=m_Pages.len(); i++ ) + if( m_Pages[i]->isAlive() ) + m_Pages[i]->onOK(); + } + + // OK/適用 -> page::onOK -> sheet::onOK -> (if ok 終了) + // virtual void onOK() + // キャンセル -> sheet::onCancel -> 終了 + // virtual void onCancel() + // PSCB_INITIALIZED + // virtual BOOL onInit() + // 適用 + virtual void onApply() {} + // ヘルプ + virtual void onHelp() {} + // その他コマンド + virtual void onCommand( UINT id ) {} + // ファイルドロップ + virtual void onDrop( HDROP hdrop ) {} + +private: //-- 内部処理 --------------------------------------- + + void begin(); + bool m_bStateModal; + + static kiPropSheet* st_CurInitPS; + WNDPROC m_DefProc; + bool isDlgMsg( MSG* msg ) + { return (FALSE!=PropSheet_IsDialogMessage( hwnd(),msg )); } + static int CALLBACK main_initProc( HWND dlg, UINT msg, LPARAM lp ); + static LRESULT CALLBACK main_cmmnProc( HWND dlg, UINT msg, WPARAM wp, LPARAM lp ); + static BOOL CALLBACK page_cmmnProc( HWND dlg, UINT msg, WPARAM wp, LPARAM lp ); + static UINT CALLBACK page_initProc( HWND dlg, UINT msg, LPPROPSHEETPAGE ppsp ); + +protected: + kiPropSheet(); +public: + ~kiPropSheet() + { for( unsigned int i=0; i!=m_Pages.len(); i++ ) delete m_Pages[i]; } +}; + +/*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*/ +// kiListView : ListViewコントロールの簡単なラッパ + +class kiListView +{ +public: + kiListView( kiDialog* dlg, UINT id ) + { + m_hWnd = ::GetDlgItem( dlg->hwnd(), id ); + } + + void insertColumn( int y, const char* title, + int width=100, int fmt=LVCFMT_LEFT ) + { + LVCOLUMN col; + col.mask = LVCF_TEXT | LVCF_FMT | LVCF_WIDTH; + col.pszText = const_cast(title); + col.cx = width; + col.fmt = fmt; + ::SendMessage( m_hWnd, LVM_INSERTCOLUMN, y, (LPARAM)&col ); + } + + void insertItem( int x, const char* str, LPARAM param=0, int iImage=-1 ) + { + LVITEM item; + item.mask = LVIF_TEXT | LVIF_PARAM | (iImage!=-1 ? LVIF_IMAGE : 0); + item.pszText = const_cast(str); + item.iItem = x; + item.iSubItem = 0; + item.iImage = iImage; + item.lParam = param; + ::SendMessage( m_hWnd, LVM_INSERTITEM, 0, (LPARAM)&item ); + } + + void setSubItem( int x, int y, const char* str ) + { + LVITEM item; + item.mask = LVIF_TEXT; + item.pszText = const_cast(str); + item.iItem = x; + item.iSubItem = y; + ::SendMessage( m_hWnd, LVM_SETITEM, 0, (LPARAM)&item ); + } + + void setImageList( HIMAGELIST Large, HIMAGELIST Small ) + { + ::SendMessage( m_hWnd, LVM_SETIMAGELIST, LVSIL_NORMAL, (LPARAM)Large ); + ::SendMessage( m_hWnd, LVM_SETIMAGELIST, LVSIL_SMALL, (LPARAM)Small ); + } + +private: + HWND m_hWnd; +}; + +#endif ADDED kiutil.cpp Index: kiutil.cpp ================================================================== --- kiutil.cpp +++ kiutil.cpp @@ -0,0 +1,209 @@ + +#include "stdafx.h" +#include "kiutil.h" + +/////////////// + +void kiutil::timeSet( const char* fname, FILETIME* pft ) +{ + HANDLE han = CreateFile( fname, + GENERIC_READ | GENERIC_WRITE, + FILE_SHARE_READ,NULL, + OPEN_EXISTING, + FILE_ATTRIBUTE_NORMAL, + NULL ); + if( han==INVALID_HANDLE_VALUE ) + return; + + SetFileTime( han,pft,NULL,pft ); + + CloseHandle( han ); +} + +void kiutil::timeSet( const char* fname, DWORD sec ) +{ + struct tm* time=gmtime((long*)&sec); + if( time!=NULL ) + { + FILETIME ft; + SYSTEMTIME sys; + + sys.wYear = time->tm_year+1900; + sys.wMonth = time->tm_mon+1; + sys.wDayOfWeek = time->tm_wday; + sys.wDay = time->tm_mday; + sys.wHour = time->tm_hour; + sys.wMinute = time->tm_min; + sys.wSecond = time->tm_sec; + sys.wMilliseconds = 0; + SystemTimeToFileTime(&sys,&ft); + timeSet( fname,&ft ); + } +} + +void kiutil::timeSet( const char* fname,WORD date,WORD time ) +{ + FILETIME ft,lc; + if( DosDateTimeToFileTime( date, time, &lc ) ) + { + if( LocalFileTimeToFileTime( &lc, &ft ) ) + timeSet( fname,&ft ); + } +} + +////////////// + +void kiutil::wndFront( HWND wnd ) +{ + static DWORD Ver = GetVersion(); + + if( ( (Ver&0x80000000) && LOBYTE(LOWORD(Ver))>=4 && HIBYTE(LOWORD(Ver))>=10 ) || + (!(Ver&0x80000000) && LOBYTE(LOWORD(Ver))>=5 )) // 新しいWindows + { + DWORD pid; + DWORD thread1 = GetWindowThreadProcessId( GetForegroundWindow(),&pid ); + DWORD thread2 = GetCurrentThreadId(); + AttachThreadInput( thread2, thread1, TRUE ); + SetForegroundWindow( wnd ); + AttachThreadInput( thread2, thread1, FALSE ); + BringWindowToTop( wnd ); + } + else // 古いWindows + SetForegroundWindow( wnd ); +} + +/////////////// + +char kiutil::lb[256]; + +void kiutil::pathInit() +{ + lb[0] = 0; + for( int c=1; c!=256; c++ ) + lb[c] = (IsDBCSLeadByte(c) ? 2 : 1); +} + +#define isdblb(c) (lb[(unsigned char)(c)]==2) +#define step(p) (p+=lb[(unsigned char)*(p)]) + +char* kiutil::pathMake( char* path ) +{ + char* st = path; + + while( *st=='/' || *st=='\\' || *st=='?' ) + st++; + if( st[0]!='\0' && st[1]==':' ) + st+=2; + while( *st=='/' || *st=='\\' || *st=='?' ) + st++; + + for( unsigned char *p=(unsigned char*)st; *p!='\0'; step(p) ) + { + if( isdblb(*p) ) + continue; + + if( *p=='\\' || *p=='/' ) + { + *p='\0'; + CreateDirectory( st, NULL ); + *p='\\'; + } + else if( *p<' ' || ( *p>'~' && !( 0xa0<=*p && *p<=0xdf ) ) || strchr(":*?\"<>|",*p) ) + *p = '_'; + } + + return st; +} + +void kiutil::pathMakeAbs( char* path ) +{ + int i=0; + for( char* p=path; *p!='\0'; step(p) ) + { + if( i++ < 4 ) // 最初の4文字以内の \ はドライブを表す、ということにしておく。 + continue; + + if( *p=='\\' ) + { + *p='\0'; + CreateDirectory( path, NULL ); + *p='\\'; + } + } +} + +void kiutil::pathSplit( const char* path, int* y, int* d ) +{ + *y=-1, *d=-1; + for( const char* x=path; *x!='\0'; step(x) ) + { + if( *x=='\\' || *x=='/' ) *y=x-path,*d=-1; + else if( *x=='.' ) *d=x-path; + } +} + +const char* kiutil::pathExt( const char* path ) +{ + int y,d; + kiutil::pathSplit( path,&y,&d ); + return (d!=-1) ? path+d+1 : path+strlen(path); +} + +const char* kiutil::pathName( const char* path ) +{ + int y,d; + kiutil::pathSplit( path,&y,&d ); + return path+y+1; +} + +#undef step +#undef isdblb + +////////////// + +char* kiutil::getline( char* str, int size, FILE* fp ) +{ + if( size>0 ) + { + char* p=str; + + while( --size ) + { + int c = fgetc(fp); + + if( c<=0 ) // EOF || '\0' + break; + else if( c=='\n' ) + break; + else if( c=='\r' ) + { + c = fgetc(fp); + if( c!=EOF && c!='\n' ) + ungetc( c,fp ); + break; + } + else + *(p++) = c; + } + + *p='\0'; + } + + return feof(fp) ? NULL : str; +} + +void kiutil::getOriginalName( char* nw, const char* od, char* ext ) +{ + int y,d; + kiutil::pathSplit( od,&y,&d ); + strcpy( nw,od+y+1 ); + + if( ext ) + { + strcat( nw,"." ); + strcat( nw,ext ); + } + else + nw[d-y-1]='\0'; +} + ADDED kiutil.h Index: kiutil.h ================================================================== --- kiutil.h +++ kiutil.h @@ -0,0 +1,65 @@ +#ifndef AFX_KIUTIL_H__D2E1F380_468E_11D3_8D94_ECF8CA9E4339__INCLUDED_ +#define AFX_KIUTIL_H__D2E1F380_468E_11D3_8D94_ECF8CA9E4339__INCLUDED_ + +// ちょっと便利かも知れない関数群「kiutil」 +// +// VC++ のツリーでひとまとめで表示させるためにクラス化 +// しただけで、実は全部 public & static だったりする。(^^; + +class kiutil +{ +public: + +// タイムスタンプ + + // WIN( 0.1 millisec from 1601.1.1 ) + static void timeSet( const char* fname, FILETIME* pft ); + // DOS( 0-4:day 5-8:month 9-15:year+1980, 0-4:sec/2 5-10:min 11-15:hour ) + static void timeSet( const char* fname, WORD date, WORD time ); + // UNIX( sec from 1970.1.1 ) + static void timeSet( const char* fname, DWORD sec ); + +// パス文字列 + + // ↓最初に必ずコレを呼んでおくこと! + static void pathInit(); + + // 相対パスを与えると [不正文字除去],[複数階層makeDir] を行う + static char* pathMake( char* path ); + // 絶対パスを与えると [複数階層makeDir] + static void pathMakeAbs( char* path ); + // yに最後の\, dに最後の. の位置を入れる + static void pathSplit( const char* path, int* y, int* d ); + // 拡張子 + static const char* pathExt( const char* path ); + // ファイル名 + static const char* pathName( const char* path ); + +// window + + // 強制的に前面へ。( kazubon氏の TClock のソースより。感謝! ) + static void wndFront( HWND wnd ); + +// その他 + + // fgets改訂版(CR/LF/CRLFを改行と認定。改行コードは含めない文字列を返す) + static char* getline( char* str, int size, FILE* fp ); + // 拡張子変換 + static void getOriginalName( char* nw, const char* od, char* ext ); + // 安全なところに移ってからLoadLibrary + static HMODULE safepathLoadLibrary(LPCTSTR lpFileName) + { + kiPath original_cur(kiPath::Cur), sys(kiPath::Sys); + ::SetCurrentDirectory(sys); + HMODULE han = ::LoadLibrary(lpFileName); + ::SetCurrentDirectory(original_cur); + return han; + } + +// 変数 + +private: + static char lb[256]; +}; + +#endif ADDED manifest.xml Index: manifest.xml ================================================================== --- manifest.xml +++ manifest.xml @@ -0,0 +1,8 @@ + + + + DnD Melter/Freezer + + + + ADDED resource.h Index: resource.h ================================================================== --- resource.h +++ resource.h @@ -0,0 +1,81 @@ +//{{NO_DEPENDENCIES}} +// Microsoft Developer Studio generated include file. +// Used by Caldix.rc +// +#define IDS_NOINTERNET 2 +#define IDS_LV_DLLNAME 3 +#define IDS_LV_STATE 5 +#define IDS_NONEED 6 +#define IDS_FINISHED 7 +#define IDS_NEWINST 9 +#define IDS_UPDINST 10 +#define IDS_DOWNLOADING 11 +#define IDS_REBOOT 12 +#define IDS_CANCELOK 13 +#define IDS_RASHANGUP 14 +#define IDS_REST 15 +#define IDS_DLERROR 16 +#define IDD_START 106 +#define IDD_VERCHECK 108 +#define IDD_CUSTOM1 109 +#define IDD_CUSTOM2 110 +#define IDI_MAIN 111 +#define IDD_INSTALL 112 +#define IDD_PROXY 113 +#define IDD_DETAIL 114 +#define IDC_WORKTYPE1 1011 +#define IDC_WORKTYPE2 1012 +#define IDC_BAR 1012 +#define IDC_DLLDIR 1013 +#define IDC_CONNECTTO1 1014 +#define IDC_CONNECTTO2 1015 +#define IDC_CONNECTTO3 1016 +#define IDC_REF 1017 +#define IDC_UPDATELIST 1018 +#define IDC_MSG 1024 +#define IDC_RESTTIME 1025 +#define IDC_INSTMODE1 1026 +#define IDC_INSTMODE2 1027 +#define IDC_INSTMODE3 1028 +#define IDC_USEPROXY 1029 +#define IDC_HOST 1030 +#define IDC_PORT 1031 +#define IDC_HOST_N 1032 +#define IDC_PORT_N 1033 +#define IDC_ASKHANG 1034 +#define IDC_DETAIL 1035 +#define IDC_PROXY 1036 +#define IDC_CONNECT_ALWAYS 1037 +#define IDC_SAVE_DESTDIR 1038 +#define IDC_DLHA 1039 +#define IDC_DUZP 1040 +#define IDC_DZIP 1041 +#define IDC_DCAB 1042 +#define IDC_DTAR 1043 +#define IDC_DRAR 1044 +#define IDC_DGCA 1045 +#define IDC_DARJ 1046 +#define IDC_DYZ1 1047 +#define IDC_DBGA 1048 +#define IDC_DJCK 1049 +#define IDC_DAIS 1050 +#define IDC_DISH 1051 +#define IDC_DBEL 1052 +#define IDC_D7ZP 1053 +#define IDC_DIMP 1054 +#define IDC_DBH 1055 +#define IDC_FILERPATH 1056 +#define IDC_FILEROPT 1057 +#define IDC_FILEROPT2 1058 +#define IDC_SHOW_README 1059 + +// Next default values for new objects +// +#ifdef APSTUDIO_INVOKED +#ifndef APSTUDIO_READONLY_SYMBOLS +#define _APS_NEXT_RESOURCE_VALUE 114 +#define _APS_NEXT_COMMAND_VALUE 40001 +#define _APS_NEXT_CONTROL_VALUE 1060 +#define _APS_NEXT_SYMED_VALUE 101 +#endif +#endif ADDED zlib/README Index: zlib/README ================================================================== --- zlib/README +++ zlib/README @@ -0,0 +1,148 @@ +zlib 1.1.3 is a general purpose data compression library. All the code +is thread safe. The data format used by the zlib library +is described by RFCs (Request for Comments) 1950 to 1952 in the files +ftp://ds.internic.net/rfc/rfc1950.txt (zlib format), rfc1951.txt (deflate +format) and rfc1952.txt (gzip format). These documents are also available in +other formats from ftp://ftp.uu.net/graphics/png/documents/zlib/zdoc-index.html + +All functions of the compression library are documented in the file zlib.h +(volunteer to write man pages welcome, contact jloup@gzip.org). A usage +example of the library is given in the file example.c which also tests that +the library is working correctly. Another example is given in the file +minigzip.c. The compression library itself is composed of all source files +except example.c and minigzip.c. + +To compile all files and run the test program, follow the instructions +given at the top of Makefile. In short "make test; make install" +should work for most machines. For Unix: "configure; make test; make install" +For MSDOS, use one of the special makefiles such as Makefile.msc. +For VMS, use Make_vms.com or descrip.mms. + +Questions about zlib should be sent to , or to +Gilles Vollant for the Windows DLL version. +The zlib home page is http://www.cdrom.com/pub/infozip/zlib/ +The official zlib ftp site is ftp://ftp.cdrom.com/pub/infozip/zlib/ +Before reporting a problem, please check those sites to verify that +you have the latest version of zlib; otherwise get the latest version and +check whether the problem still exists or not. + +Mark Nelson wrote an article about zlib for the Jan. 1997 +issue of Dr. Dobb's Journal; a copy of the article is available in +http://web2.airmail.net/markn/articles/zlibtool/zlibtool.htm + +The changes made in version 1.1.3 are documented in the file ChangeLog. +The main changes since 1.1.2 are: + +- fix "an inflate input buffer bug that shows up on rare but persistent + occasions" (Mark) +- fix gzread and gztell for concatenated .gz files (Didier Le Botlan) +- fix gzseek(..., SEEK_SET) in write mode +- fix crc check after a gzeek (Frank Faubert) +- fix miniunzip when the last entry in a zip file is itself a zip file + (J Lillge) +- add contrib/asm586 and contrib/asm686 (Brian Raiter) + See http://www.muppetlabs.com/~breadbox/software/assembly.html +- add support for Delphi 3 in contrib/delphi (Bob Dellaca) +- add support for C++Builder 3 and Delphi 3 in contrib/delphi2 (Davide Moretti) +- do not exit prematurely in untgz if 0 at start of block (Magnus Holmgren) +- use macro EXTERN instead of extern to support DLL for BeOS (Sander Stoks) +- added a FAQ file + +plus many changes for portability. + +Unsupported third party contributions are provided in directory "contrib". + +A Java implementation of zlib is available in the Java Development Kit 1.1 +http://www.javasoft.com/products/JDK/1.1/docs/api/Package-java.util.zip.html +See the zlib home page http://www.cdrom.com/pub/infozip/zlib/ for details. + +A Perl interface to zlib written by Paul Marquess +is in the CPAN (Comprehensive Perl Archive Network) sites, such as: +ftp://ftp.cis.ufl.edu/pub/perl/CPAN/modules/by-module/Compress/Compress-Zlib* + +A Python interface to zlib written by A.M. Kuchling +is available in Python 1.5 and later versions, see +http://www.python.org/doc/lib/module-zlib.html + +A zlib binding for TCL written by Andreas Kupries +is availlable at http://www.westend.com/~kupries/doc/trf/man/man.html + +An experimental package to read and write files in .zip format, +written on top of zlib by Gilles Vollant , is +available at http://www.winimage.com/zLibDll/unzip.html +and also in the contrib/minizip directory of zlib. + + +Notes for some targets: + +- To build a Windows DLL version, include in a DLL project zlib.def, zlib.rc + and all .c files except example.c and minigzip.c; compile with -DZLIB_DLL + The zlib DLL support was initially done by Alessandro Iacopetti and is + now maintained by Gilles Vollant . Check the zlib DLL + home page at http://www.winimage.com/zLibDll + + From Visual Basic, you can call the DLL functions which do not take + a structure as argument: compress, uncompress and all gz* functions. + See contrib/visual-basic.txt for more information, or get + http://www.tcfb.com/dowseware/cmp-z-it.zip + +- For 64-bit Irix, deflate.c must be compiled without any optimization. + With -O, one libpng test fails. The test works in 32 bit mode (with + the -n32 compiler flag). The compiler bug has been reported to SGI. + +- zlib doesn't work with gcc 2.6.3 on a DEC 3000/300LX under OSF/1 2.1 + it works when compiled with cc. + +- on Digital Unix 4.0D (formely OSF/1) on AlphaServer, the cc option -std1 + is necessary to get gzprintf working correctly. This is done by configure. + +- zlib doesn't work on HP-UX 9.05 with some versions of /bin/cc. It works + with other compilers. Use "make test" to check your compiler. + +- gzdopen is not supported on RISCOS, BEOS and by some Mac compilers. + +- For Turbo C the small model is supported only with reduced performance to + avoid any far allocation; it was tested with -DMAX_WBITS=11 -DMAX_MEM_LEVEL=3 + +- For PalmOs, see http://www.cs.uit.no/~perm/PASTA/pilot/software.html + Per Harald Myrvang + + +Acknowledgments: + + The deflate format used by zlib was defined by Phil Katz. The deflate + and zlib specifications were written by L. Peter Deutsch. Thanks to all the + people who reported problems and suggested various improvements in zlib; + they are too numerous to cite here. + +Copyright notice: + + (C) 1995-1998 Jean-loup Gailly and Mark Adler + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. + + Jean-loup Gailly Mark Adler + jloup@gzip.org madler@alumni.caltech.edu + +If you use the zlib library in a product, we would appreciate *not* +receiving lengthy legal documents to sign. The sources are provided +for free but without warranty of any kind. The library has been +entirely written by Jean-loup Gailly and Mark Adler; it does not +include third-party code. + +If you redistribute modified sources, we would appreciate that you include +in the file ChangeLog history information documenting your changes. ADDED zlib/adler32.c Index: zlib/adler32.c ================================================================== --- zlib/adler32.c +++ zlib/adler32.c @@ -0,0 +1,48 @@ +/* adler32.c -- compute the Adler-32 checksum of a data stream + * Copyright (C) 1995-1998 Mark Adler + * For conditions of distribution and use, see copyright notice in zlib.h + */ + +/* @(#) $Id$ */ + +#include "zlib.h" + +#define BASE 65521L /* largest prime smaller than 65536 */ +#define NMAX 5552 +/* NMAX is the largest n such that 255n(n+1)/2 + (n+1)(BASE-1) <= 2^32-1 */ + +#define DO1(buf,i) {s1 += buf[i]; s2 += s1;} +#define DO2(buf,i) DO1(buf,i); DO1(buf,i+1); +#define DO4(buf,i) DO2(buf,i); DO2(buf,i+2); +#define DO8(buf,i) DO4(buf,i); DO4(buf,i+4); +#define DO16(buf) DO8(buf,0); DO8(buf,8); + +/* ========================================================================= */ +uLong ZEXPORT adler32(adler, buf, len) + uLong adler; + const Bytef *buf; + uInt len; +{ + unsigned long s1 = adler & 0xffff; + unsigned long s2 = (adler >> 16) & 0xffff; + int k; + + if (buf == Z_NULL) return 1L; + + while (len > 0) { + k = len < NMAX ? len : NMAX; + len -= k; + while (k >= 16) { + DO16(buf); + buf += 16; + k -= 16; + } + if (k != 0) do { + s1 += *buf++; + s2 += s1; + } while (--k); + s1 %= BASE; + s2 %= BASE; + } + return (s2 << 16) | s1; +} ADDED zlib/compress.c Index: zlib/compress.c ================================================================== --- zlib/compress.c +++ zlib/compress.c @@ -0,0 +1,71 @@ +/* compress.c -- compress a memory buffer + * Copyright (C) 1995-1998 Jean-loup Gailly. + * For conditions of distribution and use, see copyright notice in zlib.h + */ + +/* @(#) $Id$ */ + +#include "zlib.h" +#ifndef KI_GZ_NO_COMPRESSION + +/* =========================================================================== + Compresses the source buffer into the destination buffer. The level + parameter has the same meaning as in deflateInit. sourceLen is the byte + length of the source buffer. Upon entry, destLen is the total size of the + destination buffer, which must be at least 0.1% larger than sourceLen plus + 12 bytes. Upon exit, destLen is the actual size of the compressed buffer. + + compress2 returns Z_OK if success, Z_MEM_ERROR if there was not enough + memory, Z_BUF_ERROR if there was not enough room in the output buffer, + Z_STREAM_ERROR if the level parameter is invalid. +*/ +int ZEXPORT compress2 (dest, destLen, source, sourceLen, level) + Bytef *dest; + uLongf *destLen; + const Bytef *source; + uLong sourceLen; + int level; +{ + z_stream stream; + int err; + + stream.next_in = (Bytef*)source; + stream.avail_in = (uInt)sourceLen; +#ifdef MAXSEG_64K + /* Check for source > 64K on 16-bit machine: */ + if ((uLong)stream.avail_in != sourceLen) return Z_BUF_ERROR; +#endif + stream.next_out = dest; + stream.avail_out = (uInt)*destLen; + if ((uLong)stream.avail_out != *destLen) return Z_BUF_ERROR; + + stream.zalloc = (alloc_func)0; + stream.zfree = (free_func)0; + stream.opaque = (voidpf)0; + + err = deflateInit(&stream, level); + if (err != Z_OK) return err; + + err = deflate(&stream, Z_FINISH); + if (err != Z_STREAM_END) { + deflateEnd(&stream); + return err == Z_OK ? Z_BUF_ERROR : err; + } + *destLen = stream.total_out; + + err = deflateEnd(&stream); + return err; +} + +/* =========================================================================== + */ +int ZEXPORT compress (dest, destLen, source, sourceLen) + Bytef *dest; + uLongf *destLen; + const Bytef *source; + uLong sourceLen; +{ + return compress2(dest, destLen, source, sourceLen, Z_DEFAULT_COMPRESSION); +} + +#endif /* KI_GZ_NO_COMPRESSION */ ADDED zlib/crc32.c Index: zlib/crc32.c ================================================================== --- zlib/crc32.c +++ zlib/crc32.c @@ -0,0 +1,162 @@ +/* crc32.c -- compute the CRC-32 of a data stream + * Copyright (C) 1995-1998 Mark Adler + * For conditions of distribution and use, see copyright notice in zlib.h + */ + +/* @(#) $Id$ */ + +#include "zlib.h" + +#define local static + +#ifdef DYNAMIC_CRC_TABLE + +local int crc_table_empty = 1; +local uLongf crc_table[256]; +local void make_crc_table OF((void)); + +/* + Generate a table for a byte-wise 32-bit CRC calculation on the polynomial: + x^32+x^26+x^23+x^22+x^16+x^12+x^11+x^10+x^8+x^7+x^5+x^4+x^2+x+1. + + Polynomials over GF(2) are represented in binary, one bit per coefficient, + with the lowest powers in the most significant bit. Then adding polynomials + is just exclusive-or, and multiplying a polynomial by x is a right shift by + one. If we call the above polynomial p, and represent a byte as the + polynomial q, also with the lowest power in the most significant bit (so the + byte 0xb1 is the polynomial x^7+x^3+x+1), then the CRC is (q*x^32) mod p, + where a mod b means the remainder after dividing a by b. + + This calculation is done using the shift-register method of multiplying and + taking the remainder. The register is initialized to zero, and for each + incoming bit, x^32 is added mod p to the register if the bit is a one (where + x^32 mod p is p+x^32 = x^26+...+1), and the register is multiplied mod p by + x (which is shifting right by one and adding x^32 mod p if the bit shifted + out is a one). We start with the highest power (least significant bit) of + q and repeat for all eight bits of q. + + The table is simply the CRC of all possible eight bit values. This is all + the information needed to generate CRC's on data a byte at a time for all + combinations of CRC register values and incoming bytes. +*/ +local void make_crc_table() +{ + uLong c; + int n, k; + uLong poly; /* polynomial exclusive-or pattern */ + /* terms of polynomial defining this crc (except x^32): */ + static const Byte p[] = {0,1,2,4,5,7,8,10,11,12,16,22,23,26}; + + /* make exclusive-or pattern from polynomial (0xedb88320L) */ + poly = 0L; + for (n = 0; n < sizeof(p)/sizeof(Byte); n++) + poly |= 1L << (31 - p[n]); + + for (n = 0; n < 256; n++) + { + c = (uLong)n; + for (k = 0; k < 8; k++) + c = c & 1 ? poly ^ (c >> 1) : c >> 1; + crc_table[n] = c; + } + crc_table_empty = 0; +} +#else +/* ======================================================================== + * Table of CRC-32's of all single-byte values (made by make_crc_table) + */ +local const uLongf crc_table[256] = { + 0x00000000L, 0x77073096L, 0xee0e612cL, 0x990951baL, 0x076dc419L, + 0x706af48fL, 0xe963a535L, 0x9e6495a3L, 0x0edb8832L, 0x79dcb8a4L, + 0xe0d5e91eL, 0x97d2d988L, 0x09b64c2bL, 0x7eb17cbdL, 0xe7b82d07L, + 0x90bf1d91L, 0x1db71064L, 0x6ab020f2L, 0xf3b97148L, 0x84be41deL, + 0x1adad47dL, 0x6ddde4ebL, 0xf4d4b551L, 0x83d385c7L, 0x136c9856L, + 0x646ba8c0L, 0xfd62f97aL, 0x8a65c9ecL, 0x14015c4fL, 0x63066cd9L, + 0xfa0f3d63L, 0x8d080df5L, 0x3b6e20c8L, 0x4c69105eL, 0xd56041e4L, + 0xa2677172L, 0x3c03e4d1L, 0x4b04d447L, 0xd20d85fdL, 0xa50ab56bL, + 0x35b5a8faL, 0x42b2986cL, 0xdbbbc9d6L, 0xacbcf940L, 0x32d86ce3L, + 0x45df5c75L, 0xdcd60dcfL, 0xabd13d59L, 0x26d930acL, 0x51de003aL, + 0xc8d75180L, 0xbfd06116L, 0x21b4f4b5L, 0x56b3c423L, 0xcfba9599L, + 0xb8bda50fL, 0x2802b89eL, 0x5f058808L, 0xc60cd9b2L, 0xb10be924L, + 0x2f6f7c87L, 0x58684c11L, 0xc1611dabL, 0xb6662d3dL, 0x76dc4190L, + 0x01db7106L, 0x98d220bcL, 0xefd5102aL, 0x71b18589L, 0x06b6b51fL, + 0x9fbfe4a5L, 0xe8b8d433L, 0x7807c9a2L, 0x0f00f934L, 0x9609a88eL, + 0xe10e9818L, 0x7f6a0dbbL, 0x086d3d2dL, 0x91646c97L, 0xe6635c01L, + 0x6b6b51f4L, 0x1c6c6162L, 0x856530d8L, 0xf262004eL, 0x6c0695edL, + 0x1b01a57bL, 0x8208f4c1L, 0xf50fc457L, 0x65b0d9c6L, 0x12b7e950L, + 0x8bbeb8eaL, 0xfcb9887cL, 0x62dd1ddfL, 0x15da2d49L, 0x8cd37cf3L, + 0xfbd44c65L, 0x4db26158L, 0x3ab551ceL, 0xa3bc0074L, 0xd4bb30e2L, + 0x4adfa541L, 0x3dd895d7L, 0xa4d1c46dL, 0xd3d6f4fbL, 0x4369e96aL, + 0x346ed9fcL, 0xad678846L, 0xda60b8d0L, 0x44042d73L, 0x33031de5L, + 0xaa0a4c5fL, 0xdd0d7cc9L, 0x5005713cL, 0x270241aaL, 0xbe0b1010L, + 0xc90c2086L, 0x5768b525L, 0x206f85b3L, 0xb966d409L, 0xce61e49fL, + 0x5edef90eL, 0x29d9c998L, 0xb0d09822L, 0xc7d7a8b4L, 0x59b33d17L, + 0x2eb40d81L, 0xb7bd5c3bL, 0xc0ba6cadL, 0xedb88320L, 0x9abfb3b6L, + 0x03b6e20cL, 0x74b1d29aL, 0xead54739L, 0x9dd277afL, 0x04db2615L, + 0x73dc1683L, 0xe3630b12L, 0x94643b84L, 0x0d6d6a3eL, 0x7a6a5aa8L, + 0xe40ecf0bL, 0x9309ff9dL, 0x0a00ae27L, 0x7d079eb1L, 0xf00f9344L, + 0x8708a3d2L, 0x1e01f268L, 0x6906c2feL, 0xf762575dL, 0x806567cbL, + 0x196c3671L, 0x6e6b06e7L, 0xfed41b76L, 0x89d32be0L, 0x10da7a5aL, + 0x67dd4accL, 0xf9b9df6fL, 0x8ebeeff9L, 0x17b7be43L, 0x60b08ed5L, + 0xd6d6a3e8L, 0xa1d1937eL, 0x38d8c2c4L, 0x4fdff252L, 0xd1bb67f1L, + 0xa6bc5767L, 0x3fb506ddL, 0x48b2364bL, 0xd80d2bdaL, 0xaf0a1b4cL, + 0x36034af6L, 0x41047a60L, 0xdf60efc3L, 0xa867df55L, 0x316e8eefL, + 0x4669be79L, 0xcb61b38cL, 0xbc66831aL, 0x256fd2a0L, 0x5268e236L, + 0xcc0c7795L, 0xbb0b4703L, 0x220216b9L, 0x5505262fL, 0xc5ba3bbeL, + 0xb2bd0b28L, 0x2bb45a92L, 0x5cb36a04L, 0xc2d7ffa7L, 0xb5d0cf31L, + 0x2cd99e8bL, 0x5bdeae1dL, 0x9b64c2b0L, 0xec63f226L, 0x756aa39cL, + 0x026d930aL, 0x9c0906a9L, 0xeb0e363fL, 0x72076785L, 0x05005713L, + 0x95bf4a82L, 0xe2b87a14L, 0x7bb12baeL, 0x0cb61b38L, 0x92d28e9bL, + 0xe5d5be0dL, 0x7cdcefb7L, 0x0bdbdf21L, 0x86d3d2d4L, 0xf1d4e242L, + 0x68ddb3f8L, 0x1fda836eL, 0x81be16cdL, 0xf6b9265bL, 0x6fb077e1L, + 0x18b74777L, 0x88085ae6L, 0xff0f6a70L, 0x66063bcaL, 0x11010b5cL, + 0x8f659effL, 0xf862ae69L, 0x616bffd3L, 0x166ccf45L, 0xa00ae278L, + 0xd70dd2eeL, 0x4e048354L, 0x3903b3c2L, 0xa7672661L, 0xd06016f7L, + 0x4969474dL, 0x3e6e77dbL, 0xaed16a4aL, 0xd9d65adcL, 0x40df0b66L, + 0x37d83bf0L, 0xa9bcae53L, 0xdebb9ec5L, 0x47b2cf7fL, 0x30b5ffe9L, + 0xbdbdf21cL, 0xcabac28aL, 0x53b39330L, 0x24b4a3a6L, 0xbad03605L, + 0xcdd70693L, 0x54de5729L, 0x23d967bfL, 0xb3667a2eL, 0xc4614ab8L, + 0x5d681b02L, 0x2a6f2b94L, 0xb40bbe37L, 0xc30c8ea1L, 0x5a05df1bL, + 0x2d02ef8dL +}; +#endif + +/* ========================================================================= + * This function can be used by asm versions of crc32() + */ +const uLongf * ZEXPORT get_crc_table() +{ +#ifdef DYNAMIC_CRC_TABLE + if (crc_table_empty) make_crc_table(); +#endif + return (const uLongf *)crc_table; +} + +/* ========================================================================= */ +#define DO1(buf) crc = crc_table[((int)crc ^ (*buf++)) & 0xff] ^ (crc >> 8); +#define DO2(buf) DO1(buf); DO1(buf); +#define DO4(buf) DO2(buf); DO2(buf); +#define DO8(buf) DO4(buf); DO4(buf); + +/* ========================================================================= */ +uLong ZEXPORT crc32(crc, buf, len) + uLong crc; + const Bytef *buf; + uInt len; +{ + if (buf == Z_NULL) return 0L; +#ifdef DYNAMIC_CRC_TABLE + if (crc_table_empty) + make_crc_table(); +#endif + crc = crc ^ 0xffffffffL; + while (len >= 8) + { + DO8(buf); + len -= 8; + } + if (len) do { + DO1(buf); + } while (--len); + return crc ^ 0xffffffffL; +} ADDED zlib/deflate.c Index: zlib/deflate.c ================================================================== --- zlib/deflate.c +++ zlib/deflate.c @@ -0,0 +1,1353 @@ +/* deflate.c -- compress data using the deflation algorithm + * Copyright (C) 1995-1998 Jean-loup Gailly. + * For conditions of distribution and use, see copyright notice in zlib.h + */ + +/* + * ALGORITHM + * + * The "deflation" process depends on being able to identify portions + * of the input text which are identical to earlier input (within a + * sliding window trailing behind the input currently being processed). + * + * The most straightforward technique turns out to be the fastest for + * most input files: try all possible matches and select the longest. + * The key feature of this algorithm is that insertions into the string + * dictionary are very simple and thus fast, and deletions are avoided + * completely. Insertions are performed at each input character, whereas + * string matches are performed only when the previous match ends. So it + * is preferable to spend more time in matches to allow very fast string + * insertions and avoid deletions. The matching algorithm for small + * strings is inspired from that of Rabin & Karp. A brute force approach + * is used to find longer strings when a small match has been found. + * A similar algorithm is used in comic (by Jan-Mark Wams) and freeze + * (by Leonid Broukhis). + * A previous version of this file used a more sophisticated algorithm + * (by Fiala and Greene) which is guaranteed to run in linear amortized + * time, but has a larger average cost, uses more memory and is patented. + * However the F&G algorithm may be faster for some highly redundant + * files if the parameter max_chain_length (described below) is too large. + * + * ACKNOWLEDGEMENTS + * + * The idea of lazy evaluation of matches is due to Jan-Mark Wams, and + * I found it in 'freeze' written by Leonid Broukhis. + * Thanks to many people for bug reports and testing. + * + * REFERENCES + * + * Deutsch, L.P.,"DEFLATE Compressed Data Format Specification". + * Available in ftp://ds.internic.net/rfc/rfc1951.txt + * + * A description of the Rabin and Karp algorithm is given in the book + * "Algorithms" by R. Sedgewick, Addison-Wesley, p252. + * + * Fiala,E.R., and Greene,D.H. + * Data Compression with Finite Windows, Comm.ACM, 32,4 (1989) 490-595 + * + */ + +/* @(#) $Id$ */ + +#include "deflate.h" +#ifndef KI_GZ_NO_COMPRESSION + +const char deflate_copyright[] = + " deflate 1.1.3 Copyright 1995-1998 Jean-loup Gailly "; +/* + If you use the zlib library in a product, an acknowledgment is welcome + in the documentation of your product. If for some reason you cannot + include such an acknowledgment, I would appreciate that you keep this + copyright string in the executable of your product. + */ + +/* =========================================================================== + * Function prototypes. + */ +typedef enum { + need_more, /* block not completed, need more input or more output */ + block_done, /* block flush performed */ + finish_started, /* finish started, need only more output at next deflate */ + finish_done /* finish done, accept no more input or output */ +} block_state; + +typedef block_state (*compress_func) OF((deflate_state *s, int flush)); +/* Compression function. Returns the block state after the call. */ + +local void fill_window OF((deflate_state *s)); +local block_state deflate_stored OF((deflate_state *s, int flush)); +local block_state deflate_fast OF((deflate_state *s, int flush)); +local block_state deflate_slow OF((deflate_state *s, int flush)); +local void lm_init OF((deflate_state *s)); +local void putShortMSB OF((deflate_state *s, uInt b)); +local void flush_pending OF((z_streamp strm)); +local int read_buf OF((z_streamp strm, Bytef *buf, unsigned size)); +#ifdef ASMV + void match_init OF((void)); /* asm code initialization */ + uInt longest_match OF((deflate_state *s, IPos cur_match)); +#else +local uInt longest_match OF((deflate_state *s, IPos cur_match)); +#endif + +#ifdef DEBUG +local void check_match OF((deflate_state *s, IPos start, IPos match, + int length)); +#endif + +/* =========================================================================== + * Local data + */ + +#define NIL 0 +/* Tail of hash chains */ + +#ifndef TOO_FAR +# define TOO_FAR 4096 +#endif +/* Matches of length 3 are discarded if their distance exceeds TOO_FAR */ + +#define MIN_LOOKAHEAD (MAX_MATCH+MIN_MATCH+1) +/* Minimum amount of lookahead, except at the end of the input file. + * See deflate.c for comments about the MIN_MATCH+1. + */ + +/* Values for max_lazy_match, good_match and max_chain_length, depending on + * the desired pack level (0..9). The values given below have been tuned to + * exclude worst case performance for pathological files. Better values may be + * found for specific files. + */ +typedef struct config_s { + ush good_length; /* reduce lazy search above this match length */ + ush max_lazy; /* do not perform lazy search above this match length */ + ush nice_length; /* quit search above this match length */ + ush max_chain; + compress_func func; +} config; + +local const config configuration_table[10] = { +/* good lazy nice chain */ +/* 0 */ {0, 0, 0, 0, deflate_stored}, /* store only */ +/* 1 */ {4, 4, 8, 4, deflate_fast}, /* maximum speed, no lazy matches */ +/* 2 */ {4, 5, 16, 8, deflate_fast}, +/* 3 */ {4, 6, 32, 32, deflate_fast}, + +/* 4 */ {4, 4, 16, 16, deflate_slow}, /* lazy matches */ +/* 5 */ {8, 16, 32, 32, deflate_slow}, +/* 6 */ {8, 16, 128, 128, deflate_slow}, +/* 7 */ {8, 32, 128, 256, deflate_slow}, +/* 8 */ {32, 128, 258, 1024, deflate_slow}, +/* 9 */ {32, 258, 258, 4096, deflate_slow}}; /* maximum compression */ + +/* Note: the deflate() code requires max_lazy >= MIN_MATCH and max_chain >= 4 + * For deflate_fast() (levels <= 3) good is ignored and lazy has a different + * meaning. + */ + +#define EQUAL 0 +/* result of memcmp for equal strings */ + +struct static_tree_desc_s {int dummy;}; /* for buggy compilers */ + +/* =========================================================================== + * Update a hash value with the given input byte + * IN assertion: all calls to to UPDATE_HASH are made with consecutive + * input characters, so that a running hash key can be computed from the + * previous key instead of complete recalculation each time. + */ +#define UPDATE_HASH(s,h,c) (h = (((h)<hash_shift) ^ (c)) & s->hash_mask) + + +/* =========================================================================== + * Insert string str in the dictionary and set match_head to the previous head + * of the hash chain (the most recent string with same hash key). Return + * the previous length of the hash chain. + * If this file is compiled with -DFASTEST, the compression level is forced + * to 1, and no hash chains are maintained. + * IN assertion: all calls to to INSERT_STRING are made with consecutive + * input characters and the first MIN_MATCH bytes of str are valid + * (except for the last MIN_MATCH-1 bytes of the input file). + */ +#ifdef FASTEST +#define INSERT_STRING(s, str, match_head) \ + (UPDATE_HASH(s, s->ins_h, s->window[(str) + (MIN_MATCH-1)]), \ + match_head = s->head[s->ins_h], \ + s->head[s->ins_h] = (Pos)(str)) +#else +#define INSERT_STRING(s, str, match_head) \ + (UPDATE_HASH(s, s->ins_h, s->window[(str) + (MIN_MATCH-1)]), \ + s->prev[(str) & s->w_mask] = match_head = s->head[s->ins_h], \ + s->head[s->ins_h] = (Pos)(str)) +#endif + +/* =========================================================================== + * Initialize the hash table (avoiding 64K overflow for 16 bit systems). + * prev[] will be initialized on the fly. + */ +#define CLEAR_HASH(s) \ + s->head[s->hash_size-1] = NIL; \ + zmemzero((Bytef *)s->head, (unsigned)(s->hash_size-1)*sizeof(*s->head)); + +/* ========================================================================= */ +int ZEXPORT deflateInit_(strm, level, version, stream_size) + z_streamp strm; + int level; + const char *version; + int stream_size; +{ + return deflateInit2_(strm, level, Z_DEFLATED, MAX_WBITS, DEF_MEM_LEVEL, + Z_DEFAULT_STRATEGY, version, stream_size); + /* To do: ignore strm->next_in if we use it as window */ +} + +/* ========================================================================= */ +int ZEXPORT deflateInit2_(strm, level, method, windowBits, memLevel, strategy, + version, stream_size) + z_streamp strm; + int level; + int method; + int windowBits; + int memLevel; + int strategy; + const char *version; + int stream_size; +{ + deflate_state *s; + int noheader = 0; + static const char* my_version = ZLIB_VERSION; + + ushf *overlay; + /* We overlay pending_buf and d_buf+l_buf. This works since the average + * output size for (length,distance) codes is <= 24 bits. + */ + + if (version == Z_NULL || version[0] != my_version[0] || + stream_size != sizeof(z_stream)) { + return Z_VERSION_ERROR; + } + if (strm == Z_NULL) return Z_STREAM_ERROR; + + strm->msg = Z_NULL; + if (strm->zalloc == Z_NULL) { + strm->zalloc = zcalloc; + strm->opaque = (voidpf)0; + } + if (strm->zfree == Z_NULL) strm->zfree = zcfree; + + if (level == Z_DEFAULT_COMPRESSION) level = 6; +#ifdef FASTEST + level = 1; +#endif + + if (windowBits < 0) { /* undocumented feature: suppress zlib header */ + noheader = 1; + windowBits = -windowBits; + } + if (memLevel < 1 || memLevel > MAX_MEM_LEVEL || method != Z_DEFLATED || + windowBits < 8 || windowBits > 15 || level < 0 || level > 9 || + strategy < 0 || strategy > Z_HUFFMAN_ONLY) { + return Z_STREAM_ERROR; + } + s = (deflate_state *) ZALLOC(strm, 1, sizeof(deflate_state)); + if (s == Z_NULL) return Z_MEM_ERROR; + strm->state = (struct internal_state FAR *)s; + s->strm = strm; + + s->noheader = noheader; + s->w_bits = windowBits; + s->w_size = 1 << s->w_bits; + s->w_mask = s->w_size - 1; + + s->hash_bits = memLevel + 7; + s->hash_size = 1 << s->hash_bits; + s->hash_mask = s->hash_size - 1; + s->hash_shift = ((s->hash_bits+MIN_MATCH-1)/MIN_MATCH); + + s->window = (Bytef *) ZALLOC(strm, s->w_size, 2*sizeof(Byte)); + s->prev = (Posf *) ZALLOC(strm, s->w_size, sizeof(Pos)); + s->head = (Posf *) ZALLOC(strm, s->hash_size, sizeof(Pos)); + + s->lit_bufsize = 1 << (memLevel + 6); /* 16K elements by default */ + + overlay = (ushf *) ZALLOC(strm, s->lit_bufsize, sizeof(ush)+2); + s->pending_buf = (uchf *) overlay; + s->pending_buf_size = (ulg)s->lit_bufsize * (sizeof(ush)+2L); + + if (s->window == Z_NULL || s->prev == Z_NULL || s->head == Z_NULL || + s->pending_buf == Z_NULL) { + strm->msg = (char*)ERR_MSG(Z_MEM_ERROR); + deflateEnd (strm); + return Z_MEM_ERROR; + } + s->d_buf = overlay + s->lit_bufsize/sizeof(ush); + s->l_buf = s->pending_buf + (1+sizeof(ush))*s->lit_bufsize; + + s->level = level; + s->strategy = strategy; + s->method = (Byte)method; + + return deflateReset(strm); +} + +/* ========================================================================= */ +int ZEXPORT deflateSetDictionary (strm, dictionary, dictLength) + z_streamp strm; + const Bytef *dictionary; + uInt dictLength; +{ + deflate_state *s; + uInt length = dictLength; + uInt n; + IPos hash_head = 0; + + if (strm == Z_NULL || strm->state == Z_NULL || dictionary == Z_NULL || + strm->state->status != INIT_STATE) return Z_STREAM_ERROR; + + s = strm->state; + strm->adler = adler32(strm->adler, dictionary, dictLength); + + if (length < MIN_MATCH) return Z_OK; + if (length > MAX_DIST(s)) { + length = MAX_DIST(s); +#ifndef USE_DICT_HEAD + dictionary += dictLength - length; /* use the tail of the dictionary */ +#endif + } + zmemcpy(s->window, dictionary, length); + s->strstart = length; + s->block_start = (long)length; + + /* Insert all strings in the hash table (except for the last two bytes). + * s->lookahead stays null, so s->ins_h will be recomputed at the next + * call of fill_window. + */ + s->ins_h = s->window[0]; + UPDATE_HASH(s, s->ins_h, s->window[1]); + for (n = 0; n <= length - MIN_MATCH; n++) { + INSERT_STRING(s, n, hash_head); + } + if (hash_head) hash_head = 0; /* to make compiler happy */ + return Z_OK; +} + +/* ========================================================================= */ +int ZEXPORT deflateReset (strm) + z_streamp strm; +{ + deflate_state *s; + + if (strm == Z_NULL || strm->state == Z_NULL || + strm->zalloc == Z_NULL || strm->zfree == Z_NULL) return Z_STREAM_ERROR; + + strm->total_in = strm->total_out = 0; + strm->msg = Z_NULL; /* use zfree if we ever allocate msg dynamically */ + strm->data_type = Z_UNKNOWN; + + s = (deflate_state *)strm->state; + s->pending = 0; + s->pending_out = s->pending_buf; + + if (s->noheader < 0) { + s->noheader = 0; /* was set to -1 by deflate(..., Z_FINISH); */ + } + s->status = s->noheader ? BUSY_STATE : INIT_STATE; + strm->adler = 1; + s->last_flush = Z_NO_FLUSH; + + _tr_init(s); + lm_init(s); + + return Z_OK; +} + +/* ========================================================================= */ +int ZEXPORT deflateParams(strm, level, strategy) + z_streamp strm; + int level; + int strategy; +{ + deflate_state *s; + compress_func func; + int err = Z_OK; + + if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR; + s = strm->state; + + if (level == Z_DEFAULT_COMPRESSION) { + level = 6; + } + if (level < 0 || level > 9 || strategy < 0 || strategy > Z_HUFFMAN_ONLY) { + return Z_STREAM_ERROR; + } + func = configuration_table[s->level].func; + + if (func != configuration_table[level].func && strm->total_in != 0) { + /* Flush the last buffer: */ + err = deflate(strm, Z_PARTIAL_FLUSH); + } + if (s->level != level) { + s->level = level; + s->max_lazy_match = configuration_table[level].max_lazy; + s->good_match = configuration_table[level].good_length; + s->nice_match = configuration_table[level].nice_length; + s->max_chain_length = configuration_table[level].max_chain; + } + s->strategy = strategy; + return err; +} + +/* ========================================================================= + * Put a short in the pending buffer. The 16-bit value is put in MSB order. + * IN assertion: the stream state is correct and there is enough room in + * pending_buf. + */ +local void putShortMSB (s, b) + deflate_state *s; + uInt b; +{ + put_byte(s, (Byte)(b >> 8)); + put_byte(s, (Byte)(b & 0xff)); +} + +/* ========================================================================= + * Flush as much pending output as possible. All deflate() output goes + * through this function so some applications may wish to modify it + * to avoid allocating a large strm->next_out buffer and copying into it. + * (See also read_buf()). + */ +local void flush_pending(strm) + z_streamp strm; +{ + unsigned len = strm->state->pending; + + if (len > strm->avail_out) len = strm->avail_out; + if (len == 0) return; + + zmemcpy(strm->next_out, strm->state->pending_out, len); + strm->next_out += len; + strm->state->pending_out += len; + strm->total_out += len; + strm->avail_out -= len; + strm->state->pending -= len; + if (strm->state->pending == 0) { + strm->state->pending_out = strm->state->pending_buf; + } +} + +/* ========================================================================= */ +int ZEXPORT deflate (strm, flush) + z_streamp strm; + int flush; +{ + int old_flush; /* value of flush param for previous deflate call */ + deflate_state *s; + + if (strm == Z_NULL || strm->state == Z_NULL || + flush > Z_FINISH || flush < 0) { + return Z_STREAM_ERROR; + } + s = strm->state; + + if (strm->next_out == Z_NULL || + (strm->next_in == Z_NULL && strm->avail_in != 0) || + (s->status == FINISH_STATE && flush != Z_FINISH)) { + ERR_RETURN(strm, Z_STREAM_ERROR); + } + if (strm->avail_out == 0) ERR_RETURN(strm, Z_BUF_ERROR); + + s->strm = strm; /* just in case */ + old_flush = s->last_flush; + s->last_flush = flush; + + /* Write the zlib header */ + if (s->status == INIT_STATE) { + + uInt header = (Z_DEFLATED + ((s->w_bits-8)<<4)) << 8; + uInt level_flags = (s->level-1) >> 1; + + if (level_flags > 3) level_flags = 3; + header |= (level_flags << 6); + if (s->strstart != 0) header |= PRESET_DICT; + header += 31 - (header % 31); + + s->status = BUSY_STATE; + putShortMSB(s, header); + + /* Save the adler32 of the preset dictionary: */ + if (s->strstart != 0) { + putShortMSB(s, (uInt)(strm->adler >> 16)); + putShortMSB(s, (uInt)(strm->adler & 0xffff)); + } + strm->adler = 1L; + } + + /* Flush as much pending output as possible */ + if (s->pending != 0) { + flush_pending(strm); + if (strm->avail_out == 0) { + /* Since avail_out is 0, deflate will be called again with + * more output space, but possibly with both pending and + * avail_in equal to zero. There won't be anything to do, + * but this is not an error situation so make sure we + * return OK instead of BUF_ERROR at next call of deflate: + */ + s->last_flush = -1; + return Z_OK; + } + + /* Make sure there is something to do and avoid duplicate consecutive + * flushes. For repeated and useless calls with Z_FINISH, we keep + * returning Z_STREAM_END instead of Z_BUFF_ERROR. + */ + } else if (strm->avail_in == 0 && flush <= old_flush && + flush != Z_FINISH) { + ERR_RETURN(strm, Z_BUF_ERROR); + } + + /* User must not provide more input after the first FINISH: */ + if (s->status == FINISH_STATE && strm->avail_in != 0) { + ERR_RETURN(strm, Z_BUF_ERROR); + } + + /* Start a new block or continue the current one. + */ + if (strm->avail_in != 0 || s->lookahead != 0 || + (flush != Z_NO_FLUSH && s->status != FINISH_STATE)) { + block_state bstate; + + bstate = (*(configuration_table[s->level].func))(s, flush); + + if (bstate == finish_started || bstate == finish_done) { + s->status = FINISH_STATE; + } + if (bstate == need_more || bstate == finish_started) { + if (strm->avail_out == 0) { + s->last_flush = -1; /* avoid BUF_ERROR next call, see above */ + } + return Z_OK; + /* If flush != Z_NO_FLUSH && avail_out == 0, the next call + * of deflate should use the same flush parameter to make sure + * that the flush is complete. So we don't have to output an + * empty block here, this will be done at next call. This also + * ensures that for a very small output buffer, we emit at most + * one empty block. + */ + } + if (bstate == block_done) { + if (flush == Z_PARTIAL_FLUSH) { + _tr_align(s); + } else { /* FULL_FLUSH or SYNC_FLUSH */ + _tr_stored_block(s, (char*)0, 0L, 0); + /* For a full flush, this empty block will be recognized + * as a special marker by inflate_sync(). + */ + if (flush == Z_FULL_FLUSH) { + CLEAR_HASH(s); /* forget history */ + } + } + flush_pending(strm); + if (strm->avail_out == 0) { + s->last_flush = -1; /* avoid BUF_ERROR at next call, see above */ + return Z_OK; + } + } + } + Assert(strm->avail_out > 0, "bug2"); + + if (flush != Z_FINISH) return Z_OK; + if (s->noheader) return Z_STREAM_END; + + /* Write the zlib trailer (adler32) */ + putShortMSB(s, (uInt)(strm->adler >> 16)); + putShortMSB(s, (uInt)(strm->adler & 0xffff)); + flush_pending(strm); + /* If avail_out is zero, the application will call deflate again + * to flush the rest. + */ + s->noheader = -1; /* write the trailer only once! */ + return s->pending != 0 ? Z_OK : Z_STREAM_END; +} + +/* ========================================================================= */ +int ZEXPORT deflateEnd (strm) + z_streamp strm; +{ + int status; + + if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR; + + status = strm->state->status; + if (status != INIT_STATE && status != BUSY_STATE && + status != FINISH_STATE) { + return Z_STREAM_ERROR; + } + + /* Deallocate in reverse order of allocations: */ + TRY_FREE(strm, strm->state->pending_buf); + TRY_FREE(strm, strm->state->head); + TRY_FREE(strm, strm->state->prev); + TRY_FREE(strm, strm->state->window); + + ZFREE(strm, strm->state); + strm->state = Z_NULL; + + return status == BUSY_STATE ? Z_DATA_ERROR : Z_OK; +} + +/* ========================================================================= + * Copy the source state to the destination state. + * To simplify the source, this is not supported for 16-bit MSDOS (which + * doesn't have enough memory anyway to duplicate compression states). + */ +int ZEXPORT deflateCopy (dest, source) + z_streamp dest; + z_streamp source; +{ +#ifdef MAXSEG_64K + return Z_STREAM_ERROR; +#else + deflate_state *ds; + deflate_state *ss; + ushf *overlay; + + + if (source == Z_NULL || dest == Z_NULL || source->state == Z_NULL) { + return Z_STREAM_ERROR; + } + + ss = source->state; + + *dest = *source; + + ds = (deflate_state *) ZALLOC(dest, 1, sizeof(deflate_state)); + if (ds == Z_NULL) return Z_MEM_ERROR; + dest->state = (struct internal_state FAR *) ds; + *ds = *ss; + ds->strm = dest; + + ds->window = (Bytef *) ZALLOC(dest, ds->w_size, 2*sizeof(Byte)); + ds->prev = (Posf *) ZALLOC(dest, ds->w_size, sizeof(Pos)); + ds->head = (Posf *) ZALLOC(dest, ds->hash_size, sizeof(Pos)); + overlay = (ushf *) ZALLOC(dest, ds->lit_bufsize, sizeof(ush)+2); + ds->pending_buf = (uchf *) overlay; + + if (ds->window == Z_NULL || ds->prev == Z_NULL || ds->head == Z_NULL || + ds->pending_buf == Z_NULL) { + deflateEnd (dest); + return Z_MEM_ERROR; + } + /* following zmemcpy do not work for 16-bit MSDOS */ + zmemcpy(ds->window, ss->window, ds->w_size * 2 * sizeof(Byte)); + zmemcpy(ds->prev, ss->prev, ds->w_size * sizeof(Pos)); + zmemcpy(ds->head, ss->head, ds->hash_size * sizeof(Pos)); + zmemcpy(ds->pending_buf, ss->pending_buf, (uInt)ds->pending_buf_size); + + ds->pending_out = ds->pending_buf + (ss->pending_out - ss->pending_buf); + ds->d_buf = overlay + ds->lit_bufsize/sizeof(ush); + ds->l_buf = ds->pending_buf + (1+sizeof(ush))*ds->lit_bufsize; + + ds->l_desc.dyn_tree = ds->dyn_ltree; + ds->d_desc.dyn_tree = ds->dyn_dtree; + ds->bl_desc.dyn_tree = ds->bl_tree; + + return Z_OK; +#endif +} + +/* =========================================================================== + * Read a new buffer from the current input stream, update the adler32 + * and total number of bytes read. All deflate() input goes through + * this function so some applications may wish to modify it to avoid + * allocating a large strm->next_in buffer and copying from it. + * (See also flush_pending()). + */ +local int read_buf(strm, buf, size) + z_streamp strm; + Bytef *buf; + unsigned size; +{ + unsigned len = strm->avail_in; + + if (len > size) len = size; + if (len == 0) return 0; + + strm->avail_in -= len; + + if (!strm->state->noheader) { + strm->adler = adler32(strm->adler, strm->next_in, len); + } + zmemcpy(buf, strm->next_in, len); + strm->next_in += len; + strm->total_in += len; + + return (int)len; +} + +/* =========================================================================== + * Initialize the "longest match" routines for a new zlib stream + */ +local void lm_init (s) + deflate_state *s; +{ + s->window_size = (ulg)2L*s->w_size; + + CLEAR_HASH(s); + + /* Set the default configuration parameters: + */ + s->max_lazy_match = configuration_table[s->level].max_lazy; + s->good_match = configuration_table[s->level].good_length; + s->nice_match = configuration_table[s->level].nice_length; + s->max_chain_length = configuration_table[s->level].max_chain; + + s->strstart = 0; + s->block_start = 0L; + s->lookahead = 0; + s->match_length = s->prev_length = MIN_MATCH-1; + s->match_available = 0; + s->ins_h = 0; +#ifdef ASMV + match_init(); /* initialize the asm code */ +#endif +} + +/* =========================================================================== + * Set match_start to the longest match starting at the given string and + * return its length. Matches shorter or equal to prev_length are discarded, + * in which case the result is equal to prev_length and match_start is + * garbage. + * IN assertions: cur_match is the head of the hash chain for the current + * string (strstart) and its distance is <= MAX_DIST, and prev_length >= 1 + * OUT assertion: the match length is not greater than s->lookahead. + */ +#ifndef ASMV +/* For 80x86 and 680x0, an optimized version will be provided in match.asm or + * match.S. The code will be functionally equivalent. + */ +#ifndef FASTEST +local uInt longest_match(s, cur_match) + deflate_state *s; + IPos cur_match; /* current match */ +{ + unsigned chain_length = s->max_chain_length;/* max hash chain length */ + register Bytef *scan = s->window + s->strstart; /* current string */ + register Bytef *match; /* matched string */ + register int len; /* length of current match */ + int best_len = s->prev_length; /* best match length so far */ + int nice_match = s->nice_match; /* stop if match long enough */ + IPos limit = s->strstart > (IPos)MAX_DIST(s) ? + s->strstart - (IPos)MAX_DIST(s) : NIL; + /* Stop when cur_match becomes <= limit. To simplify the code, + * we prevent matches with the string of window index 0. + */ + Posf *prev = s->prev; + uInt wmask = s->w_mask; + +#ifdef UNALIGNED_OK + /* Compare two bytes at a time. Note: this is not always beneficial. + * Try with and without -DUNALIGNED_OK to check. + */ + register Bytef *strend = s->window + s->strstart + MAX_MATCH - 1; + register ush scan_start = *(ushf*)scan; + register ush scan_end = *(ushf*)(scan+best_len-1); +#else + register Bytef *strend = s->window + s->strstart + MAX_MATCH; + register Byte scan_end1 = scan[best_len-1]; + register Byte scan_end = scan[best_len]; +#endif + + /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16. + * It is easy to get rid of this optimization if necessary. + */ + Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever"); + + /* Do not waste too much time if we already have a good match: */ + if (s->prev_length >= s->good_match) { + chain_length >>= 2; + } + /* Do not look for matches beyond the end of the input. This is necessary + * to make deflate deterministic. + */ + if ((uInt)nice_match > s->lookahead) nice_match = s->lookahead; + + Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, "need lookahead"); + + do { + Assert(cur_match < s->strstart, "no future"); + match = s->window + cur_match; + + /* Skip to next match if the match length cannot increase + * or if the match length is less than 2: + */ +#if (defined(UNALIGNED_OK) && MAX_MATCH == 258) + /* This code assumes sizeof(unsigned short) == 2. Do not use + * UNALIGNED_OK if your compiler uses a different size. + */ + if (*(ushf*)(match+best_len-1) != scan_end || + *(ushf*)match != scan_start) continue; + + /* It is not necessary to compare scan[2] and match[2] since they are + * always equal when the other bytes match, given that the hash keys + * are equal and that HASH_BITS >= 8. Compare 2 bytes at a time at + * strstart+3, +5, ... up to strstart+257. We check for insufficient + * lookahead only every 4th comparison; the 128th check will be made + * at strstart+257. If MAX_MATCH-2 is not a multiple of 8, it is + * necessary to put more guard bytes at the end of the window, or + * to check more often for insufficient lookahead. + */ + Assert(scan[2] == match[2], "scan[2]?"); + scan++, match++; + do { + } while (*(ushf*)(scan+=2) == *(ushf*)(match+=2) && + *(ushf*)(scan+=2) == *(ushf*)(match+=2) && + *(ushf*)(scan+=2) == *(ushf*)(match+=2) && + *(ushf*)(scan+=2) == *(ushf*)(match+=2) && + scan < strend); + /* The funny "do {}" generates better code on most compilers */ + + /* Here, scan <= window+strstart+257 */ + Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan"); + if (*scan == *match) scan++; + + len = (MAX_MATCH - 1) - (int)(strend-scan); + scan = strend - (MAX_MATCH-1); + +#else /* UNALIGNED_OK */ + + if (match[best_len] != scan_end || + match[best_len-1] != scan_end1 || + *match != *scan || + *++match != scan[1]) continue; + + /* The check at best_len-1 can be removed because it will be made + * again later. (This heuristic is not always a win.) + * It is not necessary to compare scan[2] and match[2] since they + * are always equal when the other bytes match, given that + * the hash keys are equal and that HASH_BITS >= 8. + */ + scan += 2, match++; + Assert(*scan == *match, "match[2]?"); + + /* We check for insufficient lookahead only every 8th comparison; + * the 256th check will be made at strstart+258. + */ + do { + } while (*++scan == *++match && *++scan == *++match && + *++scan == *++match && *++scan == *++match && + *++scan == *++match && *++scan == *++match && + *++scan == *++match && *++scan == *++match && + scan < strend); + + Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan"); + + len = MAX_MATCH - (int)(strend - scan); + scan = strend - MAX_MATCH; + +#endif /* UNALIGNED_OK */ + + if (len > best_len) { + s->match_start = cur_match; + best_len = len; + if (len >= nice_match) break; +#ifdef UNALIGNED_OK + scan_end = *(ushf*)(scan+best_len-1); +#else + scan_end1 = scan[best_len-1]; + scan_end = scan[best_len]; +#endif + } + } while ((cur_match = prev[cur_match & wmask]) > limit + && --chain_length != 0); + + if ((uInt)best_len <= s->lookahead) return (uInt)best_len; + return s->lookahead; +} + +#else /* FASTEST */ +/* --------------------------------------------------------------------------- + * Optimized version for level == 1 only + */ +local uInt longest_match(s, cur_match) + deflate_state *s; + IPos cur_match; /* current match */ +{ + register Bytef *scan = s->window + s->strstart; /* current string */ + register Bytef *match; /* matched string */ + register int len; /* length of current match */ + register Bytef *strend = s->window + s->strstart + MAX_MATCH; + + /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16. + * It is easy to get rid of this optimization if necessary. + */ + Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever"); + + Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, "need lookahead"); + + Assert(cur_match < s->strstart, "no future"); + + match = s->window + cur_match; + + /* Return failure if the match length is less than 2: + */ + if (match[0] != scan[0] || match[1] != scan[1]) return MIN_MATCH-1; + + /* The check at best_len-1 can be removed because it will be made + * again later. (This heuristic is not always a win.) + * It is not necessary to compare scan[2] and match[2] since they + * are always equal when the other bytes match, given that + * the hash keys are equal and that HASH_BITS >= 8. + */ + scan += 2, match += 2; + Assert(*scan == *match, "match[2]?"); + + /* We check for insufficient lookahead only every 8th comparison; + * the 256th check will be made at strstart+258. + */ + do { + } while (*++scan == *++match && *++scan == *++match && + *++scan == *++match && *++scan == *++match && + *++scan == *++match && *++scan == *++match && + *++scan == *++match && *++scan == *++match && + scan < strend); + + Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan"); + + len = MAX_MATCH - (int)(strend - scan); + + if (len < MIN_MATCH) return MIN_MATCH - 1; + + s->match_start = cur_match; + return len <= s->lookahead ? len : s->lookahead; +} +#endif /* FASTEST */ +#endif /* ASMV */ + +#ifdef DEBUG +/* =========================================================================== + * Check that the match at match_start is indeed a match. + */ +local void check_match(s, start, match, length) + deflate_state *s; + IPos start, match; + int length; +{ + /* check that the match is indeed a match */ + if (zmemcmp(s->window + match, + s->window + start, length) != EQUAL) { + fprintf(stderr, " start %u, match %u, length %d\n", + start, match, length); + do { + fprintf(stderr, "%c%c", s->window[match++], s->window[start++]); + } while (--length != 0); + z_error("invalid match"); + } + if (z_verbose > 1) { + fprintf(stderr,"\\[%d,%d]", start-match, length); + do { putc(s->window[start++], stderr); } while (--length != 0); + } +} +#else +# define check_match(s, start, match, length) +#endif + +/* =========================================================================== + * Fill the window when the lookahead becomes insufficient. + * Updates strstart and lookahead. + * + * IN assertion: lookahead < MIN_LOOKAHEAD + * OUT assertions: strstart <= window_size-MIN_LOOKAHEAD + * At least one byte has been read, or avail_in == 0; reads are + * performed for at least two bytes (required for the zip translate_eol + * option -- not supported here). + */ +local void fill_window(s) + deflate_state *s; +{ + register unsigned n, m; + register Posf *p; + unsigned more; /* Amount of free space at the end of the window. */ + uInt wsize = s->w_size; + + do { + more = (unsigned)(s->window_size -(ulg)s->lookahead -(ulg)s->strstart); + + /* Deal with !@#$% 64K limit: */ + if (more == 0 && s->strstart == 0 && s->lookahead == 0) { + more = wsize; + + } else if (more == (unsigned)(-1)) { + /* Very unlikely, but possible on 16 bit machine if strstart == 0 + * and lookahead == 1 (input done one byte at time) + */ + more--; + + /* If the window is almost full and there is insufficient lookahead, + * move the upper half to the lower one to make room in the upper half. + */ + } else if (s->strstart >= wsize+MAX_DIST(s)) { + + zmemcpy(s->window, s->window+wsize, (unsigned)wsize); + s->match_start -= wsize; + s->strstart -= wsize; /* we now have strstart >= MAX_DIST */ + s->block_start -= (long) wsize; + + /* Slide the hash table (could be avoided with 32 bit values + at the expense of memory usage). We slide even when level == 0 + to keep the hash table consistent if we switch back to level > 0 + later. (Using level 0 permanently is not an optimal usage of + zlib, so we don't care about this pathological case.) + */ + n = s->hash_size; + p = &s->head[n]; + do { + m = *--p; + *p = (Pos)(m >= wsize ? m-wsize : NIL); + } while (--n); + + n = wsize; +#ifndef FASTEST + p = &s->prev[n]; + do { + m = *--p; + *p = (Pos)(m >= wsize ? m-wsize : NIL); + /* If n is not on any hash chain, prev[n] is garbage but + * its value will never be used. + */ + } while (--n); +#endif + more += wsize; + } + if (s->strm->avail_in == 0) return; + + /* If there was no sliding: + * strstart <= WSIZE+MAX_DIST-1 && lookahead <= MIN_LOOKAHEAD - 1 && + * more == window_size - lookahead - strstart + * => more >= window_size - (MIN_LOOKAHEAD-1 + WSIZE + MAX_DIST-1) + * => more >= window_size - 2*WSIZE + 2 + * In the BIG_MEM or MMAP case (not yet supported), + * window_size == input_size + MIN_LOOKAHEAD && + * strstart + s->lookahead <= input_size => more >= MIN_LOOKAHEAD. + * Otherwise, window_size == 2*WSIZE so more >= 2. + * If there was sliding, more >= WSIZE. So in all cases, more >= 2. + */ + Assert(more >= 2, "more < 2"); + + n = read_buf(s->strm, s->window + s->strstart + s->lookahead, more); + s->lookahead += n; + + /* Initialize the hash value now that we have some input: */ + if (s->lookahead >= MIN_MATCH) { + s->ins_h = s->window[s->strstart]; + UPDATE_HASH(s, s->ins_h, s->window[s->strstart+1]); +#if MIN_MATCH != 3 + Call UPDATE_HASH() MIN_MATCH-3 more times +#endif + } + /* If the whole input has less than MIN_MATCH bytes, ins_h is garbage, + * but this is not important since only literal bytes will be emitted. + */ + + } while (s->lookahead < MIN_LOOKAHEAD && s->strm->avail_in != 0); +} + +/* =========================================================================== + * Flush the current block, with given end-of-file flag. + * IN assertion: strstart is set to the end of the current match. + */ +#define FLUSH_BLOCK_ONLY(s, eof) { \ + _tr_flush_block(s, (s->block_start >= 0L ? \ + (charf *)&s->window[(unsigned)s->block_start] : \ + (charf *)Z_NULL), \ + (ulg)((long)s->strstart - s->block_start), \ + (eof)); \ + s->block_start = s->strstart; \ + flush_pending(s->strm); \ + Tracev((stderr,"[FLUSH]")); \ +} + +/* Same but force premature exit if necessary. */ +#define FLUSH_BLOCK(s, eof) { \ + FLUSH_BLOCK_ONLY(s, eof); \ + if (s->strm->avail_out == 0) return (eof) ? finish_started : need_more; \ +} + +/* =========================================================================== + * Copy without compression as much as possible from the input stream, return + * the current block state. + * This function does not insert new strings in the dictionary since + * uncompressible data is probably not useful. This function is used + * only for the level=0 compression option. + * NOTE: this function should be optimized to avoid extra copying from + * window to pending_buf. + */ +local block_state deflate_stored(s, flush) + deflate_state *s; + int flush; +{ + /* Stored blocks are limited to 0xffff bytes, pending_buf is limited + * to pending_buf_size, and each stored block has a 5 byte header: + */ + ulg max_block_size = 0xffff; + ulg max_start; + + if (max_block_size > s->pending_buf_size - 5) { + max_block_size = s->pending_buf_size - 5; + } + + /* Copy as much as possible from input to output: */ + for (;;) { + /* Fill the window as much as possible: */ + if (s->lookahead <= 1) { + + Assert(s->strstart < s->w_size+MAX_DIST(s) || + s->block_start >= (long)s->w_size, "slide too late"); + + fill_window(s); + if (s->lookahead == 0 && flush == Z_NO_FLUSH) return need_more; + + if (s->lookahead == 0) break; /* flush the current block */ + } + Assert(s->block_start >= 0L, "block gone"); + + s->strstart += s->lookahead; + s->lookahead = 0; + + /* Emit a stored block if pending_buf will be full: */ + max_start = s->block_start + max_block_size; + if (s->strstart == 0 || (ulg)s->strstart >= max_start) { + /* strstart == 0 is possible when wraparound on 16-bit machine */ + s->lookahead = (uInt)(s->strstart - max_start); + s->strstart = (uInt)max_start; + FLUSH_BLOCK(s, 0); + } + /* Flush if we may have to slide, otherwise block_start may become + * negative and the data will be gone: + */ + if (s->strstart - (uInt)s->block_start >= MAX_DIST(s)) { + FLUSH_BLOCK(s, 0); + } + } + FLUSH_BLOCK(s, flush == Z_FINISH); + return flush == Z_FINISH ? finish_done : block_done; +} + +/* =========================================================================== + * Compress as much as possible from the input stream, return the current + * block state. + * This function does not perform lazy evaluation of matches and inserts + * new strings in the dictionary only for unmatched strings or for short + * matches. It is used only for the fast compression options. + */ +local block_state deflate_fast(s, flush) + deflate_state *s; + int flush; +{ + IPos hash_head = NIL; /* head of the hash chain */ + int bflush; /* set if current block must be flushed */ + + for (;;) { + /* Make sure that we always have enough lookahead, except + * at the end of the input file. We need MAX_MATCH bytes + * for the next match, plus MIN_MATCH bytes to insert the + * string following the next match. + */ + if (s->lookahead < MIN_LOOKAHEAD) { + fill_window(s); + if (s->lookahead < MIN_LOOKAHEAD && flush == Z_NO_FLUSH) { + return need_more; + } + if (s->lookahead == 0) break; /* flush the current block */ + } + + /* Insert the string window[strstart .. strstart+2] in the + * dictionary, and set hash_head to the head of the hash chain: + */ + if (s->lookahead >= MIN_MATCH) { + INSERT_STRING(s, s->strstart, hash_head); + } + + /* Find the longest match, discarding those <= prev_length. + * At this point we have always match_length < MIN_MATCH + */ + if (hash_head != NIL && s->strstart - hash_head <= MAX_DIST(s)) { + /* To simplify the code, we prevent matches with the string + * of window index 0 (in particular we have to avoid a match + * of the string with itself at the start of the input file). + */ + if (s->strategy != Z_HUFFMAN_ONLY) { + s->match_length = longest_match (s, hash_head); + } + /* longest_match() sets match_start */ + } + if (s->match_length >= MIN_MATCH) { + check_match(s, s->strstart, s->match_start, s->match_length); + + _tr_tally_dist(s, s->strstart - s->match_start, + s->match_length - MIN_MATCH, bflush); + + s->lookahead -= s->match_length; + + /* Insert new strings in the hash table only if the match length + * is not too large. This saves time but degrades compression. + */ +#ifndef FASTEST + if (s->match_length <= s->max_insert_length && + s->lookahead >= MIN_MATCH) { + s->match_length--; /* string at strstart already in hash table */ + do { + s->strstart++; + INSERT_STRING(s, s->strstart, hash_head); + /* strstart never exceeds WSIZE-MAX_MATCH, so there are + * always MIN_MATCH bytes ahead. + */ + } while (--s->match_length != 0); + s->strstart++; + } else +#endif + { + s->strstart += s->match_length; + s->match_length = 0; + s->ins_h = s->window[s->strstart]; + UPDATE_HASH(s, s->ins_h, s->window[s->strstart+1]); +#if MIN_MATCH != 3 + Call UPDATE_HASH() MIN_MATCH-3 more times +#endif + /* If lookahead < MIN_MATCH, ins_h is garbage, but it does not + * matter since it will be recomputed at next deflate call. + */ + } + } else { + /* No match, output a literal byte */ + Tracevv((stderr,"%c", s->window[s->strstart])); + _tr_tally_lit (s, s->window[s->strstart], bflush); + s->lookahead--; + s->strstart++; + } + if (bflush) FLUSH_BLOCK(s, 0); + } + FLUSH_BLOCK(s, flush == Z_FINISH); + return flush == Z_FINISH ? finish_done : block_done; +} + +/* =========================================================================== + * Same as above, but achieves better compression. We use a lazy + * evaluation for matches: a match is finally adopted only if there is + * no better match at the next window position. + */ +local block_state deflate_slow(s, flush) + deflate_state *s; + int flush; +{ + IPos hash_head = NIL; /* head of hash chain */ + int bflush; /* set if current block must be flushed */ + + /* Process the input block. */ + for (;;) { + /* Make sure that we always have enough lookahead, except + * at the end of the input file. We need MAX_MATCH bytes + * for the next match, plus MIN_MATCH bytes to insert the + * string following the next match. + */ + if (s->lookahead < MIN_LOOKAHEAD) { + fill_window(s); + if (s->lookahead < MIN_LOOKAHEAD && flush == Z_NO_FLUSH) { + return need_more; + } + if (s->lookahead == 0) break; /* flush the current block */ + } + + /* Insert the string window[strstart .. strstart+2] in the + * dictionary, and set hash_head to the head of the hash chain: + */ + if (s->lookahead >= MIN_MATCH) { + INSERT_STRING(s, s->strstart, hash_head); + } + + /* Find the longest match, discarding those <= prev_length. + */ + s->prev_length = s->match_length, s->prev_match = s->match_start; + s->match_length = MIN_MATCH-1; + + if (hash_head != NIL && s->prev_length < s->max_lazy_match && + s->strstart - hash_head <= MAX_DIST(s)) { + /* To simplify the code, we prevent matches with the string + * of window index 0 (in particular we have to avoid a match + * of the string with itself at the start of the input file). + */ + if (s->strategy != Z_HUFFMAN_ONLY) { + s->match_length = longest_match (s, hash_head); + } + /* longest_match() sets match_start */ + + if (s->match_length <= 5 && (s->strategy == Z_FILTERED || + (s->match_length == MIN_MATCH && + s->strstart - s->match_start > TOO_FAR))) { + + /* If prev_match is also MIN_MATCH, match_start is garbage + * but we will ignore the current match anyway. + */ + s->match_length = MIN_MATCH-1; + } + } + /* If there was a match at the previous step and the current + * match is not better, output the previous match: + */ + if (s->prev_length >= MIN_MATCH && s->match_length <= s->prev_length) { + uInt max_insert = s->strstart + s->lookahead - MIN_MATCH; + /* Do not insert strings in hash table beyond this. */ + + check_match(s, s->strstart-1, s->prev_match, s->prev_length); + + _tr_tally_dist(s, s->strstart -1 - s->prev_match, + s->prev_length - MIN_MATCH, bflush); + + /* Insert in hash table all strings up to the end of the match. + * strstart-1 and strstart are already inserted. If there is not + * enough lookahead, the last two strings are not inserted in + * the hash table. + */ + s->lookahead -= s->prev_length-1; + s->prev_length -= 2; + do { + if (++s->strstart <= max_insert) { + INSERT_STRING(s, s->strstart, hash_head); + } + } while (--s->prev_length != 0); + s->match_available = 0; + s->match_length = MIN_MATCH-1; + s->strstart++; + + if (bflush) FLUSH_BLOCK(s, 0); + + } else if (s->match_available) { + /* If there was no match at the previous position, output a + * single literal. If there was a match but the current match + * is longer, truncate the previous match to a single literal. + */ + Tracevv((stderr,"%c", s->window[s->strstart-1])); + _tr_tally_lit(s, s->window[s->strstart-1], bflush); + if (bflush) { + FLUSH_BLOCK_ONLY(s, 0); + } + s->strstart++; + s->lookahead--; + if (s->strm->avail_out == 0) return need_more; + } else { + /* There is no previous match to compare with, wait for + * the next step to decide. + */ + s->match_available = 1; + s->strstart++; + s->lookahead--; + } + } + Assert (flush != Z_NO_FLUSH, "no flush?"); + if (s->match_available) { + Tracevv((stderr,"%c", s->window[s->strstart-1])); + _tr_tally_lit(s, s->window[s->strstart-1], bflush); + s->match_available = 0; + } + FLUSH_BLOCK(s, flush == Z_FINISH); + return flush == Z_FINISH ? finish_done : block_done; +} + +#endif /* KI_GZ_NO_COMPRESSION */ ADDED zlib/deflate.h Index: zlib/deflate.h ================================================================== --- zlib/deflate.h +++ zlib/deflate.h @@ -0,0 +1,320 @@ +/* deflate.h -- internal compression state + * Copyright (C) 1995-1998 Jean-loup Gailly + * For conditions of distribution and use, see copyright notice in zlib.h + */ + +/* WARNING: this file should *not* be used by applications. It is + part of the implementation of the compression library and is + subject to change. Applications should only use zlib.h. + */ + +/* @(#) $Id$ */ + +#ifndef _DEFLATE_H +#define _DEFLATE_H +#ifndef KI_GZ_NO_COMPRESSION + +#include "zutil.h" + +/* =========================================================================== + * Internal compression state. + */ + +#define LENGTH_CODES 29 +/* number of length codes, not counting the special END_BLOCK code */ + +#define LITERALS 256 +/* number of literal bytes 0..255 */ + +#define L_CODES (LITERALS+1+LENGTH_CODES) +/* number of Literal or Length codes, including the END_BLOCK code */ + +#define D_CODES 30 +/* number of distance codes */ + +#define BL_CODES 19 +/* number of codes used to transfer the bit lengths */ + +#define HEAP_SIZE (2*L_CODES+1) +/* maximum heap size */ + +#define MAX_BITS 15 +/* All codes must not exceed MAX_BITS bits */ + +#define INIT_STATE 42 +#define BUSY_STATE 113 +#define FINISH_STATE 666 +/* Stream status */ + + +/* Data structure describing a single value and its code string. */ +typedef struct ct_data_s { + union { + ush freq; /* frequency count */ + ush code; /* bit string */ + } fc; + union { + ush dad; /* father node in Huffman tree */ + ush len; /* length of bit string */ + } dl; +} FAR ct_data; + +#define Freq fc.freq +#define Code fc.code +#define Dad dl.dad +#define Len dl.len + +typedef struct static_tree_desc_s static_tree_desc; + +typedef struct tree_desc_s { + ct_data *dyn_tree; /* the dynamic tree */ + int max_code; /* largest code with non zero frequency */ + static_tree_desc *stat_desc; /* the corresponding static tree */ +} FAR tree_desc; + +typedef ush Pos; +typedef Pos FAR Posf; +typedef unsigned IPos; + +/* A Pos is an index in the character window. We use short instead of int to + * save space in the various tables. IPos is used only for parameter passing. + */ + +typedef struct internal_state { + z_streamp strm; /* pointer back to this zlib stream */ + int status; /* as the name implies */ + Bytef *pending_buf; /* output still pending */ + ulg pending_buf_size; /* size of pending_buf */ + Bytef *pending_out; /* next pending byte to output to the stream */ + int pending; /* nb of bytes in the pending buffer */ + int noheader; /* suppress zlib header and adler32 */ + Byte data_type; /* UNKNOWN, BINARY or ASCII */ + Byte method; /* STORED (for zip only) or DEFLATED */ + int last_flush; /* value of flush param for previous deflate call */ + + /* used by deflate.c: */ + + uInt w_size; /* LZ77 window size (32K by default) */ + uInt w_bits; /* log2(w_size) (8..16) */ + uInt w_mask; /* w_size - 1 */ + + Bytef *window; + /* Sliding window. Input bytes are read into the second half of the window, + * and move to the first half later to keep a dictionary of at least wSize + * bytes. With this organization, matches are limited to a distance of + * wSize-MAX_MATCH bytes, but this ensures that IO is always + * performed with a length multiple of the block size. Also, it limits + * the window size to 64K, which is quite useful on MSDOS. + * To do: use the user input buffer as sliding window. + */ + + ulg window_size; + /* Actual size of window: 2*wSize, except when the user input buffer + * is directly used as sliding window. + */ + + Posf *prev; + /* Link to older string with same hash index. To limit the size of this + * array to 64K, this link is maintained only for the last 32K strings. + * An index in this array is thus a window index modulo 32K. + */ + + Posf *head; /* Heads of the hash chains or NIL. */ + + uInt ins_h; /* hash index of string to be inserted */ + uInt hash_size; /* number of elements in hash table */ + uInt hash_bits; /* log2(hash_size) */ + uInt hash_mask; /* hash_size-1 */ + + uInt hash_shift; + /* Number of bits by which ins_h must be shifted at each input + * step. It must be such that after MIN_MATCH steps, the oldest + * byte no longer takes part in the hash key, that is: + * hash_shift * MIN_MATCH >= hash_bits + */ + + long block_start; + /* Window position at the beginning of the current output block. Gets + * negative when the window is moved backwards. + */ + + uInt match_length; /* length of best match */ + IPos prev_match; /* previous match */ + int match_available; /* set if previous match exists */ + uInt strstart; /* start of string to insert */ + uInt match_start; /* start of matching string */ + uInt lookahead; /* number of valid bytes ahead in window */ + + uInt prev_length; + /* Length of the best match at previous step. Matches not greater than this + * are discarded. This is used in the lazy match evaluation. + */ + + uInt max_chain_length; + /* To speed up deflation, hash chains are never searched beyond this + * length. A higher limit improves compression ratio but degrades the + * speed. + */ + + uInt max_lazy_match; + /* Attempt to find a better match only when the current match is strictly + * smaller than this value. This mechanism is used only for compression + * levels >= 4. + */ +# define max_insert_length max_lazy_match + /* Insert new strings in the hash table only if the match length is not + * greater than this length. This saves time but degrades compression. + * max_insert_length is used only for compression levels <= 3. + */ + + int level; /* compression level (1..9) */ + int strategy; /* favor or force Huffman coding*/ + + uInt good_match; + /* Use a faster search when the previous match is longer than this */ + + int nice_match; /* Stop searching when current match exceeds this */ + + /* used by trees.c: */ + /* Didn't use ct_data typedef below to supress compiler warning */ + struct ct_data_s dyn_ltree[HEAP_SIZE]; /* literal and length tree */ + struct ct_data_s dyn_dtree[2*D_CODES+1]; /* distance tree */ + struct ct_data_s bl_tree[2*BL_CODES+1]; /* Huffman tree for bit lengths */ + + struct tree_desc_s l_desc; /* desc. for literal tree */ + struct tree_desc_s d_desc; /* desc. for distance tree */ + struct tree_desc_s bl_desc; /* desc. for bit length tree */ + + ush bl_count[MAX_BITS+1]; + /* number of codes at each bit length for an optimal tree */ + + int heap[2*L_CODES+1]; /* heap used to build the Huffman trees */ + int heap_len; /* number of elements in the heap */ + int heap_max; /* element of largest frequency */ + /* The sons of heap[n] are heap[2*n] and heap[2*n+1]. heap[0] is not used. + * The same heap array is used to build all trees. + */ + + uch depth[2*L_CODES+1]; + /* Depth of each subtree used as tie breaker for trees of equal frequency + */ + + uchf *l_buf; /* buffer for literals or lengths */ + + uInt lit_bufsize; + /* Size of match buffer for literals/lengths. There are 4 reasons for + * limiting lit_bufsize to 64K: + * - frequencies can be kept in 16 bit counters + * - if compression is not successful for the first block, all input + * data is still in the window so we can still emit a stored block even + * when input comes from standard input. (This can also be done for + * all blocks if lit_bufsize is not greater than 32K.) + * - if compression is not successful for a file smaller than 64K, we can + * even emit a stored file instead of a stored block (saving 5 bytes). + * This is applicable only for zip (not gzip or zlib). + * - creating new Huffman trees less frequently may not provide fast + * adaptation to changes in the input data statistics. (Take for + * example a binary file with poorly compressible code followed by + * a highly compressible string table.) Smaller buffer sizes give + * fast adaptation but have of course the overhead of transmitting + * trees more frequently. + * - I can't count above 4 + */ + + uInt last_lit; /* running index in l_buf */ + + ushf *d_buf; + /* Buffer for distances. To simplify the code, d_buf and l_buf have + * the same number of elements. To use different lengths, an extra flag + * array would be necessary. + */ + + ulg opt_len; /* bit length of current block with optimal trees */ + ulg static_len; /* bit length of current block with static trees */ + uInt matches; /* number of string matches in current block */ + int last_eob_len; /* bit length of EOB code for last block */ + +#ifdef DEBUG + ulg compressed_len; /* total bit length of compressed file mod 2^32 */ + ulg bits_sent; /* bit length of compressed data sent mod 2^32 */ +#endif + + ush bi_buf; + /* Output buffer. bits are inserted starting at the bottom (least + * significant bits). + */ + int bi_valid; + /* Number of valid bits in bi_buf. All bits above the last valid bit + * are always zero. + */ + +} FAR deflate_state; + +/* Output a byte on the stream. + * IN assertion: there is enough room in pending_buf. + */ +#define put_byte(s, c) {s->pending_buf[s->pending++] = (c);} + + +#define MIN_LOOKAHEAD (MAX_MATCH+MIN_MATCH+1) +/* Minimum amount of lookahead, except at the end of the input file. + * See deflate.c for comments about the MIN_MATCH+1. + */ + +#define MAX_DIST(s) ((s)->w_size-MIN_LOOKAHEAD) +/* In order to simplify the code, particularly on 16 bit machines, match + * distances are limited to MAX_DIST instead of WSIZE. + */ + + /* in trees.c */ +void _tr_init OF((deflate_state *s)); +int _tr_tally OF((deflate_state *s, unsigned dist, unsigned lc)); +void _tr_flush_block OF((deflate_state *s, charf *buf, ulg stored_len, + int eof)); +void _tr_align OF((deflate_state *s)); +void _tr_stored_block OF((deflate_state *s, charf *buf, ulg stored_len, + int eof)); + +#define d_code(dist) \ + ((dist) < 256 ? _dist_code[dist] : _dist_code[256+((dist)>>7)]) +/* Mapping from a distance to a distance code. dist is the distance - 1 and + * must not have side effects. _dist_code[256] and _dist_code[257] are never + * used. + */ + +#ifndef DEBUG +/* Inline versions of _tr_tally for speed: */ + +#if defined(GEN_TREES_H) || !defined(STDC) + extern uch _length_code[]; + extern uch _dist_code[]; +#else + extern const uch _length_code[]; + extern const uch _dist_code[]; +#endif + +# define _tr_tally_lit(s, c, flush) \ + { uch cc = (c); \ + s->d_buf[s->last_lit] = 0; \ + s->l_buf[s->last_lit++] = cc; \ + s->dyn_ltree[cc].Freq++; \ + flush = (s->last_lit == s->lit_bufsize-1); \ + } +# define _tr_tally_dist(s, distance, length, flush) \ + { uch len = (length); \ + ush dist = (distance); \ + s->d_buf[s->last_lit] = dist; \ + s->l_buf[s->last_lit++] = len; \ + dist--; \ + s->dyn_ltree[_length_code[len]+LITERALS+1].Freq++; \ + s->dyn_dtree[d_code(dist)].Freq++; \ + flush = (s->last_lit == s->lit_bufsize-1); \ + } +#else +# define _tr_tally_lit(s, c, flush) flush = _tr_tally(s, 0, c) +# define _tr_tally_dist(s, distance, length, flush) \ + flush = _tr_tally(s, distance, length) +#endif + +#endif /* KI_GZ_NO_COMPRESSION */ +#endif ADDED zlib/gzio.c Index: zlib/gzio.c ================================================================== --- zlib/gzio.c +++ zlib/gzio.c @@ -0,0 +1,881 @@ +/* gzio.c -- IO on .gz files + * Copyright (C) 1995-1998 Jean-loup Gailly. + * For conditions of distribution and use, see copyright notice in zlib.h + * + * Compile this file with -DNO_DEFLATE to avoid the compression code. + */ + +/* @(#) $Id$ */ + +#include + +#include "zutil.h" + +#ifdef KI_GZ_NO_COMPRESSION +#define NO_DEFLATE +#endif /* KI_GZ_NO_COMPRESSION */ + +struct internal_state {int dummy;}; /* for buggy compilers */ + +#ifndef Z_BUFSIZE +# ifdef MAXSEG_64K +# define Z_BUFSIZE 4096 /* minimize memory usage for 16-bit DOS */ +# else +# define Z_BUFSIZE 16384 +# endif +#endif +#ifndef Z_PRINTF_BUFSIZE +# define Z_PRINTF_BUFSIZE 4096 +#endif + +#define ALLOC(size) malloc(size) +#define TRYFREE(p) {if (p) free(p);} + +static int gz_magic[2] = {0x1f, 0x8b}; /* gzip magic header */ + +/* gzip flag byte */ +#define ASCII_FLAG 0x01 /* bit 0 set: file probably ascii text */ +#define HEAD_CRC 0x02 /* bit 1 set: header CRC present */ +#define EXTRA_FIELD 0x04 /* bit 2 set: extra field present */ +#define ORIG_NAME 0x08 /* bit 3 set: original file name present */ +#define COMMENT 0x10 /* bit 4 set: file comment present */ +#define RESERVED 0xE0 /* bits 5..7: reserved */ + +typedef struct gz_stream { + z_stream stream; + int z_err; /* error code for last stream operation */ + int z_eof; /* set if end of input file */ + FILE *file; /* .gz file */ + Byte *inbuf; /* input buffer */ + Byte *outbuf; /* output buffer */ + uLong crc; /* crc32 of uncompressed data */ + char *msg; /* error message */ + char *path; /* path name for debugging only */ + int transparent; /* 1 if input file is not a .gz file */ + char mode; /* 'w' or 'r' */ + long startpos; /* start of compressed data in file (header skipped) */ +} gz_stream; + + +local gzFile gz_open OF((const char *path, const char *mode, int fd)); +local int do_flush OF((gzFile file, int flush)); +local int get_byte OF((gz_stream *s)); +local void check_header OF((gz_stream *s)); +local int destroy OF((gz_stream *s)); +local void putLong OF((FILE *file, uLong x)); +local uLong getLong OF((gz_stream *s)); + +/* =========================================================================== + Opens a gzip (.gz) file for reading or writing. The mode parameter + is as in fopen ("rb" or "wb"). The file is given either by file descriptor + or path name (if fd == -1). + gz_open return NULL if the file could not be opened or if there was + insufficient memory to allocate the (de)compression state; errno + can be checked to distinguish the two cases (if errno is zero, the + zlib error is Z_MEM_ERROR). +*/ +local gzFile gz_open (path, mode, fd) + const char *path; + const char *mode; + int fd; +{ + int err; + int level = Z_DEFAULT_COMPRESSION; /* compression level */ + int strategy = Z_DEFAULT_STRATEGY; /* compression strategy */ + char *p = (char*)mode; + gz_stream *s; + char fmode[80]; /* copy of mode, without the compression level */ + char *m = fmode; + + if (!path || !mode) return Z_NULL; + + s = (gz_stream *)ALLOC(sizeof(gz_stream)); + if (!s) return Z_NULL; + + s->stream.zalloc = (alloc_func)0; + s->stream.zfree = (free_func)0; + s->stream.opaque = (voidpf)0; + s->stream.next_in = s->inbuf = Z_NULL; + s->stream.next_out = s->outbuf = Z_NULL; + s->stream.avail_in = s->stream.avail_out = 0; + s->file = NULL; + s->z_err = Z_OK; + s->z_eof = 0; + s->crc = crc32(0L, Z_NULL, 0); + s->msg = NULL; + s->transparent = 0; + + s->path = (char*)ALLOC(strlen(path)+1); + if (s->path == NULL) { + return destroy(s), (gzFile)Z_NULL; + } + strcpy(s->path, path); /* do this early for debugging */ + + s->mode = '\0'; + do { + if (*p == 'r') s->mode = 'r'; + if (*p == 'w' || *p == 'a') s->mode = 'w'; + if (*p >= '0' && *p <= '9') { + level = *p - '0'; + } else if (*p == 'f') { + strategy = Z_FILTERED; + } else if (*p == 'h') { + strategy = Z_HUFFMAN_ONLY; + } else { + *m++ = *p; /* copy the mode */ + } + } while (*p++ && m != fmode + sizeof(fmode)); + if (s->mode == '\0') return destroy(s), (gzFile)Z_NULL; + + if (s->mode == 'w') { +#ifdef NO_DEFLATE + err = Z_STREAM_ERROR; +#else + err = deflateInit2(&(s->stream), level, + Z_DEFLATED, -MAX_WBITS, DEF_MEM_LEVEL, strategy); + /* windowBits is passed < 0 to suppress zlib header */ + + s->stream.next_out = s->outbuf = (Byte*)ALLOC(Z_BUFSIZE); +#endif + if (err != Z_OK || s->outbuf == Z_NULL) { + return destroy(s), (gzFile)Z_NULL; + } + } else { + s->stream.next_in = s->inbuf = (Byte*)ALLOC(Z_BUFSIZE); + + err = inflateInit2(&(s->stream), -MAX_WBITS); + /* windowBits is passed < 0 to tell that there is no zlib header. + * Note that in this case inflate *requires* an extra "dummy" byte + * after the compressed stream in order to complete decompression and + * return Z_STREAM_END. Here the gzip CRC32 ensures that 4 bytes are + * present after the compressed stream. + */ + if (err != Z_OK || s->inbuf == Z_NULL) { + return destroy(s), (gzFile)Z_NULL; + } + } + s->stream.avail_out = Z_BUFSIZE; + + errno = 0; + s->file = fd < 0 ? F_OPEN(path, fmode) : (FILE*)fdopen(fd, fmode); + + if (s->file == NULL) { + return destroy(s), (gzFile)Z_NULL; + } + if (s->mode == 'w') { + /* Write a very simple .gz header: + */ + fprintf(s->file, "%c%c%c%c%c%c%c%c%c%c", gz_magic[0], gz_magic[1], + Z_DEFLATED, 0 /*flags*/, 0,0,0,0 /*time*/, 0 /*xflags*/, OS_CODE); + s->startpos = 10L; + /* We use 10L instead of ftell(s->file) to because ftell causes an + * fflush on some systems. This version of the library doesn't use + * startpos anyway in write mode, so this initialization is not + * necessary. + */ + } else { + check_header(s); /* skip the .gz header */ + s->startpos = (ftell(s->file) - s->stream.avail_in); + } + + return (gzFile)s; +} + +/* =========================================================================== + Opens a gzip (.gz) file for reading or writing. +*/ +gzFile ZEXPORT gzopen (path, mode) + const char *path; + const char *mode; +{ + return gz_open (path, mode, -1); +} + +/* =========================================================================== + Associate a gzFile with the file descriptor fd. fd is not dup'ed here + to mimic the behavio(u)r of fdopen. +*/ +gzFile ZEXPORT gzdopen (fd, mode) + int fd; + const char *mode; +{ + char name[20]; + + if (fd < 0) return (gzFile)Z_NULL; + sprintf(name, "", fd); /* for debugging */ + + return gz_open (name, mode, fd); +} + +/* =========================================================================== + * Update the compression level and strategy + */ +int ZEXPORT gzsetparams (file, level, strategy) + gzFile file; + int level; + int strategy; +{ +#ifndef KI_GZ_NO_COMPRESSION + gz_stream *s = (gz_stream*)file; + + if (s == NULL || s->mode != 'w') return Z_STREAM_ERROR; + + /* Make room to allow flushing */ + if (s->stream.avail_out == 0) { + + s->stream.next_out = s->outbuf; + if (fwrite(s->outbuf, 1, Z_BUFSIZE, s->file) != Z_BUFSIZE) { + s->z_err = Z_ERRNO; + } + s->stream.avail_out = Z_BUFSIZE; + } + + return deflateParams (&(s->stream), level, strategy); +#else + return Z_STREAM_ERROR; +#endif /* KI_GZ_NO_COMPRESSION */ +} + +/* =========================================================================== + Read a byte from a gz_stream; update next_in and avail_in. Return EOF + for end of file. + IN assertion: the stream s has been sucessfully opened for reading. +*/ +local int get_byte(s) + gz_stream *s; +{ + if (s->z_eof) return EOF; + if (s->stream.avail_in == 0) { + errno = 0; + s->stream.avail_in = fread(s->inbuf, 1, Z_BUFSIZE, s->file); + if (s->stream.avail_in == 0) { + s->z_eof = 1; + if (ferror(s->file)) s->z_err = Z_ERRNO; + return EOF; + } + s->stream.next_in = s->inbuf; + } + s->stream.avail_in--; + return *(s->stream.next_in)++; +} + +/* =========================================================================== + Check the gzip header of a gz_stream opened for reading. Set the stream + mode to transparent if the gzip magic header is not present; set s->err + to Z_DATA_ERROR if the magic header is present but the rest of the header + is incorrect. + IN assertion: the stream s has already been created sucessfully; + s->stream.avail_in is zero for the first time, but may be non-zero + for concatenated .gz files. +*/ +local void check_header(s) + gz_stream *s; +{ + int method; /* method byte */ + int flags; /* flags byte */ + uInt len; + int c; + + /* Check the gzip magic header */ + for (len = 0; len < 2; len++) { + c = get_byte(s); + if (c != gz_magic[len]) { + if (len != 0) s->stream.avail_in++, s->stream.next_in--; + if (c != EOF) { + s->stream.avail_in++, s->stream.next_in--; + s->transparent = 1; + } + s->z_err = s->stream.avail_in != 0 ? Z_OK : Z_STREAM_END; + return; + } + } + method = get_byte(s); + flags = get_byte(s); + if (method != Z_DEFLATED || (flags & RESERVED) != 0) { + s->z_err = Z_DATA_ERROR; + return; + } + + /* Discard time, xflags and OS code: */ + for (len = 0; len < 6; len++) (void)get_byte(s); + + if ((flags & EXTRA_FIELD) != 0) { /* skip the extra field */ + len = (uInt)get_byte(s); + len += ((uInt)get_byte(s))<<8; + /* len is garbage if EOF but the loop below will quit anyway */ + while (len-- != 0 && get_byte(s) != EOF) ; + } + if ((flags & ORIG_NAME) != 0) { /* skip the original file name */ + while ((c = get_byte(s)) != 0 && c != EOF) ; + } + if ((flags & COMMENT) != 0) { /* skip the .gz file comment */ + while ((c = get_byte(s)) != 0 && c != EOF) ; + } + if ((flags & HEAD_CRC) != 0) { /* skip the header crc */ + for (len = 0; len < 2; len++) (void)get_byte(s); + } + s->z_err = s->z_eof ? Z_DATA_ERROR : Z_OK; +} + + /* =========================================================================== + * Cleanup then free the given gz_stream. Return a zlib error code. + Try freeing in the reverse order of allocations. + */ +local int destroy (s) + gz_stream *s; +{ + int err = Z_OK; + + if (!s) return Z_STREAM_ERROR; + + TRYFREE(s->msg); + + if (s->stream.state != NULL) { + if (s->mode == 'w') { +#ifdef NO_DEFLATE + err = Z_STREAM_ERROR; +#else + err = deflateEnd(&(s->stream)); +#endif + } else if (s->mode == 'r') { + err = inflateEnd(&(s->stream)); + } + } + if (s->file != NULL && fclose(s->file)) { +#ifdef ESPIPE + if (errno != ESPIPE) /* fclose is broken for pipes in HP/UX */ +#endif + err = Z_ERRNO; + } + if (s->z_err < 0) err = s->z_err; + + TRYFREE(s->inbuf); + TRYFREE(s->outbuf); + TRYFREE(s->path); + TRYFREE(s); + return err; +} + +/* =========================================================================== + Reads the given number of uncompressed bytes from the compressed file. + gzread returns the number of bytes actually read (0 for end of file). +*/ +int ZEXPORT gzread (file, buf, len) + gzFile file; + voidp buf; + unsigned len; +{ + gz_stream *s = (gz_stream*)file; + Bytef *start = (Bytef*)buf; /* starting point for crc computation */ + Byte *next_out; /* == stream.next_out but not forced far (for MSDOS) */ + + if (s == NULL || s->mode != 'r') return Z_STREAM_ERROR; + + if (s->z_err == Z_DATA_ERROR || s->z_err == Z_ERRNO) return -1; + if (s->z_err == Z_STREAM_END) return 0; /* EOF */ + + next_out = (Byte*)buf; + s->stream.next_out = (Bytef*)buf; + s->stream.avail_out = len; + + while (s->stream.avail_out != 0) { + + if (s->transparent) { + /* Copy first the lookahead bytes: */ + uInt n = s->stream.avail_in; + if (n > s->stream.avail_out) n = s->stream.avail_out; + if (n > 0) { + zmemcpy(s->stream.next_out, s->stream.next_in, n); + next_out += n; + s->stream.next_out = next_out; + s->stream.next_in += n; + s->stream.avail_out -= n; + s->stream.avail_in -= n; + } + if (s->stream.avail_out > 0) { + s->stream.avail_out -= fread(next_out, 1, s->stream.avail_out, + s->file); + } + len -= s->stream.avail_out; + s->stream.total_in += (uLong)len; + s->stream.total_out += (uLong)len; + if (len == 0) s->z_eof = 1; + return (int)len; + } + if (s->stream.avail_in == 0 && !s->z_eof) { + + errno = 0; + s->stream.avail_in = fread(s->inbuf, 1, Z_BUFSIZE, s->file); + if (s->stream.avail_in == 0) { + s->z_eof = 1; + if (ferror(s->file)) { + s->z_err = Z_ERRNO; + break; + } + } + s->stream.next_in = s->inbuf; + } + s->z_err = inflate(&(s->stream), Z_NO_FLUSH); + + if (s->z_err == Z_STREAM_END) { + /* Check CRC and original size */ + s->crc = crc32(s->crc, start, (uInt)(s->stream.next_out - start)); + start = s->stream.next_out; + + if (getLong(s) != s->crc) { + s->z_err = Z_DATA_ERROR; + } else { + (void)getLong(s); + /* The uncompressed length returned by above getlong() may + * be different from s->stream.total_out) in case of + * concatenated .gz files. Check for such files: + */ + check_header(s); + if (s->z_err == Z_OK) { + uLong total_in = s->stream.total_in; + uLong total_out = s->stream.total_out; + + inflateReset(&(s->stream)); + s->stream.total_in = total_in; + s->stream.total_out = total_out; + s->crc = crc32(0L, Z_NULL, 0); + } + } + } + if (s->z_err != Z_OK || s->z_eof) break; + } + s->crc = crc32(s->crc, start, (uInt)(s->stream.next_out - start)); + + return (int)(len - s->stream.avail_out); +} + + +/* =========================================================================== + Reads one byte from the compressed file. gzgetc returns this byte + or -1 in case of end of file or error. +*/ +int ZEXPORT gzgetc(file) + gzFile file; +{ + unsigned char c; + + return gzread(file, &c, 1) == 1 ? c : -1; +} + + +/* =========================================================================== + Reads bytes from the compressed file until len-1 characters are + read, or a newline character is read and transferred to buf, or an + end-of-file condition is encountered. The string is then terminated + with a null character. + gzgets returns buf, or Z_NULL in case of error. + + The current implementation is not optimized at all. +*/ +char * ZEXPORT gzgets(file, buf, len) + gzFile file; + char *buf; + int len; +{ + char *b = buf; + if (buf == Z_NULL || len <= 0) return Z_NULL; + + while (--len > 0 && gzread(file, buf, 1) == 1 && *buf++ != '\n') ; + *buf = '\0'; + return b == buf && len > 0 ? Z_NULL : b; +} + + +#ifndef NO_DEFLATE +/* =========================================================================== + Writes the given number of uncompressed bytes into the compressed file. + gzwrite returns the number of bytes actually written (0 in case of error). +*/ +int ZEXPORT gzwrite (file, buf, len) + gzFile file; + const voidp buf; + unsigned len; +{ + gz_stream *s = (gz_stream*)file; + + if (s == NULL || s->mode != 'w') return Z_STREAM_ERROR; + + s->stream.next_in = (Bytef*)buf; + s->stream.avail_in = len; + + while (s->stream.avail_in != 0) { + + if (s->stream.avail_out == 0) { + + s->stream.next_out = s->outbuf; + if (fwrite(s->outbuf, 1, Z_BUFSIZE, s->file) != Z_BUFSIZE) { + s->z_err = Z_ERRNO; + break; + } + s->stream.avail_out = Z_BUFSIZE; + } + s->z_err = deflate(&(s->stream), Z_NO_FLUSH); + if (s->z_err != Z_OK) break; + } + s->crc = crc32(s->crc, (const Bytef *)buf, len); + + return (int)(len - s->stream.avail_in); +} + +/* =========================================================================== + Converts, formats, and writes the args to the compressed file under + control of the format string, as in fprintf. gzprintf returns the number of + uncompressed bytes actually written (0 in case of error). +*/ +#ifdef STDC +#include + +int ZEXPORTVA gzprintf (gzFile file, const char *format, /* args */ ...) +{ + char buf[Z_PRINTF_BUFSIZE]; + va_list va; + int len; + + va_start(va, format); +#ifdef HAS_vsnprintf + (void)vsnprintf(buf, sizeof(buf), format, va); +#else + (void)vsprintf(buf, format, va); +#endif + va_end(va); + len = strlen(buf); /* some *sprintf don't return the nb of bytes written */ + if (len <= 0) return 0; + + return gzwrite(file, buf, (unsigned)len); +} +#else /* not ANSI C */ + +int ZEXPORTVA gzprintf (file, format, a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, + a11, a12, a13, a14, a15, a16, a17, a18, a19, a20) + gzFile file; + const char *format; + int a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, + a11, a12, a13, a14, a15, a16, a17, a18, a19, a20; +{ + char buf[Z_PRINTF_BUFSIZE]; + int len; + +#ifdef HAS_snprintf + snprintf(buf, sizeof(buf), format, a1, a2, a3, a4, a5, a6, a7, a8, + a9, a10, a11, a12, a13, a14, a15, a16, a17, a18, a19, a20); +#else + sprintf(buf, format, a1, a2, a3, a4, a5, a6, a7, a8, + a9, a10, a11, a12, a13, a14, a15, a16, a17, a18, a19, a20); +#endif + len = strlen(buf); /* old sprintf doesn't return the nb of bytes written */ + if (len <= 0) return 0; + + return gzwrite(file, buf, len); +} +#endif + +/* =========================================================================== + Writes c, converted to an unsigned char, into the compressed file. + gzputc returns the value that was written, or -1 in case of error. +*/ +int ZEXPORT gzputc(file, c) + gzFile file; + int c; +{ + unsigned char cc = (unsigned char) c; /* required for big endian systems */ + + return gzwrite(file, &cc, 1) == 1 ? (int)cc : -1; +} + + +/* =========================================================================== + Writes the given null-terminated string to the compressed file, excluding + the terminating null character. + gzputs returns the number of characters written, or -1 in case of error. +*/ +int ZEXPORT gzputs(file, s) + gzFile file; + const char *s; +{ + return gzwrite(file, (char*)s, (unsigned)strlen(s)); +} + +/* =========================================================================== + Flushes all pending output into the compressed file. The parameter + flush is as in the deflate() function. +*/ +local int do_flush (file, flush) + gzFile file; + int flush; +{ + uInt len; + int done = 0; + gz_stream *s = (gz_stream*)file; + + if (s == NULL || s->mode != 'w') return Z_STREAM_ERROR; + + s->stream.avail_in = 0; /* should be zero already anyway */ + + for (;;) { + len = Z_BUFSIZE - s->stream.avail_out; + + if (len != 0) { + if ((uInt)fwrite(s->outbuf, 1, len, s->file) != len) { + s->z_err = Z_ERRNO; + return Z_ERRNO; + } + s->stream.next_out = s->outbuf; + s->stream.avail_out = Z_BUFSIZE; + } + if (done) break; + s->z_err = deflate(&(s->stream), flush); + + /* Ignore the second of two consecutive flushes: */ + if (len == 0 && s->z_err == Z_BUF_ERROR) s->z_err = Z_OK; + + /* deflate has finished flushing only when it hasn't used up + * all the available space in the output buffer: + */ + done = (s->stream.avail_out != 0 || s->z_err == Z_STREAM_END); + + if (s->z_err != Z_OK && s->z_err != Z_STREAM_END) break; + } + return s->z_err == Z_STREAM_END ? Z_OK : s->z_err; +} + +int ZEXPORT gzflush (file, flush) + gzFile file; + int flush; +{ + gz_stream *s = (gz_stream*)file; + int err = do_flush (file, flush); + + if (err) return err; + fflush(s->file); + return s->z_err == Z_STREAM_END ? Z_OK : s->z_err; +} +#endif /* NO_DEFLATE */ + +/* =========================================================================== + Sets the starting position for the next gzread or gzwrite on the given + compressed file. The offset represents a number of bytes in the + gzseek returns the resulting offset location as measured in bytes from + the beginning of the uncompressed stream, or -1 in case of error. + SEEK_END is not implemented, returns error. + In this version of the library, gzseek can be extremely slow. +*/ +z_off_t ZEXPORT gzseek (file, offset, whence) + gzFile file; + z_off_t offset; + int whence; +{ + gz_stream *s = (gz_stream*)file; + + if (s == NULL || whence == SEEK_END || + s->z_err == Z_ERRNO || s->z_err == Z_DATA_ERROR) { + return -1L; + } + + if (s->mode == 'w') { +#ifdef NO_DEFLATE + return -1L; +#else + if (whence == SEEK_SET) { + offset -= s->stream.total_in; + } + if (offset < 0) return -1L; + + /* At this point, offset is the number of zero bytes to write. */ + if (s->inbuf == Z_NULL) { + s->inbuf = (Byte*)ALLOC(Z_BUFSIZE); /* for seeking */ + zmemzero(s->inbuf, Z_BUFSIZE); + } + while (offset > 0) { + uInt size = Z_BUFSIZE; + if (offset < Z_BUFSIZE) size = (uInt)offset; + + size = gzwrite(file, s->inbuf, size); + if (size == 0) return -1L; + + offset -= size; + } + return (z_off_t)s->stream.total_in; +#endif + } + /* Rest of function is for reading only */ + + /* compute absolute position */ + if (whence == SEEK_CUR) { + offset += s->stream.total_out; + } + if (offset < 0) return -1L; + + if (s->transparent) { + /* map to fseek */ + s->stream.avail_in = 0; + s->stream.next_in = s->inbuf; + if (fseek(s->file, offset, SEEK_SET) < 0) return -1L; + + s->stream.total_in = s->stream.total_out = (uLong)offset; + return offset; + } + + /* For a negative seek, rewind and use positive seek */ + if ((uLong)offset >= s->stream.total_out) { + offset -= s->stream.total_out; + } else if (gzrewind(file) < 0) { + return -1L; + } + /* offset is now the number of bytes to skip. */ + + if (offset != 0 && s->outbuf == Z_NULL) { + s->outbuf = (Byte*)ALLOC(Z_BUFSIZE); + } + while (offset > 0) { + int size = Z_BUFSIZE; + if (offset < Z_BUFSIZE) size = (int)offset; + + size = gzread(file, s->outbuf, (uInt)size); + if (size <= 0) return -1L; + offset -= size; + } + return (z_off_t)s->stream.total_out; +} + +/* =========================================================================== + Rewinds input file. +*/ +int ZEXPORT gzrewind (file) + gzFile file; +{ + gz_stream *s = (gz_stream*)file; + + if (s == NULL || s->mode != 'r') return -1; + + s->z_err = Z_OK; + s->z_eof = 0; + s->stream.avail_in = 0; + s->stream.next_in = s->inbuf; + s->crc = crc32(0L, Z_NULL, 0); + + if (s->startpos == 0) { /* not a compressed file */ + rewind(s->file); + return 0; + } + + (void) inflateReset(&s->stream); + return fseek(s->file, s->startpos, SEEK_SET); +} + +/* =========================================================================== + Returns the starting position for the next gzread or gzwrite on the + given compressed file. This position represents a number of bytes in the + uncompressed data stream. +*/ +z_off_t ZEXPORT gztell (file) + gzFile file; +{ + return gzseek(file, 0L, SEEK_CUR); +} + +/* =========================================================================== + Returns 1 when EOF has previously been detected reading the given + input stream, otherwise zero. +*/ +int ZEXPORT gzeof (file) + gzFile file; +{ + gz_stream *s = (gz_stream*)file; + + return (s == NULL || s->mode != 'r') ? 0 : s->z_eof; +} + +/* =========================================================================== + Outputs a long in LSB order to the given file +*/ +local void putLong (file, x) + FILE *file; + uLong x; +{ + int n; + for (n = 0; n < 4; n++) { + fputc((int)(x & 0xff), file); + x >>= 8; + } +} + +/* =========================================================================== + Reads a long in LSB order from the given gz_stream. Sets z_err in case + of error. +*/ +local uLong getLong (s) + gz_stream *s; +{ + uLong x = (uLong)get_byte(s); + int c; + + x += ((uLong)get_byte(s))<<8; + x += ((uLong)get_byte(s))<<16; + c = get_byte(s); + if (c == EOF) s->z_err = Z_DATA_ERROR; + x += ((uLong)c)<<24; + return x; +} + +/* =========================================================================== + Flushes all pending output if necessary, closes the compressed file + and deallocates all the (de)compression state. +*/ +int ZEXPORT gzclose (file) + gzFile file; +{ + gz_stream *s = (gz_stream*)file; + + if (s == NULL) return Z_STREAM_ERROR; + + if (s->mode == 'w') { +#ifdef NO_DEFLATE + return Z_STREAM_ERROR; +#else + err = do_flush (file, Z_FINISH); + if (err != Z_OK) return destroy((gz_stream*)file); + + putLong (s->file, s->crc); + putLong (s->file, s->stream.total_in); +#endif + } + return destroy((gz_stream*)file); +} + +/* =========================================================================== + Returns the error message for the last error which occured on the + given compressed file. errnum is set to zlib error number. If an + error occured in the file system and not in the compression library, + errnum is set to Z_ERRNO and the application may consult errno + to get the exact error code. +*/ +const char* ZEXPORT gzerror (file, errnum) + gzFile file; + int *errnum; +{ + char *m; + gz_stream *s = (gz_stream*)file; + + if (s == NULL) { + *errnum = Z_STREAM_ERROR; + return (const char*)ERR_MSG(Z_STREAM_ERROR); + } + *errnum = s->z_err; + if (*errnum == Z_OK) return (const char*)""; + + m = (char*)(*errnum == Z_ERRNO ? zstrerror(errno) : s->stream.msg); + + if (m == NULL || *m == '\0') m = (char*)ERR_MSG(s->z_err); + + TRYFREE(s->msg); + s->msg = (char*)ALLOC(strlen(s->path) + strlen(m) + 3); + strcpy(s->msg, s->path); + strcat(s->msg, ": "); + strcat(s->msg, m); + return (const char*)s->msg; +} ADDED zlib/infblock.c Index: zlib/infblock.c ================================================================== --- zlib/infblock.c +++ zlib/infblock.c @@ -0,0 +1,398 @@ +/* infblock.c -- interpret and process block types to last block + * Copyright (C) 1995-1998 Mark Adler + * For conditions of distribution and use, see copyright notice in zlib.h + */ + +#include "zutil.h" +#include "infblock.h" +#include "inftrees.h" +#include "infcodes.h" +#include "infutil.h" + +struct inflate_codes_state {int dummy;}; /* for buggy compilers */ + +/* simplify the use of the inflate_huft type with some defines */ +#define exop word.what.Exop +#define bits word.what.Bits + +/* Table for deflate from PKZIP's appnote.txt. */ +local const uInt border[] = { /* Order of the bit length code lengths */ + 16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15}; + +/* + Notes beyond the 1.93a appnote.txt: + + 1. Distance pointers never point before the beginning of the output + stream. + 2. Distance pointers can point back across blocks, up to 32k away. + 3. There is an implied maximum of 7 bits for the bit length table and + 15 bits for the actual data. + 4. If only one code exists, then it is encoded using one bit. (Zero + would be more efficient, but perhaps a little confusing.) If two + codes exist, they are coded using one bit each (0 and 1). + 5. There is no way of sending zero distance codes--a dummy must be + sent if there are none. (History: a pre 2.0 version of PKZIP would + store blocks with no distance codes, but this was discovered to be + too harsh a criterion.) Valid only for 1.93a. 2.04c does allow + zero distance codes, which is sent as one code of zero bits in + length. + 6. There are up to 286 literal/length codes. Code 256 represents the + end-of-block. Note however that the static length tree defines + 288 codes just to fill out the Huffman codes. Codes 286 and 287 + cannot be used though, since there is no length base or extra bits + defined for them. Similarily, there are up to 30 distance codes. + However, static trees define 32 codes (all 5 bits) to fill out the + Huffman codes, but the last two had better not show up in the data. + 7. Unzip can check dynamic Huffman blocks for complete code sets. + The exception is that a single code would not be complete (see #4). + 8. The five bits following the block type is really the number of + literal codes sent minus 257. + 9. Length codes 8,16,16 are interpreted as 13 length codes of 8 bits + (1+6+6). Therefore, to output three times the length, you output + three codes (1+1+1), whereas to output four times the same length, + you only need two codes (1+3). Hmm. + 10. In the tree reconstruction algorithm, Code = Code + Increment + only if BitLength(i) is not zero. (Pretty obvious.) + 11. Correction: 4 Bits: # of Bit Length codes - 4 (4 - 19) + 12. Note: length code 284 can represent 227-258, but length code 285 + really is 258. The last length deserves its own, short code + since it gets used a lot in very redundant files. The length + 258 is special since 258 - 3 (the min match length) is 255. + 13. The literal/length and distance code bit lengths are read as a + single stream of lengths. It is possible (and advantageous) for + a repeat code (16, 17, or 18) to go across the boundary between + the two sets of lengths. + */ + + +void inflate_blocks_reset(s, z, c) +inflate_blocks_statef *s; +z_streamp z; +uLongf *c; +{ + if (c != Z_NULL) + *c = s->check; + if (s->mode == BTREE || s->mode == DTREE) + ZFREE(z, s->sub.trees.blens); + if (s->mode == CODES) + inflate_codes_free(s->sub.decode.codes, z); + s->mode = TYPE; + s->bitk = 0; + s->bitb = 0; + s->read = s->write = s->window; + if (s->checkfn != Z_NULL) + z->adler = s->check = (*s->checkfn)(0L, (const Bytef *)Z_NULL, 0); + Tracev((stderr, "inflate: blocks reset\n")); +} + + +inflate_blocks_statef *inflate_blocks_new(z, c, w) +z_streamp z; +check_func c; +uInt w; +{ + inflate_blocks_statef *s; + + if ((s = (inflate_blocks_statef *)ZALLOC + (z,1,sizeof(struct inflate_blocks_state))) == Z_NULL) + return s; + if ((s->hufts = + (inflate_huft *)ZALLOC(z, sizeof(inflate_huft), MANY)) == Z_NULL) + { + ZFREE(z, s); + return Z_NULL; + } + if ((s->window = (Bytef *)ZALLOC(z, 1, w)) == Z_NULL) + { + ZFREE(z, s->hufts); + ZFREE(z, s); + return Z_NULL; + } + s->end = s->window + w; + s->checkfn = c; + s->mode = TYPE; + Tracev((stderr, "inflate: blocks allocated\n")); + inflate_blocks_reset(s, z, Z_NULL); + return s; +} + + +int inflate_blocks(s, z, r) +inflate_blocks_statef *s; +z_streamp z; +int r; +{ + uInt t; /* temporary storage */ + uLong b; /* bit buffer */ + uInt k; /* bits in bit buffer */ + Bytef *p; /* input data pointer */ + uInt n; /* bytes available there */ + Bytef *q; /* output window write pointer */ + uInt m; /* bytes to end of window or read pointer */ + + /* copy input/output information to locals (UPDATE macro restores) */ + LOAD + + /* process input based on current state */ + while (1) switch (s->mode) + { + case TYPE: + NEEDBITS(3) + t = (uInt)b & 7; + s->last = t & 1; + switch (t >> 1) + { + case 0: /* stored */ + Tracev((stderr, "inflate: stored block%s\n", + s->last ? " (last)" : "")); + DUMPBITS(3) + t = k & 7; /* go to byte boundary */ + DUMPBITS(t) + s->mode = LENS; /* get length of stored block */ + break; + case 1: /* fixed */ + Tracev((stderr, "inflate: fixed codes block%s\n", + s->last ? " (last)" : "")); + { + uInt bl, bd; + inflate_huft *tl, *td; + + inflate_trees_fixed(&bl, &bd, &tl, &td, z); + s->sub.decode.codes = inflate_codes_new(bl, bd, tl, td, z); + if (s->sub.decode.codes == Z_NULL) + { + r = Z_MEM_ERROR; + LEAVE + } + } + DUMPBITS(3) + s->mode = CODES; + break; + case 2: /* dynamic */ + Tracev((stderr, "inflate: dynamic codes block%s\n", + s->last ? " (last)" : "")); + DUMPBITS(3) + s->mode = TABLE; + break; + case 3: /* illegal */ + DUMPBITS(3) + s->mode = BAD; + z->msg = (char*)"invalid block type"; + r = Z_DATA_ERROR; + LEAVE + } + break; + case LENS: + NEEDBITS(32) + if ((((~b) >> 16) & 0xffff) != (b & 0xffff)) + { + s->mode = BAD; + z->msg = (char*)"invalid stored block lengths"; + r = Z_DATA_ERROR; + LEAVE + } + s->sub.left = (uInt)b & 0xffff; + b = k = 0; /* dump bits */ + Tracev((stderr, "inflate: stored length %u\n", s->sub.left)); + s->mode = s->sub.left ? STORED : (s->last ? DRY : TYPE); + break; + case STORED: + if (n == 0) + LEAVE + NEEDOUT + t = s->sub.left; + if (t > n) t = n; + if (t > m) t = m; + zmemcpy(q, p, t); + p += t; n -= t; + q += t; m -= t; + if ((s->sub.left -= t) != 0) + break; + Tracev((stderr, "inflate: stored end, %lu total out\n", + z->total_out + (q >= s->read ? q - s->read : + (s->end - s->read) + (q - s->window)))); + s->mode = s->last ? DRY : TYPE; + break; + case TABLE: + NEEDBITS(14) + s->sub.trees.table = t = (uInt)b & 0x3fff; +#ifndef PKZIP_BUG_WORKAROUND + if ((t & 0x1f) > 29 || ((t >> 5) & 0x1f) > 29) + { + s->mode = BAD; + z->msg = (char*)"too many length or distance symbols"; + r = Z_DATA_ERROR; + LEAVE + } +#endif + t = 258 + (t & 0x1f) + ((t >> 5) & 0x1f); + if ((s->sub.trees.blens = (uIntf*)ZALLOC(z, t, sizeof(uInt))) == Z_NULL) + { + r = Z_MEM_ERROR; + LEAVE + } + DUMPBITS(14) + s->sub.trees.index = 0; + Tracev((stderr, "inflate: table sizes ok\n")); + s->mode = BTREE; + case BTREE: + while (s->sub.trees.index < 4 + (s->sub.trees.table >> 10)) + { + NEEDBITS(3) + s->sub.trees.blens[border[s->sub.trees.index++]] = (uInt)b & 7; + DUMPBITS(3) + } + while (s->sub.trees.index < 19) + s->sub.trees.blens[border[s->sub.trees.index++]] = 0; + s->sub.trees.bb = 7; + t = inflate_trees_bits(s->sub.trees.blens, &s->sub.trees.bb, + &s->sub.trees.tb, s->hufts, z); + if (t != Z_OK) + { + ZFREE(z, s->sub.trees.blens); + r = t; + if (r == Z_DATA_ERROR) + s->mode = BAD; + LEAVE + } + s->sub.trees.index = 0; + Tracev((stderr, "inflate: bits tree ok\n")); + s->mode = DTREE; + case DTREE: + while (t = s->sub.trees.table, + s->sub.trees.index < 258 + (t & 0x1f) + ((t >> 5) & 0x1f)) + { + inflate_huft *h; + uInt i, j, c; + + t = s->sub.trees.bb; + NEEDBITS(t) + h = s->sub.trees.tb + ((uInt)b & inflate_mask[t]); + t = h->bits; + c = h->base; + if (c < 16) + { + DUMPBITS(t) + s->sub.trees.blens[s->sub.trees.index++] = c; + } + else /* c == 16..18 */ + { + i = c == 18 ? 7 : c - 14; + j = c == 18 ? 11 : 3; + NEEDBITS(t + i) + DUMPBITS(t) + j += (uInt)b & inflate_mask[i]; + DUMPBITS(i) + i = s->sub.trees.index; + t = s->sub.trees.table; + if (i + j > 258 + (t & 0x1f) + ((t >> 5) & 0x1f) || + (c == 16 && i < 1)) + { + ZFREE(z, s->sub.trees.blens); + s->mode = BAD; + z->msg = (char*)"invalid bit length repeat"; + r = Z_DATA_ERROR; + LEAVE + } + c = c == 16 ? s->sub.trees.blens[i - 1] : 0; + do { + s->sub.trees.blens[i++] = c; + } while (--j); + s->sub.trees.index = i; + } + } + s->sub.trees.tb = Z_NULL; + { + uInt bl, bd; + inflate_huft *tl, *td; + inflate_codes_statef *c; + + bl = 9; /* must be <= 9 for lookahead assumptions */ + bd = 6; /* must be <= 9 for lookahead assumptions */ + t = s->sub.trees.table; + t = inflate_trees_dynamic(257 + (t & 0x1f), 1 + ((t >> 5) & 0x1f), + s->sub.trees.blens, &bl, &bd, &tl, &td, + s->hufts, z); + ZFREE(z, s->sub.trees.blens); + if (t != Z_OK) + { + if (t == (uInt)Z_DATA_ERROR) + s->mode = BAD; + r = t; + LEAVE + } + Tracev((stderr, "inflate: trees ok\n")); + if ((c = inflate_codes_new(bl, bd, tl, td, z)) == Z_NULL) + { + r = Z_MEM_ERROR; + LEAVE + } + s->sub.decode.codes = c; + } + s->mode = CODES; + case CODES: + UPDATE + if ((r = inflate_codes(s, z, r)) != Z_STREAM_END) + return inflate_flush(s, z, r); + r = Z_OK; + inflate_codes_free(s->sub.decode.codes, z); + LOAD + Tracev((stderr, "inflate: codes end, %lu total out\n", + z->total_out + (q >= s->read ? q - s->read : + (s->end - s->read) + (q - s->window)))); + if (!s->last) + { + s->mode = TYPE; + break; + } + s->mode = DRY; + case DRY: + FLUSH + if (s->read != s->write) + LEAVE + s->mode = DONE; + case DONE: + r = Z_STREAM_END; + LEAVE + case BAD: + r = Z_DATA_ERROR; + LEAVE + default: + r = Z_STREAM_ERROR; + LEAVE + } +} + + +int inflate_blocks_free(s, z) +inflate_blocks_statef *s; +z_streamp z; +{ + inflate_blocks_reset(s, z, Z_NULL); + ZFREE(z, s->window); + ZFREE(z, s->hufts); + ZFREE(z, s); + Tracev((stderr, "inflate: blocks freed\n")); + return Z_OK; +} + + +void inflate_set_dictionary(s, d, n) +inflate_blocks_statef *s; +const Bytef *d; +uInt n; +{ + zmemcpy(s->window, d, n); + s->read = s->write = s->window + n; +} + + +/* Returns true if inflate is currently at the end of a block generated + * by Z_SYNC_FLUSH or Z_FULL_FLUSH. + * IN assertion: s != Z_NULL + */ +int inflate_blocks_sync_point(s) +inflate_blocks_statef *s; +{ + return s->mode == LENS; +} ADDED zlib/infblock.h Index: zlib/infblock.h ================================================================== --- zlib/infblock.h +++ zlib/infblock.h @@ -0,0 +1,39 @@ +/* infblock.h -- header to use infblock.c + * Copyright (C) 1995-1998 Mark Adler + * For conditions of distribution and use, see copyright notice in zlib.h + */ + +/* WARNING: this file should *not* be used by applications. It is + part of the implementation of the compression library and is + subject to change. Applications should only use zlib.h. + */ + +struct inflate_blocks_state; +typedef struct inflate_blocks_state FAR inflate_blocks_statef; + +extern inflate_blocks_statef * inflate_blocks_new OF(( + z_streamp z, + check_func c, /* check function */ + uInt w)); /* window size */ + +extern int inflate_blocks OF(( + inflate_blocks_statef *, + z_streamp , + int)); /* initial return code */ + +extern void inflate_blocks_reset OF(( + inflate_blocks_statef *, + z_streamp , + uLongf *)); /* check value on output */ + +extern int inflate_blocks_free OF(( + inflate_blocks_statef *, + z_streamp)); + +extern void inflate_set_dictionary OF(( + inflate_blocks_statef *s, + const Bytef *d, /* dictionary */ + uInt n)); /* dictionary length */ + +extern int inflate_blocks_sync_point OF(( + inflate_blocks_statef *s)); ADDED zlib/infcodes.c Index: zlib/infcodes.c ================================================================== --- zlib/infcodes.c +++ zlib/infcodes.c @@ -0,0 +1,257 @@ +/* infcodes.c -- process literals and length/distance pairs + * Copyright (C) 1995-1998 Mark Adler + * For conditions of distribution and use, see copyright notice in zlib.h + */ + +#include "zutil.h" +#include "inftrees.h" +#include "infblock.h" +#include "infcodes.h" +#include "infutil.h" +#include "inffast.h" + +/* simplify the use of the inflate_huft type with some defines */ +#define exop word.what.Exop +#define bits word.what.Bits + +typedef enum { /* waiting for "i:"=input, "o:"=output, "x:"=nothing */ + START, /* x: set up for LEN */ + LEN, /* i: get length/literal/eob next */ + LENEXT, /* i: getting length extra (have base) */ + DIST, /* i: get distance next */ + DISTEXT, /* i: getting distance extra */ + COPY, /* o: copying bytes in window, waiting for space */ + LIT, /* o: got literal, waiting for output space */ + WASH, /* o: got eob, possibly still output waiting */ + END, /* x: got eob and all data flushed */ + BADCODE} /* x: got error */ +inflate_codes_mode; + +/* inflate codes private state */ +struct inflate_codes_state { + + /* mode */ + inflate_codes_mode mode; /* current inflate_codes mode */ + + /* mode dependent information */ + uInt len; + union { + struct { + inflate_huft *tree; /* pointer into tree */ + uInt need; /* bits needed */ + } code; /* if LEN or DIST, where in tree */ + uInt lit; /* if LIT, literal */ + struct { + uInt get; /* bits to get for extra */ + uInt dist; /* distance back to copy from */ + } copy; /* if EXT or COPY, where and how much */ + } sub; /* submode */ + + /* mode independent information */ + Byte lbits; /* ltree bits decoded per branch */ + Byte dbits; /* dtree bits decoder per branch */ + inflate_huft *ltree; /* literal/length/eob tree */ + inflate_huft *dtree; /* distance tree */ + +}; + + +inflate_codes_statef *inflate_codes_new(bl, bd, tl, td, z) +uInt bl, bd; +inflate_huft *tl; +inflate_huft *td; /* need separate declaration for Borland C++ */ +z_streamp z; +{ + inflate_codes_statef *c; + + if ((c = (inflate_codes_statef *) + ZALLOC(z,1,sizeof(struct inflate_codes_state))) != Z_NULL) + { + c->mode = START; + c->lbits = (Byte)bl; + c->dbits = (Byte)bd; + c->ltree = tl; + c->dtree = td; + Tracev((stderr, "inflate: codes new\n")); + } + return c; +} + + +int inflate_codes(s, z, r) +inflate_blocks_statef *s; +z_streamp z; +int r; +{ + uInt j; /* temporary storage */ + inflate_huft *t; /* temporary pointer */ + uInt e; /* extra bits or operation */ + uLong b; /* bit buffer */ + uInt k; /* bits in bit buffer */ + Bytef *p; /* input data pointer */ + uInt n; /* bytes available there */ + Bytef *q; /* output window write pointer */ + uInt m; /* bytes to end of window or read pointer */ + Bytef *f; /* pointer to copy strings from */ + inflate_codes_statef *c = s->sub.decode.codes; /* codes state */ + + /* copy input/output information to locals (UPDATE macro restores) */ + LOAD + + /* process input and output based on current state */ + while (1) switch (c->mode) + { /* waiting for "i:"=input, "o:"=output, "x:"=nothing */ + case START: /* x: set up for LEN */ +#ifndef SLOW + if (m >= 258 && n >= 10) + { + UPDATE + r = inflate_fast(c->lbits, c->dbits, c->ltree, c->dtree, s, z); + LOAD + if (r != Z_OK) + { + c->mode = r == Z_STREAM_END ? WASH : BADCODE; + break; + } + } +#endif /* !SLOW */ + c->sub.code.need = c->lbits; + c->sub.code.tree = c->ltree; + c->mode = LEN; + case LEN: /* i: get length/literal/eob next */ + j = c->sub.code.need; + NEEDBITS(j) + t = c->sub.code.tree + ((uInt)b & inflate_mask[j]); + DUMPBITS(t->bits) + e = (uInt)(t->exop); + if (e == 0) /* literal */ + { + c->sub.lit = t->base; + Tracevv((stderr, t->base >= 0x20 && t->base < 0x7f ? + "inflate: literal '%c'\n" : + "inflate: literal 0x%02x\n", t->base)); + c->mode = LIT; + break; + } + if (e & 16) /* length */ + { + c->sub.copy.get = e & 15; + c->len = t->base; + c->mode = LENEXT; + break; + } + if ((e & 64) == 0) /* next table */ + { + c->sub.code.need = e; + c->sub.code.tree = t + t->base; + break; + } + if (e & 32) /* end of block */ + { + Tracevv((stderr, "inflate: end of block\n")); + c->mode = WASH; + break; + } + c->mode = BADCODE; /* invalid code */ + z->msg = (char*)"invalid literal/length code"; + r = Z_DATA_ERROR; + LEAVE + case LENEXT: /* i: getting length extra (have base) */ + j = c->sub.copy.get; + NEEDBITS(j) + c->len += (uInt)b & inflate_mask[j]; + DUMPBITS(j) + c->sub.code.need = c->dbits; + c->sub.code.tree = c->dtree; + Tracevv((stderr, "inflate: length %u\n", c->len)); + c->mode = DIST; + case DIST: /* i: get distance next */ + j = c->sub.code.need; + NEEDBITS(j) + t = c->sub.code.tree + ((uInt)b & inflate_mask[j]); + DUMPBITS(t->bits) + e = (uInt)(t->exop); + if (e & 16) /* distance */ + { + c->sub.copy.get = e & 15; + c->sub.copy.dist = t->base; + c->mode = DISTEXT; + break; + } + if ((e & 64) == 0) /* next table */ + { + c->sub.code.need = e; + c->sub.code.tree = t + t->base; + break; + } + c->mode = BADCODE; /* invalid code */ + z->msg = (char*)"invalid distance code"; + r = Z_DATA_ERROR; + LEAVE + case DISTEXT: /* i: getting distance extra */ + j = c->sub.copy.get; + NEEDBITS(j) + c->sub.copy.dist += (uInt)b & inflate_mask[j]; + DUMPBITS(j) + Tracevv((stderr, "inflate: distance %u\n", c->sub.copy.dist)); + c->mode = COPY; + case COPY: /* o: copying bytes in window, waiting for space */ +#ifndef __TURBOC__ /* Turbo C bug for following expression */ + f = (uInt)(q - s->window) < c->sub.copy.dist ? + s->end - (c->sub.copy.dist - (q - s->window)) : + q - c->sub.copy.dist; +#else + f = q - c->sub.copy.dist; + if ((uInt)(q - s->window) < c->sub.copy.dist) + f = s->end - (c->sub.copy.dist - (uInt)(q - s->window)); +#endif + while (c->len) + { + NEEDOUT + OUTBYTE(*f++) + if (f == s->end) + f = s->window; + c->len--; + } + c->mode = START; + break; + case LIT: /* o: got literal, waiting for output space */ + NEEDOUT + OUTBYTE(c->sub.lit) + c->mode = START; + break; + case WASH: /* o: got eob, possibly more output */ + if (k > 7) /* return unused byte, if any */ + { + Assert(k < 16, "inflate_codes grabbed too many bytes") + k -= 8; + n++; + p--; /* can always return one */ + } + FLUSH + if (s->read != s->write) + LEAVE + c->mode = END; + case END: + r = Z_STREAM_END; + LEAVE + case BADCODE: /* x: got error */ + r = Z_DATA_ERROR; + LEAVE + default: + r = Z_STREAM_ERROR; + LEAVE + } +#ifdef NEED_DUMMY_RETURN + return Z_STREAM_ERROR; /* Some dumb compilers complain without this */ +#endif +} + + +void inflate_codes_free(c, z) +inflate_codes_statef *c; +z_streamp z; +{ + ZFREE(z, c); + Tracev((stderr, "inflate: codes free\n")); +} ADDED zlib/infcodes.h Index: zlib/infcodes.h ================================================================== --- zlib/infcodes.h +++ zlib/infcodes.h @@ -0,0 +1,27 @@ +/* infcodes.h -- header to use infcodes.c + * Copyright (C) 1995-1998 Mark Adler + * For conditions of distribution and use, see copyright notice in zlib.h + */ + +/* WARNING: this file should *not* be used by applications. It is + part of the implementation of the compression library and is + subject to change. Applications should only use zlib.h. + */ + +struct inflate_codes_state; +typedef struct inflate_codes_state FAR inflate_codes_statef; + +extern inflate_codes_statef *inflate_codes_new OF(( + uInt, uInt, + inflate_huft *, inflate_huft *, + z_streamp )); + +extern int inflate_codes OF(( + inflate_blocks_statef *, + z_streamp , + int)); + +extern void inflate_codes_free OF(( + inflate_codes_statef *, + z_streamp )); + ADDED zlib/inffast.c Index: zlib/inffast.c ================================================================== --- zlib/inffast.c +++ zlib/inffast.c @@ -0,0 +1,170 @@ +/* inffast.c -- process literals and length/distance pairs fast + * Copyright (C) 1995-1998 Mark Adler + * For conditions of distribution and use, see copyright notice in zlib.h + */ + +#include "zutil.h" +#include "inftrees.h" +#include "infblock.h" +#include "infcodes.h" +#include "infutil.h" +#include "inffast.h" + +struct inflate_codes_state {int dummy;}; /* for buggy compilers */ + +/* simplify the use of the inflate_huft type with some defines */ +#define exop word.what.Exop +#define bits word.what.Bits + +/* macros for bit input with no checking and for returning unused bytes */ +#define GRABBITS(j) {while(k<(j)){b|=((uLong)NEXTBYTE)<avail_in-n;c=(k>>3)>3:c;n+=c;p-=c;k-=c<<3;} + +/* Called with number of bytes left to write in window at least 258 + (the maximum string length) and number of input bytes available + at least ten. The ten bytes are six bytes for the longest length/ + distance pair plus four bytes for overloading the bit buffer. */ + +int inflate_fast(bl, bd, tl, td, s, z) +uInt bl, bd; +inflate_huft *tl; +inflate_huft *td; /* need separate declaration for Borland C++ */ +inflate_blocks_statef *s; +z_streamp z; +{ + inflate_huft *t; /* temporary pointer */ + uInt e; /* extra bits or operation */ + uLong b; /* bit buffer */ + uInt k; /* bits in bit buffer */ + Bytef *p; /* input data pointer */ + uInt n; /* bytes available there */ + Bytef *q; /* output window write pointer */ + uInt m; /* bytes to end of window or read pointer */ + uInt ml; /* mask for literal/length tree */ + uInt md; /* mask for distance tree */ + uInt c; /* bytes to copy */ + uInt d; /* distance back to copy from */ + Bytef *r; /* copy source pointer */ + + /* load input, output, bit values */ + LOAD + + /* initialize masks */ + ml = inflate_mask[bl]; + md = inflate_mask[bd]; + + /* do until not enough input or output space for fast loop */ + do { /* assume called with m >= 258 && n >= 10 */ + /* get literal/length code */ + GRABBITS(20) /* max bits for literal/length code */ + if ((e = (t = tl + ((uInt)b & ml))->exop) == 0) + { + DUMPBITS(t->bits) + Tracevv((stderr, t->base >= 0x20 && t->base < 0x7f ? + "inflate: * literal '%c'\n" : + "inflate: * literal 0x%02x\n", t->base)); + *q++ = (Byte)t->base; + m--; + continue; + } + do { + DUMPBITS(t->bits) + if (e & 16) + { + /* get extra bits for length */ + e &= 15; + c = t->base + ((uInt)b & inflate_mask[e]); + DUMPBITS(e) + Tracevv((stderr, "inflate: * length %u\n", c)); + + /* decode distance base of block to copy */ + GRABBITS(15); /* max bits for distance code */ + e = (t = td + ((uInt)b & md))->exop; + do { + DUMPBITS(t->bits) + if (e & 16) + { + /* get extra bits to add to distance base */ + e &= 15; + GRABBITS(e) /* get extra bits (up to 13) */ + d = t->base + ((uInt)b & inflate_mask[e]); + DUMPBITS(e) + Tracevv((stderr, "inflate: * distance %u\n", d)); + + /* do the copy */ + m -= c; + if ((uInt)(q - s->window) >= d) /* offset before dest */ + { /* just copy */ + r = q - d; + *q++ = *r++; c--; /* minimum count is three, */ + *q++ = *r++; c--; /* so unroll loop a little */ + } + else /* else offset after destination */ + { + e = d - (uInt)(q - s->window); /* bytes from offset to end */ + r = s->end - e; /* pointer to offset */ + if (c > e) /* if source crosses, */ + { + c -= e; /* copy to end of window */ + do { + *q++ = *r++; + } while (--e); + r = s->window; /* copy rest from start of window */ + } + } + do { /* copy all or what's left */ + *q++ = *r++; + } while (--c); + break; + } + else if ((e & 64) == 0) + { + t += t->base; + e = (t += ((uInt)b & inflate_mask[e]))->exop; + } + else + { + z->msg = (char*)"invalid distance code"; + UNGRAB + UPDATE + return Z_DATA_ERROR; + } + } while (1); + break; + } + if ((e & 64) == 0) + { + t += t->base; + if ((e = (t += ((uInt)b & inflate_mask[e]))->exop) == 0) + { + DUMPBITS(t->bits) + Tracevv((stderr, t->base >= 0x20 && t->base < 0x7f ? + "inflate: * literal '%c'\n" : + "inflate: * literal 0x%02x\n", t->base)); + *q++ = (Byte)t->base; + m--; + break; + } + } + else if (e & 32) + { + Tracevv((stderr, "inflate: * end of block\n")); + UNGRAB + UPDATE + return Z_STREAM_END; + } + else + { + z->msg = (char*)"invalid literal/length code"; + UNGRAB + UPDATE + return Z_DATA_ERROR; + } + } while (1); + } while (m >= 258 && n >= 10); + + /* not enough input or output--restore pointers and return */ + UNGRAB + UPDATE + return Z_OK; +} ADDED zlib/inffast.h Index: zlib/inffast.h ================================================================== --- zlib/inffast.h +++ zlib/inffast.h @@ -0,0 +1,17 @@ +/* inffast.h -- header to use inffast.c + * Copyright (C) 1995-1998 Mark Adler + * For conditions of distribution and use, see copyright notice in zlib.h + */ + +/* WARNING: this file should *not* be used by applications. It is + part of the implementation of the compression library and is + subject to change. Applications should only use zlib.h. + */ + +extern int inflate_fast OF(( + uInt, + uInt, + inflate_huft *, + inflate_huft *, + inflate_blocks_statef *, + z_streamp )); ADDED zlib/inffixed.h Index: zlib/inffixed.h ================================================================== --- zlib/inffixed.h +++ zlib/inffixed.h @@ -0,0 +1,151 @@ +/* inffixed.h -- table for decoding fixed codes + * Generated automatically by the maketree.c program + */ + +/* WARNING: this file should *not* be used by applications. It is + part of the implementation of the compression library and is + subject to change. Applications should only use zlib.h. + */ + +local uInt fixed_bl = 9; +local uInt fixed_bd = 5; +local inflate_huft fixed_tl[] = { + {{{96,7}},256}, {{{0,8}},80}, {{{0,8}},16}, {{{84,8}},115}, + {{{82,7}},31}, {{{0,8}},112}, {{{0,8}},48}, {{{0,9}},192}, + {{{80,7}},10}, {{{0,8}},96}, {{{0,8}},32}, {{{0,9}},160}, + {{{0,8}},0}, {{{0,8}},128}, {{{0,8}},64}, {{{0,9}},224}, + {{{80,7}},6}, {{{0,8}},88}, {{{0,8}},24}, {{{0,9}},144}, + {{{83,7}},59}, {{{0,8}},120}, {{{0,8}},56}, {{{0,9}},208}, + {{{81,7}},17}, {{{0,8}},104}, {{{0,8}},40}, {{{0,9}},176}, + {{{0,8}},8}, {{{0,8}},136}, {{{0,8}},72}, {{{0,9}},240}, + {{{80,7}},4}, {{{0,8}},84}, {{{0,8}},20}, {{{85,8}},227}, + {{{83,7}},43}, {{{0,8}},116}, {{{0,8}},52}, {{{0,9}},200}, + {{{81,7}},13}, {{{0,8}},100}, {{{0,8}},36}, {{{0,9}},168}, + {{{0,8}},4}, {{{0,8}},132}, {{{0,8}},68}, {{{0,9}},232}, + {{{80,7}},8}, {{{0,8}},92}, {{{0,8}},28}, {{{0,9}},152}, + {{{84,7}},83}, {{{0,8}},124}, {{{0,8}},60}, {{{0,9}},216}, + {{{82,7}},23}, {{{0,8}},108}, {{{0,8}},44}, {{{0,9}},184}, + {{{0,8}},12}, {{{0,8}},140}, {{{0,8}},76}, {{{0,9}},248}, + {{{80,7}},3}, {{{0,8}},82}, {{{0,8}},18}, {{{85,8}},163}, + {{{83,7}},35}, {{{0,8}},114}, {{{0,8}},50}, {{{0,9}},196}, + {{{81,7}},11}, {{{0,8}},98}, {{{0,8}},34}, {{{0,9}},164}, + {{{0,8}},2}, {{{0,8}},130}, {{{0,8}},66}, {{{0,9}},228}, + {{{80,7}},7}, {{{0,8}},90}, {{{0,8}},26}, {{{0,9}},148}, + {{{84,7}},67}, {{{0,8}},122}, {{{0,8}},58}, {{{0,9}},212}, + {{{82,7}},19}, {{{0,8}},106}, {{{0,8}},42}, {{{0,9}},180}, + {{{0,8}},10}, {{{0,8}},138}, {{{0,8}},74}, {{{0,9}},244}, + {{{80,7}},5}, {{{0,8}},86}, {{{0,8}},22}, {{{192,8}},0}, + {{{83,7}},51}, {{{0,8}},118}, {{{0,8}},54}, {{{0,9}},204}, + {{{81,7}},15}, {{{0,8}},102}, {{{0,8}},38}, {{{0,9}},172}, + {{{0,8}},6}, {{{0,8}},134}, {{{0,8}},70}, {{{0,9}},236}, + {{{80,7}},9}, {{{0,8}},94}, {{{0,8}},30}, {{{0,9}},156}, + {{{84,7}},99}, {{{0,8}},126}, {{{0,8}},62}, {{{0,9}},220}, + {{{82,7}},27}, {{{0,8}},110}, {{{0,8}},46}, {{{0,9}},188}, + {{{0,8}},14}, {{{0,8}},142}, {{{0,8}},78}, {{{0,9}},252}, + {{{96,7}},256}, {{{0,8}},81}, {{{0,8}},17}, {{{85,8}},131}, + {{{82,7}},31}, {{{0,8}},113}, {{{0,8}},49}, {{{0,9}},194}, + {{{80,7}},10}, {{{0,8}},97}, {{{0,8}},33}, {{{0,9}},162}, + {{{0,8}},1}, {{{0,8}},129}, {{{0,8}},65}, {{{0,9}},226}, + {{{80,7}},6}, {{{0,8}},89}, {{{0,8}},25}, {{{0,9}},146}, + {{{83,7}},59}, {{{0,8}},121}, {{{0,8}},57}, {{{0,9}},210}, + {{{81,7}},17}, {{{0,8}},105}, {{{0,8}},41}, {{{0,9}},178}, + {{{0,8}},9}, {{{0,8}},137}, {{{0,8}},73}, {{{0,9}},242}, + {{{80,7}},4}, {{{0,8}},85}, {{{0,8}},21}, {{{80,8}},258}, + {{{83,7}},43}, {{{0,8}},117}, {{{0,8}},53}, {{{0,9}},202}, + {{{81,7}},13}, {{{0,8}},101}, {{{0,8}},37}, {{{0,9}},170}, + {{{0,8}},5}, {{{0,8}},133}, {{{0,8}},69}, {{{0,9}},234}, + {{{80,7}},8}, {{{0,8}},93}, {{{0,8}},29}, {{{0,9}},154}, + {{{84,7}},83}, {{{0,8}},125}, {{{0,8}},61}, {{{0,9}},218}, + {{{82,7}},23}, {{{0,8}},109}, {{{0,8}},45}, {{{0,9}},186}, + {{{0,8}},13}, {{{0,8}},141}, {{{0,8}},77}, {{{0,9}},250}, + {{{80,7}},3}, {{{0,8}},83}, {{{0,8}},19}, {{{85,8}},195}, + {{{83,7}},35}, {{{0,8}},115}, {{{0,8}},51}, {{{0,9}},198}, + {{{81,7}},11}, {{{0,8}},99}, {{{0,8}},35}, {{{0,9}},166}, + {{{0,8}},3}, {{{0,8}},131}, {{{0,8}},67}, {{{0,9}},230}, + {{{80,7}},7}, {{{0,8}},91}, {{{0,8}},27}, {{{0,9}},150}, + {{{84,7}},67}, {{{0,8}},123}, {{{0,8}},59}, {{{0,9}},214}, + {{{82,7}},19}, {{{0,8}},107}, {{{0,8}},43}, {{{0,9}},182}, + {{{0,8}},11}, {{{0,8}},139}, {{{0,8}},75}, {{{0,9}},246}, + {{{80,7}},5}, {{{0,8}},87}, {{{0,8}},23}, {{{192,8}},0}, + {{{83,7}},51}, {{{0,8}},119}, {{{0,8}},55}, {{{0,9}},206}, + {{{81,7}},15}, {{{0,8}},103}, {{{0,8}},39}, {{{0,9}},174}, + {{{0,8}},7}, {{{0,8}},135}, {{{0,8}},71}, {{{0,9}},238}, + {{{80,7}},9}, {{{0,8}},95}, {{{0,8}},31}, {{{0,9}},158}, + {{{84,7}},99}, {{{0,8}},127}, {{{0,8}},63}, {{{0,9}},222}, + {{{82,7}},27}, {{{0,8}},111}, {{{0,8}},47}, {{{0,9}},190}, + {{{0,8}},15}, {{{0,8}},143}, {{{0,8}},79}, {{{0,9}},254}, + {{{96,7}},256}, {{{0,8}},80}, {{{0,8}},16}, {{{84,8}},115}, + {{{82,7}},31}, {{{0,8}},112}, {{{0,8}},48}, {{{0,9}},193}, + {{{80,7}},10}, {{{0,8}},96}, {{{0,8}},32}, {{{0,9}},161}, + {{{0,8}},0}, {{{0,8}},128}, {{{0,8}},64}, {{{0,9}},225}, + {{{80,7}},6}, {{{0,8}},88}, {{{0,8}},24}, {{{0,9}},145}, + {{{83,7}},59}, {{{0,8}},120}, {{{0,8}},56}, {{{0,9}},209}, + {{{81,7}},17}, {{{0,8}},104}, {{{0,8}},40}, {{{0,9}},177}, + {{{0,8}},8}, {{{0,8}},136}, {{{0,8}},72}, {{{0,9}},241}, + {{{80,7}},4}, {{{0,8}},84}, {{{0,8}},20}, {{{85,8}},227}, + {{{83,7}},43}, {{{0,8}},116}, {{{0,8}},52}, {{{0,9}},201}, + {{{81,7}},13}, {{{0,8}},100}, {{{0,8}},36}, {{{0,9}},169}, + {{{0,8}},4}, {{{0,8}},132}, {{{0,8}},68}, {{{0,9}},233}, + {{{80,7}},8}, {{{0,8}},92}, {{{0,8}},28}, {{{0,9}},153}, + {{{84,7}},83}, {{{0,8}},124}, {{{0,8}},60}, {{{0,9}},217}, + {{{82,7}},23}, {{{0,8}},108}, {{{0,8}},44}, {{{0,9}},185}, + {{{0,8}},12}, {{{0,8}},140}, {{{0,8}},76}, {{{0,9}},249}, + {{{80,7}},3}, {{{0,8}},82}, {{{0,8}},18}, {{{85,8}},163}, + {{{83,7}},35}, {{{0,8}},114}, {{{0,8}},50}, {{{0,9}},197}, + {{{81,7}},11}, {{{0,8}},98}, {{{0,8}},34}, {{{0,9}},165}, + {{{0,8}},2}, {{{0,8}},130}, {{{0,8}},66}, {{{0,9}},229}, + {{{80,7}},7}, {{{0,8}},90}, {{{0,8}},26}, {{{0,9}},149}, + {{{84,7}},67}, {{{0,8}},122}, {{{0,8}},58}, {{{0,9}},213}, + {{{82,7}},19}, {{{0,8}},106}, {{{0,8}},42}, {{{0,9}},181}, + {{{0,8}},10}, {{{0,8}},138}, {{{0,8}},74}, {{{0,9}},245}, + {{{80,7}},5}, {{{0,8}},86}, {{{0,8}},22}, {{{192,8}},0}, + {{{83,7}},51}, {{{0,8}},118}, {{{0,8}},54}, {{{0,9}},205}, + {{{81,7}},15}, {{{0,8}},102}, {{{0,8}},38}, {{{0,9}},173}, + {{{0,8}},6}, {{{0,8}},134}, {{{0,8}},70}, {{{0,9}},237}, + {{{80,7}},9}, {{{0,8}},94}, {{{0,8}},30}, {{{0,9}},157}, + {{{84,7}},99}, {{{0,8}},126}, {{{0,8}},62}, {{{0,9}},221}, + {{{82,7}},27}, {{{0,8}},110}, {{{0,8}},46}, {{{0,9}},189}, + {{{0,8}},14}, {{{0,8}},142}, {{{0,8}},78}, {{{0,9}},253}, + {{{96,7}},256}, {{{0,8}},81}, {{{0,8}},17}, {{{85,8}},131}, + {{{82,7}},31}, {{{0,8}},113}, {{{0,8}},49}, {{{0,9}},195}, + {{{80,7}},10}, {{{0,8}},97}, {{{0,8}},33}, {{{0,9}},163}, + {{{0,8}},1}, {{{0,8}},129}, {{{0,8}},65}, {{{0,9}},227}, + {{{80,7}},6}, {{{0,8}},89}, {{{0,8}},25}, {{{0,9}},147}, + {{{83,7}},59}, {{{0,8}},121}, {{{0,8}},57}, {{{0,9}},211}, + {{{81,7}},17}, {{{0,8}},105}, {{{0,8}},41}, {{{0,9}},179}, + {{{0,8}},9}, {{{0,8}},137}, {{{0,8}},73}, {{{0,9}},243}, + {{{80,7}},4}, {{{0,8}},85}, {{{0,8}},21}, {{{80,8}},258}, + {{{83,7}},43}, {{{0,8}},117}, {{{0,8}},53}, {{{0,9}},203}, + {{{81,7}},13}, {{{0,8}},101}, {{{0,8}},37}, {{{0,9}},171}, + {{{0,8}},5}, {{{0,8}},133}, {{{0,8}},69}, {{{0,9}},235}, + {{{80,7}},8}, {{{0,8}},93}, {{{0,8}},29}, {{{0,9}},155}, + {{{84,7}},83}, {{{0,8}},125}, {{{0,8}},61}, {{{0,9}},219}, + {{{82,7}},23}, {{{0,8}},109}, {{{0,8}},45}, {{{0,9}},187}, + {{{0,8}},13}, {{{0,8}},141}, {{{0,8}},77}, {{{0,9}},251}, + {{{80,7}},3}, {{{0,8}},83}, {{{0,8}},19}, {{{85,8}},195}, + {{{83,7}},35}, {{{0,8}},115}, {{{0,8}},51}, {{{0,9}},199}, + {{{81,7}},11}, {{{0,8}},99}, {{{0,8}},35}, {{{0,9}},167}, + {{{0,8}},3}, {{{0,8}},131}, {{{0,8}},67}, {{{0,9}},231}, + {{{80,7}},7}, {{{0,8}},91}, {{{0,8}},27}, {{{0,9}},151}, + {{{84,7}},67}, {{{0,8}},123}, {{{0,8}},59}, {{{0,9}},215}, + {{{82,7}},19}, {{{0,8}},107}, {{{0,8}},43}, {{{0,9}},183}, + {{{0,8}},11}, {{{0,8}},139}, {{{0,8}},75}, {{{0,9}},247}, + {{{80,7}},5}, {{{0,8}},87}, {{{0,8}},23}, {{{192,8}},0}, + {{{83,7}},51}, {{{0,8}},119}, {{{0,8}},55}, {{{0,9}},207}, + {{{81,7}},15}, {{{0,8}},103}, {{{0,8}},39}, {{{0,9}},175}, + {{{0,8}},7}, {{{0,8}},135}, {{{0,8}},71}, {{{0,9}},239}, + {{{80,7}},9}, {{{0,8}},95}, {{{0,8}},31}, {{{0,9}},159}, + {{{84,7}},99}, {{{0,8}},127}, {{{0,8}},63}, {{{0,9}},223}, + {{{82,7}},27}, {{{0,8}},111}, {{{0,8}},47}, {{{0,9}},191}, + {{{0,8}},15}, {{{0,8}},143}, {{{0,8}},79}, {{{0,9}},255} + }; +local inflate_huft fixed_td[] = { + {{{80,5}},1}, {{{87,5}},257}, {{{83,5}},17}, {{{91,5}},4097}, + {{{81,5}},5}, {{{89,5}},1025}, {{{85,5}},65}, {{{93,5}},16385}, + {{{80,5}},3}, {{{88,5}},513}, {{{84,5}},33}, {{{92,5}},8193}, + {{{82,5}},9}, {{{90,5}},2049}, {{{86,5}},129}, {{{192,5}},24577}, + {{{80,5}},2}, {{{87,5}},385}, {{{83,5}},25}, {{{91,5}},6145}, + {{{81,5}},7}, {{{89,5}},1537}, {{{85,5}},97}, {{{93,5}},24577}, + {{{80,5}},4}, {{{88,5}},769}, {{{84,5}},49}, {{{92,5}},12289}, + {{{82,5}},13}, {{{90,5}},3073}, {{{86,5}},193}, {{{192,5}},24577} + }; ADDED zlib/inflate.c Index: zlib/inflate.c ================================================================== --- zlib/inflate.c +++ zlib/inflate.c @@ -0,0 +1,366 @@ +/* inflate.c -- zlib interface to inflate modules + * Copyright (C) 1995-1998 Mark Adler + * For conditions of distribution and use, see copyright notice in zlib.h + */ + +#include "zutil.h" +#include "infblock.h" + +struct inflate_blocks_state {int dummy;}; /* for buggy compilers */ + +typedef enum { + METHOD, /* waiting for method byte */ + FLAG, /* waiting for flag byte */ + DICT4, /* four dictionary check bytes to go */ + DICT3, /* three dictionary check bytes to go */ + DICT2, /* two dictionary check bytes to go */ + DICT1, /* one dictionary check byte to go */ + DICT0, /* waiting for inflateSetDictionary */ + BLOCKS, /* decompressing blocks */ + CHECK4, /* four check bytes to go */ + CHECK3, /* three check bytes to go */ + CHECK2, /* two check bytes to go */ + CHECK1, /* one check byte to go */ + DONE, /* finished check, done */ + BAD} /* got an error--stay here */ +inflate_mode; + +/* inflate private state */ +struct internal_state { + + /* mode */ + inflate_mode mode; /* current inflate mode */ + + /* mode dependent information */ + union { + uInt method; /* if FLAGS, method byte */ + struct { + uLong was; /* computed check value */ + uLong need; /* stream check value */ + } check; /* if CHECK, check values to compare */ + uInt marker; /* if BAD, inflateSync's marker bytes count */ + } sub; /* submode */ + + /* mode independent information */ + int nowrap; /* flag for no wrapper */ + uInt wbits; /* log2(window size) (8..15, defaults to 15) */ + inflate_blocks_statef + *blocks; /* current inflate_blocks state */ + +}; + + +int ZEXPORT inflateReset(z) +z_streamp z; +{ + if (z == Z_NULL || z->state == Z_NULL) + return Z_STREAM_ERROR; + z->total_in = z->total_out = 0; + z->msg = Z_NULL; + z->state->mode = z->state->nowrap ? BLOCKS : METHOD; + inflate_blocks_reset(z->state->blocks, z, Z_NULL); + Tracev((stderr, "inflate: reset\n")); + return Z_OK; +} + + +int ZEXPORT inflateEnd(z) +z_streamp z; +{ + if (z == Z_NULL || z->state == Z_NULL || z->zfree == Z_NULL) + return Z_STREAM_ERROR; + if (z->state->blocks != Z_NULL) + inflate_blocks_free(z->state->blocks, z); + ZFREE(z, z->state); + z->state = Z_NULL; + Tracev((stderr, "inflate: end\n")); + return Z_OK; +} + + +int ZEXPORT inflateInit2_(z, w, version, stream_size) +z_streamp z; +int w; +const char *version; +int stream_size; +{ + if (version == Z_NULL || version[0] != ZLIB_VERSION[0] || + stream_size != sizeof(z_stream)) + return Z_VERSION_ERROR; + + /* initialize state */ + if (z == Z_NULL) + return Z_STREAM_ERROR; + z->msg = Z_NULL; + if (z->zalloc == Z_NULL) + { + z->zalloc = zcalloc; + z->opaque = (voidpf)0; + } + if (z->zfree == Z_NULL) z->zfree = zcfree; + if ((z->state = (struct internal_state FAR *) + ZALLOC(z,1,sizeof(struct internal_state))) == Z_NULL) + return Z_MEM_ERROR; + z->state->blocks = Z_NULL; + + /* handle undocumented nowrap option (no zlib header or check) */ + z->state->nowrap = 0; + if (w < 0) + { + w = - w; + z->state->nowrap = 1; + } + + /* set window size */ + if (w < 8 || w > 15) + { + inflateEnd(z); + return Z_STREAM_ERROR; + } + z->state->wbits = (uInt)w; + + /* create inflate_blocks state */ + if ((z->state->blocks = + inflate_blocks_new(z, z->state->nowrap ? Z_NULL : adler32, (uInt)1 << w)) + == Z_NULL) + { + inflateEnd(z); + return Z_MEM_ERROR; + } + Tracev((stderr, "inflate: allocated\n")); + + /* reset state */ + inflateReset(z); + return Z_OK; +} + + +int ZEXPORT inflateInit_(z, version, stream_size) +z_streamp z; +const char *version; +int stream_size; +{ + return inflateInit2_(z, DEF_WBITS, version, stream_size); +} + + +#define NEEDBYTE {if(z->avail_in==0)return r;r=f;} +#define NEXTBYTE (z->avail_in--,z->total_in++,*z->next_in++) + +int ZEXPORT inflate(z, f) +z_streamp z; +int f; +{ + int r; + uInt b; + + if (z == Z_NULL || z->state == Z_NULL || z->next_in == Z_NULL) + return Z_STREAM_ERROR; + f = f == Z_FINISH ? Z_BUF_ERROR : Z_OK; + r = Z_BUF_ERROR; + while (1) switch (z->state->mode) + { + case METHOD: + NEEDBYTE + if (((z->state->sub.method = NEXTBYTE) & 0xf) != Z_DEFLATED) + { + z->state->mode = BAD; + z->msg = (char*)"unknown compression method"; + z->state->sub.marker = 5; /* can't try inflateSync */ + break; + } + if ((z->state->sub.method >> 4) + 8 > z->state->wbits) + { + z->state->mode = BAD; + z->msg = (char*)"invalid window size"; + z->state->sub.marker = 5; /* can't try inflateSync */ + break; + } + z->state->mode = FLAG; + case FLAG: + NEEDBYTE + b = NEXTBYTE; + if (((z->state->sub.method << 8) + b) % 31) + { + z->state->mode = BAD; + z->msg = (char*)"incorrect header check"; + z->state->sub.marker = 5; /* can't try inflateSync */ + break; + } + Tracev((stderr, "inflate: zlib header ok\n")); + if (!(b & PRESET_DICT)) + { + z->state->mode = BLOCKS; + break; + } + z->state->mode = DICT4; + case DICT4: + NEEDBYTE + z->state->sub.check.need = (uLong)NEXTBYTE << 24; + z->state->mode = DICT3; + case DICT3: + NEEDBYTE + z->state->sub.check.need += (uLong)NEXTBYTE << 16; + z->state->mode = DICT2; + case DICT2: + NEEDBYTE + z->state->sub.check.need += (uLong)NEXTBYTE << 8; + z->state->mode = DICT1; + case DICT1: + NEEDBYTE + z->state->sub.check.need += (uLong)NEXTBYTE; + z->adler = z->state->sub.check.need; + z->state->mode = DICT0; + return Z_NEED_DICT; + case DICT0: + z->state->mode = BAD; + z->msg = (char*)"need dictionary"; + z->state->sub.marker = 0; /* can try inflateSync */ + return Z_STREAM_ERROR; + case BLOCKS: + r = inflate_blocks(z->state->blocks, z, r); + if (r == Z_DATA_ERROR) + { + z->state->mode = BAD; + z->state->sub.marker = 0; /* can try inflateSync */ + break; + } + if (r == Z_OK) + r = f; + if (r != Z_STREAM_END) + return r; + r = f; + inflate_blocks_reset(z->state->blocks, z, &z->state->sub.check.was); + if (z->state->nowrap) + { + z->state->mode = DONE; + break; + } + z->state->mode = CHECK4; + case CHECK4: + NEEDBYTE + z->state->sub.check.need = (uLong)NEXTBYTE << 24; + z->state->mode = CHECK3; + case CHECK3: + NEEDBYTE + z->state->sub.check.need += (uLong)NEXTBYTE << 16; + z->state->mode = CHECK2; + case CHECK2: + NEEDBYTE + z->state->sub.check.need += (uLong)NEXTBYTE << 8; + z->state->mode = CHECK1; + case CHECK1: + NEEDBYTE + z->state->sub.check.need += (uLong)NEXTBYTE; + + if (z->state->sub.check.was != z->state->sub.check.need) + { + z->state->mode = BAD; + z->msg = (char*)"incorrect data check"; + z->state->sub.marker = 5; /* can't try inflateSync */ + break; + } + Tracev((stderr, "inflate: zlib check ok\n")); + z->state->mode = DONE; + case DONE: + return Z_STREAM_END; + case BAD: + return Z_DATA_ERROR; + default: + return Z_STREAM_ERROR; + } +#ifdef NEED_DUMMY_RETURN + return Z_STREAM_ERROR; /* Some dumb compilers complain without this */ +#endif +} + + +int ZEXPORT inflateSetDictionary(z, dictionary, dictLength) +z_streamp z; +const Bytef *dictionary; +uInt dictLength; +{ + uInt length = dictLength; + + if (z == Z_NULL || z->state == Z_NULL || z->state->mode != DICT0) + return Z_STREAM_ERROR; + + if (adler32(1L, dictionary, dictLength) != z->adler) return Z_DATA_ERROR; + z->adler = 1L; + + if (length >= ((uInt)1<state->wbits)) + { + length = (1<state->wbits)-1; + dictionary += dictLength - length; + } + inflate_set_dictionary(z->state->blocks, dictionary, length); + z->state->mode = BLOCKS; + return Z_OK; +} + + +int ZEXPORT inflateSync(z) +z_streamp z; +{ + uInt n; /* number of bytes to look at */ + Bytef *p; /* pointer to bytes */ + uInt m; /* number of marker bytes found in a row */ + uLong r, w; /* temporaries to save total_in and total_out */ + + /* set up */ + if (z == Z_NULL || z->state == Z_NULL) + return Z_STREAM_ERROR; + if (z->state->mode != BAD) + { + z->state->mode = BAD; + z->state->sub.marker = 0; + } + if ((n = z->avail_in) == 0) + return Z_BUF_ERROR; + p = z->next_in; + m = z->state->sub.marker; + + /* search */ + while (n && m < 4) + { + static const Byte mark[4] = {0, 0, 0xff, 0xff}; + if (*p == mark[m]) + m++; + else if (*p) + m = 0; + else + m = 4 - m; + p++, n--; + } + + /* restore */ + z->total_in += p - z->next_in; + z->next_in = p; + z->avail_in = n; + z->state->sub.marker = m; + + /* return no joy or set up to restart on a new block */ + if (m != 4) + return Z_DATA_ERROR; + r = z->total_in; w = z->total_out; + inflateReset(z); + z->total_in = r; z->total_out = w; + z->state->mode = BLOCKS; + return Z_OK; +} + + +/* Returns true if inflate is currently at the end of a block generated + * by Z_SYNC_FLUSH or Z_FULL_FLUSH. This function is used by one PPP + * implementation to provide an additional safety check. PPP uses Z_SYNC_FLUSH + * but removes the length bytes of the resulting empty stored block. When + * decompressing, PPP checks that at the end of input packet, inflate is + * waiting for these length bytes. + */ +int ZEXPORT inflateSyncPoint(z) +z_streamp z; +{ + if (z == Z_NULL || z->state == Z_NULL || z->state->blocks == Z_NULL) + return Z_STREAM_ERROR; + return inflate_blocks_sync_point(z->state->blocks); +} ADDED zlib/inftrees.c Index: zlib/inftrees.c ================================================================== --- zlib/inftrees.c +++ zlib/inftrees.c @@ -0,0 +1,455 @@ +/* inftrees.c -- generate Huffman trees for efficient decoding + * Copyright (C) 1995-1998 Mark Adler + * For conditions of distribution and use, see copyright notice in zlib.h + */ + +#include "zutil.h" +#include "inftrees.h" + +#if !defined(BUILDFIXED) && !defined(STDC) +# define BUILDFIXED /* non ANSI compilers may not accept inffixed.h */ +#endif + +const char inflate_copyright[] = + " inflate 1.1.3 Copyright 1995-1998 Mark Adler "; +/* + If you use the zlib library in a product, an acknowledgment is welcome + in the documentation of your product. If for some reason you cannot + include such an acknowledgment, I would appreciate that you keep this + copyright string in the executable of your product. + */ +struct internal_state {int dummy;}; /* for buggy compilers */ + +/* simplify the use of the inflate_huft type with some defines */ +#define exop word.what.Exop +#define bits word.what.Bits + + +local int huft_build OF(( + uIntf *, /* code lengths in bits */ + uInt, /* number of codes */ + uInt, /* number of "simple" codes */ + const uIntf *, /* list of base values for non-simple codes */ + const uIntf *, /* list of extra bits for non-simple codes */ + inflate_huft * FAR*,/* result: starting table */ + uIntf *, /* maximum lookup bits (returns actual) */ + inflate_huft *, /* space for trees */ + uInt *, /* hufts used in space */ + uIntf * )); /* space for values */ + +/* Tables for deflate from PKZIP's appnote.txt. */ +local const uInt cplens[31] = { /* Copy lengths for literal codes 257..285 */ + 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31, + 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0}; + /* see note #13 above about 258 */ +local const uInt cplext[31] = { /* Extra bits for literal codes 257..285 */ + 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, + 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 0, 112, 112}; /* 112==invalid */ +local const uInt cpdist[30] = { /* Copy offsets for distance codes 0..29 */ + 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193, + 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145, + 8193, 12289, 16385, 24577}; +local const uInt cpdext[30] = { /* Extra bits for distance codes */ + 0, 0, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, + 7, 7, 8, 8, 9, 9, 10, 10, 11, 11, + 12, 12, 13, 13}; + +/* + Huffman code decoding is performed using a multi-level table lookup. + The fastest way to decode is to simply build a lookup table whose + size is determined by the longest code. However, the time it takes + to build this table can also be a factor if the data being decoded + is not very long. The most common codes are necessarily the + shortest codes, so those codes dominate the decoding time, and hence + the speed. The idea is you can have a shorter table that decodes the + shorter, more probable codes, and then point to subsidiary tables for + the longer codes. The time it costs to decode the longer codes is + then traded against the time it takes to make longer tables. + + This results of this trade are in the variables lbits and dbits + below. lbits is the number of bits the first level table for literal/ + length codes can decode in one step, and dbits is the same thing for + the distance codes. Subsequent tables are also less than or equal to + those sizes. These values may be adjusted either when all of the + codes are shorter than that, in which case the longest code length in + bits is used, or when the shortest code is *longer* than the requested + table size, in which case the length of the shortest code in bits is + used. + + There are two different values for the two tables, since they code a + different number of possibilities each. The literal/length table + codes 286 possible values, or in a flat code, a little over eight + bits. The distance table codes 30 possible values, or a little less + than five bits, flat. The optimum values for speed end up being + about one bit more than those, so lbits is 8+1 and dbits is 5+1. + The optimum values may differ though from machine to machine, and + possibly even between compilers. Your mileage may vary. + */ + + +/* If BMAX needs to be larger than 16, then h and x[] should be uLong. */ +#define BMAX 15 /* maximum bit length of any code */ + +local int huft_build(b, n, s, d, e, t, m, hp, hn, v) +uIntf *b; /* code lengths in bits (all assumed <= BMAX) */ +uInt n; /* number of codes (assumed <= 288) */ +uInt s; /* number of simple-valued codes (0..s-1) */ +const uIntf *d; /* list of base values for non-simple codes */ +const uIntf *e; /* list of extra bits for non-simple codes */ +inflate_huft * FAR *t; /* result: starting table */ +uIntf *m; /* maximum lookup bits, returns actual */ +inflate_huft *hp; /* space for trees */ +uInt *hn; /* hufts used in space */ +uIntf *v; /* working area: values in order of bit length */ +/* Given a list of code lengths and a maximum table size, make a set of + tables to decode that set of codes. Return Z_OK on success, Z_BUF_ERROR + if the given code set is incomplete (the tables are still built in this + case), Z_DATA_ERROR if the input is invalid (an over-subscribed set of + lengths), or Z_MEM_ERROR if not enough memory. */ +{ + + uInt a; /* counter for codes of length k */ + uInt c[BMAX+1]; /* bit length count table */ + uInt f; /* i repeats in table every f entries */ + int g; /* maximum code length */ + int h; /* table level */ + register uInt i; /* counter, current code */ + register uInt j; /* counter */ + register int k; /* number of bits in current code */ + int l; /* bits per table (returned in m) */ + uInt mask; /* (1 << w) - 1, to avoid cc -O bug on HP */ + register uIntf *p; /* pointer into c[], b[], or v[] */ + inflate_huft *q; /* points to current table */ + struct inflate_huft_s r; /* table entry for structure assignment */ + inflate_huft *u[BMAX]; /* table stack */ + register int w; /* bits before this table == (l * h) */ + uInt x[BMAX+1]; /* bit offsets, then code stack */ + uIntf *xp; /* pointer into x */ + int y; /* number of dummy codes added */ + uInt z; /* number of entries in current table */ + + + /* Generate counts for each bit length */ + p = c; +#define C0 *p++ = 0; +#define C2 C0 C0 C0 C0 +#define C4 C2 C2 C2 C2 + C4 /* clear c[]--assume BMAX+1 is 16 */ + p = b; i = n; + do { + c[*p++]++; /* assume all entries <= BMAX */ + } while (--i); + if (c[0] == n) /* null input--all zero length codes */ + { + *t = (inflate_huft *)Z_NULL; + *m = 0; + return Z_OK; + } + + + /* Find minimum and maximum length, bound *m by those */ + l = *m; + for (j = 1; j <= BMAX; j++) + if (c[j]) + break; + k = j; /* minimum code length */ + if ((uInt)l < j) + l = j; + for (i = BMAX; i; i--) + if (c[i]) + break; + g = i; /* maximum code length */ + if ((uInt)l > i) + l = i; + *m = l; + + + /* Adjust last length count to fill out codes, if needed */ + for (y = 1 << j; j < i; j++, y <<= 1) + if ((y -= c[j]) < 0) + return Z_DATA_ERROR; + if ((y -= c[i]) < 0) + return Z_DATA_ERROR; + c[i] += y; + + + /* Generate starting offsets into the value table for each length */ + x[1] = j = 0; + p = c + 1; xp = x + 2; + while (--i) { /* note that i == g from above */ + *xp++ = (j += *p++); + } + + + /* Make a table of values in order of bit lengths */ + p = b; i = 0; + do { + if ((j = *p++) != 0) + v[x[j]++] = i; + } while (++i < n); + n = x[g]; /* set n to length of v */ + + + /* Generate the Huffman codes and for each, make the table entries */ + x[0] = i = 0; /* first Huffman code is zero */ + p = v; /* grab values in bit order */ + h = -1; /* no tables yet--level -1 */ + w = -l; /* bits decoded == (l * h) */ + u[0] = (inflate_huft *)Z_NULL; /* just to keep compilers happy */ + q = (inflate_huft *)Z_NULL; /* ditto */ + z = 0; /* ditto */ + + /* go through the bit lengths (k already is bits in shortest code) */ + for (; k <= g; k++) + { + a = c[k]; + while (a--) + { + /* here i is the Huffman code of length k bits for value *p */ + /* make tables up to required level */ + while (k > w + l) + { + h++; + w += l; /* previous table always l bits */ + + /* compute minimum size table less than or equal to l bits */ + z = g - w; + z = z > (uInt)l ? l : z; /* table size upper limit */ + if ((f = 1 << (j = k - w)) > a + 1) /* try a k-w bit table */ + { /* too few codes for k-w bit table */ + f -= a + 1; /* deduct codes from patterns left */ + xp = c + k; + if (j < z) + while (++j < z) /* try smaller tables up to z bits */ + { + if ((f <<= 1) <= *++xp) + break; /* enough codes to use up j bits */ + f -= *xp; /* else deduct codes from patterns */ + } + } + z = 1 << j; /* table entries for j-bit table */ + + /* allocate new table */ + if (*hn + z > MANY) /* (note: doesn't matter for fixed) */ + return Z_MEM_ERROR; /* not enough memory */ + u[h] = q = hp + *hn; + *hn += z; + + /* connect to last table, if there is one */ + if (h) + { + x[h] = i; /* save pattern for backing up */ + r.bits = (Byte)l; /* bits to dump before this table */ + r.exop = (Byte)j; /* bits in this table */ + j = i >> (w - l); + r.base = (uInt)(q - u[h-1] - j); /* offset to this table */ + u[h-1][j] = r; /* connect to last table */ + } + else + *t = q; /* first table is returned result */ + } + + /* set up table entry in r */ + r.bits = (Byte)(k - w); + if (p >= v + n) + r.exop = 128 + 64; /* out of values--invalid code */ + else if (*p < s) + { + r.exop = (Byte)(*p < 256 ? 0 : 32 + 64); /* 256 is end-of-block */ + r.base = *p++; /* simple code is just the value */ + } + else + { + r.exop = (Byte)(e[*p - s] + 16 + 64);/* non-simple--look up in lists */ + r.base = d[*p++ - s]; + } + + /* fill code-like entries with r */ + f = 1 << (k - w); + for (j = i >> w; j < z; j += f) + q[j] = r; + + /* backwards increment the k-bit code i */ + for (j = 1 << (k - 1); i & j; j >>= 1) + i ^= j; + i ^= j; + + /* backup over finished tables */ + mask = (1 << w) - 1; /* needed on HP, cc -O bug */ + while ((i & mask) != x[h]) + { + h--; /* don't need to update q */ + w -= l; + mask = (1 << w) - 1; + } + } + } + + + /* Return Z_BUF_ERROR if we were given an incomplete table */ + return y != 0 && g != 1 ? Z_BUF_ERROR : Z_OK; +} + + +int inflate_trees_bits(c, bb, tb, hp, z) +uIntf *c; /* 19 code lengths */ +uIntf *bb; /* bits tree desired/actual depth */ +inflate_huft * FAR *tb; /* bits tree result */ +inflate_huft *hp; /* space for trees */ +z_streamp z; /* for messages */ +{ + int r; + uInt hn = 0; /* hufts used in space */ + uIntf *v; /* work area for huft_build */ + + if ((v = (uIntf*)ZALLOC(z, 19, sizeof(uInt))) == Z_NULL) + return Z_MEM_ERROR; + r = huft_build(c, 19, 19, (uIntf*)Z_NULL, (uIntf*)Z_NULL, + tb, bb, hp, &hn, v); + if (r == Z_DATA_ERROR) + z->msg = (char*)"oversubscribed dynamic bit lengths tree"; + else if (r == Z_BUF_ERROR || *bb == 0) + { + z->msg = (char*)"incomplete dynamic bit lengths tree"; + r = Z_DATA_ERROR; + } + ZFREE(z, v); + return r; +} + + +int inflate_trees_dynamic(nl, nd, c, bl, bd, tl, td, hp, z) +uInt nl; /* number of literal/length codes */ +uInt nd; /* number of distance codes */ +uIntf *c; /* that many (total) code lengths */ +uIntf *bl; /* literal desired/actual bit depth */ +uIntf *bd; /* distance desired/actual bit depth */ +inflate_huft * FAR *tl; /* literal/length tree result */ +inflate_huft * FAR *td; /* distance tree result */ +inflate_huft *hp; /* space for trees */ +z_streamp z; /* for messages */ +{ + int r; + uInt hn = 0; /* hufts used in space */ + uIntf *v; /* work area for huft_build */ + + /* allocate work area */ + if ((v = (uIntf*)ZALLOC(z, 288, sizeof(uInt))) == Z_NULL) + return Z_MEM_ERROR; + + /* build literal/length tree */ + r = huft_build(c, nl, 257, cplens, cplext, tl, bl, hp, &hn, v); + if (r != Z_OK || *bl == 0) + { + if (r == Z_DATA_ERROR) + z->msg = (char*)"oversubscribed literal/length tree"; + else if (r != Z_MEM_ERROR) + { + z->msg = (char*)"incomplete literal/length tree"; + r = Z_DATA_ERROR; + } + ZFREE(z, v); + return r; + } + + /* build distance tree */ + r = huft_build(c + nl, nd, 0, cpdist, cpdext, td, bd, hp, &hn, v); + if (r != Z_OK || (*bd == 0 && nl > 257)) + { + if (r == Z_DATA_ERROR) + z->msg = (char*)"oversubscribed distance tree"; + else if (r == Z_BUF_ERROR) { +#ifdef PKZIP_BUG_WORKAROUND + r = Z_OK; + } +#else + z->msg = (char*)"incomplete distance tree"; + r = Z_DATA_ERROR; + } + else if (r != Z_MEM_ERROR) + { + z->msg = (char*)"empty distance tree with lengths"; + r = Z_DATA_ERROR; + } + ZFREE(z, v); + return r; +#endif + } + + /* done */ + ZFREE(z, v); + return Z_OK; +} + + +/* build fixed tables only once--keep them here */ +#ifdef BUILDFIXED +local int fixed_built = 0; +#define FIXEDH 544 /* number of hufts used by fixed tables */ +local inflate_huft fixed_mem[FIXEDH]; +local uInt fixed_bl; +local uInt fixed_bd; +local inflate_huft *fixed_tl; +local inflate_huft *fixed_td; +#else +#include "inffixed.h" +#endif + + +int inflate_trees_fixed(bl, bd, tl, td, z) +uIntf *bl; /* literal desired/actual bit depth */ +uIntf *bd; /* distance desired/actual bit depth */ +inflate_huft * FAR *tl; /* literal/length tree result */ +inflate_huft * FAR *td; /* distance tree result */ +z_streamp z; /* for memory allocation */ +{ +#ifdef BUILDFIXED + /* build fixed tables if not already */ + if (!fixed_built) + { + int k; /* temporary variable */ + uInt f = 0; /* number of hufts used in fixed_mem */ + uIntf *c; /* length list for huft_build */ + uIntf *v; /* work area for huft_build */ + + /* allocate memory */ + if ((c = (uIntf*)ZALLOC(z, 288, sizeof(uInt))) == Z_NULL) + return Z_MEM_ERROR; + if ((v = (uIntf*)ZALLOC(z, 288, sizeof(uInt))) == Z_NULL) + { + ZFREE(z, c); + return Z_MEM_ERROR; + } + + /* literal table */ + for (k = 0; k < 144; k++) + c[k] = 8; + for (; k < 256; k++) + c[k] = 9; + for (; k < 280; k++) + c[k] = 7; + for (; k < 288; k++) + c[k] = 8; + fixed_bl = 9; + huft_build(c, 288, 257, cplens, cplext, &fixed_tl, &fixed_bl, + fixed_mem, &f, v); + + /* distance table */ + for (k = 0; k < 30; k++) + c[k] = 5; + fixed_bd = 5; + huft_build(c, 30, 0, cpdist, cpdext, &fixed_td, &fixed_bd, + fixed_mem, &f, v); + + /* done */ + ZFREE(z, v); + ZFREE(z, c); + fixed_built = 1; + } +#endif + *bl = fixed_bl; + *bd = fixed_bd; + *tl = fixed_tl; + *td = fixed_td; + return Z_OK; +} ADDED zlib/inftrees.h Index: zlib/inftrees.h ================================================================== --- zlib/inftrees.h +++ zlib/inftrees.h @@ -0,0 +1,58 @@ +/* inftrees.h -- header to use inftrees.c + * Copyright (C) 1995-1998 Mark Adler + * For conditions of distribution and use, see copyright notice in zlib.h + */ + +/* WARNING: this file should *not* be used by applications. It is + part of the implementation of the compression library and is + subject to change. Applications should only use zlib.h. + */ + +/* Huffman code lookup table entry--this entry is four bytes for machines + that have 16-bit pointers (e.g. PC's in the small or medium model). */ + +typedef struct inflate_huft_s FAR inflate_huft; + +struct inflate_huft_s { + union { + struct { + Byte Exop; /* number of extra bits or operation */ + Byte Bits; /* number of bits in this code or subcode */ + } what; + uInt pad; /* pad structure to a power of 2 (4 bytes for */ + } word; /* 16-bit, 8 bytes for 32-bit int's) */ + uInt base; /* literal, length base, distance base, + or table offset */ +}; + +/* Maximum size of dynamic tree. The maximum found in a long but non- + exhaustive search was 1004 huft structures (850 for length/literals + and 154 for distances, the latter actually the result of an + exhaustive search). The actual maximum is not known, but the + value below is more than safe. */ +#define MANY 1440 + +extern int inflate_trees_bits OF(( + uIntf *, /* 19 code lengths */ + uIntf *, /* bits tree desired/actual depth */ + inflate_huft * FAR *, /* bits tree result */ + inflate_huft *, /* space for trees */ + z_streamp)); /* for messages */ + +extern int inflate_trees_dynamic OF(( + uInt, /* number of literal/length codes */ + uInt, /* number of distance codes */ + uIntf *, /* that many (total) code lengths */ + uIntf *, /* literal desired/actual bit depth */ + uIntf *, /* distance desired/actual bit depth */ + inflate_huft * FAR *, /* literal/length tree result */ + inflate_huft * FAR *, /* distance tree result */ + inflate_huft *, /* space for trees */ + z_streamp)); /* for messages */ + +extern int inflate_trees_fixed OF(( + uIntf *, /* literal desired/actual bit depth */ + uIntf *, /* distance desired/actual bit depth */ + inflate_huft * FAR *, /* literal/length tree result */ + inflate_huft * FAR *, /* distance tree result */ + z_streamp)); /* for memory allocation */ ADDED zlib/infutil.c Index: zlib/infutil.c ================================================================== --- zlib/infutil.c +++ zlib/infutil.c @@ -0,0 +1,87 @@ +/* inflate_util.c -- data and routines common to blocks and codes + * Copyright (C) 1995-1998 Mark Adler + * For conditions of distribution and use, see copyright notice in zlib.h + */ + +#include "zutil.h" +#include "infblock.h" +#include "inftrees.h" +#include "infcodes.h" +#include "infutil.h" + +struct inflate_codes_state {int dummy;}; /* for buggy compilers */ + +/* And'ing with mask[n] masks the lower n bits */ +uInt inflate_mask[17] = { + 0x0000, + 0x0001, 0x0003, 0x0007, 0x000f, 0x001f, 0x003f, 0x007f, 0x00ff, + 0x01ff, 0x03ff, 0x07ff, 0x0fff, 0x1fff, 0x3fff, 0x7fff, 0xffff +}; + + +/* copy as much as possible from the sliding window to the output area */ +int inflate_flush(s, z, r) +inflate_blocks_statef *s; +z_streamp z; +int r; +{ + uInt n; + Bytef *p; + Bytef *q; + + /* local copies of source and destination pointers */ + p = z->next_out; + q = s->read; + + /* compute number of bytes to copy as far as end of window */ + n = (uInt)((q <= s->write ? s->write : s->end) - q); + if (n > z->avail_out) n = z->avail_out; + if (n && r == Z_BUF_ERROR) r = Z_OK; + + /* update counters */ + z->avail_out -= n; + z->total_out += n; + + /* update check information */ + if (s->checkfn != Z_NULL) + z->adler = s->check = (*s->checkfn)(s->check, q, n); + + /* copy as far as end of window */ + zmemcpy(p, q, n); + p += n; + q += n; + + /* see if more to copy at beginning of window */ + if (q == s->end) + { + /* wrap pointers */ + q = s->window; + if (s->write == s->end) + s->write = s->window; + + /* compute bytes to copy */ + n = (uInt)(s->write - q); + if (n > z->avail_out) n = z->avail_out; + if (n && r == Z_BUF_ERROR) r = Z_OK; + + /* update counters */ + z->avail_out -= n; + z->total_out += n; + + /* update check information */ + if (s->checkfn != Z_NULL) + z->adler = s->check = (*s->checkfn)(s->check, q, n); + + /* copy */ + zmemcpy(p, q, n); + p += n; + q += n; + } + + /* update pointers */ + z->next_out = p; + s->read = q; + + /* done */ + return r; +} ADDED zlib/infutil.h Index: zlib/infutil.h ================================================================== --- zlib/infutil.h +++ zlib/infutil.h @@ -0,0 +1,98 @@ +/* infutil.h -- types and macros common to blocks and codes + * Copyright (C) 1995-1998 Mark Adler + * For conditions of distribution and use, see copyright notice in zlib.h + */ + +/* WARNING: this file should *not* be used by applications. It is + part of the implementation of the compression library and is + subject to change. Applications should only use zlib.h. + */ + +#ifndef _INFUTIL_H +#define _INFUTIL_H + +typedef enum { + TYPE, /* get type bits (3, including end bit) */ + LENS, /* get lengths for stored */ + STORED, /* processing stored block */ + TABLE, /* get table lengths */ + BTREE, /* get bit lengths tree for a dynamic block */ + DTREE, /* get length, distance trees for a dynamic block */ + CODES, /* processing fixed or dynamic block */ + DRY, /* output remaining window bytes */ + DONE, /* finished last block, done */ + BAD} /* got a data error--stuck here */ +inflate_block_mode; + +/* inflate blocks semi-private state */ +struct inflate_blocks_state { + + /* mode */ + inflate_block_mode mode; /* current inflate_block mode */ + + /* mode dependent information */ + union { + uInt left; /* if STORED, bytes left to copy */ + struct { + uInt table; /* table lengths (14 bits) */ + uInt index; /* index into blens (or border) */ + uIntf *blens; /* bit lengths of codes */ + uInt bb; /* bit length tree depth */ + inflate_huft *tb; /* bit length decoding tree */ + } trees; /* if DTREE, decoding info for trees */ + struct { + inflate_codes_statef + *codes; + } decode; /* if CODES, current state */ + } sub; /* submode */ + uInt last; /* true if this block is the last block */ + + /* mode independent information */ + uInt bitk; /* bits in bit buffer */ + uLong bitb; /* bit buffer */ + inflate_huft *hufts; /* single malloc for tree space */ + Bytef *window; /* sliding window */ + Bytef *end; /* one byte after sliding window */ + Bytef *read; /* window read pointer */ + Bytef *write; /* window write pointer */ + check_func checkfn; /* check function */ + uLong check; /* check on output */ + +}; + + +/* defines for inflate input/output */ +/* update pointers and return */ +#define UPDBITS {s->bitb=b;s->bitk=k;} +#define UPDIN {z->avail_in=n;z->total_in+=p-z->next_in;z->next_in=p;} +#define UPDOUT {s->write=q;} +#define UPDATE {UPDBITS UPDIN UPDOUT} +#define LEAVE {UPDATE return inflate_flush(s,z,r);} +/* get bytes and bits */ +#define LOADIN {p=z->next_in;n=z->avail_in;b=s->bitb;k=s->bitk;} +#define NEEDBYTE {if(n)r=Z_OK;else LEAVE} +#define NEXTBYTE (n--,*p++) +#define NEEDBITS(j) {while(k<(j)){NEEDBYTE;b|=((uLong)NEXTBYTE)<>=(j);k-=(j);} +/* output bytes */ +#define WAVAIL (uInt)(qread?s->read-q-1:s->end-q) +#define LOADOUT {q=s->write;m=(uInt)WAVAIL;} +#define WRAP {if(q==s->end&&s->read!=s->window){q=s->window;m=(uInt)WAVAIL;}} +#define FLUSH {UPDOUT r=inflate_flush(s,z,r); LOADOUT} +#define NEEDOUT {if(m==0){WRAP if(m==0){FLUSH WRAP if(m==0) LEAVE}}r=Z_OK;} +#define OUTBYTE(a) {*q++=(Byte)(a);m--;} +/* load local pointers */ +#define LOAD {LOADIN LOADOUT} + +/* masks for lower bits (size given to avoid silly warnings with Visual C++) */ +extern uInt inflate_mask[17]; + +/* copy as much as possible from the sliding window to the output area */ +extern int inflate_flush OF(( + inflate_blocks_statef *, + z_streamp , + int)); + +struct internal_state {int dummy;}; /* for buggy compilers */ + +#endif ADDED zlib/maketree.c Index: zlib/maketree.c ================================================================== --- zlib/maketree.c +++ zlib/maketree.c @@ -0,0 +1,49 @@ +/* maketree.c -- make inffixed.h table for decoding fixed codes + * Copyright (C) 1998 Mark Adler + * For conditions of distribution and use, see copyright notice in zlib.h + */ + +/* WARNING: this file should *not* be used by applications. It is + part of the implementation of the compression library and is + subject to change. Applications should only use zlib.h. + */ + +/* This program is included in the distribution for completeness. + You do not need to compile or run this program since inffixed.h + is already included in the distribution. To use this program + you need to compile zlib with BUILDFIXED defined and then compile + and link this program with the zlib library. Then the output of + this program can be piped to inffixed.h. */ + +#include +#include +#include "zutil.h" +#include "inftrees.h" + +/* simplify the use of the inflate_huft type with some defines */ +#define exop word.what.Exop +#define bits word.what.Bits + +/* generate initialization table for an inflate_huft structure array */ +void maketree(uInt b, inflate_huft *t) +{ + int i, e; + + i = 0; + while (1) + { + e = t[i].exop; + if (e && (e & (16+64)) == 0) /* table pointer */ + { + fprintf(stderr, "maketree: cannot initialize sub-tables!\n"); + exit(1); + } + if (i % 4 == 0) + printf("\n "); + printf(" {{{%u,%u}},%u}", t[i].exop, t[i].bits, t[i].base); + if (++i == (1< +#endif + +/* =========================================================================== + * Constants + */ + +#define MAX_BL_BITS 7 +/* Bit length codes must not exceed MAX_BL_BITS bits */ + +#define END_BLOCK 256 +/* end of block literal code */ + +#define REP_3_6 16 +/* repeat previous bit length 3-6 times (2 bits of repeat count) */ + +#define REPZ_3_10 17 +/* repeat a zero length 3-10 times (3 bits of repeat count) */ + +#define REPZ_11_138 18 +/* repeat a zero length 11-138 times (7 bits of repeat count) */ + +local const int extra_lbits[LENGTH_CODES] /* extra bits for each length code */ + = {0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0}; + +local const int extra_dbits[D_CODES] /* extra bits for each distance code */ + = {0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13}; + +local const int extra_blbits[BL_CODES]/* extra bits for each bit length code */ + = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7}; + +local const uch bl_order[BL_CODES] + = {16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15}; +/* The lengths of the bit length codes are sent in order of decreasing + * probability, to avoid transmitting the lengths for unused bit length codes. + */ + +#define Buf_size (8 * 2*sizeof(char)) +/* Number of bits used within bi_buf. (bi_buf might be implemented on + * more than 16 bits on some systems.) + */ + +/* =========================================================================== + * Local data. These are initialized only once. + */ + +#define DIST_CODE_LEN 512 /* see definition of array dist_code below */ + +#if defined(GEN_TREES_H) || !defined(STDC) +/* non ANSI compilers may not accept trees.h */ + +local ct_data static_ltree[L_CODES+2]; +/* The static literal tree. Since the bit lengths are imposed, there is no + * need for the L_CODES extra codes used during heap construction. However + * The codes 286 and 287 are needed to build a canonical tree (see _tr_init + * below). + */ + +local ct_data static_dtree[D_CODES]; +/* The static distance tree. (Actually a trivial tree since all codes use + * 5 bits.) + */ + +uch _dist_code[DIST_CODE_LEN]; +/* Distance codes. The first 256 values correspond to the distances + * 3 .. 258, the last 256 values correspond to the top 8 bits of + * the 15 bit distances. + */ + +uch _length_code[MAX_MATCH-MIN_MATCH+1]; +/* length code for each normalized match length (0 == MIN_MATCH) */ + +local int base_length[LENGTH_CODES]; +/* First normalized length for each code (0 = MIN_MATCH) */ + +local int base_dist[D_CODES]; +/* First normalized distance for each code (0 = distance of 1) */ + +#else +# include "trees.h" +#endif /* GEN_TREES_H */ + +struct static_tree_desc_s { + const ct_data *static_tree; /* static tree or NULL */ + const intf *extra_bits; /* extra bits for each code or NULL */ + int extra_base; /* base index for extra_bits */ + int elems; /* max number of elements in the tree */ + int max_length; /* max bit length for the codes */ +}; + +local static_tree_desc static_l_desc = +{static_ltree, extra_lbits, LITERALS+1, L_CODES, MAX_BITS}; + +local static_tree_desc static_d_desc = +{static_dtree, extra_dbits, 0, D_CODES, MAX_BITS}; + +local static_tree_desc static_bl_desc = +{(const ct_data *)0, extra_blbits, 0, BL_CODES, MAX_BL_BITS}; + +/* =========================================================================== + * Local (static) routines in this file. + */ + +local void tr_static_init OF((void)); +local void init_block OF((deflate_state *s)); +local void pqdownheap OF((deflate_state *s, ct_data *tree, int k)); +local void gen_bitlen OF((deflate_state *s, tree_desc *desc)); +local void gen_codes OF((ct_data *tree, int max_code, ushf *bl_count)); +local void build_tree OF((deflate_state *s, tree_desc *desc)); +local void scan_tree OF((deflate_state *s, ct_data *tree, int max_code)); +local void send_tree OF((deflate_state *s, ct_data *tree, int max_code)); +local int build_bl_tree OF((deflate_state *s)); +local void send_all_trees OF((deflate_state *s, int lcodes, int dcodes, + int blcodes)); +local void compress_block OF((deflate_state *s, ct_data *ltree, + ct_data *dtree)); +local void set_data_type OF((deflate_state *s)); +local unsigned bi_reverse OF((unsigned value, int length)); +local void bi_windup OF((deflate_state *s)); +local void bi_flush OF((deflate_state *s)); +local void copy_block OF((deflate_state *s, charf *buf, unsigned len, + int header)); + +#ifdef GEN_TREES_H +local void gen_trees_header OF((void)); +#endif + +#ifndef DEBUG +# define send_code(s, c, tree) send_bits(s, tree[c].Code, tree[c].Len) + /* Send a code of the given tree. c and tree must not have side effects */ + +#else /* DEBUG */ +# define send_code(s, c, tree) \ + { if (z_verbose>2) fprintf(stderr,"\ncd %3d ",(c)); \ + send_bits(s, tree[c].Code, tree[c].Len); } +#endif + +/* =========================================================================== + * Output a short LSB first on the stream. + * IN assertion: there is enough room in pendingBuf. + */ +#define put_short(s, w) { \ + put_byte(s, (uch)((w) & 0xff)); \ + put_byte(s, (uch)((ush)(w) >> 8)); \ +} + +/* =========================================================================== + * Send a value on a given number of bits. + * IN assertion: length <= 16 and value fits in length bits. + */ +#ifdef DEBUG +local void send_bits OF((deflate_state *s, int value, int length)); + +local void send_bits(s, value, length) + deflate_state *s; + int value; /* value to send */ + int length; /* number of bits */ +{ + Tracevv((stderr," l %2d v %4x ", length, value)); + Assert(length > 0 && length <= 15, "invalid length"); + s->bits_sent += (ulg)length; + + /* If not enough room in bi_buf, use (valid) bits from bi_buf and + * (16 - bi_valid) bits from value, leaving (width - (16-bi_valid)) + * unused bits in value. + */ + if (s->bi_valid > (int)Buf_size - length) { + s->bi_buf |= (value << s->bi_valid); + put_short(s, s->bi_buf); + s->bi_buf = (ush)value >> (Buf_size - s->bi_valid); + s->bi_valid += length - Buf_size; + } else { + s->bi_buf |= value << s->bi_valid; + s->bi_valid += length; + } +} +#else /* !DEBUG */ + +#define send_bits(s, value, length) \ +{ int len = length;\ + if (s->bi_valid > (int)Buf_size - len) {\ + int val = value;\ + s->bi_buf |= (val << s->bi_valid);\ + put_short(s, s->bi_buf);\ + s->bi_buf = (ush)val >> (Buf_size - s->bi_valid);\ + s->bi_valid += len - Buf_size;\ + } else {\ + s->bi_buf |= (value) << s->bi_valid;\ + s->bi_valid += len;\ + }\ +} +#endif /* DEBUG */ + + +#define MAX(a,b) (a >= b ? a : b) +/* the arguments must not have side effects */ + +/* =========================================================================== + * Initialize the various 'constant' tables. + */ +local void tr_static_init() +{ +#if defined(GEN_TREES_H) || !defined(STDC) + static int static_init_done = 0; + int n; /* iterates over tree elements */ + int bits; /* bit counter */ + int length; /* length value */ + int code; /* code value */ + int dist; /* distance index */ + ush bl_count[MAX_BITS+1]; + /* number of codes at each bit length for an optimal tree */ + + if (static_init_done) return; + + /* For some embedded targets, global variables are not initialized: */ + static_l_desc.static_tree = static_ltree; + static_l_desc.extra_bits = extra_lbits; + static_d_desc.static_tree = static_dtree; + static_d_desc.extra_bits = extra_dbits; + static_bl_desc.extra_bits = extra_blbits; + + /* Initialize the mapping length (0..255) -> length code (0..28) */ + length = 0; + for (code = 0; code < LENGTH_CODES-1; code++) { + base_length[code] = length; + for (n = 0; n < (1< dist code (0..29) */ + dist = 0; + for (code = 0 ; code < 16; code++) { + base_dist[code] = dist; + for (n = 0; n < (1<>= 7; /* from now on, all distances are divided by 128 */ + for ( ; code < D_CODES; code++) { + base_dist[code] = dist << 7; + for (n = 0; n < (1<<(extra_dbits[code]-7)); n++) { + _dist_code[256 + dist++] = (uch)code; + } + } + Assert (dist == 256, "tr_static_init: 256+dist != 512"); + + /* Construct the codes of the static literal tree */ + for (bits = 0; bits <= MAX_BITS; bits++) bl_count[bits] = 0; + n = 0; + while (n <= 143) static_ltree[n++].Len = 8, bl_count[8]++; + while (n <= 255) static_ltree[n++].Len = 9, bl_count[9]++; + while (n <= 279) static_ltree[n++].Len = 7, bl_count[7]++; + while (n <= 287) static_ltree[n++].Len = 8, bl_count[8]++; + /* Codes 286 and 287 do not exist, but we must include them in the + * tree construction to get a canonical Huffman tree (longest code + * all ones) + */ + gen_codes((ct_data *)static_ltree, L_CODES+1, bl_count); + + /* The static distance tree is trivial: */ + for (n = 0; n < D_CODES; n++) { + static_dtree[n].Len = 5; + static_dtree[n].Code = bi_reverse((unsigned)n, 5); + } + static_init_done = 1; + +# ifdef GEN_TREES_H + gen_trees_header(); +# endif +#endif /* defined(GEN_TREES_H) || !defined(STDC) */ +} + +/* =========================================================================== + * Genererate the file trees.h describing the static trees. + */ +#ifdef GEN_TREES_H +# ifndef DEBUG +# include +# endif + +# define SEPARATOR(i, last, width) \ + ((i) == (last)? "\n};\n\n" : \ + ((i) % (width) == (width)-1 ? ",\n" : ", ")) + +void gen_trees_header() +{ + FILE *header = fopen("trees.h", "w"); + int i; + + Assert (header != NULL, "Can't open trees.h"); + fprintf(header, + "/* header created automatically with -DGEN_TREES_H */\n\n"); + + fprintf(header, "local const ct_data static_ltree[L_CODES+2] = {\n"); + for (i = 0; i < L_CODES+2; i++) { + fprintf(header, "{{%3u},{%3u}}%s", static_ltree[i].Code, + static_ltree[i].Len, SEPARATOR(i, L_CODES+1, 5)); + } + + fprintf(header, "local const ct_data static_dtree[D_CODES] = {\n"); + for (i = 0; i < D_CODES; i++) { + fprintf(header, "{{%2u},{%2u}}%s", static_dtree[i].Code, + static_dtree[i].Len, SEPARATOR(i, D_CODES-1, 5)); + } + + fprintf(header, "const uch _dist_code[DIST_CODE_LEN] = {\n"); + for (i = 0; i < DIST_CODE_LEN; i++) { + fprintf(header, "%2u%s", _dist_code[i], + SEPARATOR(i, DIST_CODE_LEN-1, 20)); + } + + fprintf(header, "const uch _length_code[MAX_MATCH-MIN_MATCH+1]= {\n"); + for (i = 0; i < MAX_MATCH-MIN_MATCH+1; i++) { + fprintf(header, "%2u%s", _length_code[i], + SEPARATOR(i, MAX_MATCH-MIN_MATCH, 20)); + } + + fprintf(header, "local const int base_length[LENGTH_CODES] = {\n"); + for (i = 0; i < LENGTH_CODES; i++) { + fprintf(header, "%1u%s", base_length[i], + SEPARATOR(i, LENGTH_CODES-1, 20)); + } + + fprintf(header, "local const int base_dist[D_CODES] = {\n"); + for (i = 0; i < D_CODES; i++) { + fprintf(header, "%5u%s", base_dist[i], + SEPARATOR(i, D_CODES-1, 10)); + } + + fclose(header); +} +#endif /* GEN_TREES_H */ + +/* =========================================================================== + * Initialize the tree data structures for a new zlib stream. + */ +void _tr_init(s) + deflate_state *s; +{ + tr_static_init(); + + s->l_desc.dyn_tree = s->dyn_ltree; + s->l_desc.stat_desc = &static_l_desc; + + s->d_desc.dyn_tree = s->dyn_dtree; + s->d_desc.stat_desc = &static_d_desc; + + s->bl_desc.dyn_tree = s->bl_tree; + s->bl_desc.stat_desc = &static_bl_desc; + + s->bi_buf = 0; + s->bi_valid = 0; + s->last_eob_len = 8; /* enough lookahead for inflate */ +#ifdef DEBUG + s->compressed_len = 0L; + s->bits_sent = 0L; +#endif + + /* Initialize the first block of the first file: */ + init_block(s); +} + +/* =========================================================================== + * Initialize a new block. + */ +local void init_block(s) + deflate_state *s; +{ + int n; /* iterates over tree elements */ + + /* Initialize the trees. */ + for (n = 0; n < L_CODES; n++) s->dyn_ltree[n].Freq = 0; + for (n = 0; n < D_CODES; n++) s->dyn_dtree[n].Freq = 0; + for (n = 0; n < BL_CODES; n++) s->bl_tree[n].Freq = 0; + + s->dyn_ltree[END_BLOCK].Freq = 1; + s->opt_len = s->static_len = 0L; + s->last_lit = s->matches = 0; +} + +#define SMALLEST 1 +/* Index within the heap array of least frequent node in the Huffman tree */ + + +/* =========================================================================== + * Remove the smallest element from the heap and recreate the heap with + * one less element. Updates heap and heap_len. + */ +#define pqremove(s, tree, top) \ +{\ + top = s->heap[SMALLEST]; \ + s->heap[SMALLEST] = s->heap[s->heap_len--]; \ + pqdownheap(s, tree, SMALLEST); \ +} + +/* =========================================================================== + * Compares to subtrees, using the tree depth as tie breaker when + * the subtrees have equal frequency. This minimizes the worst case length. + */ +#define smaller(tree, n, m, depth) \ + (tree[n].Freq < tree[m].Freq || \ + (tree[n].Freq == tree[m].Freq && depth[n] <= depth[m])) + +/* =========================================================================== + * Restore the heap property by moving down the tree starting at node k, + * exchanging a node with the smallest of its two sons if necessary, stopping + * when the heap property is re-established (each father smaller than its + * two sons). + */ +local void pqdownheap(s, tree, k) + deflate_state *s; + ct_data *tree; /* the tree to restore */ + int k; /* node to move down */ +{ + int v = s->heap[k]; + int j = k << 1; /* left son of k */ + while (j <= s->heap_len) { + /* Set j to the smallest of the two sons: */ + if (j < s->heap_len && + smaller(tree, s->heap[j+1], s->heap[j], s->depth)) { + j++; + } + /* Exit if v is smaller than both sons */ + if (smaller(tree, v, s->heap[j], s->depth)) break; + + /* Exchange v with the smallest son */ + s->heap[k] = s->heap[j]; k = j; + + /* And continue down the tree, setting j to the left son of k */ + j <<= 1; + } + s->heap[k] = v; +} + +/* =========================================================================== + * Compute the optimal bit lengths for a tree and update the total bit length + * for the current block. + * IN assertion: the fields freq and dad are set, heap[heap_max] and + * above are the tree nodes sorted by increasing frequency. + * OUT assertions: the field len is set to the optimal bit length, the + * array bl_count contains the frequencies for each bit length. + * The length opt_len is updated; static_len is also updated if stree is + * not null. + */ +local void gen_bitlen(s, desc) + deflate_state *s; + tree_desc *desc; /* the tree descriptor */ +{ + ct_data *tree = desc->dyn_tree; + int max_code = desc->max_code; + const ct_data *stree = desc->stat_desc->static_tree; + const intf *extra = desc->stat_desc->extra_bits; + int base = desc->stat_desc->extra_base; + int max_length = desc->stat_desc->max_length; + int h; /* heap index */ + int n, m; /* iterate over the tree elements */ + int bits; /* bit length */ + int xbits; /* extra bits */ + ush f; /* frequency */ + int overflow = 0; /* number of elements with bit length too large */ + + for (bits = 0; bits <= MAX_BITS; bits++) s->bl_count[bits] = 0; + + /* In a first pass, compute the optimal bit lengths (which may + * overflow in the case of the bit length tree). + */ + tree[s->heap[s->heap_max]].Len = 0; /* root of the heap */ + + for (h = s->heap_max+1; h < HEAP_SIZE; h++) { + n = s->heap[h]; + bits = tree[tree[n].Dad].Len + 1; + if (bits > max_length) bits = max_length, overflow++; + tree[n].Len = (ush)bits; + /* We overwrite tree[n].Dad which is no longer needed */ + + if (n > max_code) continue; /* not a leaf node */ + + s->bl_count[bits]++; + xbits = 0; + if (n >= base) xbits = extra[n-base]; + f = tree[n].Freq; + s->opt_len += (ulg)f * (bits + xbits); + if (stree) s->static_len += (ulg)f * (stree[n].Len + xbits); + } + if (overflow == 0) return; + + Trace((stderr,"\nbit length overflow\n")); + /* This happens for example on obj2 and pic of the Calgary corpus */ + + /* Find the first bit length which could increase: */ + do { + bits = max_length-1; + while (s->bl_count[bits] == 0) bits--; + s->bl_count[bits]--; /* move one leaf down the tree */ + s->bl_count[bits+1] += 2; /* move one overflow item as its brother */ + s->bl_count[max_length]--; + /* The brother of the overflow item also moves one step up, + * but this does not affect bl_count[max_length] + */ + overflow -= 2; + } while (overflow > 0); + + /* Now recompute all bit lengths, scanning in increasing frequency. + * h is still equal to HEAP_SIZE. (It is simpler to reconstruct all + * lengths instead of fixing only the wrong ones. This idea is taken + * from 'ar' written by Haruhiko Okumura.) + */ + for (bits = max_length; bits != 0; bits--) { + n = s->bl_count[bits]; + while (n != 0) { + m = s->heap[--h]; + if (m > max_code) continue; + if (tree[m].Len != (unsigned) bits) { + Trace((stderr,"code %d bits %d->%d\n", m, tree[m].Len, bits)); + s->opt_len += ((long)bits - (long)tree[m].Len) + *(long)tree[m].Freq; + tree[m].Len = (ush)bits; + } + n--; + } + } +} + +/* =========================================================================== + * Generate the codes for a given tree and bit counts (which need not be + * optimal). + * IN assertion: the array bl_count contains the bit length statistics for + * the given tree and the field len is set for all tree elements. + * OUT assertion: the field code is set for all tree elements of non + * zero code length. + */ +local void gen_codes (tree, max_code, bl_count) + ct_data *tree; /* the tree to decorate */ + int max_code; /* largest code with non zero frequency */ + ushf *bl_count; /* number of codes at each bit length */ +{ + ush next_code[MAX_BITS+1]; /* next code value for each bit length */ + ush code = 0; /* running code value */ + int bits; /* bit index */ + int n; /* code index */ + + /* The distribution counts are first used to generate the code values + * without bit reversal. + */ + for (bits = 1; bits <= MAX_BITS; bits++) { + next_code[bits] = code = (code + bl_count[bits-1]) << 1; + } + /* Check that the bit counts in bl_count are consistent. The last code + * must be all ones. + */ + Assert (code + bl_count[MAX_BITS]-1 == (1<dyn_tree; + const ct_data *stree = desc->stat_desc->static_tree; + int elems = desc->stat_desc->elems; + int n, m; /* iterate over heap elements */ + int max_code = -1; /* largest code with non zero frequency */ + int node; /* new node being created */ + + /* Construct the initial heap, with least frequent element in + * heap[SMALLEST]. The sons of heap[n] are heap[2*n] and heap[2*n+1]. + * heap[0] is not used. + */ + s->heap_len = 0, s->heap_max = HEAP_SIZE; + + for (n = 0; n < elems; n++) { + if (tree[n].Freq != 0) { + s->heap[++(s->heap_len)] = max_code = n; + s->depth[n] = 0; + } else { + tree[n].Len = 0; + } + } + + /* The pkzip format requires that at least one distance code exists, + * and that at least one bit should be sent even if there is only one + * possible code. So to avoid special checks later on we force at least + * two codes of non zero frequency. + */ + while (s->heap_len < 2) { + node = s->heap[++(s->heap_len)] = (max_code < 2 ? ++max_code : 0); + tree[node].Freq = 1; + s->depth[node] = 0; + s->opt_len--; if (stree) s->static_len -= stree[node].Len; + /* node is 0 or 1 so it does not have extra bits */ + } + desc->max_code = max_code; + + /* The elements heap[heap_len/2+1 .. heap_len] are leaves of the tree, + * establish sub-heaps of increasing lengths: + */ + for (n = s->heap_len/2; n >= 1; n--) pqdownheap(s, tree, n); + + /* Construct the Huffman tree by repeatedly combining the least two + * frequent nodes. + */ + node = elems; /* next internal node of the tree */ + do { + pqremove(s, tree, n); /* n = node of least frequency */ + m = s->heap[SMALLEST]; /* m = node of next least frequency */ + + s->heap[--(s->heap_max)] = n; /* keep the nodes sorted by frequency */ + s->heap[--(s->heap_max)] = m; + + /* Create a new node father of n and m */ + tree[node].Freq = tree[n].Freq + tree[m].Freq; + s->depth[node] = (uch) (MAX(s->depth[n], s->depth[m]) + 1); + tree[n].Dad = tree[m].Dad = (ush)node; +#ifdef DUMP_BL_TREE + if (tree == s->bl_tree) { + fprintf(stderr,"\nnode %d(%d), sons %d(%d) %d(%d)", + node, tree[node].Freq, n, tree[n].Freq, m, tree[m].Freq); + } +#endif + /* and insert the new node in the heap */ + s->heap[SMALLEST] = node++; + pqdownheap(s, tree, SMALLEST); + + } while (s->heap_len >= 2); + + s->heap[--(s->heap_max)] = s->heap[SMALLEST]; + + /* At this point, the fields freq and dad are set. We can now + * generate the bit lengths. + */ + gen_bitlen(s, (tree_desc *)desc); + + /* The field len is now set, we can generate the bit codes */ + gen_codes ((ct_data *)tree, max_code, s->bl_count); +} + +/* =========================================================================== + * Scan a literal or distance tree to determine the frequencies of the codes + * in the bit length tree. + */ +local void scan_tree (s, tree, max_code) + deflate_state *s; + ct_data *tree; /* the tree to be scanned */ + int max_code; /* and its largest code of non zero frequency */ +{ + int n; /* iterates over all tree elements */ + int prevlen = -1; /* last emitted length */ + int curlen; /* length of current code */ + int nextlen = tree[0].Len; /* length of next code */ + int count = 0; /* repeat count of the current code */ + int max_count = 7; /* max repeat count */ + int min_count = 4; /* min repeat count */ + + if (nextlen == 0) max_count = 138, min_count = 3; + tree[max_code+1].Len = (ush)0xffff; /* guard */ + + for (n = 0; n <= max_code; n++) { + curlen = nextlen; nextlen = tree[n+1].Len; + if (++count < max_count && curlen == nextlen) { + continue; + } else if (count < min_count) { + s->bl_tree[curlen].Freq += count; + } else if (curlen != 0) { + if (curlen != prevlen) s->bl_tree[curlen].Freq++; + s->bl_tree[REP_3_6].Freq++; + } else if (count <= 10) { + s->bl_tree[REPZ_3_10].Freq++; + } else { + s->bl_tree[REPZ_11_138].Freq++; + } + count = 0; prevlen = curlen; + if (nextlen == 0) { + max_count = 138, min_count = 3; + } else if (curlen == nextlen) { + max_count = 6, min_count = 3; + } else { + max_count = 7, min_count = 4; + } + } +} + +/* =========================================================================== + * Send a literal or distance tree in compressed form, using the codes in + * bl_tree. + */ +local void send_tree (s, tree, max_code) + deflate_state *s; + ct_data *tree; /* the tree to be scanned */ + int max_code; /* and its largest code of non zero frequency */ +{ + int n; /* iterates over all tree elements */ + int prevlen = -1; /* last emitted length */ + int curlen; /* length of current code */ + int nextlen = tree[0].Len; /* length of next code */ + int count = 0; /* repeat count of the current code */ + int max_count = 7; /* max repeat count */ + int min_count = 4; /* min repeat count */ + + /* tree[max_code+1].Len = -1; */ /* guard already set */ + if (nextlen == 0) max_count = 138, min_count = 3; + + for (n = 0; n <= max_code; n++) { + curlen = nextlen; nextlen = tree[n+1].Len; + if (++count < max_count && curlen == nextlen) { + continue; + } else if (count < min_count) { + do { send_code(s, curlen, s->bl_tree); } while (--count != 0); + + } else if (curlen != 0) { + if (curlen != prevlen) { + send_code(s, curlen, s->bl_tree); count--; + } + Assert(count >= 3 && count <= 6, " 3_6?"); + send_code(s, REP_3_6, s->bl_tree); send_bits(s, count-3, 2); + + } else if (count <= 10) { + send_code(s, REPZ_3_10, s->bl_tree); send_bits(s, count-3, 3); + + } else { + send_code(s, REPZ_11_138, s->bl_tree); send_bits(s, count-11, 7); + } + count = 0; prevlen = curlen; + if (nextlen == 0) { + max_count = 138, min_count = 3; + } else if (curlen == nextlen) { + max_count = 6, min_count = 3; + } else { + max_count = 7, min_count = 4; + } + } +} + +/* =========================================================================== + * Construct the Huffman tree for the bit lengths and return the index in + * bl_order of the last bit length code to send. + */ +local int build_bl_tree(s) + deflate_state *s; +{ + int max_blindex; /* index of last bit length code of non zero freq */ + + /* Determine the bit length frequencies for literal and distance trees */ + scan_tree(s, (ct_data *)s->dyn_ltree, s->l_desc.max_code); + scan_tree(s, (ct_data *)s->dyn_dtree, s->d_desc.max_code); + + /* Build the bit length tree: */ + build_tree(s, (tree_desc *)(&(s->bl_desc))); + /* opt_len now includes the length of the tree representations, except + * the lengths of the bit lengths codes and the 5+5+4 bits for the counts. + */ + + /* Determine the number of bit length codes to send. The pkzip format + * requires that at least 4 bit length codes be sent. (appnote.txt says + * 3 but the actual value used is 4.) + */ + for (max_blindex = BL_CODES-1; max_blindex >= 3; max_blindex--) { + if (s->bl_tree[bl_order[max_blindex]].Len != 0) break; + } + /* Update opt_len to include the bit length tree and counts */ + s->opt_len += 3*(max_blindex+1) + 5+5+4; + Tracev((stderr, "\ndyn trees: dyn %ld, stat %ld", + s->opt_len, s->static_len)); + + return max_blindex; +} + +/* =========================================================================== + * Send the header for a block using dynamic Huffman trees: the counts, the + * lengths of the bit length codes, the literal tree and the distance tree. + * IN assertion: lcodes >= 257, dcodes >= 1, blcodes >= 4. + */ +local void send_all_trees(s, lcodes, dcodes, blcodes) + deflate_state *s; + int lcodes, dcodes, blcodes; /* number of codes for each tree */ +{ + int rank; /* index in bl_order */ + + Assert (lcodes >= 257 && dcodes >= 1 && blcodes >= 4, "not enough codes"); + Assert (lcodes <= L_CODES && dcodes <= D_CODES && blcodes <= BL_CODES, + "too many codes"); + Tracev((stderr, "\nbl counts: ")); + send_bits(s, lcodes-257, 5); /* not +255 as stated in appnote.txt */ + send_bits(s, dcodes-1, 5); + send_bits(s, blcodes-4, 4); /* not -3 as stated in appnote.txt */ + for (rank = 0; rank < blcodes; rank++) { + Tracev((stderr, "\nbl code %2d ", bl_order[rank])); + send_bits(s, s->bl_tree[bl_order[rank]].Len, 3); + } + Tracev((stderr, "\nbl tree: sent %ld", s->bits_sent)); + + send_tree(s, (ct_data *)s->dyn_ltree, lcodes-1); /* literal tree */ + Tracev((stderr, "\nlit tree: sent %ld", s->bits_sent)); + + send_tree(s, (ct_data *)s->dyn_dtree, dcodes-1); /* distance tree */ + Tracev((stderr, "\ndist tree: sent %ld", s->bits_sent)); +} + +/* =========================================================================== + * Send a stored block + */ +void _tr_stored_block(s, buf, stored_len, eof) + deflate_state *s; + charf *buf; /* input block */ + ulg stored_len; /* length of input block */ + int eof; /* true if this is the last block for a file */ +{ + send_bits(s, (STORED_BLOCK<<1)+eof, 3); /* send block type */ +#ifdef DEBUG + s->compressed_len = (s->compressed_len + 3 + 7) & (ulg)~7L; + s->compressed_len += (stored_len + 4) << 3; +#endif + copy_block(s, buf, (unsigned)stored_len, 1); /* with header */ +} + +/* =========================================================================== + * Send one empty static block to give enough lookahead for inflate. + * This takes 10 bits, of which 7 may remain in the bit buffer. + * The current inflate code requires 9 bits of lookahead. If the + * last two codes for the previous block (real code plus EOB) were coded + * on 5 bits or less, inflate may have only 5+3 bits of lookahead to decode + * the last real code. In this case we send two empty static blocks instead + * of one. (There are no problems if the previous block is stored or fixed.) + * To simplify the code, we assume the worst case of last real code encoded + * on one bit only. + */ +void _tr_align(s) + deflate_state *s; +{ + send_bits(s, STATIC_TREES<<1, 3); + send_code(s, END_BLOCK, static_ltree); +#ifdef DEBUG + s->compressed_len += 10L; /* 3 for block type, 7 for EOB */ +#endif + bi_flush(s); + /* Of the 10 bits for the empty block, we have already sent + * (10 - bi_valid) bits. The lookahead for the last real code (before + * the EOB of the previous block) was thus at least one plus the length + * of the EOB plus what we have just sent of the empty static block. + */ + if (1 + s->last_eob_len + 10 - s->bi_valid < 9) { + send_bits(s, STATIC_TREES<<1, 3); + send_code(s, END_BLOCK, static_ltree); +#ifdef DEBUG + s->compressed_len += 10L; +#endif + bi_flush(s); + } + s->last_eob_len = 7; +} + +/* =========================================================================== + * Determine the best encoding for the current block: dynamic trees, static + * trees or store, and output the encoded block to the zip file. + */ +void _tr_flush_block(s, buf, stored_len, eof) + deflate_state *s; + charf *buf; /* input block, or NULL if too old */ + ulg stored_len; /* length of input block */ + int eof; /* true if this is the last block for a file */ +{ + ulg opt_lenb, static_lenb; /* opt_len and static_len in bytes */ + int max_blindex = 0; /* index of last bit length code of non zero freq */ + + /* Build the Huffman trees unless a stored block is forced */ + if (s->level > 0) { + + /* Check if the file is ascii or binary */ + if (s->data_type == Z_UNKNOWN) set_data_type(s); + + /* Construct the literal and distance trees */ + build_tree(s, (tree_desc *)(&(s->l_desc))); + Tracev((stderr, "\nlit data: dyn %ld, stat %ld", s->opt_len, + s->static_len)); + + build_tree(s, (tree_desc *)(&(s->d_desc))); + Tracev((stderr, "\ndist data: dyn %ld, stat %ld", s->opt_len, + s->static_len)); + /* At this point, opt_len and static_len are the total bit lengths of + * the compressed block data, excluding the tree representations. + */ + + /* Build the bit length tree for the above two trees, and get the index + * in bl_order of the last bit length code to send. + */ + max_blindex = build_bl_tree(s); + + /* Determine the best encoding. Compute first the block length in bytes*/ + opt_lenb = (s->opt_len+3+7)>>3; + static_lenb = (s->static_len+3+7)>>3; + + Tracev((stderr, "\nopt %lu(%lu) stat %lu(%lu) stored %lu lit %u ", + opt_lenb, s->opt_len, static_lenb, s->static_len, stored_len, + s->last_lit)); + + if (static_lenb <= opt_lenb) opt_lenb = static_lenb; + + } else { + Assert(buf != (char*)0, "lost buf"); + opt_lenb = static_lenb = stored_len + 5; /* force a stored block */ + } + +#ifdef FORCE_STORED + if (buf != (char*)0) { /* force stored block */ +#else + if (stored_len+4 <= opt_lenb && buf != (char*)0) { + /* 4: two words for the lengths */ +#endif + /* The test buf != NULL is only necessary if LIT_BUFSIZE > WSIZE. + * Otherwise we can't have processed more than WSIZE input bytes since + * the last block flush, because compression would have been + * successful. If LIT_BUFSIZE <= WSIZE, it is never too late to + * transform a block into a stored block. + */ + _tr_stored_block(s, buf, stored_len, eof); + +#ifdef FORCE_STATIC + } else if (static_lenb >= 0) { /* force static trees */ +#else + } else if (static_lenb == opt_lenb) { +#endif + send_bits(s, (STATIC_TREES<<1)+eof, 3); + compress_block(s, (ct_data *)static_ltree, (ct_data *)static_dtree); +#ifdef DEBUG + s->compressed_len += 3 + s->static_len; +#endif + } else { + send_bits(s, (DYN_TREES<<1)+eof, 3); + send_all_trees(s, s->l_desc.max_code+1, s->d_desc.max_code+1, + max_blindex+1); + compress_block(s, (ct_data *)s->dyn_ltree, (ct_data *)s->dyn_dtree); +#ifdef DEBUG + s->compressed_len += 3 + s->opt_len; +#endif + } + Assert (s->compressed_len == s->bits_sent, "bad compressed size"); + /* The above check is made mod 2^32, for files larger than 512 MB + * and uLong implemented on 32 bits. + */ + init_block(s); + + if (eof) { + bi_windup(s); +#ifdef DEBUG + s->compressed_len += 7; /* align on byte boundary */ +#endif + } + Tracev((stderr,"\ncomprlen %lu(%lu) ", s->compressed_len>>3, + s->compressed_len-7*eof)); +} + +/* =========================================================================== + * Save the match info and tally the frequency counts. Return true if + * the current block must be flushed. + */ +int _tr_tally (s, dist, lc) + deflate_state *s; + unsigned dist; /* distance of matched string */ + unsigned lc; /* match length-MIN_MATCH or unmatched char (if dist==0) */ +{ + s->d_buf[s->last_lit] = (ush)dist; + s->l_buf[s->last_lit++] = (uch)lc; + if (dist == 0) { + /* lc is the unmatched char */ + s->dyn_ltree[lc].Freq++; + } else { + s->matches++; + /* Here, lc is the match length - MIN_MATCH */ + dist--; /* dist = match distance - 1 */ + Assert((ush)dist < (ush)MAX_DIST(s) && + (ush)lc <= (ush)(MAX_MATCH-MIN_MATCH) && + (ush)d_code(dist) < (ush)D_CODES, "_tr_tally: bad match"); + + s->dyn_ltree[_length_code[lc]+LITERALS+1].Freq++; + s->dyn_dtree[d_code(dist)].Freq++; + } + +#ifdef TRUNCATE_BLOCK + /* Try to guess if it is profitable to stop the current block here */ + if ((s->last_lit & 0x1fff) == 0 && s->level > 2) { + /* Compute an upper bound for the compressed length */ + ulg out_length = (ulg)s->last_lit*8L; + ulg in_length = (ulg)((long)s->strstart - s->block_start); + int dcode; + for (dcode = 0; dcode < D_CODES; dcode++) { + out_length += (ulg)s->dyn_dtree[dcode].Freq * + (5L+extra_dbits[dcode]); + } + out_length >>= 3; + Tracev((stderr,"\nlast_lit %u, in %ld, out ~%ld(%ld%%) ", + s->last_lit, in_length, out_length, + 100L - out_length*100L/in_length)); + if (s->matches < s->last_lit/2 && out_length < in_length/2) return 1; + } +#endif + return (s->last_lit == s->lit_bufsize-1); + /* We avoid equality with lit_bufsize because of wraparound at 64K + * on 16 bit machines and because stored blocks are restricted to + * 64K-1 bytes. + */ +} + +/* =========================================================================== + * Send the block data compressed using the given Huffman trees + */ +local void compress_block(s, ltree, dtree) + deflate_state *s; + ct_data *ltree; /* literal tree */ + ct_data *dtree; /* distance tree */ +{ + unsigned dist; /* distance of matched string */ + int lc; /* match length or unmatched char (if dist == 0) */ + unsigned lx = 0; /* running index in l_buf */ + unsigned code; /* the code to send */ + int extra; /* number of extra bits to send */ + + if (s->last_lit != 0) do { + dist = s->d_buf[lx]; + lc = s->l_buf[lx++]; + if (dist == 0) { + send_code(s, lc, ltree); /* send a literal byte */ + Tracecv(isgraph(lc), (stderr," '%c' ", lc)); + } else { + /* Here, lc is the match length - MIN_MATCH */ + code = _length_code[lc]; + send_code(s, code+LITERALS+1, ltree); /* send the length code */ + extra = extra_lbits[code]; + if (extra != 0) { + lc -= base_length[code]; + send_bits(s, lc, extra); /* send the extra length bits */ + } + dist--; /* dist is now the match distance - 1 */ + code = d_code(dist); + Assert (code < D_CODES, "bad d_code"); + + send_code(s, code, dtree); /* send the distance code */ + extra = extra_dbits[code]; + if (extra != 0) { + dist -= base_dist[code]; + send_bits(s, dist, extra); /* send the extra distance bits */ + } + } /* literal or match pair ? */ + + /* Check that the overlay between pending_buf and d_buf+l_buf is ok: */ + Assert(s->pending < s->lit_bufsize + 2*lx, "pendingBuf overflow"); + + } while (lx < s->last_lit); + + send_code(s, END_BLOCK, ltree); + s->last_eob_len = ltree[END_BLOCK].Len; +} + +/* =========================================================================== + * Set the data type to ASCII or BINARY, using a crude approximation: + * binary if more than 20% of the bytes are <= 6 or >= 128, ascii otherwise. + * IN assertion: the fields freq of dyn_ltree are set and the total of all + * frequencies does not exceed 64K (to fit in an int on 16 bit machines). + */ +local void set_data_type(s) + deflate_state *s; +{ + int n = 0; + unsigned ascii_freq = 0; + unsigned bin_freq = 0; + while (n < 7) bin_freq += s->dyn_ltree[n++].Freq; + while (n < 128) ascii_freq += s->dyn_ltree[n++].Freq; + while (n < LITERALS) bin_freq += s->dyn_ltree[n++].Freq; + s->data_type = (Byte)(bin_freq > (ascii_freq >> 2) ? Z_BINARY : Z_ASCII); +} + +/* =========================================================================== + * Reverse the first len bits of a code, using straightforward code (a faster + * method would use a table) + * IN assertion: 1 <= len <= 15 + */ +local unsigned bi_reverse(code, len) + unsigned code; /* the value to invert */ + int len; /* its bit length */ +{ + register unsigned res = 0; + do { + res |= code & 1; + code >>= 1, res <<= 1; + } while (--len > 0); + return res >> 1; +} + +/* =========================================================================== + * Flush the bit buffer, keeping at most 7 bits in it. + */ +local void bi_flush(s) + deflate_state *s; +{ + if (s->bi_valid == 16) { + put_short(s, s->bi_buf); + s->bi_buf = 0; + s->bi_valid = 0; + } else if (s->bi_valid >= 8) { + put_byte(s, (Byte)s->bi_buf); + s->bi_buf >>= 8; + s->bi_valid -= 8; + } +} + +/* =========================================================================== + * Flush the bit buffer and align the output on a byte boundary + */ +local void bi_windup(s) + deflate_state *s; +{ + if (s->bi_valid > 8) { + put_short(s, s->bi_buf); + } else if (s->bi_valid > 0) { + put_byte(s, (Byte)s->bi_buf); + } + s->bi_buf = 0; + s->bi_valid = 0; +#ifdef DEBUG + s->bits_sent = (s->bits_sent+7) & ~7; +#endif +} + +/* =========================================================================== + * Copy a stored block, storing first the length and its + * one's complement if requested. + */ +local void copy_block(s, buf, len, header) + deflate_state *s; + charf *buf; /* the input data */ + unsigned len; /* its length */ + int header; /* true if block header must be written */ +{ + bi_windup(s); /* align on byte boundary */ + s->last_eob_len = 8; /* enough lookahead for inflate */ + + if (header) { + put_short(s, (ush)len); + put_short(s, (ush)~len); +#ifdef DEBUG + s->bits_sent += 2*16; +#endif + } +#ifdef DEBUG + s->bits_sent += (ulg)len<<3; +#endif + while (len--) { + put_byte(s, *buf++); + } +} ADDED zlib/trees.h Index: zlib/trees.h ================================================================== --- zlib/trees.h +++ zlib/trees.h @@ -0,0 +1,128 @@ +/* header created automatically with -DGEN_TREES_H */ + +local const ct_data static_ltree[L_CODES+2] = { +{{ 12},{ 8}}, {{140},{ 8}}, {{ 76},{ 8}}, {{204},{ 8}}, {{ 44},{ 8}}, +{{172},{ 8}}, {{108},{ 8}}, {{236},{ 8}}, {{ 28},{ 8}}, {{156},{ 8}}, +{{ 92},{ 8}}, {{220},{ 8}}, {{ 60},{ 8}}, {{188},{ 8}}, {{124},{ 8}}, +{{252},{ 8}}, {{ 2},{ 8}}, {{130},{ 8}}, {{ 66},{ 8}}, {{194},{ 8}}, +{{ 34},{ 8}}, {{162},{ 8}}, {{ 98},{ 8}}, {{226},{ 8}}, {{ 18},{ 8}}, +{{146},{ 8}}, {{ 82},{ 8}}, {{210},{ 8}}, {{ 50},{ 8}}, {{178},{ 8}}, +{{114},{ 8}}, {{242},{ 8}}, {{ 10},{ 8}}, {{138},{ 8}}, {{ 74},{ 8}}, +{{202},{ 8}}, {{ 42},{ 8}}, {{170},{ 8}}, {{106},{ 8}}, {{234},{ 8}}, +{{ 26},{ 8}}, {{154},{ 8}}, {{ 90},{ 8}}, {{218},{ 8}}, {{ 58},{ 8}}, +{{186},{ 8}}, {{122},{ 8}}, {{250},{ 8}}, {{ 6},{ 8}}, {{134},{ 8}}, +{{ 70},{ 8}}, {{198},{ 8}}, {{ 38},{ 8}}, {{166},{ 8}}, {{102},{ 8}}, +{{230},{ 8}}, {{ 22},{ 8}}, {{150},{ 8}}, {{ 86},{ 8}}, {{214},{ 8}}, +{{ 54},{ 8}}, {{182},{ 8}}, {{118},{ 8}}, {{246},{ 8}}, {{ 14},{ 8}}, +{{142},{ 8}}, {{ 78},{ 8}}, {{206},{ 8}}, {{ 46},{ 8}}, {{174},{ 8}}, +{{110},{ 8}}, {{238},{ 8}}, {{ 30},{ 8}}, {{158},{ 8}}, {{ 94},{ 8}}, +{{222},{ 8}}, {{ 62},{ 8}}, {{190},{ 8}}, {{126},{ 8}}, {{254},{ 8}}, +{{ 1},{ 8}}, {{129},{ 8}}, {{ 65},{ 8}}, {{193},{ 8}}, {{ 33},{ 8}}, +{{161},{ 8}}, {{ 97},{ 8}}, {{225},{ 8}}, {{ 17},{ 8}}, {{145},{ 8}}, +{{ 81},{ 8}}, {{209},{ 8}}, {{ 49},{ 8}}, {{177},{ 8}}, {{113},{ 8}}, +{{241},{ 8}}, {{ 9},{ 8}}, {{137},{ 8}}, {{ 73},{ 8}}, {{201},{ 8}}, +{{ 41},{ 8}}, {{169},{ 8}}, {{105},{ 8}}, {{233},{ 8}}, {{ 25},{ 8}}, +{{153},{ 8}}, {{ 89},{ 8}}, {{217},{ 8}}, {{ 57},{ 8}}, {{185},{ 8}}, +{{121},{ 8}}, {{249},{ 8}}, {{ 5},{ 8}}, {{133},{ 8}}, {{ 69},{ 8}}, +{{197},{ 8}}, {{ 37},{ 8}}, {{165},{ 8}}, {{101},{ 8}}, {{229},{ 8}}, +{{ 21},{ 8}}, {{149},{ 8}}, {{ 85},{ 8}}, {{213},{ 8}}, {{ 53},{ 8}}, +{{181},{ 8}}, {{117},{ 8}}, {{245},{ 8}}, {{ 13},{ 8}}, {{141},{ 8}}, +{{ 77},{ 8}}, {{205},{ 8}}, {{ 45},{ 8}}, {{173},{ 8}}, {{109},{ 8}}, +{{237},{ 8}}, {{ 29},{ 8}}, {{157},{ 8}}, {{ 93},{ 8}}, {{221},{ 8}}, +{{ 61},{ 8}}, {{189},{ 8}}, {{125},{ 8}}, {{253},{ 8}}, {{ 19},{ 9}}, +{{275},{ 9}}, {{147},{ 9}}, {{403},{ 9}}, {{ 83},{ 9}}, {{339},{ 9}}, +{{211},{ 9}}, {{467},{ 9}}, {{ 51},{ 9}}, {{307},{ 9}}, {{179},{ 9}}, +{{435},{ 9}}, {{115},{ 9}}, {{371},{ 9}}, {{243},{ 9}}, {{499},{ 9}}, +{{ 11},{ 9}}, {{267},{ 9}}, {{139},{ 9}}, {{395},{ 9}}, {{ 75},{ 9}}, +{{331},{ 9}}, {{203},{ 9}}, {{459},{ 9}}, {{ 43},{ 9}}, {{299},{ 9}}, +{{171},{ 9}}, {{427},{ 9}}, {{107},{ 9}}, {{363},{ 9}}, {{235},{ 9}}, +{{491},{ 9}}, {{ 27},{ 9}}, {{283},{ 9}}, {{155},{ 9}}, {{411},{ 9}}, +{{ 91},{ 9}}, {{347},{ 9}}, {{219},{ 9}}, {{475},{ 9}}, {{ 59},{ 9}}, +{{315},{ 9}}, {{187},{ 9}}, {{443},{ 9}}, {{123},{ 9}}, {{379},{ 9}}, +{{251},{ 9}}, {{507},{ 9}}, {{ 7},{ 9}}, {{263},{ 9}}, {{135},{ 9}}, +{{391},{ 9}}, {{ 71},{ 9}}, {{327},{ 9}}, {{199},{ 9}}, {{455},{ 9}}, +{{ 39},{ 9}}, {{295},{ 9}}, {{167},{ 9}}, {{423},{ 9}}, {{103},{ 9}}, +{{359},{ 9}}, {{231},{ 9}}, {{487},{ 9}}, {{ 23},{ 9}}, {{279},{ 9}}, +{{151},{ 9}}, {{407},{ 9}}, {{ 87},{ 9}}, {{343},{ 9}}, {{215},{ 9}}, +{{471},{ 9}}, {{ 55},{ 9}}, {{311},{ 9}}, {{183},{ 9}}, {{439},{ 9}}, +{{119},{ 9}}, {{375},{ 9}}, {{247},{ 9}}, {{503},{ 9}}, {{ 15},{ 9}}, +{{271},{ 9}}, {{143},{ 9}}, {{399},{ 9}}, {{ 79},{ 9}}, {{335},{ 9}}, +{{207},{ 9}}, {{463},{ 9}}, {{ 47},{ 9}}, {{303},{ 9}}, {{175},{ 9}}, +{{431},{ 9}}, {{111},{ 9}}, {{367},{ 9}}, {{239},{ 9}}, {{495},{ 9}}, +{{ 31},{ 9}}, {{287},{ 9}}, {{159},{ 9}}, {{415},{ 9}}, {{ 95},{ 9}}, +{{351},{ 9}}, {{223},{ 9}}, {{479},{ 9}}, {{ 63},{ 9}}, {{319},{ 9}}, +{{191},{ 9}}, {{447},{ 9}}, {{127},{ 9}}, {{383},{ 9}}, {{255},{ 9}}, +{{511},{ 9}}, {{ 0},{ 7}}, {{ 64},{ 7}}, {{ 32},{ 7}}, {{ 96},{ 7}}, +{{ 16},{ 7}}, {{ 80},{ 7}}, {{ 48},{ 7}}, {{112},{ 7}}, {{ 8},{ 7}}, +{{ 72},{ 7}}, {{ 40},{ 7}}, {{104},{ 7}}, {{ 24},{ 7}}, {{ 88},{ 7}}, +{{ 56},{ 7}}, {{120},{ 7}}, {{ 4},{ 7}}, {{ 68},{ 7}}, {{ 36},{ 7}}, +{{100},{ 7}}, {{ 20},{ 7}}, {{ 84},{ 7}}, {{ 52},{ 7}}, {{116},{ 7}}, +{{ 3},{ 8}}, {{131},{ 8}}, {{ 67},{ 8}}, {{195},{ 8}}, {{ 35},{ 8}}, +{{163},{ 8}}, {{ 99},{ 8}}, {{227},{ 8}} +}; + +local const ct_data static_dtree[D_CODES] = { +{{ 0},{ 5}}, {{16},{ 5}}, {{ 8},{ 5}}, {{24},{ 5}}, {{ 4},{ 5}}, +{{20},{ 5}}, {{12},{ 5}}, {{28},{ 5}}, {{ 2},{ 5}}, {{18},{ 5}}, +{{10},{ 5}}, {{26},{ 5}}, {{ 6},{ 5}}, {{22},{ 5}}, {{14},{ 5}}, +{{30},{ 5}}, {{ 1},{ 5}}, {{17},{ 5}}, {{ 9},{ 5}}, {{25},{ 5}}, +{{ 5},{ 5}}, {{21},{ 5}}, {{13},{ 5}}, {{29},{ 5}}, {{ 3},{ 5}}, +{{19},{ 5}}, {{11},{ 5}}, {{27},{ 5}}, {{ 7},{ 5}}, {{23},{ 5}} +}; + +const uch _dist_code[DIST_CODE_LEN] = { + 0, 1, 2, 3, 4, 4, 5, 5, 6, 6, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, + 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 10, 10, 10, 10, 10, 10, 10, 10, +10, 10, 10, 10, 10, 10, 10, 10, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, +11, 11, 11, 11, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, +12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 13, 13, 13, 13, +13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, +13, 13, 13, 13, 13, 13, 13, 13, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, +14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, +14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, +14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 15, 15, 15, 15, 15, 15, 15, 15, +15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, +15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, +15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 0, 0, 16, 17, +18, 18, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 22, 22, 22, 22, 22, 22, 22, 22, +23, 23, 23, 23, 23, 23, 23, 23, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, +24, 24, 24, 24, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, +26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, +26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 27, 27, 27, 27, 27, 27, 27, 27, +27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, +27, 27, 27, 27, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, +28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, +28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, +28, 28, 28, 28, 28, 28, 28, 28, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, +29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, +29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, +29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29 +}; + +const uch _length_code[MAX_MATCH-MIN_MATCH+1]= { + 0, 1, 2, 3, 4, 5, 6, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 12, 12, +13, 13, 13, 13, 14, 14, 14, 14, 15, 15, 15, 15, 16, 16, 16, 16, 16, 16, 16, 16, +17, 17, 17, 17, 17, 17, 17, 17, 18, 18, 18, 18, 18, 18, 18, 18, 19, 19, 19, 19, +19, 19, 19, 19, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, +21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 22, 22, 22, 22, +22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 23, 23, 23, 23, 23, 23, 23, 23, +23, 23, 23, 23, 23, 23, 23, 23, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, +24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, +25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, +25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 26, 26, 26, 26, 26, 26, 26, 26, +26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, +26, 26, 26, 26, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, +27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 28 +}; + +local const int base_length[LENGTH_CODES] = { +0, 1, 2, 3, 4, 5, 6, 7, 8, 10, 12, 14, 16, 20, 24, 28, 32, 40, 48, 56, +64, 80, 96, 112, 128, 160, 192, 224, 0 +}; + +local const int base_dist[D_CODES] = { + 0, 1, 2, 3, 4, 6, 8, 12, 16, 24, + 32, 48, 64, 96, 128, 192, 256, 384, 512, 768, + 1024, 1536, 2048, 3072, 4096, 6144, 8192, 12288, 16384, 24576 +}; + ADDED zlib/uncompr.c Index: zlib/uncompr.c ================================================================== --- zlib/uncompr.c +++ zlib/uncompr.c @@ -0,0 +1,58 @@ +/* uncompr.c -- decompress a memory buffer + * Copyright (C) 1995-1998 Jean-loup Gailly. + * For conditions of distribution and use, see copyright notice in zlib.h + */ + +/* @(#) $Id$ */ + +#include "zlib.h" + +/* =========================================================================== + Decompresses the source buffer into the destination buffer. sourceLen is + the byte length of the source buffer. Upon entry, destLen is the total + size of the destination buffer, which must be large enough to hold the + entire uncompressed data. (The size of the uncompressed data must have + been saved previously by the compressor and transmitted to the decompressor + by some mechanism outside the scope of this compression library.) + Upon exit, destLen is the actual size of the compressed buffer. + This function can be used to decompress a whole file at once if the + input file is mmap'ed. + + uncompress returns Z_OK if success, Z_MEM_ERROR if there was not + enough memory, Z_BUF_ERROR if there was not enough room in the output + buffer, or Z_DATA_ERROR if the input data was corrupted. +*/ +int ZEXPORT uncompress (dest, destLen, source, sourceLen) + Bytef *dest; + uLongf *destLen; + const Bytef *source; + uLong sourceLen; +{ + z_stream stream; + int err; + + stream.next_in = (Bytef*)source; + stream.avail_in = (uInt)sourceLen; + /* Check for source > 64K on 16-bit machine: */ + if ((uLong)stream.avail_in != sourceLen) return Z_BUF_ERROR; + + stream.next_out = dest; + stream.avail_out = (uInt)*destLen; + if ((uLong)stream.avail_out != *destLen) return Z_BUF_ERROR; + + stream.zalloc = (alloc_func)0; + stream.zfree = (free_func)0; + + err = inflateInit(&stream); + if (err != Z_OK) return err; + + err = inflate(&stream, Z_FINISH); + if (err != Z_STREAM_END) { + inflateEnd(&stream); + return err == Z_OK ? Z_BUF_ERROR : err; + } + *destLen = stream.total_out; + + err = inflateEnd(&stream); + return err; +} ADDED zlib/zconf.h Index: zlib/zconf.h ================================================================== --- zlib/zconf.h +++ zlib/zconf.h @@ -0,0 +1,290 @@ + +/*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*/ +/*= This source is Modified a little by K.INABA. =*/ +/*= =*/ +/*= Since 'XacRett' doesn't compress, I removed =*/ +/*= compression codes by #ifdef KI_GZ_NO_COMPRESSION . =*/ +/*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*/ +#ifndef KI_GZ_NO_COMPRESSION +#define KI_GZ_NO_COMPRESSION +#endif + +/* zconf.h -- configuration of the zlib compression library + * Copyright (C) 1995-1998 Jean-loup Gailly. + * For conditions of distribution and use, see copyright notice in zlib.h + */ + +/* @(#) $Id$ */ + +#ifndef _ZCONF_H +#define _ZCONF_H + +/* + * If you *really* need a unique prefix for all types and library functions, + * compile with -DZ_PREFIX. The "standard" zlib should be compiled without it. + */ +#ifdef Z_PREFIX +# define deflateInit_ z_deflateInit_ +# define deflate z_deflate +# define deflateEnd z_deflateEnd +# define inflateInit_ z_inflateInit_ +# define inflate z_inflate +# define inflateEnd z_inflateEnd +# define deflateInit2_ z_deflateInit2_ +# define deflateSetDictionary z_deflateSetDictionary +# define deflateCopy z_deflateCopy +# define deflateReset z_deflateReset +# define deflateParams z_deflateParams +# define inflateInit2_ z_inflateInit2_ +# define inflateSetDictionary z_inflateSetDictionary +# define inflateSync z_inflateSync +# define inflateSyncPoint z_inflateSyncPoint +# define inflateReset z_inflateReset +# define compress z_compress +# define compress2 z_compress2 +# define uncompress z_uncompress +# define adler32 z_adler32 +# define crc32 z_crc32 +# define get_crc_table z_get_crc_table + +# define Byte z_Byte +# define uInt z_uInt +# define uLong z_uLong +# define Bytef z_Bytef +# define charf z_charf +# define intf z_intf +# define uIntf z_uIntf +# define uLongf z_uLongf +# define voidpf z_voidpf +# define voidp z_voidp +#endif + +#if (defined(_WIN32) || defined(__WIN32__)) && !defined(WIN32) +# define WIN32 +#endif +#if defined(__GNUC__) || defined(WIN32) || defined(__386__) || defined(i386) +# ifndef __32BIT__ +# define __32BIT__ +# endif +#endif +#if defined(__MSDOS__) && !defined(MSDOS) +# define MSDOS +#endif + +/* + * Compile with -DMAXSEG_64K if the alloc function cannot allocate more + * than 64k bytes at a time (needed on systems with 16-bit int). + */ +#if defined(MSDOS) && !defined(__32BIT__) +# define MAXSEG_64K +#endif +#ifdef MSDOS +# define UNALIGNED_OK +#endif + +#if (defined(MSDOS) || defined(_WINDOWS) || defined(WIN32)) && !defined(STDC) +# define STDC +#endif +#if defined(__STDC__) || defined(__cplusplus) || defined(__OS2__) +# ifndef STDC +# define STDC +# endif +#endif + +#ifndef STDC +# ifndef const /* cannot use !defined(STDC) && !defined(const) on Mac */ +# define const +# endif +#endif + +/* Some Mac compilers merge all .h files incorrectly: */ +#if defined(__MWERKS__) || defined(applec) ||defined(THINK_C) ||defined(__SC__) +# define NO_DUMMY_DECL +#endif + +/* Old Borland C incorrectly complains about missing returns: */ +#if defined(__BORLANDC__) && (__BORLANDC__ < 0x500) +# define NEED_DUMMY_RETURN +#endif + + +/* Maximum value for memLevel in deflateInit2 */ +#ifndef MAX_MEM_LEVEL +# ifdef MAXSEG_64K +# define MAX_MEM_LEVEL 8 +# else +# define MAX_MEM_LEVEL 9 +# endif +#endif + +/* Maximum value for windowBits in deflateInit2 and inflateInit2. + * WARNING: reducing MAX_WBITS makes minigzip unable to extract .gz files + * created by gzip. (Files created by minigzip can still be extracted by + * gzip.) + */ +#ifndef MAX_WBITS +# define MAX_WBITS 15 /* 32K LZ77 window */ +#endif + +/* The memory requirements for deflate are (in bytes): + (1 << (windowBits+2)) + (1 << (memLevel+9)) + that is: 128K for windowBits=15 + 128K for memLevel = 8 (default values) + plus a few kilobytes for small objects. For example, if you want to reduce + the default memory requirements from 256K to 128K, compile with + make CFLAGS="-O -DMAX_WBITS=14 -DMAX_MEM_LEVEL=7" + Of course this will generally degrade compression (there's no free lunch). + + The memory requirements for inflate are (in bytes) 1 << windowBits + that is, 32K for windowBits=15 (default value) plus a few kilobytes + for small objects. +*/ + + /* Type declarations */ + +#ifndef OF /* function prototypes */ +# ifdef STDC +# define OF(args) args +# else +# define OF(args) () +# endif +#endif + +/* The following definitions for FAR are needed only for MSDOS mixed + * model programming (small or medium model with some far allocations). + * This was tested only with MSC; for other MSDOS compilers you may have + * to define NO_MEMCPY in zutil.h. If you don't need the mixed model, + * just define FAR to be empty. + */ +#if (defined(M_I86SM) || defined(M_I86MM)) && !defined(__32BIT__) + /* MSC small or medium model */ +# define SMALL_MEDIUM +# ifdef _MSC_VER +# define FAR _far +# else +# define FAR far +# endif +#endif +#if defined(__BORLANDC__) && (defined(__SMALL__) || defined(__MEDIUM__)) +# ifndef __32BIT__ +# define SMALL_MEDIUM +# define FAR _far +# endif +#endif + +/* Compile with -DZLIB_DLL for Windows DLL support */ +#if defined(ZLIB_DLL) +# if defined(_WINDOWS) || defined(WINDOWS) +# ifdef FAR +# undef FAR +# endif +# include +# define ZEXPORT WINAPI +# ifdef WIN32 +# define ZEXPORTVA WINAPIV +# else +# define ZEXPORTVA FAR _cdecl _export +# endif +# endif +# if defined (__BORLANDC__) +# if (__BORLANDC__ >= 0x0500) && defined (WIN32) +# include +# define ZEXPORT __declspec(dllexport) WINAPI +# define ZEXPORTRVA __declspec(dllexport) WINAPIV +# else +# if defined (_Windows) && defined (__DLL__) +# define ZEXPORT _export +# define ZEXPORTVA _export +# endif +# endif +# endif +#endif + +#if defined (__BEOS__) +# if defined (ZLIB_DLL) +# define ZEXTERN extern __declspec(dllexport) +# else +# define ZEXTERN extern __declspec(dllimport) +# endif +#endif + +#ifndef ZEXPORT +# define ZEXPORT +#endif +#ifndef ZEXPORTVA +# define ZEXPORTVA +#endif +#ifndef ZEXTERN +# define ZEXTERN extern +#endif + +#ifndef FAR +# define FAR +#endif + +#if !defined(MACOS) && !defined(TARGET_OS_MAC) +typedef unsigned char Byte; /* 8 bits */ +#endif +typedef unsigned int uInt; /* 16 bits or more */ +typedef unsigned long uLong; /* 32 bits or more */ + +#ifdef SMALL_MEDIUM + /* Borland C/C++ and some old MSC versions ignore FAR inside typedef */ +# define Bytef Byte FAR +#else + typedef Byte FAR Bytef; +#endif +typedef char FAR charf; +typedef int FAR intf; +typedef uInt FAR uIntf; +typedef uLong FAR uLongf; + +#ifdef STDC + typedef void FAR *voidpf; + typedef void *voidp; +#else + typedef Byte FAR *voidpf; + typedef Byte *voidp; +#endif + +#ifdef HAVE_UNISTD_H +# include /* for off_t */ +# include /* for SEEK_* and off_t */ +# define z_off_t off_t +#endif +#ifndef SEEK_SET +# define SEEK_SET 0 /* Seek from beginning of file. */ +# define SEEK_CUR 1 /* Seek from current position. */ +# define SEEK_END 2 /* Set file pointer to EOF plus "offset" */ +#endif +#ifndef z_off_t +# define z_off_t long +#endif + +/* MVS linker does not support external names larger than 8 bytes */ +#if defined(__MVS__) +# pragma map(deflateInit_,"DEIN") +# pragma map(deflateInit2_,"DEIN2") +# pragma map(deflateEnd,"DEEND") +# pragma map(inflateInit_,"ININ") +# pragma map(inflateInit2_,"ININ2") +# pragma map(inflateEnd,"INEND") +# pragma map(inflateSync,"INSY") +# pragma map(inflateSetDictionary,"INSEDI") +# pragma map(inflate_blocks,"INBL") +# pragma map(inflate_blocks_new,"INBLNE") +# pragma map(inflate_blocks_free,"INBLFR") +# pragma map(inflate_blocks_reset,"INBLRE") +# pragma map(inflate_codes_free,"INCOFR") +# pragma map(inflate_codes,"INCO") +# pragma map(inflate_fast,"INFA") +# pragma map(inflate_flush,"INFLU") +# pragma map(inflate_mask,"INMA") +# pragma map(inflate_set_dictionary,"INSEDI2") +# pragma map(inflate_copyright,"INCOPY") +# pragma map(inflate_trees_bits,"INTRBI") +# pragma map(inflate_trees_dynamic,"INTRDY") +# pragma map(inflate_trees_fixed,"INTRFI") +# pragma map(inflate_trees_free,"INTRFR") +#endif + +#endif /* _ZCONF_H */ ADDED zlib/zlib.h Index: zlib/zlib.h ================================================================== --- zlib/zlib.h +++ zlib/zlib.h @@ -0,0 +1,928 @@ + +/*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*/ +/*= This source is Modified a little by K.INABA. =*/ +/*= =*/ +/*= Since 'XacRett' doesn't compress, I removed =*/ +/*= compression codes by #ifdef KI_GZ_NO_COMPRESSION . =*/ +/*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*/ +#ifndef KI_GZ_NO_COMPRESSION +#define KI_GZ_NO_COMPRESSION +#endif + +/* zlib.h -- interface of the 'zlib' general purpose compression library + version 1.1.3, July 9th, 1998 + + Copyright (C) 1995-1998 Jean-loup Gailly and Mark Adler + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. + + Jean-loup Gailly Mark Adler + jloup@gzip.org madler@alumni.caltech.edu + + + The data format used by the zlib library is described by RFCs (Request for + Comments) 1950 to 1952 in the files ftp://ds.internic.net/rfc/rfc1950.txt + (zlib format), rfc1951.txt (deflate format) and rfc1952.txt (gzip format). +*/ + +#ifndef _ZLIB_H +#define _ZLIB_H + +#include "zconf.h" + +#ifdef __cplusplus +extern "C" { +#endif + +#define ZLIB_VERSION "1.1.3" + +/* + The 'zlib' compression library provides in-memory compression and + decompression functions, including integrity checks of the uncompressed + data. This version of the library supports only one compression method + (deflation) but other algorithms will be added later and will have the same + stream interface. + + Compression can be done in a single step if the buffers are large + enough (for example if an input file is mmap'ed), or can be done by + repeated calls of the compression function. In the latter case, the + application must provide more input and/or consume the output + (providing more output space) before each call. + + The library also supports reading and writing files in gzip (.gz) format + with an interface similar to that of stdio. + + The library does not install any signal handler. The decoder checks + the consistency of the compressed data, so the library should never + crash even in case of corrupted input. +*/ + +typedef voidpf (*alloc_func) OF((voidpf opaque, uInt items, uInt size)); +typedef void (*free_func) OF((voidpf opaque, voidpf address)); + +struct internal_state; + +typedef struct z_stream_s { + Bytef *next_in; /* next input byte */ + uInt avail_in; /* number of bytes available at next_in */ + uLong total_in; /* total nb of input bytes read so far */ + + Bytef *next_out; /* next output byte should be put there */ + uInt avail_out; /* remaining free space at next_out */ + uLong total_out; /* total nb of bytes output so far */ + + char *msg; /* last error message, NULL if no error */ + struct internal_state FAR *state; /* not visible by applications */ + + alloc_func zalloc; /* used to allocate the internal state */ + free_func zfree; /* used to free the internal state */ + voidpf opaque; /* private data object passed to zalloc and zfree */ + + int data_type; /* best guess about the data type: ascii or binary */ + uLong adler; /* adler32 value of the uncompressed data */ + uLong reserved; /* reserved for future use */ +} z_stream; + +typedef z_stream FAR *z_streamp; + +/* + The application must update next_in and avail_in when avail_in has + dropped to zero. It must update next_out and avail_out when avail_out + has dropped to zero. The application must initialize zalloc, zfree and + opaque before calling the init function. All other fields are set by the + compression library and must not be updated by the application. + + The opaque value provided by the application will be passed as the first + parameter for calls of zalloc and zfree. This can be useful for custom + memory management. The compression library attaches no meaning to the + opaque value. + + zalloc must return Z_NULL if there is not enough memory for the object. + If zlib is used in a multi-threaded application, zalloc and zfree must be + thread safe. + + On 16-bit systems, the functions zalloc and zfree must be able to allocate + exactly 65536 bytes, but will not be required to allocate more than this + if the symbol MAXSEG_64K is defined (see zconf.h). WARNING: On MSDOS, + pointers returned by zalloc for objects of exactly 65536 bytes *must* + have their offset normalized to zero. The default allocation function + provided by this library ensures this (see zutil.c). To reduce memory + requirements and avoid any allocation of 64K objects, at the expense of + compression ratio, compile the library with -DMAX_WBITS=14 (see zconf.h). + + The fields total_in and total_out can be used for statistics or + progress reports. After compression, total_in holds the total size of + the uncompressed data and may be saved for use in the decompressor + (particularly if the decompressor wants to decompress everything in + a single step). +*/ + + /* constants */ + +#define Z_NO_FLUSH 0 +#define Z_PARTIAL_FLUSH 1 /* will be removed, use Z_SYNC_FLUSH instead */ +#define Z_SYNC_FLUSH 2 +#define Z_FULL_FLUSH 3 +#define Z_FINISH 4 +/* Allowed flush values; see deflate() below for details */ + +#define Z_OK 0 +#define Z_STREAM_END 1 +#define Z_NEED_DICT 2 +#define Z_ERRNO (-1) +#define Z_STREAM_ERROR (-2) +#define Z_DATA_ERROR (-3) +#define Z_MEM_ERROR (-4) +#define Z_BUF_ERROR (-5) +#define Z_VERSION_ERROR (-6) +/* Return codes for the compression/decompression functions. Negative + * values are errors, positive values are used for special but normal events. + */ + +#define Z_NO_COMPRESSION 0 +#define Z_BEST_SPEED 1 +#define Z_BEST_COMPRESSION 9 +#define Z_DEFAULT_COMPRESSION (-1) +/* compression levels */ + +#define Z_FILTERED 1 +#define Z_HUFFMAN_ONLY 2 +#define Z_DEFAULT_STRATEGY 0 +/* compression strategy; see deflateInit2() below for details */ + +#define Z_BINARY 0 +#define Z_ASCII 1 +#define Z_UNKNOWN 2 +/* Possible values of the data_type field */ + +#define Z_DEFLATED 8 +/* The deflate compression method (the only one supported in this version) */ + +#define Z_NULL 0 /* for initializing zalloc, zfree, opaque */ + +#define zlib_version zlibVersion() +/* for compatibility with versions < 1.0.2 */ + + /* basic functions */ + +ZEXTERN const char * ZEXPORT zlibVersion OF((void)); +/* The application can compare zlibVersion and ZLIB_VERSION for consistency. + If the first character differs, the library code actually used is + not compatible with the zlib.h header file used by the application. + This check is automatically made by deflateInit and inflateInit. + */ + +/* +ZEXTERN int ZEXPORT deflateInit OF((z_streamp strm, int level)); + + Initializes the internal stream state for compression. The fields + zalloc, zfree and opaque must be initialized before by the caller. + If zalloc and zfree are set to Z_NULL, deflateInit updates them to + use default allocation functions. + + The compression level must be Z_DEFAULT_COMPRESSION, or between 0 and 9: + 1 gives best speed, 9 gives best compression, 0 gives no compression at + all (the input data is simply copied a block at a time). + Z_DEFAULT_COMPRESSION requests a default compromise between speed and + compression (currently equivalent to level 6). + + deflateInit returns Z_OK if success, Z_MEM_ERROR if there was not + enough memory, Z_STREAM_ERROR if level is not a valid compression level, + Z_VERSION_ERROR if the zlib library version (zlib_version) is incompatible + with the version assumed by the caller (ZLIB_VERSION). + msg is set to null if there is no error message. deflateInit does not + perform any compression: this will be done by deflate(). +*/ + +#ifndef KI_GZ_NO_COMPRESSION + +ZEXTERN int ZEXPORT deflate OF((z_streamp strm, int flush)); +/* + deflate compresses as much data as possible, and stops when the input + buffer becomes empty or the output buffer becomes full. It may introduce some + output latency (reading input without producing any output) except when + forced to flush. + + The detailed semantics are as follows. deflate performs one or both of the + following actions: + + - Compress more input starting at next_in and update next_in and avail_in + accordingly. If not all input can be processed (because there is not + enough room in the output buffer), next_in and avail_in are updated and + processing will resume at this point for the next call of deflate(). + + - Provide more output starting at next_out and update next_out and avail_out + accordingly. This action is forced if the parameter flush is non zero. + Forcing flush frequently degrades the compression ratio, so this parameter + should be set only when necessary (in interactive applications). + Some output may be provided even if flush is not set. + + Before the call of deflate(), the application should ensure that at least + one of the actions is possible, by providing more input and/or consuming + more output, and updating avail_in or avail_out accordingly; avail_out + should never be zero before the call. The application can consume the + compressed output when it wants, for example when the output buffer is full + (avail_out == 0), or after each call of deflate(). If deflate returns Z_OK + and with zero avail_out, it must be called again after making room in the + output buffer because there might be more output pending. + + If the parameter flush is set to Z_SYNC_FLUSH, all pending output is + flushed to the output buffer and the output is aligned on a byte boundary, so + that the decompressor can get all input data available so far. (In particular + avail_in is zero after the call if enough output space has been provided + before the call.) Flushing may degrade compression for some compression + algorithms and so it should be used only when necessary. + + If flush is set to Z_FULL_FLUSH, all output is flushed as with + Z_SYNC_FLUSH, and the compression state is reset so that decompression can + restart from this point if previous compressed data has been damaged or if + random access is desired. Using Z_FULL_FLUSH too often can seriously degrade + the compression. + + If deflate returns with avail_out == 0, this function must be called again + with the same value of the flush parameter and more output space (updated + avail_out), until the flush is complete (deflate returns with non-zero + avail_out). + + If the parameter flush is set to Z_FINISH, pending input is processed, + pending output is flushed and deflate returns with Z_STREAM_END if there + was enough output space; if deflate returns with Z_OK, this function must be + called again with Z_FINISH and more output space (updated avail_out) but no + more input data, until it returns with Z_STREAM_END or an error. After + deflate has returned Z_STREAM_END, the only possible operations on the + stream are deflateReset or deflateEnd. + + Z_FINISH can be used immediately after deflateInit if all the compression + is to be done in a single step. In this case, avail_out must be at least + 0.1% larger than avail_in plus 12 bytes. If deflate does not return + Z_STREAM_END, then it must be called again as described above. + + deflate() sets strm->adler to the adler32 checksum of all input read + so far (that is, total_in bytes). + + deflate() may update data_type if it can make a good guess about + the input data type (Z_ASCII or Z_BINARY). In doubt, the data is considered + binary. This field is only for information purposes and does not affect + the compression algorithm in any manner. + + deflate() returns Z_OK if some progress has been made (more input + processed or more output produced), Z_STREAM_END if all input has been + consumed and all output has been produced (only when flush is set to + Z_FINISH), Z_STREAM_ERROR if the stream state was inconsistent (for example + if next_in or next_out was NULL), Z_BUF_ERROR if no progress is possible + (for example avail_in or avail_out was zero). +*/ + + +ZEXTERN int ZEXPORT deflateEnd OF((z_streamp strm)); +/* + All dynamically allocated data structures for this stream are freed. + This function discards any unprocessed input and does not flush any + pending output. + + deflateEnd returns Z_OK if success, Z_STREAM_ERROR if the + stream state was inconsistent, Z_DATA_ERROR if the stream was freed + prematurely (some input or output was discarded). In the error case, + msg may be set but then points to a static string (which must not be + deallocated). +*/ + +#endif /* KI_GZ_NO_COMPRESSION */ + +/* +ZEXTERN int ZEXPORT inflateInit OF((z_streamp strm)); + + Initializes the internal stream state for decompression. The fields + next_in, avail_in, zalloc, zfree and opaque must be initialized before by + the caller. If next_in is not Z_NULL and avail_in is large enough (the exact + value depends on the compression method), inflateInit determines the + compression method from the zlib header and allocates all data structures + accordingly; otherwise the allocation will be deferred to the first call of + inflate. If zalloc and zfree are set to Z_NULL, inflateInit updates them to + use default allocation functions. + + inflateInit returns Z_OK if success, Z_MEM_ERROR if there was not enough + memory, Z_VERSION_ERROR if the zlib library version is incompatible with the + version assumed by the caller. msg is set to null if there is no error + message. inflateInit does not perform any decompression apart from reading + the zlib header if present: this will be done by inflate(). (So next_in and + avail_in may be modified, but next_out and avail_out are unchanged.) +*/ + + +ZEXTERN int ZEXPORT inflate OF((z_streamp strm, int flush)); +/* + inflate decompresses as much data as possible, and stops when the input + buffer becomes empty or the output buffer becomes full. It may some + introduce some output latency (reading input without producing any output) + except when forced to flush. + + The detailed semantics are as follows. inflate performs one or both of the + following actions: + + - Decompress more input starting at next_in and update next_in and avail_in + accordingly. If not all input can be processed (because there is not + enough room in the output buffer), next_in is updated and processing + will resume at this point for the next call of inflate(). + + - Provide more output starting at next_out and update next_out and avail_out + accordingly. inflate() provides as much output as possible, until there + is no more input data or no more space in the output buffer (see below + about the flush parameter). + + Before the call of inflate(), the application should ensure that at least + one of the actions is possible, by providing more input and/or consuming + more output, and updating the next_* and avail_* values accordingly. + The application can consume the uncompressed output when it wants, for + example when the output buffer is full (avail_out == 0), or after each + call of inflate(). If inflate returns Z_OK and with zero avail_out, it + must be called again after making room in the output buffer because there + might be more output pending. + + If the parameter flush is set to Z_SYNC_FLUSH, inflate flushes as much + output as possible to the output buffer. The flushing behavior of inflate is + not specified for values of the flush parameter other than Z_SYNC_FLUSH + and Z_FINISH, but the current implementation actually flushes as much output + as possible anyway. + + inflate() should normally be called until it returns Z_STREAM_END or an + error. However if all decompression is to be performed in a single step + (a single call of inflate), the parameter flush should be set to + Z_FINISH. In this case all pending input is processed and all pending + output is flushed; avail_out must be large enough to hold all the + uncompressed data. (The size of the uncompressed data may have been saved + by the compressor for this purpose.) The next operation on this stream must + be inflateEnd to deallocate the decompression state. The use of Z_FINISH + is never required, but can be used to inform inflate that a faster routine + may be used for the single inflate() call. + + If a preset dictionary is needed at this point (see inflateSetDictionary + below), inflate sets strm-adler to the adler32 checksum of the + dictionary chosen by the compressor and returns Z_NEED_DICT; otherwise + it sets strm->adler to the adler32 checksum of all output produced + so far (that is, total_out bytes) and returns Z_OK, Z_STREAM_END or + an error code as described below. At the end of the stream, inflate() + checks that its computed adler32 checksum is equal to that saved by the + compressor and returns Z_STREAM_END only if the checksum is correct. + + inflate() returns Z_OK if some progress has been made (more input processed + or more output produced), Z_STREAM_END if the end of the compressed data has + been reached and all uncompressed output has been produced, Z_NEED_DICT if a + preset dictionary is needed at this point, Z_DATA_ERROR if the input data was + corrupted (input stream not conforming to the zlib format or incorrect + adler32 checksum), Z_STREAM_ERROR if the stream structure was inconsistent + (for example if next_in or next_out was NULL), Z_MEM_ERROR if there was not + enough memory, Z_BUF_ERROR if no progress is possible or if there was not + enough room in the output buffer when Z_FINISH is used. In the Z_DATA_ERROR + case, the application may then call inflateSync to look for a good + compression block. +*/ + + +ZEXTERN int ZEXPORT inflateEnd OF((z_streamp strm)); +/* + All dynamically allocated data structures for this stream are freed. + This function discards any unprocessed input and does not flush any + pending output. + + inflateEnd returns Z_OK if success, Z_STREAM_ERROR if the stream state + was inconsistent. In the error case, msg may be set but then points to a + static string (which must not be deallocated). +*/ + + /* Advanced functions */ + +/* + The following functions are needed only in some special applications. +*/ + +/* +ZEXTERN int ZEXPORT deflateInit2 OF((z_streamp strm, + int level, + int method, + int windowBits, + int memLevel, + int strategy)); + + This is another version of deflateInit with more compression options. The + fields next_in, zalloc, zfree and opaque must be initialized before by + the caller. + + The method parameter is the compression method. It must be Z_DEFLATED in + this version of the library. + + The windowBits parameter is the base two logarithm of the window size + (the size of the history buffer). It should be in the range 8..15 for this + version of the library. Larger values of this parameter result in better + compression at the expense of memory usage. The default value is 15 if + deflateInit is used instead. + + The memLevel parameter specifies how much memory should be allocated + for the internal compression state. memLevel=1 uses minimum memory but + is slow and reduces compression ratio; memLevel=9 uses maximum memory + for optimal speed. The default value is 8. See zconf.h for total memory + usage as a function of windowBits and memLevel. + + The strategy parameter is used to tune the compression algorithm. Use the + value Z_DEFAULT_STRATEGY for normal data, Z_FILTERED for data produced by a + filter (or predictor), or Z_HUFFMAN_ONLY to force Huffman encoding only (no + string match). Filtered data consists mostly of small values with a + somewhat random distribution. In this case, the compression algorithm is + tuned to compress them better. The effect of Z_FILTERED is to force more + Huffman coding and less string matching; it is somewhat intermediate + between Z_DEFAULT and Z_HUFFMAN_ONLY. The strategy parameter only affects + the compression ratio but not the correctness of the compressed output even + if it is not set appropriately. + + deflateInit2 returns Z_OK if success, Z_MEM_ERROR if there was not enough + memory, Z_STREAM_ERROR if a parameter is invalid (such as an invalid + method). msg is set to null if there is no error message. deflateInit2 does + not perform any compression: this will be done by deflate(). +*/ + +#ifndef KI_GZ_NO_COMPRESSION + +ZEXTERN int ZEXPORT deflateSetDictionary OF((z_streamp strm, + const Bytef *dictionary, + uInt dictLength)); +/* + Initializes the compression dictionary from the given byte sequence + without producing any compressed output. This function must be called + immediately after deflateInit, deflateInit2 or deflateReset, before any + call of deflate. The compressor and decompressor must use exactly the same + dictionary (see inflateSetDictionary). + + The dictionary should consist of strings (byte sequences) that are likely + to be encountered later in the data to be compressed, with the most commonly + used strings preferably put towards the end of the dictionary. Using a + dictionary is most useful when the data to be compressed is short and can be + predicted with good accuracy; the data can then be compressed better than + with the default empty dictionary. + + Depending on the size of the compression data structures selected by + deflateInit or deflateInit2, a part of the dictionary may in effect be + discarded, for example if the dictionary is larger than the window size in + deflate or deflate2. Thus the strings most likely to be useful should be + put at the end of the dictionary, not at the front. + + Upon return of this function, strm->adler is set to the Adler32 value + of the dictionary; the decompressor may later use this value to determine + which dictionary has been used by the compressor. (The Adler32 value + applies to the whole dictionary even if only a subset of the dictionary is + actually used by the compressor.) + + deflateSetDictionary returns Z_OK if success, or Z_STREAM_ERROR if a + parameter is invalid (such as NULL dictionary) or the stream state is + inconsistent (for example if deflate has already been called for this stream + or if the compression method is bsort). deflateSetDictionary does not + perform any compression: this will be done by deflate(). +*/ + +ZEXTERN int ZEXPORT deflateCopy OF((z_streamp dest, + z_streamp source)); +/* + Sets the destination stream as a complete copy of the source stream. + + This function can be useful when several compression strategies will be + tried, for example when there are several ways of pre-processing the input + data with a filter. The streams that will be discarded should then be freed + by calling deflateEnd. Note that deflateCopy duplicates the internal + compression state which can be quite large, so this strategy is slow and + can consume lots of memory. + + deflateCopy returns Z_OK if success, Z_MEM_ERROR if there was not + enough memory, Z_STREAM_ERROR if the source stream state was inconsistent + (such as zalloc being NULL). msg is left unchanged in both source and + destination. +*/ + +ZEXTERN int ZEXPORT deflateReset OF((z_streamp strm)); +/* + This function is equivalent to deflateEnd followed by deflateInit, + but does not free and reallocate all the internal compression state. + The stream will keep the same compression level and any other attributes + that may have been set by deflateInit2. + + deflateReset returns Z_OK if success, or Z_STREAM_ERROR if the source + stream state was inconsistent (such as zalloc or state being NULL). +*/ + +ZEXTERN int ZEXPORT deflateParams OF((z_streamp strm, + int level, + int strategy)); +/* + Dynamically update the compression level and compression strategy. The + interpretation of level and strategy is as in deflateInit2. This can be + used to switch between compression and straight copy of the input data, or + to switch to a different kind of input data requiring a different + strategy. If the compression level is changed, the input available so far + is compressed with the old level (and may be flushed); the new level will + take effect only at the next call of deflate(). + + Before the call of deflateParams, the stream state must be set as for + a call of deflate(), since the currently available input may have to + be compressed and flushed. In particular, strm->avail_out must be non-zero. + + deflateParams returns Z_OK if success, Z_STREAM_ERROR if the source + stream state was inconsistent or if a parameter was invalid, Z_BUF_ERROR + if strm->avail_out was zero. +*/ + +#endif /* KI_GZ_NO_COMPRESSION */ + +/* +ZEXTERN int ZEXPORT inflateInit2 OF((z_streamp strm, + int windowBits)); + + This is another version of inflateInit with an extra parameter. The + fields next_in, avail_in, zalloc, zfree and opaque must be initialized + before by the caller. + + The windowBits parameter is the base two logarithm of the maximum window + size (the size of the history buffer). It should be in the range 8..15 for + this version of the library. The default value is 15 if inflateInit is used + instead. If a compressed stream with a larger window size is given as + input, inflate() will return with the error code Z_DATA_ERROR instead of + trying to allocate a larger window. + + inflateInit2 returns Z_OK if success, Z_MEM_ERROR if there was not enough + memory, Z_STREAM_ERROR if a parameter is invalid (such as a negative + memLevel). msg is set to null if there is no error message. inflateInit2 + does not perform any decompression apart from reading the zlib header if + present: this will be done by inflate(). (So next_in and avail_in may be + modified, but next_out and avail_out are unchanged.) +*/ + +ZEXTERN int ZEXPORT inflateSetDictionary OF((z_streamp strm, + const Bytef *dictionary, + uInt dictLength)); +/* + Initializes the decompression dictionary from the given uncompressed byte + sequence. This function must be called immediately after a call of inflate + if this call returned Z_NEED_DICT. The dictionary chosen by the compressor + can be determined from the Adler32 value returned by this call of + inflate. The compressor and decompressor must use exactly the same + dictionary (see deflateSetDictionary). + + inflateSetDictionary returns Z_OK if success, Z_STREAM_ERROR if a + parameter is invalid (such as NULL dictionary) or the stream state is + inconsistent, Z_DATA_ERROR if the given dictionary doesn't match the + expected one (incorrect Adler32 value). inflateSetDictionary does not + perform any decompression: this will be done by subsequent calls of + inflate(). +*/ + +ZEXTERN int ZEXPORT inflateSync OF((z_streamp strm)); +/* + Skips invalid compressed data until a full flush point (see above the + description of deflate with Z_FULL_FLUSH) can be found, or until all + available input is skipped. No output is provided. + + inflateSync returns Z_OK if a full flush point has been found, Z_BUF_ERROR + if no more input was provided, Z_DATA_ERROR if no flush point has been found, + or Z_STREAM_ERROR if the stream structure was inconsistent. In the success + case, the application may save the current current value of total_in which + indicates where valid compressed data was found. In the error case, the + application may repeatedly call inflateSync, providing more input each time, + until success or end of the input data. +*/ + +ZEXTERN int ZEXPORT inflateReset OF((z_streamp strm)); +/* + This function is equivalent to inflateEnd followed by inflateInit, + but does not free and reallocate all the internal decompression state. + The stream will keep attributes that may have been set by inflateInit2. + + inflateReset returns Z_OK if success, or Z_STREAM_ERROR if the source + stream state was inconsistent (such as zalloc or state being NULL). +*/ + + + /* utility functions */ + +/* + The following utility functions are implemented on top of the + basic stream-oriented functions. To simplify the interface, some + default options are assumed (compression level and memory usage, + standard memory allocation functions). The source code of these + utility functions can easily be modified if you need special options. +*/ + +#ifndef KI_GZ_NO_COMPRESSION + +ZEXTERN int ZEXPORT compress OF((Bytef *dest, uLongf *destLen, + const Bytef *source, uLong sourceLen)); +/* + Compresses the source buffer into the destination buffer. sourceLen is + the byte length of the source buffer. Upon entry, destLen is the total + size of the destination buffer, which must be at least 0.1% larger than + sourceLen plus 12 bytes. Upon exit, destLen is the actual size of the + compressed buffer. + This function can be used to compress a whole file at once if the + input file is mmap'ed. + compress returns Z_OK if success, Z_MEM_ERROR if there was not + enough memory, Z_BUF_ERROR if there was not enough room in the output + buffer. +*/ + +ZEXTERN int ZEXPORT compress2 OF((Bytef *dest, uLongf *destLen, + const Bytef *source, uLong sourceLen, + int level)); +/* + Compresses the source buffer into the destination buffer. The level + parameter has the same meaning as in deflateInit. sourceLen is the byte + length of the source buffer. Upon entry, destLen is the total size of the + destination buffer, which must be at least 0.1% larger than sourceLen plus + 12 bytes. Upon exit, destLen is the actual size of the compressed buffer. + + compress2 returns Z_OK if success, Z_MEM_ERROR if there was not enough + memory, Z_BUF_ERROR if there was not enough room in the output buffer, + Z_STREAM_ERROR if the level parameter is invalid. +*/ + +#endif /* KI_GZ_NO_COMPRESSION */ + +ZEXTERN int ZEXPORT uncompress OF((Bytef *dest, uLongf *destLen, + const Bytef *source, uLong sourceLen)); +/* + Decompresses the source buffer into the destination buffer. sourceLen is + the byte length of the source buffer. Upon entry, destLen is the total + size of the destination buffer, which must be large enough to hold the + entire uncompressed data. (The size of the uncompressed data must have + been saved previously by the compressor and transmitted to the decompressor + by some mechanism outside the scope of this compression library.) + Upon exit, destLen is the actual size of the compressed buffer. + This function can be used to decompress a whole file at once if the + input file is mmap'ed. + + uncompress returns Z_OK if success, Z_MEM_ERROR if there was not + enough memory, Z_BUF_ERROR if there was not enough room in the output + buffer, or Z_DATA_ERROR if the input data was corrupted. +*/ + + +typedef voidp gzFile; + +ZEXTERN gzFile ZEXPORT gzopen OF((const char *path, const char *mode)); +/* + Opens a gzip (.gz) file for reading or writing. The mode parameter + is as in fopen ("rb" or "wb") but can also include a compression level + ("wb9") or a strategy: 'f' for filtered data as in "wb6f", 'h' for + Huffman only compression as in "wb1h". (See the description + of deflateInit2 for more information about the strategy parameter.) + + gzopen can be used to read a file which is not in gzip format; in this + case gzread will directly read from the file without decompression. + + gzopen returns NULL if the file could not be opened or if there was + insufficient memory to allocate the (de)compression state; errno + can be checked to distinguish the two cases (if errno is zero, the + zlib error is Z_MEM_ERROR). */ + +ZEXTERN gzFile ZEXPORT gzdopen OF((int fd, const char *mode)); +/* + gzdopen() associates a gzFile with the file descriptor fd. File + descriptors are obtained from calls like open, dup, creat, pipe or + fileno (in the file has been previously opened with fopen). + The mode parameter is as in gzopen. + The next call of gzclose on the returned gzFile will also close the + file descriptor fd, just like fclose(fdopen(fd), mode) closes the file + descriptor fd. If you want to keep fd open, use gzdopen(dup(fd), mode). + gzdopen returns NULL if there was insufficient memory to allocate + the (de)compression state. +*/ + +ZEXTERN int ZEXPORT gzsetparams OF((gzFile file, int level, int strategy)); +/* + Dynamically update the compression level or strategy. See the description + of deflateInit2 for the meaning of these parameters. + gzsetparams returns Z_OK if success, or Z_STREAM_ERROR if the file was not + opened for writing. +*/ + +ZEXTERN int ZEXPORT gzread OF((gzFile file, voidp buf, unsigned len)); +/* + Reads the given number of uncompressed bytes from the compressed file. + If the input file was not in gzip format, gzread copies the given number + of bytes into the buffer. + gzread returns the number of uncompressed bytes actually read (0 for + end of file, -1 for error). */ + +#ifndef KI_GZ_NO_COMPRESSION + +ZEXTERN int ZEXPORT gzwrite OF((gzFile file, + const voidp buf, unsigned len)); +/* + Writes the given number of uncompressed bytes into the compressed file. + gzwrite returns the number of uncompressed bytes actually written + (0 in case of error). +*/ + +ZEXTERN int ZEXPORTVA gzprintf OF((gzFile file, const char *format, ...)); +/* + Converts, formats, and writes the args to the compressed file under + control of the format string, as in fprintf. gzprintf returns the number of + uncompressed bytes actually written (0 in case of error). +*/ + +ZEXTERN int ZEXPORT gzputs OF((gzFile file, const char *s)); +/* + Writes the given null-terminated string to the compressed file, excluding + the terminating null character. + gzputs returns the number of characters written, or -1 in case of error. +*/ + +#endif /* KI_GZ_NO_COMPRESSION */ + +ZEXTERN char * ZEXPORT gzgets OF((gzFile file, char *buf, int len)); +/* + Reads bytes from the compressed file until len-1 characters are read, or + a newline character is read and transferred to buf, or an end-of-file + condition is encountered. The string is then terminated with a null + character. + gzgets returns buf, or Z_NULL in case of error. +*/ + +#ifdef KI_GZ_NO_COMPRESSION + +ZEXTERN int ZEXPORT gzputc OF((gzFile file, int c)); +/* + Writes c, converted to an unsigned char, into the compressed file. + gzputc returns the value that was written, or -1 in case of error. +*/ + +#endif /* KI_GZ_NO_COMPRESSION */ + +ZEXTERN int ZEXPORT gzgetc OF((gzFile file)); +/* + Reads one byte from the compressed file. gzgetc returns this byte + or -1 in case of end of file or error. +*/ + +#ifndef KI_GZ_NO_COMPRESSION +ZEXTERN int ZEXPORT gzflush OF((gzFile file, int flush)); +/* + Flushes all pending output into the compressed file. The parameter + flush is as in the deflate() function. The return value is the zlib + error number (see function gzerror below). gzflush returns Z_OK if + the flush parameter is Z_FINISH and all output could be flushed. + gzflush should be called only when strictly necessary because it can + degrade compression. +*/ +#endif /* KI_GZ_NO_COMPRESSION */ + +ZEXTERN z_off_t ZEXPORT gzseek OF((gzFile file, + z_off_t offset, int whence)); +/* + Sets the starting position for the next gzread or gzwrite on the + given compressed file. The offset represents a number of bytes in the + uncompressed data stream. The whence parameter is defined as in lseek(2); + the value SEEK_END is not supported. + If the file is opened for reading, this function is emulated but can be + extremely slow. If the file is opened for writing, only forward seeks are + supported; gzseek then compresses a sequence of zeroes up to the new + starting position. + + gzseek returns the resulting offset location as measured in bytes from + the beginning of the uncompressed stream, or -1 in case of error, in + particular if the file is opened for writing and the new starting position + would be before the current position. +*/ + +ZEXTERN int ZEXPORT gzrewind OF((gzFile file)); +/* + Rewinds the given file. This function is supported only for reading. + + gzrewind(file) is equivalent to (int)gzseek(file, 0L, SEEK_SET) +*/ + +ZEXTERN z_off_t ZEXPORT gztell OF((gzFile file)); +/* + Returns the starting position for the next gzread or gzwrite on the + given compressed file. This position represents a number of bytes in the + uncompressed data stream. + + gztell(file) is equivalent to gzseek(file, 0L, SEEK_CUR) +*/ + +ZEXTERN int ZEXPORT gzeof OF((gzFile file)); +/* + Returns 1 when EOF has previously been detected reading the given + input stream, otherwise zero. +*/ + +ZEXTERN int ZEXPORT gzclose OF((gzFile file)); +/* + Flushes all pending output if necessary, closes the compressed file + and deallocates all the (de)compression state. The return value is the zlib + error number (see function gzerror below). +*/ + +ZEXTERN const char * ZEXPORT gzerror OF((gzFile file, int *errnum)); +/* + Returns the error message for the last error which occurred on the + given compressed file. errnum is set to zlib error number. If an + error occurred in the file system and not in the compression library, + errnum is set to Z_ERRNO and the application may consult errno + to get the exact error code. +*/ + + /* checksum functions */ + +/* + These functions are not related to compression but are exported + anyway because they might be useful in applications using the + compression library. +*/ + +ZEXTERN uLong ZEXPORT adler32 OF((uLong adler, const Bytef *buf, uInt len)); + +/* + Update a running Adler-32 checksum with the bytes buf[0..len-1] and + return the updated checksum. If buf is NULL, this function returns + the required initial value for the checksum. + An Adler-32 checksum is almost as reliable as a CRC32 but can be computed + much faster. Usage example: + + uLong adler = adler32(0L, Z_NULL, 0); + + while (read_buffer(buffer, length) != EOF) { + adler = adler32(adler, buffer, length); + } + if (adler != original_adler) error(); +*/ + +ZEXTERN uLong ZEXPORT crc32 OF((uLong crc, const Bytef *buf, uInt len)); +/* + Update a running crc with the bytes buf[0..len-1] and return the updated + crc. If buf is NULL, this function returns the required initial value + for the crc. Pre- and post-conditioning (one's complement) is performed + within this function so it shouldn't be done by the application. + Usage example: + + uLong crc = crc32(0L, Z_NULL, 0); + + while (read_buffer(buffer, length) != EOF) { + crc = crc32(crc, buffer, length); + } + if (crc != original_crc) error(); +*/ + + + /* various hacks, don't look :) */ + +/* deflateInit and inflateInit are macros to allow checking the zlib version + * and the compiler's view of z_stream: + */ +#ifndef KI_GZ_NO_COMPRESSION +ZEXTERN int ZEXPORT deflateInit_ OF((z_streamp strm, int level, + const char *version, int stream_size)); +#endif /* KI_GZ_NO_COMPRESSION */ +ZEXTERN int ZEXPORT inflateInit_ OF((z_streamp strm, + const char *version, int stream_size)); +#ifndef KI_GZ_NO_COMPRESSION +ZEXTERN int ZEXPORT deflateInit2_ OF((z_streamp strm, int level, int method, + int windowBits, int memLevel, + int strategy, const char *version, + int stream_size)); +#endif /* KI_GZ_NO_COMPRESSION */ +ZEXTERN int ZEXPORT inflateInit2_ OF((z_streamp strm, int windowBits, + const char *version, int stream_size)); +#define deflateInit(strm, level) \ + deflateInit_((strm), (level), ZLIB_VERSION, sizeof(z_stream)) +#define inflateInit(strm) \ + inflateInit_((strm), ZLIB_VERSION, sizeof(z_stream)) +#define deflateInit2(strm, level, method, windowBits, memLevel, strategy) \ + deflateInit2_((strm),(level),(method),(windowBits),(memLevel),\ + (strategy), ZLIB_VERSION, sizeof(z_stream)) +#define inflateInit2(strm, windowBits) \ + inflateInit2_((strm), (windowBits), ZLIB_VERSION, sizeof(z_stream)) + + +#if !defined(_Z_UTIL_H) && !defined(NO_DUMMY_DECL) + struct internal_state {int dummy;}; /* hack for buggy compilers */ +#endif + +ZEXTERN const char * ZEXPORT zError OF((int err)); +ZEXTERN int ZEXPORT inflateSyncPoint OF((z_streamp z)); +ZEXTERN const uLongf * ZEXPORT get_crc_table OF((void)); + +#ifdef __cplusplus +} +#endif + +#endif /* _ZLIB_H */ ADDED zlib/zutil.c Index: zlib/zutil.c ================================================================== --- zlib/zutil.c +++ zlib/zutil.c @@ -0,0 +1,225 @@ +/* zutil.c -- target dependent utility functions for the compression library + * Copyright (C) 1995-1998 Jean-loup Gailly. + * For conditions of distribution and use, see copyright notice in zlib.h + */ + +/* @(#) $Id$ */ + +#include "zutil.h" + +struct internal_state {int dummy;}; /* for buggy compilers */ + +#ifndef STDC +extern void exit OF((int)); +#endif + +const char *z_errmsg[10] = { +"need dictionary", /* Z_NEED_DICT 2 */ +"stream end", /* Z_STREAM_END 1 */ +"", /* Z_OK 0 */ +"file error", /* Z_ERRNO (-1) */ +"stream error", /* Z_STREAM_ERROR (-2) */ +"data error", /* Z_DATA_ERROR (-3) */ +"insufficient memory", /* Z_MEM_ERROR (-4) */ +"buffer error", /* Z_BUF_ERROR (-5) */ +"incompatible version",/* Z_VERSION_ERROR (-6) */ +""}; + + +const char * ZEXPORT zlibVersion() +{ + return ZLIB_VERSION; +} + +#ifdef DEBUG + +# ifndef verbose +# define verbose 0 +# endif +int z_verbose = verbose; + +void z_error (m) + char *m; +{ + fprintf(stderr, "%s\n", m); + exit(1); +} +#endif + +/* exported to allow conversion of error code to string for compress() and + * uncompress() + */ +const char * ZEXPORT zError(err) + int err; +{ + return ERR_MSG(err); +} + + +#ifndef HAVE_MEMCPY + +void zmemcpy(dest, source, len) + Bytef* dest; + const Bytef* source; + uInt len; +{ + if (len == 0) return; + do { + *dest++ = *source++; /* ??? to be unrolled */ + } while (--len != 0); +} + +int zmemcmp(s1, s2, len) + const Bytef* s1; + const Bytef* s2; + uInt len; +{ + uInt j; + + for (j = 0; j < len; j++) { + if (s1[j] != s2[j]) return 2*(s1[j] > s2[j])-1; + } + return 0; +} + +void zmemzero(dest, len) + Bytef* dest; + uInt len; +{ + if (len == 0) return; + do { + *dest++ = 0; /* ??? to be unrolled */ + } while (--len != 0); +} +#endif + +#ifdef __TURBOC__ +#if (defined( __BORLANDC__) || !defined(SMALL_MEDIUM)) && !defined(__32BIT__) +/* Small and medium model in Turbo C are for now limited to near allocation + * with reduced MAX_WBITS and MAX_MEM_LEVEL + */ +# define MY_ZCALLOC + +/* Turbo C malloc() does not allow dynamic allocation of 64K bytes + * and farmalloc(64K) returns a pointer with an offset of 8, so we + * must fix the pointer. Warning: the pointer must be put back to its + * original form in order to free it, use zcfree(). + */ + +#define MAX_PTR 10 +/* 10*64K = 640K */ + +local int next_ptr = 0; + +typedef struct ptr_table_s { + voidpf org_ptr; + voidpf new_ptr; +} ptr_table; + +local ptr_table table[MAX_PTR]; +/* This table is used to remember the original form of pointers + * to large buffers (64K). Such pointers are normalized with a zero offset. + * Since MSDOS is not a preemptive multitasking OS, this table is not + * protected from concurrent access. This hack doesn't work anyway on + * a protected system like OS/2. Use Microsoft C instead. + */ + +voidpf zcalloc (voidpf opaque, unsigned items, unsigned size) +{ + voidpf buf = opaque; /* just to make some compilers happy */ + ulg bsize = (ulg)items*size; + + /* If we allocate less than 65520 bytes, we assume that farmalloc + * will return a usable pointer which doesn't have to be normalized. + */ + if (bsize < 65520L) { + buf = farmalloc(bsize); + if (*(ush*)&buf != 0) return buf; + } else { + buf = farmalloc(bsize + 16L); + } + if (buf == NULL || next_ptr >= MAX_PTR) return NULL; + table[next_ptr].org_ptr = buf; + + /* Normalize the pointer to seg:0 */ + *((ush*)&buf+1) += ((ush)((uch*)buf-0) + 15) >> 4; + *(ush*)&buf = 0; + table[next_ptr++].new_ptr = buf; + return buf; +} + +void zcfree (voidpf opaque, voidpf ptr) +{ + int n; + if (*(ush*)&ptr != 0) { /* object < 64K */ + farfree(ptr); + return; + } + /* Find the original pointer */ + for (n = 0; n < next_ptr; n++) { + if (ptr != table[n].new_ptr) continue; + + farfree(table[n].org_ptr); + while (++n < next_ptr) { + table[n-1] = table[n]; + } + next_ptr--; + return; + } + ptr = opaque; /* just to make some compilers happy */ + Assert(0, "zcfree: ptr not found"); +} +#endif +#endif /* __TURBOC__ */ + + +#if defined(M_I86) && !defined(__32BIT__) +/* Microsoft C in 16-bit mode */ + +# define MY_ZCALLOC + +#if (!defined(_MSC_VER) || (_MSC_VER <= 600)) +# define _halloc halloc +# define _hfree hfree +#endif + +voidpf zcalloc (voidpf opaque, unsigned items, unsigned size) +{ + if (opaque) opaque = 0; /* to make compiler happy */ + return _halloc((long)items, size); +} + +void zcfree (voidpf opaque, voidpf ptr) +{ + if (opaque) opaque = 0; /* to make compiler happy */ + _hfree(ptr); +} + +#endif /* MSC */ + + +#ifndef MY_ZCALLOC /* Any system without a special alloc function */ + +#ifndef STDC +extern voidp calloc OF((uInt items, uInt size)); +extern void free OF((voidpf ptr)); +#endif + +voidpf zcalloc (opaque, items, size) + voidpf opaque; + unsigned items; + unsigned size; +{ + if (opaque) items += size - size; /* make compiler happy */ + return (voidpf)calloc(items, size); +} + +void zcfree (opaque, ptr) + voidpf opaque; + voidpf ptr; +{ + free(ptr); + if (opaque) return; /* make compiler happy */ +} + +#endif /* MY_ZCALLOC */ ADDED zlib/zutil.h Index: zlib/zutil.h ================================================================== --- zlib/zutil.h +++ zlib/zutil.h @@ -0,0 +1,220 @@ +/* zutil.h -- internal interface and configuration of the compression library + * Copyright (C) 1995-1998 Jean-loup Gailly. + * For conditions of distribution and use, see copyright notice in zlib.h + */ + +/* WARNING: this file should *not* be used by applications. It is + part of the implementation of the compression library and is + subject to change. Applications should only use zlib.h. + */ + +/* @(#) $Id$ */ + +#ifndef _Z_UTIL_H +#define _Z_UTIL_H + +#include "zlib.h" + +#ifdef STDC +# include +# include +# include +#endif +#ifdef NO_ERRNO_H + extern int errno; +#else +# include +#endif + +#ifndef local +# define local static +#endif +/* compile with -Dlocal if your debugger can't find static symbols */ + +typedef unsigned char uch; +typedef uch FAR uchf; +typedef unsigned short ush; +typedef ush FAR ushf; +typedef unsigned long ulg; + +extern const char *z_errmsg[10]; /* indexed by 2-zlib_error */ +/* (size given to avoid silly warnings with Visual C++) */ + +#define ERR_MSG(err) z_errmsg[Z_NEED_DICT-(err)] + +#define ERR_RETURN(strm,err) \ + return (strm->msg = (char*)ERR_MSG(err), (err)) +/* To be used only when the state is known to be valid */ + + /* common constants */ + +#ifndef DEF_WBITS +# define DEF_WBITS MAX_WBITS +#endif +/* default windowBits for decompression. MAX_WBITS is for compression only */ + +#if MAX_MEM_LEVEL >= 8 +# define DEF_MEM_LEVEL 8 +#else +# define DEF_MEM_LEVEL MAX_MEM_LEVEL +#endif +/* default memLevel */ + +#define STORED_BLOCK 0 +#define STATIC_TREES 1 +#define DYN_TREES 2 +/* The three kinds of block type */ + +#define MIN_MATCH 3 +#define MAX_MATCH 258 +/* The minimum and maximum match lengths */ + +#define PRESET_DICT 0x20 /* preset dictionary flag in zlib header */ + + /* target dependencies */ + +#ifdef MSDOS +# define OS_CODE 0x00 +# if defined(__TURBOC__) || defined(__BORLANDC__) +# if(__STDC__ == 1) && (defined(__LARGE__) || defined(__COMPACT__)) + /* Allow compilation with ANSI keywords only enabled */ + void _Cdecl farfree( void *block ); + void *_Cdecl farmalloc( unsigned long nbytes ); +# else +# include +# endif +# else /* MSC or DJGPP */ +# include +# endif +#endif + +#ifdef OS2 +# define OS_CODE 0x06 +#endif + +#ifdef WIN32 /* Window 95 & Windows NT */ +# define OS_CODE 0x0b +#endif + +#if defined(VAXC) || defined(VMS) +# define OS_CODE 0x02 +# define F_OPEN(name, mode) \ + fopen((name), (mode), "mbc=60", "ctx=stm", "rfm=fix", "mrs=512") +#endif + +#ifdef AMIGA +# define OS_CODE 0x01 +#endif + +#if defined(ATARI) || defined(atarist) +# define OS_CODE 0x05 +#endif + +#if defined(MACOS) || defined(TARGET_OS_MAC) +# define OS_CODE 0x07 +# if defined(__MWERKS__) && __dest_os != __be_os && __dest_os != __win32_os +# include /* for fdopen */ +# else +# ifndef fdopen +# define fdopen(fd,mode) NULL /* No fdopen() */ +# endif +# endif +#endif + +#ifdef __50SERIES /* Prime/PRIMOS */ +# define OS_CODE 0x0F +#endif + +#ifdef TOPS20 +# define OS_CODE 0x0a +#endif + +#if defined(_BEOS_) || defined(RISCOS) +# define fdopen(fd,mode) NULL /* No fdopen() */ +#endif + +#if (defined(_MSC_VER) && (_MSC_VER > 600)) +# define fdopen(fd,type) _fdopen(fd,type) +#endif + + + /* Common defaults */ + +#ifndef OS_CODE +# define OS_CODE 0x03 /* assume Unix */ +#endif + +#ifndef F_OPEN +# define F_OPEN(name, mode) fopen((name), (mode)) +#endif + + /* functions */ + +#ifdef HAVE_STRERROR + extern char *strerror OF((int)); +# define zstrerror(errnum) strerror(errnum) +#else +# define zstrerror(errnum) "" +#endif + +#if defined(pyr) +# define NO_MEMCPY +#endif +#if defined(SMALL_MEDIUM) && !defined(_MSC_VER) && !defined(__SC__) + /* Use our own functions for small and medium model with MSC <= 5.0. + * You may have to use the same strategy for Borland C (untested). + * The __SC__ check is for Symantec. + */ +# define NO_MEMCPY +#endif +#if defined(STDC) && !defined(HAVE_MEMCPY) && !defined(NO_MEMCPY) +# define HAVE_MEMCPY +#endif +#ifdef HAVE_MEMCPY +# ifdef SMALL_MEDIUM /* MSDOS small or medium model */ +# define zmemcpy _fmemcpy +# define zmemcmp _fmemcmp +# define zmemzero(dest, len) _fmemset(dest, 0, len) +# else +# define zmemcpy memcpy +# define zmemcmp memcmp +# define zmemzero(dest, len) memset(dest, 0, len) +# endif +#else + extern void zmemcpy OF((Bytef* dest, const Bytef* source, uInt len)); + extern int zmemcmp OF((const Bytef* s1, const Bytef* s2, uInt len)); + extern void zmemzero OF((Bytef* dest, uInt len)); +#endif + +/* Diagnostic functions */ +#ifdef DEBUG +# include + extern int z_verbose; + extern void z_error OF((char *m)); +# define Assert(cond,msg) {if(!(cond)) z_error(msg);} +# define Trace(x) {if (z_verbose>=0) fprintf x ;} +# define Tracev(x) {if (z_verbose>0) fprintf x ;} +# define Tracevv(x) {if (z_verbose>1) fprintf x ;} +# define Tracec(c,x) {if (z_verbose>0 && (c)) fprintf x ;} +# define Tracecv(c,x) {if (z_verbose>1 && (c)) fprintf x ;} +#else +# define Assert(cond,msg) +# define Trace(x) +# define Tracev(x) +# define Tracevv(x) +# define Tracec(c,x) +# define Tracecv(c,x) +#endif + + +typedef uLong (ZEXPORT *check_func) OF((uLong check, const Bytef *buf, + uInt len)); +voidpf zcalloc OF((voidpf opaque, unsigned items, unsigned size)); +void zcfree OF((voidpf opaque, voidpf ptr)); + +#define ZALLOC(strm, items, size) \ + (*((strm)->zalloc))((strm)->opaque, (items), (size)) +#define ZFREE(strm, addr) (*((strm)->zfree))((strm)->opaque, (voidpf)(addr)) +#define TRY_FREE(s, p) {if (p) ZFREE(s, p);} + +#endif /* _Z_UTIL_H */