id
int64
1
722k
file_path
stringlengths
8
177
funcs
stringlengths
1
35.8M
722,401
./openmeap/clients/c/openmeap-slic-core/src/zip.c
/* ############################################################################### # # # Copyright (C) 2011-2013 OpenMEAP, Inc. # # Credits to Jonathan Schang & Robert Thacher # # # # Released under the LGPLv3 # # # # OpenMEAP is free software: you can redistribute it and/or modify # # it under the terms of the GNU Lesser General Public License as published # # by the Free Software Foundation, either version 3 of the License, or # # (at your option) any later version. # # # # OpenMEAP is distributed in the hope that it will be useful, # # but WITHOUT ANY WARRANTY; without even the implied warranty of # # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # # GNU Lesser General Public License for more details. # # # # You should have received a copy of the GNU Lesser General Public License # # along with OpenMEAP. If not, see <http://www.gnu.org/licenses/>. # # # ############################################################################### */ #include <stdio.h> #include "unzip.h" #include <openmeap-slic-core.h> #include <errno.h> #include <dirent.h> OM_PRIVATE_FUNC int __om_unzip_mymkdir(om_unzip_archive_ptr archive, const char* dirname); OM_PRIVATE_FUNC int __om_unzip_makedir(om_unzip_archive_ptr archive, const char *rootExportPath, char *newdir); OM_PRIVATE_FUNC int __om_unzip_extract_currentfile(om_unzip_archive_ptr archive, const char *rootExportPath, om_uint32 options, const char* password); OM_PRIVATE_FUNC int __om_unzip_extract(om_unzip_archive_ptr archive, const char *rootExportPath, om_uint32 options, const char* password); om_unzip_archive_ptr om_unzip_open_archive(const char *file_path) { int err; unz_global_info * gip = om_malloc(sizeof(unz_global_info)); if( gip==OM_NULL ) { return OM_NULL; } unzFile uf = unzOpen(file_path); err = unzGetGlobalInfo(uf,gip); if( err!=UNZ_OK ) { om_free(gip); om_error_set(OM_ERR_ZIP_GLOBALINFO,"Error getting global info for the zip archive."); return OM_NULL; } om_list_ptr error_log = om_list_new(); if( error_log==OM_NULL ) { om_free(gip); return OM_NULL; } om_unzip_archive_ptr arch = om_malloc(sizeof(om_unzip_archive)); if( arch==OM_NULL ) { om_list_release(error_log); om_free(gip); return OM_NULL; } arch->error_log = error_log; arch->file = uf; arch->global_info_ptr = gip; return arch; } om_bool om_unzip_close_archive(om_unzip_archive_ptr archive) { om_bool ret = OM_TRUE; om_list_release(archive->error_log); om_free(archive->global_info_ptr); if( unzClose(archive->file) != UNZ_OK ) { ret=OM_FALSE; } om_free(archive); return ret; } om_bool om_unzip_archive_into_path(om_unzip_archive_ptr archive, const char *exportBasePath) { int err = __om_unzip_extract(archive,exportBasePath,0,OM_NULL); if (err!=UNZ_OK) { return OM_FALSE; } return OM_TRUE; } /***************** * Everything below here was imported from miniunz.c, * the sample application from MiniZip * The functions have been renamed, but the code is * still mostly the product of */ om_bool __om_unzip_append_error(om_unzip_archive_ptr archive, char * err) { return om_list_append(archive->error_log,err); } int __om_unzip_mymkdir(om_unzip_archive_ptr archive, const char* dirname) { int ret=0; ret = mkdir (dirname,0700); return ret; } int __om_unzip_makedir (om_unzip_archive_ptr archive, const char *rootExportPath, char *newdir) { char *buffer = om_string_copy(newdir); if( buffer==OM_NULL ) { return UNZ_INTERNALERROR; } char *p; int len = (int)strlen(newdir); if (len <= 0) return 0; // prefix with the location where we want to create the dir structure if( buffer[0]==OM_FS_FILE_SEP ) { p = om_string_append(rootExportPath,buffer); } else { p = om_string_format("%s%c%s",rootExportPath,OM_FS_FILE_SEP,buffer); } om_free(buffer); buffer = p; p = OM_NULL; // if the path ended with a '/', // then take that off if (buffer[len-1] == '/') { buffer[len-1] = '\0'; } if (__om_unzip_mymkdir(archive,buffer) == 0) { om_free(buffer); return 1; } p = buffer+1; while (1) { char hold; // we shouldn't need to create the rootExportPath if( strcmp(rootExportPath,buffer)==0 ) break; while(*p && *p != '\\' && *p != '/') p++; hold = *p; *p = 0; if ( (__om_unzip_mymkdir(archive,buffer) == -1) && (errno == ENOENT) ) { __om_unzip_append_error(archive,om_string_format("couldn't create directory %s\n",buffer)); om_free(buffer); return 0; } if ( hold == 0 ) break; *p++ = hold; } om_free(buffer); return 1; } int __om_unzip_extract_currentfile( om_unzip_archive_ptr archive, const char *rootExportPath, om_uint32 options, const char *password ) { unzFile uf = archive->file; char filename_inzip[256]; char *filename_withoutpath; char *p; int err=UNZ_OK; FILE *fout=NULL; void *buf; uInt size_buf; unz_file_info file_info; uLong ratio = 0; err = unzGetCurrentFileInfo(uf,&file_info,filename_inzip,sizeof(filename_inzip),NULL,0,NULL,0); if (err!=UNZ_OK) { __om_unzip_append_error(archive,om_string_format("error %d with zipfile in unzGetCurrentFileInfo\n",err)); return err; } size_buf = OM_ZIP_WRITEBUFFERSIZE; buf = (void*)om_malloc(size_buf); if (buf==NULL) { // Error allocating memory for the write buffer return UNZ_INTERNALERROR; } // this appears to be a string copy // some zip files do not put in a path p = filename_withoutpath = filename_inzip; while ((*p) != '\0') { // if the current character is a dir path separator // then the next character starts either a directory segment // or a file name if (((*p)=='/') || ((*p)=='\\')) filename_withoutpath = p+1; p++; } // if the element after the last '/' was a '\0', then this is a directory if ( (*filename_withoutpath) == '\0' ) { if( ! options & OM_ZIP_OPTS_NOPATH ) { char * full_file_path = om_string_format("%s%c%s",rootExportPath,OM_FS_FILE_SEP,filename_inzip); if(full_file_path==OM_NULL) { om_free(buf); return UNZ_INTERNALERROR; } __om_unzip_mymkdir(archive,full_file_path); om_free(full_file_path); } } // otherwise it was a file name else { char* write_filename; int skip=0; if( options & OM_ZIP_OPTS_NOPATH ) { write_filename = filename_withoutpath; } else { write_filename = filename_inzip; } err = unzOpenCurrentFilePassword(uf,password); if ( err != UNZ_OK ) { __om_unzip_append_error(archive,om_string_format("error %d with zipfile in unzOpenCurrentFilePassword\n",err)); return err; } // removed a file existence test here if ( skip == 0 && err == UNZ_OK ) { // the write_filename should, at this point, // have the relative directory on it // now we have to prepend with our rootExportPath char * full_file_path = om_string_format("%s%c%s",rootExportPath,OM_FS_FILE_SEP,write_filename); fout = fopen(full_file_path,"wb"); // some zipfile don't contain the directory alone before file if ( (fout==NULL) && (!(options & OM_ZIP_OPTS_NOPATH)) && (filename_withoutpath!=(char*)filename_inzip) ) { char c = *(filename_withoutpath-1); *(filename_withoutpath-1)='\0'; __om_unzip_makedir(archive,rootExportPath,write_filename); *(filename_withoutpath-1)=c; fout=fopen(full_file_path,"wb"); } om_free(full_file_path); if (fout==NULL) { __om_unzip_append_error(archive,om_string_format("error opening %s",write_filename)); om_free(buf); return UNZ_INTERNALERROR; } } if (fout!=NULL) { //printf(" extracting: %s\n",write_filename); do { err = unzReadCurrentFile(uf,buf,size_buf); if (err<0) { __om_unzip_append_error(archive,om_string_format("error %d with zipfile in unzReadCurrentFile\n",err)); break; } if (err>0) { if (fwrite(buf,err,1,fout)!=1) { __om_unzip_append_error(archive,om_string_format("error in writing extracted file\n")); err=UNZ_ERRNO; break; } } } while (err>0); if (fout) fclose(fout); // OpenMEAP doesn't care if the date of the files on the device // are the same as in the archive. // if (err==0) // change_file_date(write_filename,file_info.dosDate, file_info.tmu_date); } if (err==UNZ_OK) { err = unzCloseCurrentFile (uf); if (err!=UNZ_OK) { __om_unzip_append_error(archive,om_string_format("error %d with zipfile in unzCloseCurrentFile\n",err)); } } else { unzCloseCurrentFile(uf); /* don't lose the error */ } } om_free(buf); return err; } int __om_unzip_extract( om_unzip_archive_ptr archive, const char* rootExtractPath, om_uint32 options, const char* password ) { unzFile uf = archive->file; uLong i; unz_global_info * gi = archive->global_info_ptr; int err; err = unzGoToFirstFile(uf); if (err!=UNZ_OK) { __om_unzip_append_error(archive,om_string_format("error %d with zipfile in unzGoToNextFile\n",err)); return err; } for (i=0;i<gi->number_entry;i++) { if ( (err=__om_unzip_extract_currentfile(archive,rootExtractPath,options,password)) != UNZ_OK ) break; if ((i+1)<gi->number_entry) { err = unzGoToNextFile(uf); if (err!=UNZ_OK) { __om_unzip_append_error(archive,om_string_format("error %d with zipfile in unzGoToNextFile\n",err)); break; } } } return err; }
722,402
./openmeap/clients/c/openmeap-slic-core/src/storage-default.c
/* ############################################################################### # # # Copyright (C) 2011-2013 OpenMEAP, Inc. # # Credits to Jonathan Schang & Robert Thacher # # # # Released under the LGPLv3 # # # # OpenMEAP is free software: you can redistribute it and/or modify # # it under the terms of the GNU Lesser General Public License as published # # by the Free Software Foundation, either version 3 of the License, or # # (at your option) any later version. # # # # OpenMEAP is distributed in the hope that it will be useful, # # but WITHOUT ANY WARRANTY; without even the implied warranty of # # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # # GNU Lesser General Public License for more details. # # # # You should have received a copy of the GNU Lesser General Public License # # along with OpenMEAP. If not, see <http://www.gnu.org/licenses/>. # # # ############################################################################### */ #include <openmeap-slic-core.h> #include <stdio.h> #include <stdlib.h> #include <sys/types.h> #include <sys/stat.h> #include <dirent.h> /*******/ om_storage_ptr default_om_storage_alloc(om_config_ptr *cfg) { om_storage_ptr stg = om_malloc( sizeof(om_storage) ); if(stg==OM_NULL) { return OM_NULL; } stg->cfg = cfg; stg->open_file_input_stream=default_om_storage_open_file_input_stream; stg->open_file_output_stream=default_om_storage_open_file_output_stream; stg->write=default_om_storage_write; stg->read=default_om_storage_read; stg->close_file_input_stream=default_om_storage_close_file_input_stream; stg->close_file_output_stream=default_om_storage_close_file_output_stream; stg->delete_file=default_om_storage_delete_file; stg->create_directories_for_path=default_om_storage_create_directories_for_path; stg->get_import_archive_input_stream=default_om_storage_get_import_archive_input_stream; stg->get_import_archive_output_stream=default_om_storage_get_import_archive_output_stream; stg->delete_import_archive=default_om_storage_delete_import_archive; stg->get_current_location=default_om_storage_get_current_location; stg->reset_storage=default_om_storage_reset_storage; stg->delete_directory=default_om_storage_delete_directory; stg->file_get_contents=default_om_storage_file_get_contents; /* The following 4 are implemented in the device-specific storage source (storage.m for ios), and are thus provided by that implementations om_storage_alloc: stg->get_localstorage_path stg->get_bundleresources_path stg->get_bytes_free stg->get_current_assets_prefix */ return stg; } /****** * DEFAULT IMPLEMENTATION BELOW */ om_file_input_stream_ptr default_om_storage_get_import_archive_input_stream(om_storage_ptr storage) { char * location = om_config_get(storage->cfg,OM_CFG_IMPORT_ARCHIVE_PATH); om_file_input_stream_ptr ret = om_storage_open_file_input_stream(storage,location); om_free(location); return ret; } om_file_output_stream_ptr default_om_storage_get_import_archive_output_stream(om_storage_ptr storage) { char * location = om_config_get(storage->cfg,OM_CFG_IMPORT_ARCHIVE_PATH); om_file_output_stream_ptr ret = om_storage_open_file_output_stream(storage,location,OM_TRUE); om_free(location); return ret; } om_bool default_om_storage_delete_import_archive(om_storage_ptr storage) { char * importArchLoc = om_config_get((om_config_ptr)storage->cfg,OM_CFG_IMPORT_ARCHIVE_PATH); om_bool result = om_storage_delete_file(storage, importArchLoc); om_free(importArchLoc); return result; } char * default_om_storage_get_current_location(om_storage_ptr storage) { om_error_clear(); char *locPtr = om_config_get((om_config_ptr)storage->cfg,OM_CFG_CURRENT_STORAGE); return locPtr; } om_bool default_om_storage_delete_directory(om_storage_ptr storage, char *rootPath, om_bool include_root) { DIR *dp = OM_NULL; struct dirent *ep = OM_NULL; char *currentEntry=OM_NULL; char *tmp=OM_NULL; om_bool retVal=OM_FALSE; struct stat *currentEntryStat = om_malloc(sizeof(struct stat)); if( currentEntryStat==OM_NULL ) return OM_NULL; dp = opendir (rootPath); if (dp != NULL) { while (ep = readdir (dp)) { if( strcmp(ep->d_name,"..")==0 || strcmp(ep->d_name,".")==0 ) continue; currentEntry = om_string_append(rootPath,(char[]){OM_FS_FILE_SEP,'\0'}); tmp=currentEntry; currentEntry = om_string_append(tmp,ep->d_name); om_free(tmp); if( 0==stat(currentEntry,currentEntryStat) ) { if( S_ISDIR(currentEntryStat->st_mode) ) { om_storage_delete_directory(storage,currentEntry,OM_TRUE); } else if ( S_ISREG(currentEntryStat->st_mode) ) { unlink(currentEntry); } } memset(currentEntryStat,0,sizeof(struct stat)); om_free(currentEntry); } closedir (dp); if( include_root==OM_TRUE ) { rmdir(rootPath); } retVal=OM_TRUE; } else om_error_set_format(OM_ERR_DIR_DEL_RECURSE,"Could not open \"%s\" as a directory.",rootPath); om_free(currentEntryStat); return retVal; } om_bool default_om_storage_reset_storage(om_storage_ptr storage) { char *pathToStorage = om_storage_get_current_location(storage); om_bool ret = om_storage_delete_directory(storage,pathToStorage,OM_TRUE); om_free(pathToStorage); return ret; } /////////////////////////// // /** * Opens a file for writing * * @param filePath the path to the file to open * @param truncate truncate the file if it exists, else position to the end. * @return A pointer to the om_file_output_stream struct or OM_NULL. Sets the error flag. */ om_file_output_stream_ptr default_om_storage_open_file_output_stream(om_storage_ptr storage, const char *filePath, om_bool truncate) { char *path = om_string_copy(filePath); if( path == OM_NULL ) { return OM_NULL; } FILE *f = fopen( filePath, truncate ? "w" : "a" ); if( f==NULL ) { om_error_set(OM_ERR_FILE_OPEN,"Could not open the file"); return OM_NULL; } // at this point, the file is successfully open // and we can safely allocate an om_file_input_stream_ptr om_file_output_stream_ptr ret = om_malloc(sizeof(om_file_output_stream)); if( ret==OM_NULL ) { return OM_NULL; } ret->device_data = f; ret->device_path = path; ret->storage = storage; return ret; } /** * Write num_bytes from bytes, starting at index, to the om_file_output_stream pointer passed in. * * @param ostream The om_file_output_stream pointer to write to * @param bytes The bytes to write to the output stream * @param index The index to start writing at * @param num_bytes The number of bytes to write */ om_uint32 default_om_storage_write(om_file_output_stream_ptr ostream, void *bytes, om_uint32 index, om_uint32 num_bytes) { clearerr((FILE*)ostream->device_data); om_uint32 ret = fwrite(bytes+index,1,num_bytes,(FILE*)ostream->device_data); int errInt; if( ret!=num_bytes && (errInt=ferror((FILE*)ostream->device_data)) ) { om_error_set_format(OM_ERR_FILE_WRITE,"Error occurred writing to file output stream : %s", strerror(errInt)); clearerr((FILE*)ostream->device_data); } return ret; } /** * */ void default_om_storage_close_file_output_stream(om_file_output_stream_ptr file) { fclose((FILE*)file->device_data); om_free(file->device_path); om_free(file); } /** * Opens a file for reading * * @param storage the storage context * @param filePath the path to the file to open */ om_file_input_stream_ptr default_om_storage_open_file_input_stream(om_storage_ptr storage, const char *filePath) { char *path = om_string_copy(filePath); if( path == OM_NULL ) { return path; } FILE *f = fopen(filePath,"r"); if( f==NULL ) { om_error_set_format(OM_ERR_FILE_OPEN,"Could not open the file \"%s\".",filePath); return OM_NULL; } // at this point, the file is successfully open // and we can safely allocate an om_file_input_stream_ptr om_file_input_stream_ptr ret = om_malloc(sizeof(om_file_input_stream)); if( ret==OM_NULL ) { return OM_NULL; } ret->device_data = f; ret->device_path = path; ret->storage = storage; return ret; } /** * Read num_bytes into bytes from the om_file_input_stream pointer passed in * * @param istream The om_file_input_stream to read from * @param bytes A pointer to the pointer to allocate and pass back * @param num_bytes The number of bytes preferred to read * @return The number of bytes read. Sets an error code on error */ om_uint32 default_om_storage_read(om_file_input_stream_ptr istream, void *bytes, om_uint32 num_bytes) { clearerr((FILE*)istream->device_data); om_uint32 ret = fread(bytes,1,num_bytes,istream->device_data); int errInt; if( ret!=num_bytes && (errInt=ferror((FILE*)istream->device_data)) ) { om_error_set_format(OM_ERR_FILE_READ,"Error occurred reading from file \"%s\" : %s",istream->device_path,strerror(errInt)); } return ret; } /** * Closes a file input stream and releases associated resources * * @param storage * @param file */ void default_om_storage_close_file_input_stream(om_file_input_stream_ptr file) { int ret = fclose((FILE*)file->device_data); if( ret ) { int errInt = ferror((FILE*)file->device_data); om_error_set_format(OM_ERR_FILE_CLOSE,"Error occurred closing file \"%s\" : %s",file->device_path,strerror(errInt)); } om_free(file->device_path); om_free(file); } /** * Delete the file or directory passed in. If directory, then it must be empty. * Implemented in device library */ om_bool default_om_storage_delete_file(om_storage_ptr storage, const char *filePath) { if( remove(filePath)!=0 ) { om_error_set_format(OM_ERR_FILE_CLOSE,"Error occurred deleting file \"%s\".",filePath); return OM_FALSE; } else { return OM_TRUE; } } /** * Creates the directory structure for a path. It is assumed that the trailing slash is not used * * @param path The full path to be created. * @return om_bool true if successful, else false. */ om_bool default_om_storage_create_directories_for_path(om_storage_ptr stg, char *path) { om_list_ptr segments = om_string_explode(path,OM_FS_FILE_SEP); if( segments==OM_NULL ) { return OM_FALSE; } int count = om_list_count(segments); char * pathInProgress = OM_NULL; struct stat *currentEntryStat = om_malloc(sizeof(struct stat)); if( currentEntryStat==OM_NULL ) { return OM_FALSE; } for( int i=0; i<count; i++ ) { char * segment = om_list_get(segments,i); if( strlen(segment)==0 ) { continue; } if( pathInProgress!=OM_NULL ) { char * t = pathInProgress; pathInProgress=om_string_format("%s%c%s",pathInProgress,OM_FS_FILE_SEP,segment); om_free(t); } else { pathInProgress=om_string_format("%c%s",OM_FS_FILE_SEP,segment); } if( 0==stat(pathInProgress,currentEntryStat) ) { if( !S_ISDIR(currentEntryStat->st_mode) ) { mkdir(path,0700); } memset(currentEntryStat,0,sizeof(struct stat)); } else { mkdir(path,0700); } } om_list_release(segments); om_free(currentEntryStat); if(pathInProgress!=OM_NULL) { om_free(pathInProgress); } return OM_TRUE; } char * default_om_storage_file_get_contents(om_storage_ptr storage, const char *fullFilePath) { char * toret = om_malloc(256); if( toret==OM_NULL ) return OM_NULL; char * p = toret; om_uint32 size = 0; char bytes[256]; int numRead = 0; int numToRead = 256; om_file_input_stream_ptr is = om_storage_open_file_input_stream(storage,fullFilePath); if( is==OM_NULL ) { om_free(toret); return OM_NULL; } while( (numRead=om_storage_read(is,bytes,256)) > 0 ) { p = toret; toret = om_malloc(size+numRead+1); if( toret==OM_NULL ) { om_free(toret); return OM_NULL; } memcpy(toret,p,size); memcpy(toret+size,bytes,numRead); size+=numRead; om_free(p); if( numRead<numToRead ) break; } om_storage_close_file_input_stream(is); return toret; }
722,403
./openmeap/clients/c/openmeap-slic-core/src/storage.c
/* ############################################################################### # # # Copyright (C) 2011-2013 OpenMEAP, Inc. # # Credits to Jonathan Schang & Robert Thacher # # # # Released under the LGPLv3 # # # # OpenMEAP is free software: you can redistribute it and/or modify # # it under the terms of the GNU Lesser General Public License as published # # by the Free Software Foundation, either version 3 of the License, or # # (at your option) any later version. # # # # OpenMEAP is distributed in the hope that it will be useful, # # but WITHOUT ANY WARRANTY; without even the implied warranty of # # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # # GNU Lesser General Public License for more details. # # # # You should have received a copy of the GNU Lesser General Public License # # along with OpenMEAP. If not, see <http://www.gnu.org/licenses/>. # # # ############################################################################### */ #include <openmeap-slic-core.h> om_file_input_stream_ptr om_storage_open_file_input_stream(om_storage_ptr storage, const char *filePath) { return storage->open_file_input_stream(storage,filePath); } om_file_output_stream_ptr om_storage_open_file_output_stream(om_storage_ptr storage, const char *filePath, om_bool truncate) { return storage->open_file_output_stream(storage,filePath,truncate); } om_uint32 om_storage_write(om_file_output_stream_ptr file, void *bytes, om_uint32 index, om_uint32 num_bytes) { return ((om_storage_ptr)(file->storage))->write(file,bytes,index,num_bytes); } om_uint32 om_storage_read(om_file_input_stream_ptr file, void *bytes, om_uint32 num_bytes) { return ((om_storage_ptr)(file->storage))->read(file,bytes,num_bytes); } void om_storage_close_file_input_stream(om_file_input_stream_ptr file) { ((om_storage_ptr)(file->storage))->close_file_input_stream(file); } void om_storage_close_file_output_stream(om_file_output_stream_ptr file) { ((om_storage_ptr)(file->storage))->close_file_output_stream(file); } om_bool om_storage_delete_file(om_storage_ptr storage, const char *filePath) { return storage->delete_file(storage,filePath); } om_bool om_storage_create_directories_for_path(om_storage_ptr storage, char *path) { return storage->create_directories_for_path(storage,path); } om_file_input_stream_ptr om_storage_get_import_archive_input_stream(om_storage_ptr storage) { return storage->get_import_archive_input_stream(storage); } om_file_output_stream_ptr om_storage_get_import_archive_output_stream(om_storage_ptr storage) { return storage->get_import_archive_output_stream(storage); } om_bool om_storage_delete_import_archive(om_storage_ptr storage) { return storage->delete_import_archive(storage); } char * om_storage_get_current_location(om_storage_ptr storage) { return storage->get_current_location(storage); } om_bool om_storage_reset_storage(om_storage_ptr storage) { return storage->reset_storage(storage); } om_bool om_storage_delete_directory(om_storage_ptr storage, char *rootPath, om_bool include_root) { return storage->delete_directory(storage,rootPath,include_root); } char * om_storage_get_localstorage_path(om_storage_ptr storage) { return storage->get_localstorage_path(storage); } char * om_storage_get_current_assets_prefix(om_storage_ptr storage) { return storage->get_current_assets_prefix(storage); } char * om_storage_get_bundleresources_path(om_storage_ptr storage) { return storage->get_bundleresources_path(storage); } om_uint64 om_storage_get_bytes_free(om_storage_ptr storage) { return storage->get_bytes_free(storage); } char * om_storage_file_get_contents(om_storage_ptr storage, const char *fullFilePath) { return storage->file_get_contents(storage,fullFilePath); }
722,404
./openmeap/clients/c/openmeap-slic-core/src/string.c
/* ############################################################################### # # # Copyright (C) 2011-2013 OpenMEAP, Inc. # # Credits to Jonathan Schang & Robert Thacher # # # # Released under the LGPLv3 # # # # OpenMEAP is free software: you can redistribute it and/or modify # # it under the terms of the GNU Lesser General Public License as published # # by the Free Software Foundation, either version 3 of the License, or # # (at your option) any later version. # # # # OpenMEAP is distributed in the hope that it will be useful, # # but WITHOUT ANY WARRANTY; without even the implied warranty of # # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # # GNU Lesser General Public License for more details. # # # # You should have received a copy of the GNU Lesser General Public License # # along with OpenMEAP. If not, see <http://www.gnu.org/licenses/>. # # # ############################################################################### */ #include <openmeap-slic-core.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <stdarg.h> #include <memory.h> om_substring_ptr om_substring_new(const char *str, int len) { om_substring_ptr ret = om_malloc(sizeof(om_substring)); if( ret==NULL ) { om_error_set(OM_ERR_MALLOC,"Could not malloc() a new substring"); return OM_NULL; } ret->str = str; ret->len = len; return ret; } void om_substring_release(om_substring_ptr str) { om_free(str); } om_bool om_substring_equals(om_substring_ptr ptr, char *match) { for( int i=0; i<ptr->len; i++ ) { if( ptr->str[i] != match[i] ) { return OM_FALSE; } } return OM_TRUE; } char * om_substring_copy(om_substring_ptr ptr) { char * ret = om_malloc((ptr->len+1)*sizeof(char)); if( ret==NULL ) { om_error_set(OM_ERR_MALLOC,"could not allocate to copy string in om_substring_copy()"); return OM_NULL; } memcpy(ret,ptr->str,ptr->len*sizeof(char)); return ret; } char * om_string_format(const char *formatting, ...) { char *str = om_malloc(OM_STRING_FORMAT_LIMIT+1); if( str==OM_NULL ) return OM_NULL; va_list ap; va_start(ap,formatting); vsnprintf(str, OM_STRING_FORMAT_LIMIT, formatting, ap); va_end(ap); char *ret = om_string_copy(str); om_free(str); if( ret==OM_NULL ) return OM_NULL; return ret; } char * om_string_copy(const char *str) { char *ret = om_malloc(sizeof(char)*strlen(str)+1); if( ret==NULL ) { om_error_set(OM_ERR_MALLOC,"Could not allocate to copy string in om_string_copy()"); return OM_NULL; } strcpy(ret,str); return ret; } char * om_string_append(const char *str, const char *app) { int size = sizeof(char)*(strlen(str)+strlen(app)+1); char * ret = om_malloc(size); if( ret==OM_NULL ) { om_error_set_code(OM_ERR_MALLOC); return OM_NULL; } memcpy(ret,str,strlen(str)); strcat(ret,app); return ret; } char * om_string_substr(const char *str, int start, int length) { char * ret = om_malloc(length+1); if( ret==OM_NULL ) return ret; int len = strlen(str); len = len >= start+length ? length : (len+1)-start; memcpy(ret,str+start,len); return ret; } char * om_string_tolower(const char *str_in) { char *str = om_string_copy(str_in); int i; for (i = 0; str[i] != '\0'; ++i) { if (str[i] >= 'A' && str[i] <= 'Z') { str[i] = str[i] + ('a'-'A'); } } return str; } char * om_string_toupper(const char *str_in) { char *str = om_string_copy(str_in); int i; for (i = 0; str[i] != '\0'; ++i) { if (str[i] >= 'a' && str[i] <= 'z') { str[i] = str[i] - ('a'-'A'); } } return str; } om_list_ptr om_string_explode(const char *str, const char sep) { om_list_ptr list = om_list_new(); if( list==OM_NULL ) return OM_NULL; char * p = OM_NULL; char * seg = str; char * start = seg; while(1) { if(*seg==sep||(*seg=='\0'&&start!=seg)) { char * p = om_string_substr(start,0,(seg-start)); if( p == OM_NULL ) { // all or nothing om_list_release(list); return OM_NULL; } if( ! om_list_append(list,p) ) { // all or nothing om_list_release(list); return OM_NULL; } // we may be at the end, so check if(*seg=='\0') break; seg++; // get beyond the '/' start = seg; // start tracking a new segment } // we may be at the end, so check if(*seg=='\0') break; seg++; } return list; } char * om_string_implode(om_list_ptr list, const char sep) { int items = om_list_count(list); char separ[] = {sep,'\0'}; char *ret=OM_NULL; char *t=OM_NULL; for( int i=0; i<items; i++ ) { char *ptr = om_string_copy( om_list_get(list,i) ); if(ret==OM_NULL) { ret=ptr; } else { t=ret; ret = om_string_append(t,ptr); om_free(t); om_free(ptr); if( ret==OM_NULL ) { return OM_NULL; } } if( i<items-1 ) { t=ret; ret = om_string_append(t,separ); om_free(t); if( ret==OM_NULL ) { return OM_NULL; } } } return ret; } char * om_string_encodeURI(const char *str) { const char* reserved = "!ΓÇÖ\"();:@&=+$,/?%#[]% \0"; // count characters to encode int i=0, encodePadding=0, reservedLen=strlen(reserved); while(str[i]!=0) { for(int j=0; j<reservedLen; j++) { if(reserved[j]==str[i]) { encodePadding+=3; } } i++; } // allocate new string char *newStr = om_malloc( sizeof(char) * (strlen(str)+encodePadding+1) ); // copy each character, encoding as we go i=0; char *pos = newStr; om_bool charHandled; while(str[i]!=0) { charHandled=OM_FALSE; for(int j=0; j<reservedLen; j++) { if(str[i]==reserved[j]) { sprintf(pos,"%%%X",str[i]); pos+=3; charHandled=OM_TRUE; break; } } if( !charHandled ) { *pos=str[i]; pos++; } i++; } // return new string return newStr; } char * om_string_decodeURI(const char *str) { // count characters to decode int i=0, charCount=0, len=strlen(str), lenMinus2=len-2; while(str[i]!=0) { if('%'==str[i]) { charCount+=1; } i++; } // allocate new string char *newStr = om_malloc( sizeof(char) * (len-(charCount*2)+1) ); // copy each character, decoding as we go i=0; for( int p=0; p<len; p++ ) { char *p2 = str+p; if( *p2=='%' && p<=lenMinus2 && om_string_is_hex_char(*(p2+1)) && om_string_is_hex_char(*(p2+2)) ) { char tmp[3]={om_char_toupper(*(p2+1)),om_char_toupper(*(p2+2)),'\0'}; sscanf(&tmp,"%X",newStr+i); p+=2; } else { newStr[i]=*p2; } i++; } // return new string return newStr; }
722,405
./openmeap/clients/c/openmeap-slic-core/src/prefs.c
/* ############################################################################### # # # Copyright (C) 2011-2013 OpenMEAP, Inc. # # Credits to Jonathan Schang & Robert Thacher # # # # Released under the LGPLv3 # # # # OpenMEAP is free software: you can redistribute it and/or modify # # it under the terms of the GNU Lesser General Public License as published # # by the Free Software Foundation, either version 3 of the License, or # # (at your option) any later version. # # # # OpenMEAP is distributed in the hope that it will be useful, # # but WITHOUT ANY WARRANTY; without even the implied warranty of # # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # # GNU Lesser General Public License for more details. # # # # You should have received a copy of the GNU Lesser General Public License # # along with OpenMEAP. If not, see <http://www.gnu.org/licenses/>. # # # ############################################################################### */ #include <openmeap-slic-core.h> void om_prefs_clear(const om_prefs_ptr prefs) { prefs->clear(prefs); } om_bool om_prefs_set(const om_prefs_ptr prefs, const char *key, const char *value) { return prefs->set(prefs,key,value); } char * om_prefs_get(const om_prefs_ptr prefs, const char *key) { return prefs->get(prefs,key); } void om_prefs_remove(const om_prefs_ptr prefs, const char *key) { prefs->remove(prefs,key); }
722,406
./openmeap/clients/c/openmeap-slic-core/src/dict.c
/* ############################################################################### # # # Copyright (C) 2011-2013 OpenMEAP, Inc. # # Credits to Jonathan Schang & Robert Thacher # # # # Released under the LGPLv3 # # # # OpenMEAP is free software: you can redistribute it and/or modify # # it under the terms of the GNU Lesser General Public License as published # # by the Free Software Foundation, either version 3 of the License, or # # (at your option) any later version. # # # # OpenMEAP is distributed in the hope that it will be useful, # # but WITHOUT ANY WARRANTY; without even the implied warranty of # # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # # GNU Lesser General Public License for more details. # # # # You should have received a copy of the GNU Lesser General Public License # # along with OpenMEAP. If not, see <http://www.gnu.org/licenses/>. # # # ############################################################################### */ #include <openmeap-slic-core.h> #include <stdio.h> #include <stdlib.h> /* private function declarations */ OM_PRIVATE_FUNC om_dict_entry_ptr __om_dict_new_entry(void * key, void * val); OM_PRIVATE_FUNC om_list_ptr __om_dict_get_bucket_for_key(om_dict_ptr dict, void *key); OM_PRIVATE_FUNC om_dict_entry_ptr __om_dict_get_entry(om_dict_ptr ptr, void *key); OM_PRIVATE_FUNC void __om_dict_release_entry_func(void *entry, void *release_data); OM_PRIVATE_FUNC void __om_dict_free_key_value(om_dict_ptr dict, void *key, void *val); /* implementation */ /** * @return om_dict_ptr where the hash_func is the default om_dict_hash_string function */ om_dict_ptr om_dict_new(int size) { om_dict_ptr ret = om_malloc(sizeof(om_dict)); if( ret==OM_NULL ) { om_error_set( OM_ERR_MALLOC, "Could not allocate a new dict" ); return OM_NULL; } ret->hash_func = om_dict_hash_string; ret->bucket_count = size; ret->buckets = om_malloc(sizeof(om_list_ptr)*size); return ret; } void om_dict_release(om_dict_ptr dict) { om_dict_clear(dict); om_free(dict->buckets); om_free(dict); } void om_dict_release_default_func(void *key, void *value, void *release_data) { om_free(key); om_free(value); } void om_dict_release_prefs_by_name_func(void *key, void *value, void *release_data) { om_free(key); om_prefs_release(value); } om_dict_ptr om_dict_from_query_string(const char *queryString) { om_list_ptr keyValPairs = om_string_explode(queryString,'&'); om_dict_ptr ret = om_dict_new(5); ret->release_func=om_dict_release_default_func; int c = om_list_count(keyValPairs); for( int i=0; i<c; i++ ) { char * val = om_list_get(keyValPairs,i); om_list_ptr keyVal = om_string_explode( val, '=' ); if( om_list_count(keyVal)==2 ) { om_dict_put( ret, om_string_copy(om_list_get(keyVal,0)), om_string_copy(om_list_get(keyVal,1)) ); } else if( om_list_count(keyVal)==1 ) { om_dict_put( ret, om_string_copy(om_list_get(keyVal,0)), "" ); } om_list_release(keyVal); } om_list_release(keyValPairs); return ret; } om_bool om_dict_put(om_dict_ptr dict, void *key, void *val) { om_uint64 hash = dict->hash_func(key); int index = hash % dict->bucket_count; om_list_ptr bucket = __om_dict_get_bucket_for_key(dict,key); void * value = val; void * key_ins = key; // if the bucket has not been initialized if( bucket==OM_NULL ) { bucket = dict->buckets[index] = om_list_new(); if( bucket==OM_NULL ) { return OM_FALSE; } bucket->release_func = __om_dict_release_entry_func; bucket->release_data = dict; } // if a copy function for incoming values has been assigned if( dict->copy_value_func!=OM_NULL ) { value = dict->copy_value_func(val); if( value == OM_NULL ) { return OM_FALSE; } } // if a key copy function has been assigned if( dict->copy_key_func!=OM_NULL ) { key_ins = dict->copy_key_func(val); if( key_ins == OM_NULL ) { __om_dict_free_key_value(dict,key,value); return OM_FALSE; } } // try to find an existing dictionary entry for the key om_dict_entry_ptr ent = __om_dict_get_entry(dict,key_ins); if( ent==OM_NULL ) { ent = __om_dict_new_entry(key_ins,value); if( ent==OM_NULL ) { return OM_FALSE; } if( ! om_list_append(bucket,ent) ) { return OM_FALSE; } } // an existing entry was found, so we'll just replace the value else { __om_dict_free_key_value(dict,ent->key,ent->value); ent->key=key_ins; ent->value=val; } return OM_TRUE; } void * om_dict_get(om_dict_ptr dict, void *key) { om_dict_entry_ptr ptr = __om_dict_get_entry(dict,key); if( ptr==OM_NULL ) return OM_NULL; return ptr->value; } void * om_dict_remove(om_dict_ptr dict, void *key) { void * toret = OM_NULL; om_uint64 hash = dict->hash_func(key); int bucket_index = hash % dict->bucket_count; om_list_ptr bucket = dict->buckets[bucket_index]; // om_list_ptr bucket = om_dict_get_bucket_for_key(dict,key); if( bucket==OM_NULL ) { return OM_NULL; } int end = om_list_count(bucket); for( int i=0; i<end; i++ ) { om_dict_entry_ptr ent = om_list_get(bucket,i); if( dict->hash_func(ent->key) == dict->hash_func(key) ) { toret = ent->value; om_list_remove(bucket,ent); break; } } // if it was the only value in the bucket, // then go ahead and free-up the list of the // bucket if(end==1) { om_list_release(dict->buckets[bucket_index]); dict->buckets[bucket_index] = OM_NULL; } return toret; } om_bool om_dict_clear(om_dict_ptr dict) { for( int i=0; i < dict->bucket_count; i++ ) { if( dict->buckets[i]!=OM_NULL ) { om_list_release(dict->buckets[i]); dict->buckets[i]=OM_NULL; } } return OM_TRUE; } int om_dict_count(om_dict_ptr dict) { int cnt = 0; for( int i=0; i<dict->bucket_count; i++ ) { if( dict->buckets[i]!=OM_NULL ) { cnt += om_list_count(dict->buckets[i]); } } return cnt; } om_list_ptr om_dict_get_keys(om_dict_ptr dict) { om_list_ptr lst = om_list_new(); if( lst == OM_NULL ) { return OM_NULL; } // set the release_func to null, // so that the caller doesn't inadvertantly // free their keys lst->release_func=OM_NULL; for( int i=0; i<dict->bucket_count; i++ ) { if( dict->buckets[i]!=OM_NULL ) { int cnt = om_list_count(dict->buckets[i]); for( int j=0; j<cnt; j++ ) { om_dict_entry_ptr ent = om_list_get(dict->buckets[i],j); om_list_append(lst,ent->key); } } } return lst; } /* Provided hash algorithms */ om_uint64 om_dict_hash_string(void * string_key) { char * str = (char *)string_key; int i = 0; char code = 0; while(str[i++]!='\0') { code = code ^ str[i-1]; } return (int)code; } /* private function definitions */ void __om_dict_release_entry_func(void* entry, void *release_data) { om_dict_entry_ptr ent = (om_dict_entry_ptr)entry; om_dict_ptr dict = (om_dict_ptr)release_data; __om_dict_free_key_value(dict,ent->key,ent->value); om_free(ent); } void __om_dict_free_key_value(om_dict_ptr dict, void *key, void *val) { if( dict->release_func!=OM_NULL ) { dict->release_func(key,val,dict->release_data); } } om_list_ptr __om_dict_get_bucket_for_key(om_dict_ptr dict, void *key) { om_uint64 hash = dict->hash_func(key); int index = hash % dict->bucket_count; om_list_ptr bucket = dict->buckets[index]; if( bucket==OM_NULL ) return OM_NULL; return bucket; } om_dict_entry_ptr __om_dict_get_entry(om_dict_ptr dict, void *key) { om_list_ptr bucket = __om_dict_get_bucket_for_key(dict,key); if( bucket==OM_NULL ) return OM_NULL; int i = om_list_count(bucket); for( int j=0; j<i; j++ ) { om_dict_entry_ptr item = om_list_get(bucket,j); if( dict->hash_func(item->key)==dict->hash_func(key) ) { return item; } } return OM_NULL; } om_dict_entry_ptr __om_dict_new_entry(void * key, void * val) { om_dict_entry_ptr ret = om_malloc(sizeof(om_dict_entry)); if( ret==NULL ) { om_error_set(OM_ERR_MALLOC,"Couldn't allocate a new dict entry"); return OM_NULL; } ret->key=key; ret->value=val; return ret; }
722,407
./openmeap/clients/c/openmeap-slic-core/test/digest-test.c
/* ############################################################################### # # # Copyright (C) 2011-2013 OpenMEAP, Inc. # # Credits to Jonathan Schang & Robert Thacher # # # # Released under the LGPLv3 # # # # OpenMEAP is free software: you can redistribute it and/or modify # # it under the terms of the GNU Lesser General Public License as published # # by the Free Software Foundation, either version 3 of the License, or # # (at your option) any later version. # # # # OpenMEAP is distributed in the hope that it will be useful, # # but WITHOUT ANY WARRANTY; without even the implied warranty of # # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # # GNU Lesser General Public License for more details. # # # # You should have received a copy of the GNU Lesser General Public License # # along with OpenMEAP. If not, see <http://www.gnu.org/licenses/>. # # # ############################################################################### */ #include <stdio.h> #include <string.h> #include <openmeap-slic-core.h> #include "unit-tests.h" #include "digest-test.h" START_TEST(test_digest_set) { om_props_ptr props = om_props_acquire("test properties"); om_prefs_ptr prefs = om_prefs_acquire("test preferences"); om_config_ptr cfg = om_config_obtain(prefs,props); om_storage_ptr stg = default_om_storage_alloc(cfg); om_file_input_stream *istr = om_storage_open_file_input_stream(stg,"test.zip"); ASSERT(istr!=OM_NULL,"Whoops!"); char *md5 = om_digest_hash_file(istr,OM_HASH_MD5); ASSERT(strcmp(md5,"df9c8c31053a0cc3f52d0a593ca330f3")==0,"Md5 message digest did not match expectations"); om_free(md5); rewind((FILE*)istr->device_data); char *sha1 = om_digest_hash_file(istr,OM_HASH_SHA1); ASSERT(strcmp(sha1,"8a57f901db58425430021a8dfbfaaf543a42ed2f")==0,"Sha1 message digest did not match expectations."); om_free(sha1); om_storage_close_file_input_stream(istr); om_storage_release(stg); om_config_release(cfg); om_prefs_release(prefs); om_props_release(props); ASSERT_FREE } END_TEST() void run_digest_tests() { UNIT_TEST(test_digest_set); }
722,408
./openmeap/clients/c/openmeap-slic-core/test/zip-test.c
/* ############################################################################### # # # Copyright (C) 2011-2013 OpenMEAP, Inc. # # Credits to Jonathan Schang & Robert Thacher # # # # Released under the LGPLv3 # # # # OpenMEAP is free software: you can redistribute it and/or modify # # it under the terms of the GNU Lesser General Public License as published # # by the Free Software Foundation, either version 3 of the License, or # # (at your option) any later version. # # # # OpenMEAP is distributed in the hope that it will be useful, # # but WITHOUT ANY WARRANTY; without even the implied warranty of # # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # # GNU Lesser General Public License for more details. # # # # You should have received a copy of the GNU Lesser General Public License # # along with OpenMEAP. If not, see <http://www.gnu.org/licenses/>. # # # ############################################################################### */ #include <openmeap-slic-core.h> #include "unit-tests.h" #include "unzip.h" START_TEST(test_list_zip) { om_unzip_archive_ptr ptr = om_unzip_open_archive("test.zip"); ASSERT(ptr!=OM_NULL,"Should have been able to open a file"); om_bool err = om_unzip_archive_into_path(ptr,"/tmp"); if( err==OM_FALSE ) { int n = om_list_count(ptr->error_log); for( int i=0; i<n; i++ ) { printf("%s\n",om_list_get(ptr->error_log,i)); } } om_unzip_close_archive(ptr); ASSERT_FREE om_storage_ptr stg = om_malloc(sizeof(om_storage)); stg->delete_directory=default_om_storage_delete_directory; om_storage_delete_directory( (om_storage_ptr)stg, "/tmp/version-0.0.3a", OM_FALSE ); om_free(stg); ASSERT_FREE } END_TEST() void run_zip_tests() { UNIT_TEST(test_list_zip); }
722,409
./openmeap/clients/c/openmeap-slic-core/test/dict-test.c
/* ############################################################################### # # # Copyright (C) 2011-2013 OpenMEAP, Inc. # # Credits to Jonathan Schang & Robert Thacher # # # # Released under the LGPLv3 # # # # OpenMEAP is free software: you can redistribute it and/or modify # # it under the terms of the GNU Lesser General Public License as published # # by the Free Software Foundation, either version 3 of the License, or # # (at your option) any later version. # # # # OpenMEAP is distributed in the hope that it will be useful, # # but WITHOUT ANY WARRANTY; without even the implied warranty of # # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # # GNU Lesser General Public License for more details. # # # # You should have received a copy of the GNU Lesser General Public License # # along with OpenMEAP. If not, see <http://www.gnu.org/licenses/>. # # # ############################################################################### */ #include <openmeap-slic-core.h> #include "unit-tests.h" #include "dict-test.h" void * __keyPassed = OM_NULL; void * __valuePassed = OM_NULL; void * __releaseDataPassed = OM_NULL; OM_PRIVATE_FUNC void __mock_release_dict_func(void *key, void *value, void *release_data) { __keyPassed = key; __valuePassed = value; __releaseDataPassed = release_data; } START_TEST(test_dict) { int hashVal = om_dict_hash_string("jon"); ASSERT(hashVal==107,"should be 107"); hashVal = om_dict_hash_string("jons"); ASSERT(hashVal==24,"should be 24"); ASSERT_FREE }END_TEST() /** * Validate that the count function is correct */ START_TEST(test_dict_put_get_count) { om_dict_ptr dict = om_dict_new(20); om_dict_put(dict,"test","value"); om_dict_put(dict,"test1","value1"); om_dict_put(dict,"test2","value2"); char *val = om_dict_get(dict,"test"); ASSERT(val!=OM_NULL && strcmp(val,"value")==0,"should be 'value'"); ASSERT(om_dict_count(dict)==3,"the dict should have 3 values at this point"); ASSERT(strcmp(om_dict_remove(dict,"test1"),"value1")==0 && om_dict_count(dict)==2 && strcmp(om_dict_get(dict,"test"),"value")==0, "value should be returned and removed"); om_dict_release(dict); ASSERT_FREE }END_TEST() /** * Validate that the release function is called on overwriting a value. */ START_TEST(test_dict_release_func_on_overwrite) { om_dict_ptr dict = om_dict_new(15); dict->release_func=&__mock_release_dict_func; om_dict_put(dict,"test4","value4"); om_dict_put(dict,"test5","value5"); om_dict_put(dict,"test6","value6"); ASSERT(om_dict_count(dict)==3,"count should, again, be 3"); om_dict_put(dict,"test6","another value"); ASSERT(strcmp(om_dict_get(dict,"test6"),"another value")==0, "should be 'another value'"); ASSERT( __keyPassed!=OM_NULL && __valuePassed!=OM_NULL && __releaseDataPassed==OM_NULL, "release_func should have been called"); om_dict_release(dict); ASSERT_FREE }END_TEST() /** * Validate that put returns false when an alloc failure occurs. */ START_TEST(test_dict_alloc_failures) { om_dict_ptr dict = om_dict_new(15); om_malloc_fail=OM_TRUE; om_bool ret = om_dict_put(dict,"test7","test7"); ASSERT(ret==OM_FALSE && om_error_get_code()==OM_ERR_MALLOC,"a failure should have been triggered"); om_error_clear(); om_malloc_fail=OM_FALSE; om_dict_release(dict); ASSERT_FREE }END_TEST() /** * Verify that we can successfully clear the dict. */ START_TEST(test_dict_clear) { om_dict_ptr dict = om_dict_new(15); om_dict_put(dict,"test","value4"); om_dict_put(dict,"test5","value5"); om_dict_put(dict,"test6","value6"); om_dict_clear(dict); ASSERT(om_dict_get(dict,"test")==OM_NULL && om_dict_count(dict)==0, "dict should be clear now"); for( int i=0; i<dict->bucket_count; i++ ) { ASSERT(dict->buckets[i]==OM_NULL,"buckets should be all null"); } om_dict_release(dict); ASSERT_FREE } END_TEST() /** * Verify the om_dict_from_query_string method. */ START_TEST(test_dict_from_query_string) { char * query = "key1=value1&key2=value2&key3=value3"; om_dict_ptr dict = om_dict_from_query_string(query); char * r=OM_NULL; ASSERT(dict!=OM_NULL && om_dict_count(dict)==3,"dict should have 3 entries"); r=om_dict_get(dict,"key1"); ASSERT(strcmp(r,"value1")==0,"key/value pair is incorrect, should be 1"); r=om_dict_get(dict,"key2"); ASSERT(strcmp(r,"value2")==0,"key/value pair is incorrect, should be 2"); r=om_dict_get(dict,"key3"); ASSERT(strcmp(r,"value3")==0,"key/value pair is incorrect, should be 3"); om_dict_release(dict); ASSERT_FREE }END_TEST() void run_dict_tests() { UNIT_TEST(test_dict); UNIT_TEST(test_dict_put_get_count); UNIT_TEST(test_dict_release_func_on_overwrite); UNIT_TEST(test_dict_alloc_failures); UNIT_TEST(test_dict_clear); UNIT_TEST(test_dict_from_query_string); }
722,410
./openmeap/clients/c/openmeap-slic-core/test/core-test.c
/* ############################################################################### # # # Copyright (C) 2011-2013 OpenMEAP, Inc. # # Credits to Jonathan Schang & Robert Thacher # # # # Released under the LGPLv3 # # # # OpenMEAP is free software: you can redistribute it and/or modify # # it under the terms of the GNU Lesser General Public License as published # # by the Free Software Foundation, either version 3 of the License, or # # (at your option) any later version. # # # # OpenMEAP is distributed in the hope that it will be useful, # # but WITHOUT ANY WARRANTY; without even the implied warranty of # # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # # GNU Lesser General Public License for more details. # # # # You should have received a copy of the GNU Lesser General Public License # # along with OpenMEAP. If not, see <http://www.gnu.org/licenses/>. # # # ############################################################################### */ #include <openmeap-slic-core.h> #include "unit-tests.h" START_TEST(test_core) { } END_TEST() void run_core_tests() { UNIT_TEST(test_core); }
722,411
./openmeap/clients/c/openmeap-slic-core/test/jsapi-test.c
/* ############################################################################### # # # Copyright (C) 2011-2013 OpenMEAP, Inc. # # Credits to Jonathan Schang & Robert Thacher # # # # Released under the LGPLv3 # # # # OpenMEAP is free software: you can redistribute it and/or modify # # it under the terms of the GNU Lesser General Public License as published # # by the Free Software Foundation, either version 3 of the License, or # # (at your option) any later version. # # # # OpenMEAP is distributed in the hope that it will be useful, # # but WITHOUT ANY WARRANTY; without even the implied warranty of # # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # # GNU Lesser General Public License for more details. # # # # You should have received a copy of the GNU Lesser General Public License # # along with OpenMEAP. If not, see <http://www.gnu.org/licenses/>. # # # ############################################################################### */
722,412
./openmeap/clients/c/openmeap-slic-core/test/unit-tests.c
/* ############################################################################### # # # Copyright (C) 2011-2013 OpenMEAP, Inc. # # Credits to Jonathan Schang & Robert Thacher # # # # Released under the LGPLv3 # # # # OpenMEAP is free software: you can redistribute it and/or modify # # it under the terms of the GNU Lesser General Public License as published # # by the Free Software Foundation, either version 3 of the License, or # # (at your option) any later version. # # # # OpenMEAP is distributed in the hope that it will be useful, # # but WITHOUT ANY WARRANTY; without even the implied warranty of # # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # # GNU Lesser General Public License for more details. # # # # You should have received a copy of the GNU Lesser General Public License # # along with OpenMEAP. If not, see <http://www.gnu.org/licenses/>. # # # ############################################################################### */ #include <stdio.h> #include <string.h> #include <openmeap-slic-core.h> #include "unit-tests.h" #include "error-test.h" #include "list-test.h" #include "storage-test.h" #include "dict-test.h" #include "config-test.h" #include "update-test.h" #include "zip-test.h" #include "digest-test.h" int main (void) { run_dict_tests(); run_string_tests(); run_zip_tests(); run_core_tests(); run_error_tests(); run_list_tests(); run_update_tests(); run_config_tests(); run_storage_tests(); run_digest_tests(); return 0; }
722,413
./openmeap/clients/c/openmeap-slic-core/test/config-test.c
/* ############################################################################### # # # Copyright (C) 2011-2013 OpenMEAP, Inc. # # Credits to Jonathan Schang & Robert Thacher # # # # Released under the LGPLv3 # # # # OpenMEAP is free software: you can redistribute it and/or modify # # it under the terms of the GNU Lesser General Public License as published # # by the Free Software Foundation, either version 3 of the License, or # # (at your option) any later version. # # # # OpenMEAP is distributed in the hope that it will be useful, # # but WITHOUT ANY WARRANTY; without even the implied warranty of # # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # # GNU Lesser General Public License for more details. # # # # You should have received a copy of the GNU Lesser General Public License # # along with OpenMEAP. If not, see <http://www.gnu.org/licenses/>. # # # ############################################################################### */ #include <openmeap-slic-core.h> #include "unit-tests.h" #include "config-test.h" START_TEST(test_config) { om_props_ptr props = om_props_acquire("properties"); om_prefs_ptr prefs = om_prefs_acquire("preferences"); ASSERT(props!=OM_NULL && prefs!=OM_NULL,"prefs and props should be set"); om_dict_put(props->device_data,"com.openmeap.slic.appName","app_name"); // validate that failure to allocate functions as expected om_malloc_fail = OM_TRUE; om_config_ptr cfg = om_config_obtain(prefs,props); ASSERT(cfg==OM_NULL && om_error_get_code()==OM_ERR_MALLOC,"should have set error and returned null"); om_error_clear(); om_malloc_fail = OM_FALSE; // validate that a config object can be allocated cfg = om_config_obtain(prefs,props); ASSERT(cfg!=OM_NULL,"should be able to get a config object"); // verify that error is set and null is returned if the string cannot be copied om_malloc_fail = OM_TRUE; char *ptr = om_config_get(cfg,OM_CFG_APP_NAME); ASSERT(ptr==OM_NULL && om_error_get_code()==OM_ERR_MALLOC,"should have set error and returned null"); om_error_clear(); om_malloc_fail = OM_FALSE; // test that the initial props value will be returned, // if the prefs haven't been updated ptr = om_config_get(cfg,OM_CFG_APP_NAME); ASSERT(strcmp(ptr,"app_name")==0,"should be app_name"); om_free(ptr); om_config_set(cfg,OM_CFG_APP_NAME,"app_name_2"); ptr = om_config_get(cfg,OM_CFG_APP_NAME); ASSERT(strcmp(ptr,"app_name_2")==0,"should be app_name_2 at this point"); om_free(ptr); // per the interface contract, i need to free this. ptr = om_config_get_original(cfg,OM_CFG_APP_NAME); ASSERT(strcmp(ptr,"app_name")==0,"the original should return app_name at this point."); om_free(ptr); ptr = om_dict_get(props->device_data, "com.openmeap.slic.appName"); ASSERT(strcmp(ptr,"app_name")==0, "props data should not have changed"); // test the type conversion om_uint32 last_update=9827343; om_uint32 *last_update_ptr; om_config_set(cfg,OM_CFG_UPDATE_LAST_ATTEMPT,&last_update); last_update_ptr = om_config_get(cfg,OM_CFG_UPDATE_LAST_ATTEMPT); ASSERT( *last_update_ptr == last_update, "the last update uint32 should have survived the round trip" ); om_free(last_update_ptr); last_update=9827343; *last_update_ptr; last_update_ptr = om_config_get(cfg,OM_CFG_UPDATE_FREQ); ASSERT( last_update_ptr == OM_NULL && om_error_get_code()==OM_ERR_NONE, "the last update uint32 should have survived the round trip" ); om_free(last_update_ptr); om_props_release(props); om_prefs_release(prefs); om_config_release(cfg); ASSERT_FREE } END_TEST() void run_config_tests() { UNIT_TEST(test_config); }
722,414
./openmeap/clients/c/openmeap-slic-core/test/storage-test.c
/* ############################################################################### # # # Copyright (C) 2011-2013 OpenMEAP, Inc. # # Credits to Jonathan Schang & Robert Thacher # # # # Released under the LGPLv3 # # # # OpenMEAP is free software: you can redistribute it and/or modify # # it under the terms of the GNU Lesser General Public License as published # # by the Free Software Foundation, either version 3 of the License, or # # (at your option) any later version. # # # # OpenMEAP is distributed in the hope that it will be useful, # # but WITHOUT ANY WARRANTY; without even the implied warranty of # # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # # GNU Lesser General Public License for more details. # # # # You should have received a copy of the GNU Lesser General Public License # # along with OpenMEAP. If not, see <http://www.gnu.org/licenses/>. # # # ############################################################################### */ #include <openmeap-slic-core.h> #include "unit-tests.h" #include "storage-test.h" #include <memory.h> START_TEST(test_storage) { char *ptr = OM_NULL; om_bool result = OM_FALSE; om_storage_ptr stg = om_storage_alloc(NULL); // just make sure i can use my mock vars object om_storage_mock_vars vars; memset( (void*)&vars, 0, sizeof(om_storage_mock_vars) ); om_storage_set_mock_vars(&vars); vars.get_bytes_free_result=666; ASSERT((void*)om_storage_get_bytes_free(stg)==666,"should have been correct"); om_props_ptr props = om_props_acquire("test properties"); ASSERT(props!=OM_NULL,"props should not be null"); om_prefs_ptr prefs = om_prefs_acquire("test preferences"); ASSERT(prefs!=OM_NULL,"prefs should not be null"); om_config_ptr cfg = om_config_obtain(prefs,props); ASSERT(cfg!=OM_NULL,"cfg should not be null"); om_storage_release(stg); // verify that we can flip flop the storage location // must be a str so strlen will work in supporting code /*om_config_set(cfg,OM_CFG_CURRENT_STORAGE,"a"); stg = om_storage_alloc(cfg); om_storage_do_flip_flop(stg); ptr = om_config_get(cfg,OM_CFG_CURRENT_STORAGE); ASSERT(ptr[0]=='b',"we should be in the 'b' storage location now"); om_free(ptr); //om_storage_free_mock_vars(&vars); om_storage_do_flip_flop(stg); ptr = om_config_get(cfg,OM_CFG_CURRENT_STORAGE); ASSERT(ptr[0]=='a',"we should be in the 'a' storage location now"); om_free(ptr);*/ // validate the delete import archive function stg = om_storage_alloc(cfg); om_config_set(cfg,OM_CFG_IMPORT_ARCHIVE_PATH,"path"); vars.delete_file_result = OM_TRUE; result = om_storage_delete_import_archive(stg); ASSERT(result==OM_TRUE,"the result from delete_file_result should have made it here"); ASSERT(strcmp(vars.delete_file_arg,"path")==0,"om_storage_delete_import_archive called om_storage_delete_file with the wrong arg"); om_storage_free_mock_vars(&vars); om_storage_release(stg); om_config_release(cfg); om_prefs_release(prefs); om_props_release(props); om_storage_free_mock_vars(vars); ASSERT_FREE } END_TEST() void run_storage_tests() { UNIT_TEST(test_storage); }
722,415
./openmeap/clients/c/openmeap-slic-core/test/string-test.c
/* ############################################################################### # # # Copyright (C) 2011-2013 OpenMEAP, Inc. # # Credits to Jonathan Schang & Robert Thacher # # # # Released under the LGPLv3 # # # # OpenMEAP is free software: you can redistribute it and/or modify # # it under the terms of the GNU Lesser General Public License as published # # by the Free Software Foundation, either version 3 of the License, or # # (at your option) any later version. # # # # OpenMEAP is distributed in the hope that it will be useful, # # but WITHOUT ANY WARRANTY; without even the implied warranty of # # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # # GNU Lesser General Public License for more details. # # # # You should have received a copy of the GNU Lesser General Public License # # along with OpenMEAP. If not, see <http://www.gnu.org/licenses/>. # # # ############################################################################### */ #include <openmeap-slic-core.h> #include "unit-tests.h" #include "string-test.h" #include <stdio.h> #include <string.h> START_TEST(test_string_substr) { char * vals = "This is the string to take a substring of"; om_substring_ptr ptr = om_substring_new((char*)(vals+12),6); char * copy = om_substring_copy(ptr); ASSERT(strcmp(copy,"string")==0 && strlen(copy)==6,"string should strcmp==0 with \"string\""); ASSERT(om_substring_equals(ptr,"string")==OM_TRUE,"om_substring_equals failed"); om_free(copy); om_substring_release(ptr); ASSERT_FREE } END_TEST(); START_TEST(test_string_substr_new) { char * vals = "This is the string to take a substring of"; om_malloc_fail=OM_TRUE; char * ptr = om_substring_new((char*)(vals+12),6); ASSERT(ptr==OM_NULL && om_error_get_code()==OM_ERR_MALLOC,"error code should have been set"); om_error_clear(); om_malloc_fail=OM_FALSE; ASSERT_FREE } END_TEST(); START_TEST(test_string_append) { char * newstr = om_string_append("this is ","a string that should be"); ASSERT(strcmp(newstr,"this is a string that should be")==0,"string contains incorrect content"); om_free(newstr); ASSERT_FREE } END_TEST(); START_TEST(test_string_substr_range) { char * newstr = om_string_substr("this is a string",5,4); ASSERT(strcmp(newstr,"is a")==0,"substr should return \"is a\""); om_free(newstr); ASSERT_FREE } END_TEST(); START_TEST(test_string_format) { char *newstr = om_string_format("%u : %s",1001,"This is a string"); ASSERT(strcmp("1001 : This is a string", newstr)==0,"String returned was incorrect"); om_free(newstr); ASSERT_FREE } END_TEST(); START_TEST(test_string_explode) { const char *testStr = "this/is/a/typical/path"; om_list_ptr list = om_string_explode(testStr,'/'); ASSERT(om_list_count(list)==5,"Should be 5 segments"); om_list_release(list); ASSERT_FREE } END_TEST(); START_TEST(test_string_implode) { const char *testStr = "this/is/a/typical/path"; om_list_ptr list = om_string_explode(testStr,'/'); char *newstr = om_string_implode(list,'/'); ASSERT(strcmp(newstr,testStr)==0,"should be this/is/a/typical/path"); om_list_release(list); om_free(newstr); ASSERT_FREE } END_TEST(); START_TEST(test_string_encodeURI) { const char *toUrlEncode = "this_string should*be@url#encoded"; char * encoded = om_string_encodeURI(toUrlEncode); ASSERT(strcmp(encoded,"this_string%20should*be%40url%23encoded")==0,"result is not correctly encoded"); om_free(encoded); ASSERT_FREE } END_TEST(); START_TEST(test_string_decodeURI) { const char *toUrlDecode = "this_string%20should*be%40url%23encoded"; char * decoded = om_string_decodeURI(toUrlDecode); ASSERT(strcmp(decoded,"this_string should*be@url#encoded")==0,"result is not correctly decoded"); om_free(decoded); ASSERT_FREE } END_TEST(); void run_string_tests() { UNIT_TEST(test_string_substr); UNIT_TEST(test_string_substr_new); UNIT_TEST(test_string_append); UNIT_TEST(test_string_substr_range); UNIT_TEST(test_string_format); UNIT_TEST(test_string_explode); UNIT_TEST(test_string_implode); UNIT_TEST(test_string_encodeURI); UNIT_TEST(test_string_decodeURI); }
722,416
./openmeap/clients/c/openmeap-slic-core/test/error-test.c
/* ############################################################################### # # # Copyright (C) 2011-2013 OpenMEAP, Inc. # # Credits to Jonathan Schang & Robert Thacher # # # # Released under the LGPLv3 # # # # OpenMEAP is free software: you can redistribute it and/or modify # # it under the terms of the GNU Lesser General Public License as published # # by the Free Software Foundation, either version 3 of the License, or # # (at your option) any later version. # # # # OpenMEAP is distributed in the hope that it will be useful, # # but WITHOUT ANY WARRANTY; without even the implied warranty of # # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # # GNU Lesser General Public License for more details. # # # # You should have received a copy of the GNU Lesser General Public License # # along with OpenMEAP. If not, see <http://www.gnu.org/licenses/>. # # # ############################################################################### */ #include <stdio.h> #include <string.h> #include <openmeap-slic-core.h> #include "unit-tests.h" #include "error-test.h" START_TEST(test_error_set) { const char *mesg = "testing om_set_error"; om_error_set(OM_ERR_APP_SVC_CONN,mesg); ASSERT( strcmp(mesg,om_error_get_message())==0, "expecting om_error_get_message() to return a valid pointer" ); om_error_set(OM_ERR_MALLOC,mesg); ASSERT( strcmp(om_error_get_message_for_code(OM_ERR_MALLOC),om_error_get_message())==0, "expecting om_error_get_message() to return the default message for malloc" ); ASSERT_FREE } END_TEST() void run_error_tests() { UNIT_TEST(test_error_set); }
722,417
./openmeap/clients/c/openmeap-slic-core/test/list-test.c
/* ############################################################################### # # # Copyright (C) 2011-2013 OpenMEAP, Inc. # # Credits to Jonathan Schang & Robert Thacher # # # # Released under the LGPLv3 # # # # OpenMEAP is free software: you can redistribute it and/or modify # # it under the terms of the GNU Lesser General Public License as published # # by the Free Software Foundation, either version 3 of the License, or # # (at your option) any later version. # # # # OpenMEAP is distributed in the hope that it will be useful, # # but WITHOUT ANY WARRANTY; without even the implied warranty of # # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # # GNU Lesser General Public License for more details. # # # # You should have received a copy of the GNU Lesser General Public License # # along with OpenMEAP. If not, see <http://www.gnu.org/licenses/>. # # # ############################################################################### */ #include <openmeap-slic-core.h> #include <stdio.h> #include <string.h> #include "unit-tests.h" START_TEST(test_list) { char *str[] = { "static string\0", "static string 2\0" }; om_list_ptr myList = om_list_new(); myList->release_func=OM_NULL; ASSERT(myList!=OM_NULL,"allocate a new list failed"); ASSERT(om_list_prepend(myList,str[0]),"prepend a static string failed"); ASSERT(strcmp(om_list_get(myList,0),str[0])==0,"access an item failed"); ASSERT(om_list_append(myList,str[1]),"appending static string failed"); ASSERT(strcmp(om_list_get(myList,1),str[1])==0,"get appended string failed"); ASSERT(om_list_append(myList,"test"),"appending static string failed"); ASSERT(strcmp(om_list_get(myList,2),"test")==0,"get appended string failed"); ASSERT(om_list_count(myList)==3,"count at this point should be 3"); ASSERT(om_list_remove(myList,str[1])==OM_TRUE,"removing a middle element failed"); ASSERT(om_list_append(myList,str[1]) && om_list_get_index(myList,str[1])==2, "appending static string failed"); ASSERT(om_list_get(myList,0)==str[0],"pointer at index 0 should be different"); ASSERT(om_list_count(myList)==3,"count should be 3"); ASSERT(om_list_remove(myList,str[0])==OM_TRUE && om_list_get_index(myList,str[0])==(-1), "removing (1) by pointer failed"); ASSERT(om_list_remove_index(myList,0)==OM_TRUE,"removing (2) by index failed"); ASSERT(om_list_remove_index(myList,0)==OM_TRUE,"removing (3) by index failed"); ASSERT(om_list_remove_index(myList,0)==OM_FALSE && om_list_count(myList)==0, "removing (4) by index succeeded but should have failed with an empty list"); om_malloc_fail=OM_TRUE; om_bool ret = om_list_append(myList,str[0]); ASSERT(ret==OM_FALSE && om_error_get_code()==OM_ERR_MALLOC,"append should have triggered malloc() error"); om_malloc_fail=OM_FALSE; om_error_clear(); om_malloc_fail=OM_TRUE; ret = om_list_prepend(myList,str[0]); ASSERT(ret==OM_FALSE && om_error_get_code()==OM_ERR_MALLOC,"prepend should have triggered malloc() error"); om_malloc_fail=OM_FALSE; om_error_clear(); om_list_release(myList); ASSERT_FREE } END_TEST() void run_list_tests(void) { UNIT_TEST(test_list); }
722,418
./openmeap/clients/c/openmeap-slic-core/test/update-test.c
/* ############################################################################### # # # Copyright (C) 2011-2013 OpenMEAP, Inc. # # Credits to Jonathan Schang & Robert Thacher # # # # Released under the LGPLv3 # # # # OpenMEAP is free software: you can redistribute it and/or modify # # it under the terms of the GNU Lesser General Public License as published # # by the Free Software Foundation, either version 3 of the License, or # # (at your option) any later version. # # # # OpenMEAP is distributed in the hope that it will be useful, # # but WITHOUT ANY WARRANTY; without even the implied warranty of # # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # # GNU Lesser General Public License for more details. # # # # You should have received a copy of the GNU Lesser General Public License # # along with OpenMEAP. If not, see <http://www.gnu.org/licenses/>. # # # ############################################################################### */ #include <openmeap-slic-core.h> #include "unit-tests.h" #include "mock/network-mock.h" om_update_header_ptr om_update_header_ptr_response; om_update_header_ptr om_update_parse_connreq_resp(char *resp) { return om_update_header_ptr_response; } const char *test_response = "{\"connectionOpenResponse\":{\"update\":{\"storageNeeds\":809126,\"updateUrl\":\"http://dev.openmeap.com:8081/openmeap-services-web/application-management/?action=archiveDownload&app-name=Application%20Name&auth=auth_token&app-version=cof-banking-v1\",\"hash\":{\"value\":\"99eabf34466dbb2e11d6c0550cbaccfb\",\"algorithm\":\"MD5\"},\"versionIdentifier\":\"version-2.0.3\",\"type\":\"IMMEDIATE\",\"installNeeds\":1157102},\"authToken\":\"auth_token\"}}"; // defined in config.c, but not explicitly in the config.h const char * om_config_map_to_str(int om_config_enum); START_TEST(test_update_decision){ om_prefs_ptr prefs = om_prefs_acquire("new prefs"); om_props_ptr props = om_props_acquire("new props"); om_prefs_set(prefs,om_config_map_to_str(OM_CFG_DEV_TYPE),"device_type"); om_prefs_set(prefs,om_config_map_to_str(OM_CFG_DEV_UUID),"device_uuid"); om_prefs_set(prefs,om_config_map_to_str(OM_CFG_APP_NAME),"app_name"); om_prefs_set(prefs,om_config_map_to_str(OM_CFG_APP_VER),"app_version"); om_prefs_set(prefs,om_config_map_to_str(OM_CFG_SLIC_VER),"slic_version"); om_config_ptr cfg = om_config_obtain(prefs,props); // create a connreq object from the configuration passed in om_update_connreq_ptr connreq = om_update_create_connreq(cfg); ASSERT(strcmp("device_type",connreq->device_type)==0,"device_type should have been 'device_type'"); ASSERT(strcmp("device_uuid",connreq->device_uuid)==0,"device_uuid should have been 'device_uuid'"); ASSERT(strcmp("app_name",connreq->app_name)==0,"app_name should have been 'app_name'"); ASSERT(strcmp("app_version",connreq->app_version)==0,"app_version should have been 'app_version'"); ASSERT(strcmp("slic_version",connreq->slic_version)==0,"slic_version should have been 'slic_version'"); char * str = om_update_connreq_create_post(connreq); ASSERT(strcmp("action=connection-open-request&device-type=device_type&device-uuid=device_uuid&"\ "app-name=app_name&app-version=app_version&hash=&slic-version=slic_version", \ str)==0, "the post data created for the connection request generated was not correct"); om_free(str); om_update_release_connreq(connreq); // use the mock method to create a connresp struct // so that we can verify releasing it with the ASSERT_FREE om_update_connresp_ptr om_update_parse_connresp_result = om_update_parse_connresp(test_response); om_update_release_connresp(om_update_parse_connresp_result); // validate the om_update_decision function char tmp[200]; sprintf(tmp,"%u",om_time(0)-16); om_prefs_set(prefs,om_config_map_to_str(OM_CFG_UPDATE_LAST_ATTEMPT),tmp); om_prefs_set(prefs,om_config_map_to_str(OM_CFG_UPDATE_FREQ),"15"); om_prefs_set(prefs,om_config_map_to_str(OM_CFG_UPDATE_SHOULD_PULL),"1"); ASSERT(om_update_decision(cfg),"we should need to pull an update now"); // assert that we won't needlessly pull updates sprintf(tmp,"%u",om_time(0)-10); om_prefs_set(prefs,om_config_map_to_str(OM_CFG_UPDATE_LAST_ATTEMPT),tmp); ASSERT(!om_update_decision(cfg),"we should not need to pull an update now"); // assert that we won't say we need an update if the customer doesn't want them sprintf(tmp,"%u",om_time(0)-16); om_prefs_set(prefs,om_config_map_to_str(OM_CFG_UPDATE_LAST_ATTEMPT),tmp); om_prefs_set(prefs,om_config_map_to_str(OM_CFG_UPDATE_SHOULD_PULL),"0"); ASSERT(!om_update_decision(cfg),"we should not need to pull an update now"); ASSERT( om_uint32_update_parse_helper(OM_UPDATE_TYPE,"required") == OM_UPDATE_TYPE_REQUIRED, \ "should be OM_UPDATE_TYPE_REQUIRED" ); ASSERT( om_uint32_update_parse_helper(OM_UPDATE_TYPE,"optional") == OM_UPDATE_TYPE_OPTIONAL, \ "should be OM_UPDATE_TYPE_OPTIONAL" ); ASSERT( om_uint32_update_parse_helper(OM_UPDATE_TYPE,"none") == OM_UPDATE_TYPE_NONE, \ "should be OM_UPDATE_TYPE_NONE" ); ASSERT( om_uint32_update_parse_helper(OM_UPDATE_STORAGE_NEEDS,"23432") == 23432, \ "result should have been 23432" ); ASSERT( om_uint32_update_parse_helper(OM_UPDATE_INSTALL_NEEDS,"23432") == 23432, \ "result should have been 23432" ); om_prefs_release(prefs); om_props_release(props); om_config_release(cfg); ASSERT_FREE } END_TEST() START_TEST(test_update_perform) { { om_prefs_ptr prefs = om_prefs_acquire("new prefs"); om_props_ptr props = om_props_acquire("new props"); om_prefs_set(prefs,om_config_map_to_str(OM_CFG_DEV_TYPE),"device_type"); om_prefs_set(prefs,om_config_map_to_str(OM_CFG_DEV_UUID),"device_uuid"); om_prefs_set(prefs,om_config_map_to_str(OM_CFG_APP_NAME),"app_name"); om_prefs_set(prefs,om_config_map_to_str(OM_CFG_APP_VER),"app_version"); om_prefs_set(prefs,om_config_map_to_str(OM_CFG_SLIC_VER),"slic_version"); om_prefs_set(prefs,om_config_map_to_str(OM_CFG_UPDATE_LAST_CHECK),"0"); om_config_ptr cfg = om_config_obtain(prefs,props); om_config_set(cfg,OM_CFG_APP_MGMT_URL,"http://tests.openmeap.com/doesntexist"); // we don't need valid xml here, as we're mocking the result of parsing // but we do need some content om_net_mock_vars vars; memset( (void*)&vars, 0, sizeof(om_net_mock_vars) ); om_net_set_mock_vars(&vars); om_http_response http_post_result; memset( (void*)&http_post_result, 0, sizeof(om_http_response) ); vars.do_http_post_result = &http_post_result; vars.do_http_post_result->status_code=200; vars.do_http_post_result->result="<none/>"; ///// om_prefs_release(prefs); om_props_release(props); om_config_release(cfg); ASSERT_FREE } } END_TEST() #include "storage-test.h" START_TEST(test_update_header_json_functions) { om_prefs_ptr prefs = om_prefs_acquire("new prefs"); om_props_ptr props = om_props_acquire("new props"); om_config_ptr cfg = om_config_obtain(prefs,props); om_storage_ptr stg = om_storage_alloc(cfg); om_storage_mock_vars_ptr mock_vars = om_malloc(sizeof(om_storage_mock_vars)); mock_vars->get_bytes_free_result = 666; om_storage_set_mock_vars(mock_vars); om_update_header_ptr header = om_malloc(sizeof(om_update_header)); header->install_needs=1000; header->storage_needs=11661; header->update_url="update_url"; header->version_id="version_id"; header->type=OM_UPDATE_TYPE_REQUIRED; header->hash=om_malloc(sizeof(om_hash_ptr)); header->hash->hash_type=OM_HASH_MD5; header->hash->hash="hash"; char * json = om_update_header_to_json(stg, header); om_update_header_ptr header2 = om_update_header_from_json(json); char * roundTripJson = om_update_header_to_json(stg, header2); ASSERT(strcmp(json,roundTripJson)==0,"header to json round trip failed"); om_free(json); om_free(roundTripJson); om_update_release_update_header(header2); om_free(header->hash); om_free(header); om_free(mock_vars); om_storage_release(stg); om_prefs_release(prefs); om_props_release(props); om_config_release(cfg); ASSERT_FREE } END_TEST() START_TEST(test_update_check) { om_prefs_ptr prefs = om_prefs_acquire("new prefs"); om_props_ptr props = om_props_acquire("new props"); om_prefs_set(prefs,om_config_map_to_str(OM_CFG_DEV_TYPE),"device_type"); om_prefs_set(prefs,om_config_map_to_str(OM_CFG_DEV_UUID),"device_uuid"); om_prefs_set(prefs,om_config_map_to_str(OM_CFG_APP_NAME),"app_name"); om_prefs_set(prefs,om_config_map_to_str(OM_CFG_APP_VER),"app_version"); om_prefs_set(prefs,om_config_map_to_str(OM_CFG_SLIC_VER),"slic_version"); om_prefs_set(prefs,om_config_map_to_str(OM_CFG_UPDATE_LAST_CHECK),"0"); om_config_ptr cfg = om_config_obtain(prefs,props); om_config_set(cfg,OM_CFG_APP_MGMT_URL,"http://tests.openmeap.com/doesntexist"); om_net_mock_vars vars; memset( (void*)&vars, 0, sizeof(om_net_mock_vars) ); om_net_set_mock_vars(&vars); om_http_response http_post_result; memset( (void*)&http_post_result, 0, sizeof(om_http_response) ); vars.do_http_post_result = &http_post_result; vars.do_http_post_result->status_code=200; vars.do_http_post_result->result=test_response; { om_update_header_ptr header = om_update_check(cfg); ASSERT(header!=OM_NULL,"om_update_check should have returned an update pointer"); om_update_release_update_header(header); // verify that the posted data passed to om_net_do_http_post() was correct ASSERT(strcmp(vars.last_post_data,"action=connection-open-request&device-type=device_type&device-uuid=device_uuid&"\ "app-name=app_name&app-version=app_version&hash=&slic-version=slic_version")==0, \ "posted data was incorrect"); om_free(vars.last_post_data); char *authToken = om_config_get(cfg,OM_CFG_AUTH_LAST_TOKEN); ASSERT(strcmp(authToken,"auth_token")==0,"the auth token should have been \"auth_token\""); om_free(authToken); // maybe we shouldn't rely on the clock or runtime of the test in a unit test, // but i'm sure that 10 seconds will be sufficient for most processors... >_< om_uint32 * lastUpdateCheck = om_config_get(cfg,OM_CFG_UPDATE_LAST_CHECK); ASSERT(*lastUpdateCheck>(om_time(0)-10),"om_update_connect should have updated the last update check config"); om_free(lastUpdateCheck); } om_prefs_release(prefs); om_props_release(props); om_config_release(cfg); ASSERT_FREE } END_TEST() void run_update_tests() { UNIT_TEST(test_update_perform); UNIT_TEST(test_update_decision); UNIT_TEST(test_update_check); UNIT_TEST(test_update_header_json_functions); }
722,419
./openmeap/clients/c/openmeap-slic-core/test/mock/props-mock.c
/* ############################################################################### # # # Copyright (C) 2011-2013 OpenMEAP, Inc. # # Credits to Jonathan Schang & Robert Thacher # # # # Released under the LGPLv3 # # # # OpenMEAP is free software: you can redistribute it and/or modify # # it under the terms of the GNU Lesser General Public License as published # # by the Free Software Foundation, either version 3 of the License, or # # (at your option) any later version. # # # # OpenMEAP is distributed in the hope that it will be useful, # # but WITHOUT ANY WARRANTY; without even the implied warranty of # # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # # GNU Lesser General Public License for more details. # # # # You should have received a copy of the GNU Lesser General Public License # # along with OpenMEAP. If not, see <http://www.gnu.org/licenses/>. # # # ############################################################################### */ #include <openmeap-slic-core.h> char * om_mock_props_get(om_props_ptr props, const char *key) { char * ptr = om_dict_get(props->device_data,key); if( ptr==OM_NULL ) return ptr; return om_string_copy(ptr); } /////////////////// om_props_ptr om_props_acquire(const char *name) { om_props_ptr props = om_malloc(sizeof(om_props)); props->device_data = om_dict_new(15); //((om_dict_ptr)props->device_data))->copy_value_func props->get=om_mock_props_get; return props; } void om_props_release(om_props_ptr props) { om_dict_release(props->device_data); om_free(props); }
722,420
./openmeap/clients/c/openmeap-slic-core/test/mock/prefs-mock.c
/* ############################################################################### # # # Copyright (C) 2011-2013 OpenMEAP, Inc. # # Credits to Jonathan Schang & Robert Thacher # # # # Released under the LGPLv3 # # # # OpenMEAP is free software: you can redistribute it and/or modify # # it under the terms of the GNU Lesser General Public License as published # # by the Free Software Foundation, either version 3 of the License, or # # (at your option) any later version. # # # # OpenMEAP is distributed in the hope that it will be useful, # # but WITHOUT ANY WARRANTY; without even the implied warranty of # # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # # GNU Lesser General Public License for more details. # # # # You should have received a copy of the GNU Lesser General Public License # # along with OpenMEAP. If not, see <http://www.gnu.org/licenses/>. # # # ############################################################################### */ #include <openmeap-slic-core.h> void om_mock_prefs_dict_release_entry(void * key, void * value, void * release_data) { om_free(key); om_free(value); } void om_mock_prefs_clear(const om_prefs_ptr prefs) { om_dict_clear((om_dict_ptr)prefs->device_data); } om_bool om_mock_prefs_set(const om_prefs_ptr prefs, const char *key, const char *value) { // the device implementation will have to copy these return om_dict_put((om_prefs_ptr)prefs->device_data,om_string_copy(key),om_string_copy(value))!=OM_NULL ? OM_TRUE : OM_FALSE; } char * om_mock_prefs_get(const om_prefs_ptr prefs, const char *key) { char *val = (char*)om_dict_get((om_dict_ptr)prefs->device_data,key); if( val==OM_NULL ) return OM_NULL; char *ret = om_string_copy(val); if( ret==OM_NULL ) { om_error_set(OM_ERR_MALLOC,"Could not malloc() for string in om_prefs_get()"); return OM_NULL; } return ret; } void om_mock_prefs_remove(const om_prefs_ptr prefs, const char *key) { om_dict_remove((om_dict_ptr)prefs->device_data,key); } ///////////////// om_prefs_ptr om_prefs_acquire(const char *name) { om_prefs_ptr prefs = om_malloc(sizeof(om_prefs)); strcpy(prefs->name,name); prefs->device_data = om_dict_new(15); ((om_dict_ptr)prefs->device_data)->release_func = om_mock_prefs_dict_release_entry; prefs->get=om_mock_prefs_get; prefs->set=om_mock_prefs_set; prefs->clear=om_mock_prefs_clear; prefs->remove=om_mock_prefs_remove; return prefs; } void om_prefs_release(om_prefs_ptr prefs) { om_dict_release((om_dict_ptr)prefs->device_data); om_free(prefs); }
722,421
./openmeap/clients/c/openmeap-slic-core/test/mock/network-mock.c
/* ############################################################################### # # # Copyright (C) 2011-2013 OpenMEAP, Inc. # # Credits to Jonathan Schang & Robert Thacher # # # # Released under the LGPLv3 # # # # OpenMEAP is free software: you can redistribute it and/or modify # # it under the terms of the GNU Lesser General Public License as published # # by the Free Software Foundation, either version 3 of the License, or # # (at your option) any later version. # # # # OpenMEAP is distributed in the hope that it will be useful, # # but WITHOUT ANY WARRANTY; without even the implied warranty of # # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # # GNU Lesser General Public License for more details. # # # # You should have received a copy of the GNU Lesser General Public License # # along with OpenMEAP. If not, see <http://www.gnu.org/licenses/>. # # # ############################################################################### */ #include <openmeap-slic-core.h> #include "network-mock.h" om_net_mock_vars_ptr om_net_mock_vars_var = OM_NULL; void om_net_set_mock_vars(om_net_mock_vars_ptr ptr) { om_net_mock_vars_var = ptr; } om_http_response_ptr om_net_do_http_post(const char *url, const char *post_data) { om_net_mock_vars_var->last_post_data = om_string_copy(post_data); om_http_response_ptr resp = om_malloc(sizeof(om_http_response)); resp->status_code = om_net_mock_vars_var->do_http_post_result->status_code; resp->result = om_string_copy(om_net_mock_vars_var->do_http_post_result->result); return resp; } om_http_response_ptr om_net_do_http_get_to_file_output_stream(const char *url, om_file_output_stream_ptr ostream, void (*call_back)(void *callback_data, om_http_response_ptr response, om_uint32 bytes_total, om_uint32 bytes_downloaded), void *callback_data) { om_net_mock_vars_var->last_input_stream_passed = ostream; om_net_mock_vars_var->last_get_url_passed = om_string_copy(url); om_http_response_ptr resp = om_malloc(sizeof(om_http_response)); resp->status_code = om_net_mock_vars_var->do_http_get_result->status_code; resp->result = om_string_copy(om_net_mock_vars_var->do_http_get_result->result); return resp; }
722,422
./openmeap/clients/c/openmeap-slic-core/test/mock/storage-mock.c
/* ############################################################################### # # # Copyright (C) 2011-2013 OpenMEAP, Inc. # # Credits to Jonathan Schang & Robert Thacher # # # # Released under the LGPLv3 # # # # OpenMEAP is free software: you can redistribute it and/or modify # # it under the terms of the GNU Lesser General Public License as published # # by the Free Software Foundation, either version 3 of the License, or # # (at your option) any later version. # # # # OpenMEAP is distributed in the hope that it will be useful, # # but WITHOUT ANY WARRANTY; without even the implied warranty of # # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # # GNU Lesser General Public License for more details. # # # # You should have received a copy of the GNU Lesser General Public License # # along with OpenMEAP. If not, see <http://www.gnu.org/licenses/>. # # # ############################################################################### */ #include <openmeap-slic-core.h> #include "../storage-test.h" om_storage_mock_vars_ptr om_storage_mock_vars_var = OM_NULL; void om_storage_free_mock_vars(om_storage_mock_vars_ptr ptr) { if( om_storage_mock_vars_var->delete_file_arg!=OM_NULL ) { om_free(om_storage_mock_vars_var->delete_file_arg); om_storage_mock_vars_var->delete_file_arg = OM_NULL; } if( om_storage_mock_vars_var->open_file_output_stream_filePath!=OM_NULL ) { om_free(om_storage_mock_vars_var->open_file_output_stream_filePath); om_storage_mock_vars_var->open_file_output_stream_filePath = OM_NULL; } if( om_storage_mock_vars_var->open_file_input_stream_filePath!=OM_NULL ) { om_free(om_storage_mock_vars_var->open_file_input_stream_filePath); om_storage_mock_vars_var->open_file_input_stream_filePath = OM_NULL; } } void om_storage_set_mock_vars(om_storage_mock_vars_ptr ptr) { om_storage_mock_vars_var = ptr; } om_uint64 mock_om_storage_get_bytes_free(om_storage_ptr storage) { return om_storage_mock_vars_var->get_bytes_free_result; } om_bool mock_om_storage_delete_file(om_storage_ptr storage, const char *filePath) { om_storage_mock_vars_var->delete_file_arg = om_string_copy(filePath); return om_storage_mock_vars_var->delete_file_result; } om_file_input_stream_ptr mock_om_storage_open_file_input_stream(om_storage_ptr storage, const char *filePath) { om_storage_mock_vars_var->open_file_input_stream_filePath = om_string_copy(filePath); return om_storage_mock_vars_var->open_file_input_stream_result; } om_file_output_stream_ptr mock_om_storage_open_file_output_stream(om_storage_ptr storage, const char *filePath, om_bool truncate) { om_storage_mock_vars_var->open_file_output_stream_filePath = om_string_copy(filePath); om_storage_mock_vars_var->open_file_output_stream_truncate = truncate; return om_storage_mock_vars_var->open_file_output_stream_result; } void mock_om_storage_close_file_input_stream(om_file_input_stream_ptr file) { om_storage_mock_vars_var->close_file_input_stream_file=file; om_storage_mock_vars_var->close_file_input_stream_called=OM_TRUE; } void mock_om_storage_close_file_output_stream(om_file_output_stream_ptr file) { om_storage_mock_vars_var->close_file_output_stream_file=file; om_storage_mock_vars_var->close_file_output_stream_called=OM_TRUE; } void om_storage_release(om_storage_ptr storage) { om_free(storage); } om_storage_ptr om_storage_alloc(om_config_ptr *cfg) { om_storage_ptr stg = default_om_storage_alloc(cfg); if( stg==OM_NULL ) return stg; stg->cfg=cfg; stg->get_bytes_free=mock_om_storage_get_bytes_free; stg->delete_file=mock_om_storage_delete_file; stg->open_file_input_stream=mock_om_storage_open_file_input_stream; stg->open_file_output_stream=mock_om_storage_open_file_output_stream; stg->close_file_input_stream=mock_om_storage_close_file_input_stream; stg->close_file_output_stream=mock_om_storage_close_file_output_stream; return stg; }
722,423
./openmeap/clients/c/openmeap-slic-core/3rd_party/minzip-1.01h/ioapi.c
/* ioapi.c -- IO base function header for compress/uncompress .zip files using zlib + zip or unzip API Version 1.01h, December 28th, 2009 Copyright (C) 1998-2009 Gilles Vollant */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include "zlib.h" #include "ioapi.h" /* I've found an old Unix (a SunOS 4.1.3_U1) without all SEEK_* defined.... */ #ifndef SEEK_CUR #define SEEK_CUR 1 #endif #ifndef SEEK_END #define SEEK_END 2 #endif #ifndef SEEK_SET #define SEEK_SET 0 #endif voidpf ZCALLBACK fopen_file_func OF(( voidpf opaque, const char* filename, int mode)); uLong ZCALLBACK fread_file_func OF(( voidpf opaque, voidpf stream, void* buf, uLong size)); uLong ZCALLBACK fwrite_file_func OF(( voidpf opaque, voidpf stream, const void* buf, uLong size)); long ZCALLBACK ftell_file_func OF(( voidpf opaque, voidpf stream)); long ZCALLBACK fseek_file_func OF(( voidpf opaque, voidpf stream, uLong offset, int origin)); int ZCALLBACK fclose_file_func OF(( voidpf opaque, voidpf stream)); int ZCALLBACK ferror_file_func OF(( voidpf opaque, voidpf stream)); voidpf ZCALLBACK fopen_file_func (opaque, filename, mode) voidpf opaque; const char* filename; int mode; { FILE* file = NULL; const char* mode_fopen = NULL; if ((mode & ZLIB_FILEFUNC_MODE_READWRITEFILTER)==ZLIB_FILEFUNC_MODE_READ) mode_fopen = "rb"; else if (mode & ZLIB_FILEFUNC_MODE_EXISTING) mode_fopen = "r+b"; else if (mode & ZLIB_FILEFUNC_MODE_CREATE) mode_fopen = "wb"; if ((filename!=NULL) && (mode_fopen != NULL)) file = fopen(filename, mode_fopen); return file; } uLong ZCALLBACK fread_file_func (opaque, stream, buf, size) voidpf opaque; voidpf stream; void* buf; uLong size; { uLong ret; ret = (uLong)fread(buf, 1, (size_t)size, (FILE *)stream); return ret; } uLong ZCALLBACK fwrite_file_func (opaque, stream, buf, size) voidpf opaque; voidpf stream; const void* buf; uLong size; { uLong ret; ret = (uLong)fwrite(buf, 1, (size_t)size, (FILE *)stream); return ret; } long ZCALLBACK ftell_file_func (opaque, stream) voidpf opaque; voidpf stream; { long ret; ret = ftell((FILE *)stream); return ret; } long ZCALLBACK fseek_file_func (opaque, stream, offset, origin) voidpf opaque; voidpf stream; uLong offset; int origin; { int fseek_origin=0; long ret; switch (origin) { case ZLIB_FILEFUNC_SEEK_CUR : fseek_origin = SEEK_CUR; break; case ZLIB_FILEFUNC_SEEK_END : fseek_origin = SEEK_END; break; case ZLIB_FILEFUNC_SEEK_SET : fseek_origin = SEEK_SET; break; default: return -1; } ret = 0; if (fseek((FILE *)stream, offset, fseek_origin) != 0) ret = -1; return ret; } int ZCALLBACK fclose_file_func (opaque, stream) voidpf opaque; voidpf stream; { int ret; ret = fclose((FILE *)stream); return ret; } int ZCALLBACK ferror_file_func (opaque, stream) voidpf opaque; voidpf stream; { int ret; ret = ferror((FILE *)stream); return ret; } void fill_fopen_filefunc (pzlib_filefunc_def) zlib_filefunc_def* pzlib_filefunc_def; { pzlib_filefunc_def->zopen_file = fopen_file_func; pzlib_filefunc_def->zread_file = fread_file_func; pzlib_filefunc_def->zwrite_file = fwrite_file_func; pzlib_filefunc_def->ztell_file = ftell_file_func; pzlib_filefunc_def->zseek_file = fseek_file_func; pzlib_filefunc_def->zclose_file = fclose_file_func; pzlib_filefunc_def->zerror_file = ferror_file_func; pzlib_filefunc_def->opaque = NULL; }
722,424
./openmeap/clients/c/openmeap-slic-core/3rd_party/minzip-1.01h/unzip.c
/* unzip.c -- IO for uncompress .zip files using zlib Version 1.01h, December 28th, 2009 Copyright (C) 1998-2009 Gilles Vollant Read unzip.h for more info */ /* Decryption code comes from crypt.c by Info-ZIP but has been greatly reduced in terms of compatibility with older software. The following is from the original crypt.c. Code woven in by Terry Thorsen 1/2003. */ /* Copyright (c) 1990-2000 Info-ZIP. All rights reserved. See the accompanying file LICENSE, version 2000-Apr-09 or later (the contents of which are also included in zip.h) for terms of use. If, for some reason, all these files are missing, the Info-ZIP license also may be found at: ftp://ftp.info-zip.org/pub/infozip/license.html */ /* crypt.c (full version) by Info-ZIP. Last revised: [see crypt.h] The encryption/decryption parts of this source code (as opposed to the non-echoing password parts) were originally written in Europe. The whole source package can be freely distributed, including from the USA. (Prior to January 2000, re-export from the US was a violation of US law.) */ /* This encryption code is a direct transcription of the algorithm from Roger Schlafly, described by Phil Katz in the file appnote.txt. This file (appnote.txt) is distributed with the PKZIP program (even in the version without encryption capabilities). */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include "zlib.h" #include "unzip.h" #ifdef STDC # include <stddef.h> # include <string.h> # include <stdlib.h> #endif #ifdef NO_ERRNO_H extern int errno; #else # include <errno.h> #endif #ifndef local # define local static #endif /* compile with -Dlocal if your debugger can't find static symbols */ #ifndef CASESENSITIVITYDEFAULT_NO # if !defined(unix) && !defined(CASESENSITIVITYDEFAULT_YES) # define CASESENSITIVITYDEFAULT_NO # endif #endif #ifndef UNZ_BUFSIZE #define UNZ_BUFSIZE (16384) #endif #ifndef UNZ_MAXFILENAMEINZIP #define UNZ_MAXFILENAMEINZIP (256) #endif #ifndef ALLOC # define ALLOC(size) (malloc(size)) #endif #ifndef TRYFREE # define TRYFREE(p) {if (p) free(p);} #endif #define SIZECENTRALDIRITEM (0x2e) #define SIZEZIPLOCALHEADER (0x1e) const char unz_copyright[] = " unzip 1.01 Copyright 1998-2004 Gilles Vollant - http://www.winimage.com/zLibDll"; /* unz_file_info_interntal contain internal info about a file in zipfile*/ typedef struct unz_file_info_internal_s { uLong offset_curfile;/* relative offset of local header 4 bytes */ } unz_file_info_internal; /* file_in_zip_read_info_s contain internal information about a file in zipfile, when reading and decompress it */ typedef struct { char *read_buffer; /* internal buffer for compressed data */ z_stream stream; /* zLib stream structure for inflate */ #ifdef HAVE_BZIP2 bz_stream bstream; /* bzLib stream structure for bziped */ #endif uLong pos_in_zipfile; /* position in byte on the zipfile, for fseek*/ uLong stream_initialised; /* flag set if stream structure is initialised*/ uLong offset_local_extrafield;/* offset of the local extra field */ uInt size_local_extrafield;/* size of the local extra field */ uLong pos_local_extrafield; /* position in the local extra field in read*/ uLong crc32; /* crc32 of all data uncompressed */ uLong crc32_wait; /* crc32 we must obtain after decompress all */ uLong rest_read_compressed; /* number of byte to be decompressed */ uLong rest_read_uncompressed;/*number of byte to be obtained after decomp*/ zlib_filefunc_def z_filefunc; voidpf filestream; /* io structore of the zipfile */ uLong compression_method; /* compression method (0==store) */ uLong byte_before_the_zipfile;/* byte before the zipfile, (>0 for sfx)*/ int raw; } file_in_zip_read_info_s; /* unz_s contain internal information about the zipfile */ typedef struct { zlib_filefunc_def z_filefunc; voidpf filestream; /* io structore of the zipfile */ unz_global_info gi; /* public global information */ uLong byte_before_the_zipfile;/* byte before the zipfile, (>0 for sfx)*/ uLong num_file; /* number of the current file in the zipfile*/ uLong pos_in_central_dir; /* pos of the current file in the central dir*/ uLong current_file_ok; /* flag about the usability of the current file*/ uLong central_pos; /* position of the beginning of the central dir*/ uLong size_central_dir; /* size of the central directory */ uLong offset_central_dir; /* offset of start of central directory with respect to the starting disk number */ unz_file_info cur_file_info; /* public info about the current file in zip*/ unz_file_info_internal cur_file_info_internal; /* private info about it*/ file_in_zip_read_info_s* pfile_in_zip_read; /* structure about the current file if we are decompressing it */ int encrypted; # ifndef NOUNCRYPT unsigned long keys[3]; /* keys defining the pseudo-random sequence */ const unsigned long* pcrc_32_tab; # endif } unz_s; #ifndef NOUNCRYPT #include "crypt.h" #endif /* =========================================================================== 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 unzlocal_getByte OF(( const zlib_filefunc_def* pzlib_filefunc_def, voidpf filestream, int *pi)); local int unzlocal_getByte(pzlib_filefunc_def,filestream,pi) const zlib_filefunc_def* pzlib_filefunc_def; voidpf filestream; int *pi; { unsigned char c; int err = (int)ZREAD(*pzlib_filefunc_def,filestream,&c,1); if (err==1) { *pi = (int)c; return UNZ_OK; } else { if (ZERROR(*pzlib_filefunc_def,filestream)) return UNZ_ERRNO; else return UNZ_EOF; } } /* =========================================================================== Reads a long in LSB order from the given gz_stream. Sets */ local int unzlocal_getShort OF(( const zlib_filefunc_def* pzlib_filefunc_def, voidpf filestream, uLong *pX)); local int unzlocal_getShort (pzlib_filefunc_def,filestream,pX) const zlib_filefunc_def* pzlib_filefunc_def; voidpf filestream; uLong *pX; { uLong x ; int i = 0; int err; err = unzlocal_getByte(pzlib_filefunc_def,filestream,&i); x = (uLong)i; if (err==UNZ_OK) err = unzlocal_getByte(pzlib_filefunc_def,filestream,&i); x += ((uLong)i)<<8; if (err==UNZ_OK) *pX = x; else *pX = 0; return err; } local int unzlocal_getLong OF(( const zlib_filefunc_def* pzlib_filefunc_def, voidpf filestream, uLong *pX)); local int unzlocal_getLong (pzlib_filefunc_def,filestream,pX) const zlib_filefunc_def* pzlib_filefunc_def; voidpf filestream; uLong *pX; { uLong x ; int i = 0; int err; err = unzlocal_getByte(pzlib_filefunc_def,filestream,&i); x = (uLong)i; if (err==UNZ_OK) err = unzlocal_getByte(pzlib_filefunc_def,filestream,&i); x += ((uLong)i)<<8; if (err==UNZ_OK) err = unzlocal_getByte(pzlib_filefunc_def,filestream,&i); x += ((uLong)i)<<16; if (err==UNZ_OK) err = unzlocal_getByte(pzlib_filefunc_def,filestream,&i); x += ((uLong)i)<<24; if (err==UNZ_OK) *pX = x; else *pX = 0; return err; } /* My own strcmpi / strcasecmp */ local int strcmpcasenosensitive_internal (fileName1,fileName2) const char* fileName1; const char* fileName2; { for (;;) { char c1=*(fileName1++); char c2=*(fileName2++); if ((c1>='a') && (c1<='z')) c1 -= 0x20; if ((c2>='a') && (c2<='z')) c2 -= 0x20; if (c1=='\0') return ((c2=='\0') ? 0 : -1); if (c2=='\0') return 1; if (c1<c2) return -1; if (c1>c2) return 1; } } #ifdef CASESENSITIVITYDEFAULT_NO #define CASESENSITIVITYDEFAULTVALUE 2 #else #define CASESENSITIVITYDEFAULTVALUE 1 #endif #ifndef STRCMPCASENOSENTIVEFUNCTION #define STRCMPCASENOSENTIVEFUNCTION strcmpcasenosensitive_internal #endif /* Compare two filename (fileName1,fileName2). If iCaseSenisivity = 1, comparision is case sensitivity (like strcmp) If iCaseSenisivity = 2, comparision is not case sensitivity (like strcmpi or strcasecmp) If iCaseSenisivity = 0, case sensitivity is defaut of your operating system (like 1 on Unix, 2 on Windows) */ extern int ZEXPORT unzStringFileNameCompare (fileName1,fileName2,iCaseSensitivity) const char* fileName1; const char* fileName2; int iCaseSensitivity; { if (iCaseSensitivity==0) iCaseSensitivity=CASESENSITIVITYDEFAULTVALUE; if (iCaseSensitivity==1) return strcmp(fileName1,fileName2); return STRCMPCASENOSENTIVEFUNCTION(fileName1,fileName2); } #ifndef BUFREADCOMMENT #define BUFREADCOMMENT (0x400) #endif /* Locate the Central directory of a zipfile (at the end, just before the global comment) */ local uLong unzlocal_SearchCentralDir OF(( const zlib_filefunc_def* pzlib_filefunc_def, voidpf filestream)); local uLong unzlocal_SearchCentralDir(pzlib_filefunc_def,filestream) const zlib_filefunc_def* pzlib_filefunc_def; voidpf filestream; { unsigned char* buf; uLong uSizeFile; uLong uBackRead; uLong uMaxBack=0xffff; /* maximum size of global comment */ uLong uPosFound=0; if (ZSEEK(*pzlib_filefunc_def,filestream,0,ZLIB_FILEFUNC_SEEK_END) != 0) return 0; uSizeFile = ZTELL(*pzlib_filefunc_def,filestream); if (uMaxBack>uSizeFile) uMaxBack = uSizeFile; buf = (unsigned char*)ALLOC(BUFREADCOMMENT+4); if (buf==NULL) return 0; uBackRead = 4; while (uBackRead<uMaxBack) { uLong uReadSize,uReadPos ; int i; if (uBackRead+BUFREADCOMMENT>uMaxBack) uBackRead = uMaxBack; else uBackRead+=BUFREADCOMMENT; uReadPos = uSizeFile-uBackRead ; uReadSize = ((BUFREADCOMMENT+4) < (uSizeFile-uReadPos)) ? (BUFREADCOMMENT+4) : (uSizeFile-uReadPos); if (ZSEEK(*pzlib_filefunc_def,filestream,uReadPos,ZLIB_FILEFUNC_SEEK_SET)!=0) break; if (ZREAD(*pzlib_filefunc_def,filestream,buf,uReadSize)!=uReadSize) break; for (i=(int)uReadSize-3; (i--)>0;) if (((*(buf+i))==0x50) && ((*(buf+i+1))==0x4b) && ((*(buf+i+2))==0x05) && ((*(buf+i+3))==0x06)) { uPosFound = uReadPos+i; break; } if (uPosFound!=0) break; } TRYFREE(buf); return uPosFound; } /* Open a Zip file. path contain the full pathname (by example, on a Windows NT computer "c:\\test\\zlib114.zip" or on an Unix computer "zlib/zlib114.zip". If the zipfile cannot be opened (file doesn't exist or in not valid), the return value is NULL. Else, the return value is a unzFile Handle, usable with other function of this unzip package. */ extern unzFile ZEXPORT unzOpen2 (path, pzlib_filefunc_def) const char *path; zlib_filefunc_def* pzlib_filefunc_def; { unz_s us; unz_s *s; uLong central_pos,uL; uLong number_disk; /* number of the current dist, used for spaning ZIP, unsupported, always 0*/ uLong number_disk_with_CD; /* number the the disk with central dir, used for spaning ZIP, unsupported, always 0*/ uLong number_entry_CD; /* total number of entries in the central dir (same than number_entry on nospan) */ int err=UNZ_OK; if (unz_copyright[0]!=' ') return NULL; if (pzlib_filefunc_def==NULL) fill_fopen_filefunc(&us.z_filefunc); else us.z_filefunc = *pzlib_filefunc_def; us.filestream= (*(us.z_filefunc.zopen_file))(us.z_filefunc.opaque, path, ZLIB_FILEFUNC_MODE_READ | ZLIB_FILEFUNC_MODE_EXISTING); if (us.filestream==NULL) return NULL; central_pos = unzlocal_SearchCentralDir(&us.z_filefunc,us.filestream); if (central_pos==0) err=UNZ_ERRNO; if (ZSEEK(us.z_filefunc, us.filestream, central_pos,ZLIB_FILEFUNC_SEEK_SET)!=0) err=UNZ_ERRNO; /* the signature, already checked */ if (unzlocal_getLong(&us.z_filefunc, us.filestream,&uL)!=UNZ_OK) err=UNZ_ERRNO; /* number of this disk */ if (unzlocal_getShort(&us.z_filefunc, us.filestream,&number_disk)!=UNZ_OK) err=UNZ_ERRNO; /* number of the disk with the start of the central directory */ if (unzlocal_getShort(&us.z_filefunc, us.filestream,&number_disk_with_CD)!=UNZ_OK) err=UNZ_ERRNO; /* total number of entries in the central dir on this disk */ if (unzlocal_getShort(&us.z_filefunc, us.filestream,&us.gi.number_entry)!=UNZ_OK) err=UNZ_ERRNO; /* total number of entries in the central dir */ if (unzlocal_getShort(&us.z_filefunc, us.filestream,&number_entry_CD)!=UNZ_OK) err=UNZ_ERRNO; if ((number_entry_CD!=us.gi.number_entry) || (number_disk_with_CD!=0) || (number_disk!=0)) err=UNZ_BADZIPFILE; /* size of the central directory */ if (unzlocal_getLong(&us.z_filefunc, us.filestream,&us.size_central_dir)!=UNZ_OK) err=UNZ_ERRNO; /* offset of start of central directory with respect to the starting disk number */ if (unzlocal_getLong(&us.z_filefunc, us.filestream,&us.offset_central_dir)!=UNZ_OK) err=UNZ_ERRNO; /* zipfile comment length */ if (unzlocal_getShort(&us.z_filefunc, us.filestream,&us.gi.size_comment)!=UNZ_OK) err=UNZ_ERRNO; if ((central_pos<us.offset_central_dir+us.size_central_dir) && (err==UNZ_OK)) err=UNZ_BADZIPFILE; if (err!=UNZ_OK) { ZCLOSE(us.z_filefunc, us.filestream); return NULL; } us.byte_before_the_zipfile = central_pos - (us.offset_central_dir+us.size_central_dir); us.central_pos = central_pos; us.pfile_in_zip_read = NULL; us.encrypted = 0; s=(unz_s*)ALLOC(sizeof(unz_s)); if (s!=NULL) { *s=us; unzGoToFirstFile((unzFile)s); } return (unzFile)s; } extern unzFile ZEXPORT unzOpen (path) const char *path; { return unzOpen2(path, NULL); } /* Close a ZipFile opened with unzipOpen. If there is files inside the .Zip opened with unzipOpenCurrentFile (see later), these files MUST be closed with unzipCloseCurrentFile before call unzipClose. return UNZ_OK if there is no problem. */ extern int ZEXPORT unzClose (file) unzFile file; { unz_s* s; if (file==NULL) return UNZ_PARAMERROR; s=(unz_s*)file; if (s->pfile_in_zip_read!=NULL) unzCloseCurrentFile(file); ZCLOSE(s->z_filefunc, s->filestream); TRYFREE(s); return UNZ_OK; } /* Write info about the ZipFile in the *pglobal_info structure. No preparation of the structure is needed return UNZ_OK if there is no problem. */ extern int ZEXPORT unzGetGlobalInfo (file,pglobal_info) unzFile file; unz_global_info *pglobal_info; { unz_s* s; if (file==NULL) return UNZ_PARAMERROR; s=(unz_s*)file; *pglobal_info=s->gi; return UNZ_OK; } /* Translate date/time from Dos format to tm_unz (readable more easilty) */ local void unzlocal_DosDateToTmuDate (ulDosDate, ptm) uLong ulDosDate; tm_unz* ptm; { uLong uDate; uDate = (uLong)(ulDosDate>>16); ptm->tm_mday = (uInt)(uDate&0x1f) ; ptm->tm_mon = (uInt)((((uDate)&0x1E0)/0x20)-1) ; ptm->tm_year = (uInt)(((uDate&0x0FE00)/0x0200)+1980) ; ptm->tm_hour = (uInt) ((ulDosDate &0xF800)/0x800); ptm->tm_min = (uInt) ((ulDosDate&0x7E0)/0x20) ; ptm->tm_sec = (uInt) (2*(ulDosDate&0x1f)) ; } /* Get Info about the current file in the zipfile, with internal only info */ local int unzlocal_GetCurrentFileInfoInternal OF((unzFile file, unz_file_info *pfile_info, unz_file_info_internal *pfile_info_internal, char *szFileName, uLong fileNameBufferSize, void *extraField, uLong extraFieldBufferSize, char *szComment, uLong commentBufferSize)); local int unzlocal_GetCurrentFileInfoInternal (file, pfile_info, pfile_info_internal, szFileName, fileNameBufferSize, extraField, extraFieldBufferSize, szComment, commentBufferSize) unzFile file; unz_file_info *pfile_info; unz_file_info_internal *pfile_info_internal; char *szFileName; uLong fileNameBufferSize; void *extraField; uLong extraFieldBufferSize; char *szComment; uLong commentBufferSize; { unz_s* s; unz_file_info file_info; unz_file_info_internal file_info_internal; int err=UNZ_OK; uLong uMagic; long lSeek=0; if (file==NULL) return UNZ_PARAMERROR; s=(unz_s*)file; if (ZSEEK(s->z_filefunc, s->filestream, s->pos_in_central_dir+s->byte_before_the_zipfile, ZLIB_FILEFUNC_SEEK_SET)!=0) err=UNZ_ERRNO; /* we check the magic */ if (err==UNZ_OK) { if (unzlocal_getLong(&s->z_filefunc, s->filestream,&uMagic) != UNZ_OK) err=UNZ_ERRNO; else if (uMagic!=0x02014b50) err=UNZ_BADZIPFILE; } if (unzlocal_getShort(&s->z_filefunc, s->filestream,&file_info.version) != UNZ_OK) err=UNZ_ERRNO; if (unzlocal_getShort(&s->z_filefunc, s->filestream,&file_info.version_needed) != UNZ_OK) err=UNZ_ERRNO; if (unzlocal_getShort(&s->z_filefunc, s->filestream,&file_info.flag) != UNZ_OK) err=UNZ_ERRNO; if (unzlocal_getShort(&s->z_filefunc, s->filestream,&file_info.compression_method) != UNZ_OK) err=UNZ_ERRNO; if (unzlocal_getLong(&s->z_filefunc, s->filestream,&file_info.dosDate) != UNZ_OK) err=UNZ_ERRNO; unzlocal_DosDateToTmuDate(file_info.dosDate,&file_info.tmu_date); if (unzlocal_getLong(&s->z_filefunc, s->filestream,&file_info.crc) != UNZ_OK) err=UNZ_ERRNO; if (unzlocal_getLong(&s->z_filefunc, s->filestream,&file_info.compressed_size) != UNZ_OK) err=UNZ_ERRNO; if (unzlocal_getLong(&s->z_filefunc, s->filestream,&file_info.uncompressed_size) != UNZ_OK) err=UNZ_ERRNO; if (unzlocal_getShort(&s->z_filefunc, s->filestream,&file_info.size_filename) != UNZ_OK) err=UNZ_ERRNO; if (unzlocal_getShort(&s->z_filefunc, s->filestream,&file_info.size_file_extra) != UNZ_OK) err=UNZ_ERRNO; if (unzlocal_getShort(&s->z_filefunc, s->filestream,&file_info.size_file_comment) != UNZ_OK) err=UNZ_ERRNO; if (unzlocal_getShort(&s->z_filefunc, s->filestream,&file_info.disk_num_start) != UNZ_OK) err=UNZ_ERRNO; if (unzlocal_getShort(&s->z_filefunc, s->filestream,&file_info.internal_fa) != UNZ_OK) err=UNZ_ERRNO; if (unzlocal_getLong(&s->z_filefunc, s->filestream,&file_info.external_fa) != UNZ_OK) err=UNZ_ERRNO; if (unzlocal_getLong(&s->z_filefunc, s->filestream,&file_info_internal.offset_curfile) != UNZ_OK) err=UNZ_ERRNO; lSeek+=file_info.size_filename; if ((err==UNZ_OK) && (szFileName!=NULL)) { uLong uSizeRead ; if (file_info.size_filename<fileNameBufferSize) { *(szFileName+file_info.size_filename)='\0'; uSizeRead = file_info.size_filename; } else uSizeRead = fileNameBufferSize; if ((file_info.size_filename>0) && (fileNameBufferSize>0)) if (ZREAD(s->z_filefunc, s->filestream,szFileName,uSizeRead)!=uSizeRead) err=UNZ_ERRNO; lSeek -= uSizeRead; } if ((err==UNZ_OK) && (extraField!=NULL)) { uLong uSizeRead ; if (file_info.size_file_extra<extraFieldBufferSize) uSizeRead = file_info.size_file_extra; else uSizeRead = extraFieldBufferSize; if (lSeek!=0) { if (ZSEEK(s->z_filefunc, s->filestream,lSeek,ZLIB_FILEFUNC_SEEK_CUR)==0) lSeek=0; else err=UNZ_ERRNO; } if ((file_info.size_file_extra>0) && (extraFieldBufferSize>0)) if (ZREAD(s->z_filefunc, s->filestream,extraField,uSizeRead)!=uSizeRead) err=UNZ_ERRNO; lSeek += file_info.size_file_extra - uSizeRead; } else lSeek+=file_info.size_file_extra; if ((err==UNZ_OK) && (szComment!=NULL)) { uLong uSizeRead ; if (file_info.size_file_comment<commentBufferSize) { *(szComment+file_info.size_file_comment)='\0'; uSizeRead = file_info.size_file_comment; } else uSizeRead = commentBufferSize; if (lSeek!=0) { if (ZSEEK(s->z_filefunc, s->filestream,lSeek,ZLIB_FILEFUNC_SEEK_CUR)==0) lSeek=0; else err=UNZ_ERRNO; } if ((file_info.size_file_comment>0) && (commentBufferSize>0)) if (ZREAD(s->z_filefunc, s->filestream,szComment,uSizeRead)!=uSizeRead) err=UNZ_ERRNO; lSeek+=file_info.size_file_comment - uSizeRead; } else lSeek+=file_info.size_file_comment; if ((err==UNZ_OK) && (pfile_info!=NULL)) *pfile_info=file_info; if ((err==UNZ_OK) && (pfile_info_internal!=NULL)) *pfile_info_internal=file_info_internal; return err; } /* Write info about the ZipFile in the *pglobal_info structure. No preparation of the structure is needed return UNZ_OK if there is no problem. */ extern int ZEXPORT unzGetCurrentFileInfo (file, pfile_info, szFileName, fileNameBufferSize, extraField, extraFieldBufferSize, szComment, commentBufferSize) unzFile file; unz_file_info *pfile_info; char *szFileName; uLong fileNameBufferSize; void *extraField; uLong extraFieldBufferSize; char *szComment; uLong commentBufferSize; { return unzlocal_GetCurrentFileInfoInternal(file,pfile_info,NULL, szFileName,fileNameBufferSize, extraField,extraFieldBufferSize, szComment,commentBufferSize); } /* Set the current file of the zipfile to the first file. return UNZ_OK if there is no problem */ extern int ZEXPORT unzGoToFirstFile (file) unzFile file; { int err=UNZ_OK; unz_s* s; if (file==NULL) return UNZ_PARAMERROR; s=(unz_s*)file; s->pos_in_central_dir=s->offset_central_dir; s->num_file=0; err=unzlocal_GetCurrentFileInfoInternal(file,&s->cur_file_info, &s->cur_file_info_internal, NULL,0,NULL,0,NULL,0); s->current_file_ok = (err == UNZ_OK); return err; } /* Set the current file of the zipfile to the next file. return UNZ_OK if there is no problem return UNZ_END_OF_LIST_OF_FILE if the actual file was the latest. */ extern int ZEXPORT unzGoToNextFile (file) unzFile file; { unz_s* s; int err; if (file==NULL) return UNZ_PARAMERROR; s=(unz_s*)file; if (!s->current_file_ok) return UNZ_END_OF_LIST_OF_FILE; if (s->gi.number_entry != 0xffff) /* 2^16 files overflow hack */ if (s->num_file+1==s->gi.number_entry) return UNZ_END_OF_LIST_OF_FILE; s->pos_in_central_dir += SIZECENTRALDIRITEM + s->cur_file_info.size_filename + s->cur_file_info.size_file_extra + s->cur_file_info.size_file_comment ; s->num_file++; err = unzlocal_GetCurrentFileInfoInternal(file,&s->cur_file_info, &s->cur_file_info_internal, NULL,0,NULL,0,NULL,0); s->current_file_ok = (err == UNZ_OK); return err; } /* Try locate the file szFileName in the zipfile. For the iCaseSensitivity signification, see unzipStringFileNameCompare return value : UNZ_OK if the file is found. It becomes the current file. UNZ_END_OF_LIST_OF_FILE if the file is not found */ extern int ZEXPORT unzLocateFile (file, szFileName, iCaseSensitivity) unzFile file; const char *szFileName; int iCaseSensitivity; { unz_s* s; int err; /* We remember the 'current' position in the file so that we can jump * back there if we fail. */ unz_file_info cur_file_infoSaved; unz_file_info_internal cur_file_info_internalSaved; uLong num_fileSaved; uLong pos_in_central_dirSaved; if (file==NULL) return UNZ_PARAMERROR; if (strlen(szFileName)>=UNZ_MAXFILENAMEINZIP) return UNZ_PARAMERROR; s=(unz_s*)file; if (!s->current_file_ok) return UNZ_END_OF_LIST_OF_FILE; /* Save the current state */ num_fileSaved = s->num_file; pos_in_central_dirSaved = s->pos_in_central_dir; cur_file_infoSaved = s->cur_file_info; cur_file_info_internalSaved = s->cur_file_info_internal; err = unzGoToFirstFile(file); while (err == UNZ_OK) { char szCurrentFileName[UNZ_MAXFILENAMEINZIP+1]; err = unzGetCurrentFileInfo(file,NULL, szCurrentFileName,sizeof(szCurrentFileName)-1, NULL,0,NULL,0); if (err == UNZ_OK) { if (unzStringFileNameCompare(szCurrentFileName, szFileName,iCaseSensitivity)==0) return UNZ_OK; err = unzGoToNextFile(file); } } /* We failed, so restore the state of the 'current file' to where we * were. */ s->num_file = num_fileSaved ; s->pos_in_central_dir = pos_in_central_dirSaved ; s->cur_file_info = cur_file_infoSaved; s->cur_file_info_internal = cur_file_info_internalSaved; return err; } /* /////////////////////////////////////////// // Contributed by Ryan Haksi (mailto://cryogen@infoserve.net) // I need random access // // Further optimization could be realized by adding an ability // to cache the directory in memory. The goal being a single // comprehensive file read to put the file I need in a memory. */ /* typedef struct unz_file_pos_s { uLong pos_in_zip_directory; // offset in file uLong num_of_file; // # of file } unz_file_pos; */ extern int ZEXPORT unzGetFilePos(file, file_pos) unzFile file; unz_file_pos* file_pos; { unz_s* s; if (file==NULL || file_pos==NULL) return UNZ_PARAMERROR; s=(unz_s*)file; if (!s->current_file_ok) return UNZ_END_OF_LIST_OF_FILE; file_pos->pos_in_zip_directory = s->pos_in_central_dir; file_pos->num_of_file = s->num_file; return UNZ_OK; } extern int ZEXPORT unzGoToFilePos(file, file_pos) unzFile file; unz_file_pos* file_pos; { unz_s* s; int err; if (file==NULL || file_pos==NULL) return UNZ_PARAMERROR; s=(unz_s*)file; /* jump to the right spot */ s->pos_in_central_dir = file_pos->pos_in_zip_directory; s->num_file = file_pos->num_of_file; /* set the current file */ err = unzlocal_GetCurrentFileInfoInternal(file,&s->cur_file_info, &s->cur_file_info_internal, NULL,0,NULL,0,NULL,0); /* return results */ s->current_file_ok = (err == UNZ_OK); return err; } /* // Unzip Helper Functions - should be here? /////////////////////////////////////////// */ /* Read the local header of the current zipfile Check the coherency of the local header and info in the end of central directory about this file store in *piSizeVar the size of extra info in local header (filename and size of extra field data) */ local int unzlocal_CheckCurrentFileCoherencyHeader (s,piSizeVar, poffset_local_extrafield, psize_local_extrafield) unz_s* s; uInt* piSizeVar; uLong *poffset_local_extrafield; uInt *psize_local_extrafield; { uLong uMagic,uData,uFlags; uLong size_filename; uLong size_extra_field; int err=UNZ_OK; *piSizeVar = 0; *poffset_local_extrafield = 0; *psize_local_extrafield = 0; if (ZSEEK(s->z_filefunc, s->filestream,s->cur_file_info_internal.offset_curfile + s->byte_before_the_zipfile,ZLIB_FILEFUNC_SEEK_SET)!=0) return UNZ_ERRNO; if (err==UNZ_OK) { if (unzlocal_getLong(&s->z_filefunc, s->filestream,&uMagic) != UNZ_OK) err=UNZ_ERRNO; else if (uMagic!=0x04034b50) err=UNZ_BADZIPFILE; } if (unzlocal_getShort(&s->z_filefunc, s->filestream,&uData) != UNZ_OK) err=UNZ_ERRNO; /* else if ((err==UNZ_OK) && (uData!=s->cur_file_info.wVersion)) err=UNZ_BADZIPFILE; */ if (unzlocal_getShort(&s->z_filefunc, s->filestream,&uFlags) != UNZ_OK) err=UNZ_ERRNO; if (unzlocal_getShort(&s->z_filefunc, s->filestream,&uData) != UNZ_OK) err=UNZ_ERRNO; else if ((err==UNZ_OK) && (uData!=s->cur_file_info.compression_method)) err=UNZ_BADZIPFILE; if ((err==UNZ_OK) && (s->cur_file_info.compression_method!=0) && /* #ifdef HAVE_BZIP2 */ (s->cur_file_info.compression_method!=Z_BZIP2ED) && /* #endif */ (s->cur_file_info.compression_method!=Z_DEFLATED)) err=UNZ_BADZIPFILE; if (unzlocal_getLong(&s->z_filefunc, s->filestream,&uData) != UNZ_OK) /* date/time */ err=UNZ_ERRNO; if (unzlocal_getLong(&s->z_filefunc, s->filestream,&uData) != UNZ_OK) /* crc */ err=UNZ_ERRNO; else if ((err==UNZ_OK) && (uData!=s->cur_file_info.crc) && ((uFlags & 8)==0)) err=UNZ_BADZIPFILE; if (unzlocal_getLong(&s->z_filefunc, s->filestream,&uData) != UNZ_OK) /* size compr */ err=UNZ_ERRNO; else if ((err==UNZ_OK) && (uData!=s->cur_file_info.compressed_size) && ((uFlags & 8)==0)) err=UNZ_BADZIPFILE; if (unzlocal_getLong(&s->z_filefunc, s->filestream,&uData) != UNZ_OK) /* size uncompr */ err=UNZ_ERRNO; else if ((err==UNZ_OK) && (uData!=s->cur_file_info.uncompressed_size) && ((uFlags & 8)==0)) err=UNZ_BADZIPFILE; if (unzlocal_getShort(&s->z_filefunc, s->filestream,&size_filename) != UNZ_OK) err=UNZ_ERRNO; else if ((err==UNZ_OK) && (size_filename!=s->cur_file_info.size_filename)) err=UNZ_BADZIPFILE; *piSizeVar += (uInt)size_filename; if (unzlocal_getShort(&s->z_filefunc, s->filestream,&size_extra_field) != UNZ_OK) err=UNZ_ERRNO; *poffset_local_extrafield= s->cur_file_info_internal.offset_curfile + SIZEZIPLOCALHEADER + size_filename; *psize_local_extrafield = (uInt)size_extra_field; *piSizeVar += (uInt)size_extra_field; return err; } /* Open for reading data the current file in the zipfile. If there is no error and the file is opened, the return value is UNZ_OK. */ extern int ZEXPORT unzOpenCurrentFile3 (file, method, level, raw, password) unzFile file; int* method; int* level; int raw; const char* password; { int err=UNZ_OK; uInt iSizeVar; unz_s* s; file_in_zip_read_info_s* pfile_in_zip_read_info; uLong offset_local_extrafield; /* offset of the local extra field */ uInt size_local_extrafield; /* size of the local extra field */ # ifndef NOUNCRYPT char source[12]; # else if (password != NULL) return UNZ_PARAMERROR; # endif if (file==NULL) return UNZ_PARAMERROR; s=(unz_s*)file; if (!s->current_file_ok) return UNZ_PARAMERROR; if (s->pfile_in_zip_read != NULL) unzCloseCurrentFile(file); if (unzlocal_CheckCurrentFileCoherencyHeader(s,&iSizeVar, &offset_local_extrafield,&size_local_extrafield)!=UNZ_OK) return UNZ_BADZIPFILE; pfile_in_zip_read_info = (file_in_zip_read_info_s*) ALLOC(sizeof(file_in_zip_read_info_s)); if (pfile_in_zip_read_info==NULL) return UNZ_INTERNALERROR; pfile_in_zip_read_info->read_buffer=(char*)ALLOC(UNZ_BUFSIZE); pfile_in_zip_read_info->offset_local_extrafield = offset_local_extrafield; pfile_in_zip_read_info->size_local_extrafield = size_local_extrafield; pfile_in_zip_read_info->pos_local_extrafield=0; pfile_in_zip_read_info->raw=raw; if (pfile_in_zip_read_info->read_buffer==NULL) { TRYFREE(pfile_in_zip_read_info); return UNZ_INTERNALERROR; } pfile_in_zip_read_info->stream_initialised=0; if (method!=NULL) *method = (int)s->cur_file_info.compression_method; if (level!=NULL) { *level = 6; switch (s->cur_file_info.flag & 0x06) { case 6 : *level = 1; break; case 4 : *level = 2; break; case 2 : *level = 9; break; } } if ((s->cur_file_info.compression_method!=0) && /* #ifdef HAVE_BZIP2 */ (s->cur_file_info.compression_method!=Z_BZIP2ED) && /* #endif */ (s->cur_file_info.compression_method!=Z_DEFLATED)) err=UNZ_BADZIPFILE; pfile_in_zip_read_info->crc32_wait=s->cur_file_info.crc; pfile_in_zip_read_info->crc32=0; pfile_in_zip_read_info->compression_method = s->cur_file_info.compression_method; pfile_in_zip_read_info->filestream=s->filestream; pfile_in_zip_read_info->z_filefunc=s->z_filefunc; pfile_in_zip_read_info->byte_before_the_zipfile=s->byte_before_the_zipfile; pfile_in_zip_read_info->stream.total_out = 0; if ((s->cur_file_info.compression_method==Z_BZIP2ED) && (!raw)) { #ifdef HAVE_BZIP2 pfile_in_zip_read_info->bstream.bzalloc = (void *(*) (void *, int, int))0; pfile_in_zip_read_info->bstream.bzfree = (free_func)0; pfile_in_zip_read_info->bstream.opaque = (voidpf)0; pfile_in_zip_read_info->bstream.state = (voidpf)0; pfile_in_zip_read_info->stream.zalloc = (alloc_func)0; pfile_in_zip_read_info->stream.zfree = (free_func)0; pfile_in_zip_read_info->stream.opaque = (voidpf)0; pfile_in_zip_read_info->stream.next_in = (voidpf)0; pfile_in_zip_read_info->stream.avail_in = 0; err=BZ2_bzDecompressInit(&pfile_in_zip_read_info->bstream, 0, 0); if (err == Z_OK) pfile_in_zip_read_info->stream_initialised=Z_BZIP2ED; else { TRYFREE(pfile_in_zip_read_info); return err; } #else pfile_in_zip_read_info->raw=1; #endif } else if ((s->cur_file_info.compression_method==Z_DEFLATED) && (!raw)) { pfile_in_zip_read_info->stream.zalloc = (alloc_func)0; pfile_in_zip_read_info->stream.zfree = (free_func)0; pfile_in_zip_read_info->stream.opaque = (voidpf)0; pfile_in_zip_read_info->stream.next_in = (voidpf)0; pfile_in_zip_read_info->stream.avail_in = 0; err=inflateInit2(&pfile_in_zip_read_info->stream, -MAX_WBITS); if (err == Z_OK) pfile_in_zip_read_info->stream_initialised=Z_DEFLATED; else { TRYFREE(pfile_in_zip_read_info); return err; } /* 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. * In unzip, i don't wait absolutely Z_STREAM_END because I known the * size of both compressed and uncompressed data */ } pfile_in_zip_read_info->rest_read_compressed = s->cur_file_info.compressed_size ; pfile_in_zip_read_info->rest_read_uncompressed = s->cur_file_info.uncompressed_size ; pfile_in_zip_read_info->pos_in_zipfile = s->cur_file_info_internal.offset_curfile + SIZEZIPLOCALHEADER + iSizeVar; pfile_in_zip_read_info->stream.avail_in = (uInt)0; s->pfile_in_zip_read = pfile_in_zip_read_info; s->encrypted = 0; # ifndef NOUNCRYPT if (password != NULL) { int i; s->pcrc_32_tab = get_crc_table(); init_keys(password,s->keys,s->pcrc_32_tab); if (ZSEEK(s->z_filefunc, s->filestream, s->pfile_in_zip_read->pos_in_zipfile + s->pfile_in_zip_read->byte_before_the_zipfile, SEEK_SET)!=0) return UNZ_INTERNALERROR; if(ZREAD(s->z_filefunc, s->filestream,source, 12)<12) return UNZ_INTERNALERROR; for (i = 0; i<12; i++) zdecode(s->keys,s->pcrc_32_tab,source[i]); s->pfile_in_zip_read->pos_in_zipfile+=12; s->encrypted=1; } # endif return UNZ_OK; } extern int ZEXPORT unzOpenCurrentFile (file) unzFile file; { return unzOpenCurrentFile3(file, NULL, NULL, 0, NULL); } extern int ZEXPORT unzOpenCurrentFilePassword (file, password) unzFile file; const char* password; { return unzOpenCurrentFile3(file, NULL, NULL, 0, password); } extern int ZEXPORT unzOpenCurrentFile2 (file,method,level,raw) unzFile file; int* method; int* level; int raw; { return unzOpenCurrentFile3(file, method, level, raw, NULL); } /* Read bytes from the current file. buf contain buffer where data must be copied len the size of buf. return the number of byte copied if somes bytes are copied return 0 if the end of file was reached return <0 with error code if there is an error (UNZ_ERRNO for IO error, or zLib error for uncompress error) */ extern int ZEXPORT unzReadCurrentFile (file, buf, len) unzFile file; voidp buf; unsigned len; { int err=UNZ_OK; uInt iRead = 0; unz_s* s; file_in_zip_read_info_s* pfile_in_zip_read_info; if (file==NULL) return UNZ_PARAMERROR; s=(unz_s*)file; pfile_in_zip_read_info=s->pfile_in_zip_read; if (pfile_in_zip_read_info==NULL) return UNZ_PARAMERROR; if ((pfile_in_zip_read_info->read_buffer == NULL)) return UNZ_END_OF_LIST_OF_FILE; if (len==0) return 0; pfile_in_zip_read_info->stream.next_out = (Bytef*)buf; pfile_in_zip_read_info->stream.avail_out = (uInt)len; if ((len>pfile_in_zip_read_info->rest_read_uncompressed) && (!(pfile_in_zip_read_info->raw))) pfile_in_zip_read_info->stream.avail_out = (uInt)pfile_in_zip_read_info->rest_read_uncompressed; if ((len>pfile_in_zip_read_info->rest_read_compressed+ pfile_in_zip_read_info->stream.avail_in) && (pfile_in_zip_read_info->raw)) pfile_in_zip_read_info->stream.avail_out = (uInt)pfile_in_zip_read_info->rest_read_compressed+ pfile_in_zip_read_info->stream.avail_in; while (pfile_in_zip_read_info->stream.avail_out>0) { if ((pfile_in_zip_read_info->stream.avail_in==0) && (pfile_in_zip_read_info->rest_read_compressed>0)) { uInt uReadThis = UNZ_BUFSIZE; if (pfile_in_zip_read_info->rest_read_compressed<uReadThis) uReadThis = (uInt)pfile_in_zip_read_info->rest_read_compressed; if (uReadThis == 0) return UNZ_EOF; if (ZSEEK(pfile_in_zip_read_info->z_filefunc, pfile_in_zip_read_info->filestream, pfile_in_zip_read_info->pos_in_zipfile + pfile_in_zip_read_info->byte_before_the_zipfile, ZLIB_FILEFUNC_SEEK_SET)!=0) return UNZ_ERRNO; if (ZREAD(pfile_in_zip_read_info->z_filefunc, pfile_in_zip_read_info->filestream, pfile_in_zip_read_info->read_buffer, uReadThis)!=uReadThis) return UNZ_ERRNO; # ifndef NOUNCRYPT if(s->encrypted) { uInt i; for(i=0;i<uReadThis;i++) pfile_in_zip_read_info->read_buffer[i] = zdecode(s->keys,s->pcrc_32_tab, pfile_in_zip_read_info->read_buffer[i]); } # endif pfile_in_zip_read_info->pos_in_zipfile += uReadThis; pfile_in_zip_read_info->rest_read_compressed-=uReadThis; pfile_in_zip_read_info->stream.next_in = (Bytef*)pfile_in_zip_read_info->read_buffer; pfile_in_zip_read_info->stream.avail_in = (uInt)uReadThis; } if ((pfile_in_zip_read_info->compression_method==0) || (pfile_in_zip_read_info->raw)) { uInt uDoCopy,i ; if ((pfile_in_zip_read_info->stream.avail_in == 0) && (pfile_in_zip_read_info->rest_read_compressed == 0)) return (iRead==0) ? UNZ_EOF : iRead; if (pfile_in_zip_read_info->stream.avail_out < pfile_in_zip_read_info->stream.avail_in) uDoCopy = pfile_in_zip_read_info->stream.avail_out ; else uDoCopy = pfile_in_zip_read_info->stream.avail_in ; for (i=0;i<uDoCopy;i++) *(pfile_in_zip_read_info->stream.next_out+i) = *(pfile_in_zip_read_info->stream.next_in+i); pfile_in_zip_read_info->crc32 = crc32(pfile_in_zip_read_info->crc32, pfile_in_zip_read_info->stream.next_out, uDoCopy); pfile_in_zip_read_info->rest_read_uncompressed-=uDoCopy; pfile_in_zip_read_info->stream.avail_in -= uDoCopy; pfile_in_zip_read_info->stream.avail_out -= uDoCopy; pfile_in_zip_read_info->stream.next_out += uDoCopy; pfile_in_zip_read_info->stream.next_in += uDoCopy; pfile_in_zip_read_info->stream.total_out += uDoCopy; iRead += uDoCopy; } else if (pfile_in_zip_read_info->compression_method==Z_BZIP2ED) { #ifdef HAVE_BZIP2 uLong uTotalOutBefore,uTotalOutAfter; const Bytef *bufBefore; uLong uOutThis; pfile_in_zip_read_info->bstream.next_in = pfile_in_zip_read_info->stream.next_in; pfile_in_zip_read_info->bstream.avail_in = pfile_in_zip_read_info->stream.avail_in; pfile_in_zip_read_info->bstream.total_in_lo32 = pfile_in_zip_read_info->stream.total_in; pfile_in_zip_read_info->bstream.total_in_hi32 = 0; pfile_in_zip_read_info->bstream.next_out = pfile_in_zip_read_info->stream.next_out; pfile_in_zip_read_info->bstream.avail_out = pfile_in_zip_read_info->stream.avail_out; pfile_in_zip_read_info->bstream.total_out_lo32 = pfile_in_zip_read_info->stream.total_out; pfile_in_zip_read_info->bstream.total_out_hi32 = 0; uTotalOutBefore = pfile_in_zip_read_info->bstream.total_out_lo32; bufBefore = pfile_in_zip_read_info->bstream.next_out; err=BZ2_bzDecompress(&pfile_in_zip_read_info->bstream); uTotalOutAfter = pfile_in_zip_read_info->bstream.total_out_lo32; uOutThis = uTotalOutAfter-uTotalOutBefore; pfile_in_zip_read_info->crc32 = crc32(pfile_in_zip_read_info->crc32,bufBefore, (uInt)(uOutThis)); pfile_in_zip_read_info->rest_read_uncompressed -= uOutThis; iRead += (uInt)(uTotalOutAfter - uTotalOutBefore); pfile_in_zip_read_info->stream.next_in = pfile_in_zip_read_info->bstream.next_in; pfile_in_zip_read_info->stream.avail_in = pfile_in_zip_read_info->bstream.avail_in; pfile_in_zip_read_info->stream.total_in = pfile_in_zip_read_info->bstream.total_in_lo32; pfile_in_zip_read_info->stream.next_out = pfile_in_zip_read_info->bstream.next_out; pfile_in_zip_read_info->stream.avail_out = pfile_in_zip_read_info->bstream.avail_out; pfile_in_zip_read_info->stream.total_out = pfile_in_zip_read_info->bstream.total_out_lo32; if (err==BZ_STREAM_END) return (iRead==0) ? UNZ_EOF : iRead; if (err!=BZ_OK) break; #endif } else { uLong uTotalOutBefore,uTotalOutAfter; const Bytef *bufBefore; uLong uOutThis; int flush=Z_SYNC_FLUSH; uTotalOutBefore = pfile_in_zip_read_info->stream.total_out; bufBefore = pfile_in_zip_read_info->stream.next_out; /* if ((pfile_in_zip_read_info->rest_read_uncompressed == pfile_in_zip_read_info->stream.avail_out) && (pfile_in_zip_read_info->rest_read_compressed == 0)) flush = Z_FINISH; */ err=inflate(&pfile_in_zip_read_info->stream,flush); if ((err>=0) && (pfile_in_zip_read_info->stream.msg!=NULL)) err = Z_DATA_ERROR; uTotalOutAfter = pfile_in_zip_read_info->stream.total_out; uOutThis = uTotalOutAfter-uTotalOutBefore; pfile_in_zip_read_info->crc32 = crc32(pfile_in_zip_read_info->crc32,bufBefore, (uInt)(uOutThis)); pfile_in_zip_read_info->rest_read_uncompressed -= uOutThis; iRead += (uInt)(uTotalOutAfter - uTotalOutBefore); if (err==Z_STREAM_END) return (iRead==0) ? UNZ_EOF : iRead; if (err!=Z_OK) break; } } if (err==Z_OK) return iRead; return err; } /* Give the current position in uncompressed data */ extern z_off_t ZEXPORT unztell (file) unzFile file; { unz_s* s; file_in_zip_read_info_s* pfile_in_zip_read_info; if (file==NULL) return UNZ_PARAMERROR; s=(unz_s*)file; pfile_in_zip_read_info=s->pfile_in_zip_read; if (pfile_in_zip_read_info==NULL) return UNZ_PARAMERROR; return (z_off_t)pfile_in_zip_read_info->stream.total_out; } /* return 1 if the end of file was reached, 0 elsewhere */ extern int ZEXPORT unzeof (file) unzFile file; { unz_s* s; file_in_zip_read_info_s* pfile_in_zip_read_info; if (file==NULL) return UNZ_PARAMERROR; s=(unz_s*)file; pfile_in_zip_read_info=s->pfile_in_zip_read; if (pfile_in_zip_read_info==NULL) return UNZ_PARAMERROR; if (pfile_in_zip_read_info->rest_read_uncompressed == 0) return 1; else return 0; } /* Read extra field from the current file (opened by unzOpenCurrentFile) This is the local-header version of the extra field (sometimes, there is more info in the local-header version than in the central-header) if buf==NULL, it return the size of the local extra field that can be read if buf!=NULL, len is the size of the buffer, the extra header is copied in buf. the return value is the number of bytes copied in buf, or (if <0) the error code */ extern int ZEXPORT unzGetLocalExtrafield (file,buf,len) unzFile file; voidp buf; unsigned len; { unz_s* s; file_in_zip_read_info_s* pfile_in_zip_read_info; uInt read_now; uLong size_to_read; if (file==NULL) return UNZ_PARAMERROR; s=(unz_s*)file; pfile_in_zip_read_info=s->pfile_in_zip_read; if (pfile_in_zip_read_info==NULL) return UNZ_PARAMERROR; size_to_read = (pfile_in_zip_read_info->size_local_extrafield - pfile_in_zip_read_info->pos_local_extrafield); if (buf==NULL) return (int)size_to_read; if (len>size_to_read) read_now = (uInt)size_to_read; else read_now = (uInt)len ; if (read_now==0) return 0; if (ZSEEK(pfile_in_zip_read_info->z_filefunc, pfile_in_zip_read_info->filestream, pfile_in_zip_read_info->offset_local_extrafield + pfile_in_zip_read_info->pos_local_extrafield, ZLIB_FILEFUNC_SEEK_SET)!=0) return UNZ_ERRNO; if (ZREAD(pfile_in_zip_read_info->z_filefunc, pfile_in_zip_read_info->filestream, buf,read_now)!=read_now) return UNZ_ERRNO; return (int)read_now; } /* Close the file in zip opened with unzipOpenCurrentFile Return UNZ_CRCERROR if all the file was read but the CRC is not good */ extern int ZEXPORT unzCloseCurrentFile (file) unzFile file; { int err=UNZ_OK; unz_s* s; file_in_zip_read_info_s* pfile_in_zip_read_info; if (file==NULL) return UNZ_PARAMERROR; s=(unz_s*)file; pfile_in_zip_read_info=s->pfile_in_zip_read; if (pfile_in_zip_read_info==NULL) return UNZ_PARAMERROR; if ((pfile_in_zip_read_info->rest_read_uncompressed == 0) && (!pfile_in_zip_read_info->raw)) { if (pfile_in_zip_read_info->crc32 != pfile_in_zip_read_info->crc32_wait) err=UNZ_CRCERROR; } TRYFREE(pfile_in_zip_read_info->read_buffer); pfile_in_zip_read_info->read_buffer = NULL; if (pfile_in_zip_read_info->stream_initialised == Z_DEFLATED) inflateEnd(&pfile_in_zip_read_info->stream); #ifdef HAVE_BZIP2 else if (pfile_in_zip_read_info->stream_initialised == Z_BZIP2ED) BZ2_bzDecompressEnd(&pfile_in_zip_read_info->bstream); #endif pfile_in_zip_read_info->stream_initialised = 0; TRYFREE(pfile_in_zip_read_info); s->pfile_in_zip_read=NULL; return err; } /* Get the global comment string of the ZipFile, in the szComment buffer. uSizeBuf is the size of the szComment buffer. return the number of byte copied or an error code <0 */ extern int ZEXPORT unzGetGlobalComment (file, szComment, uSizeBuf) unzFile file; char *szComment; uLong uSizeBuf; { unz_s* s; uLong uReadThis ; if (file==NULL) return UNZ_PARAMERROR; s=(unz_s*)file; uReadThis = uSizeBuf; if (uReadThis>s->gi.size_comment) uReadThis = s->gi.size_comment; if (ZSEEK(s->z_filefunc,s->filestream,s->central_pos+22,ZLIB_FILEFUNC_SEEK_SET)!=0) return UNZ_ERRNO; if (uReadThis>0) { *szComment='\0'; if (ZREAD(s->z_filefunc,s->filestream,szComment,uReadThis)!=uReadThis) return UNZ_ERRNO; } if ((szComment != NULL) && (uSizeBuf > s->gi.size_comment)) *(szComment+s->gi.size_comment)='\0'; return (int)uReadThis; } /* Additions by RX '2004 */ extern uLong ZEXPORT unzGetOffset (file) unzFile file; { unz_s* s; if (file==NULL) return 0; s=(unz_s*)file; if (!s->current_file_ok) return 0; if (s->gi.number_entry != 0 && s->gi.number_entry != 0xffff) if (s->num_file==s->gi.number_entry) return 0; return s->pos_in_central_dir; } extern int ZEXPORT unzSetOffset (file, pos) unzFile file; uLong pos; { unz_s* s; int err; if (file==NULL) return UNZ_PARAMERROR; s=(unz_s*)file; s->pos_in_central_dir = pos; s->num_file = s->gi.number_entry; /* hack */ err = unzlocal_GetCurrentFileInfoInternal(file,&s->cur_file_info, &s->cur_file_info_internal, NULL,0,NULL,0,NULL,0); s->current_file_ok = (err == UNZ_OK); return err; }
722,425
./openmeap/clients/c/openmeap-slic-core/3rd_party/minzip-1.01h/minizip.c
/* minizip.c Version 1.01h, December 28th, 2009 Copyright (C) 1998-2009 Gilles Vollant Changes: Aug 3, 2006. jg. support storing files with out paths. (-j) Aug 3, 2006. jg. files with paths should not have leading slashes. */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <time.h> #include <errno.h> #include <fcntl.h> #ifdef unix # include <unistd.h> # include <utime.h> # include <sys/types.h> # include <sys/stat.h> #else # include <direct.h> # include <io.h> #endif #include "zip.h" #ifdef WIN32 #define USEWIN32IOAPI #include "iowin32.h" #endif #define WRITEBUFFERSIZE (16384) #define MAXFILENAME (256) #ifdef WIN32 uLong filetime(f, tmzip, dt) char *f; /* name of file to get info on */ tm_zip *tmzip; /* return value: access, modific. and creation times */ uLong *dt; /* dostime */ { int ret = 0; { FILETIME ftLocal; HANDLE hFind; WIN32_FIND_DATAA ff32; hFind = FindFirstFileA(f,&ff32); if (hFind != INVALID_HANDLE_VALUE) { FileTimeToLocalFileTime(&(ff32.ftLastWriteTime),&ftLocal); FileTimeToDosDateTime(&ftLocal,((LPWORD)dt)+1,((LPWORD)dt)+0); FindClose(hFind); ret = 1; } } return ret; } #else #ifdef unix uLong filetime(f, tmzip, dt) char *f; /* name of file to get info on */ tm_zip *tmzip; /* return value: access, modific. and creation times */ uLong *dt; /* dostime */ { int ret=0; struct stat s; /* results of stat() */ struct tm* filedate; time_t tm_t=0; if (strcmp(f,"-")!=0) { char name[MAXFILENAME+1]; int len = strlen(f); if (len > MAXFILENAME) len = MAXFILENAME; strncpy(name, f,MAXFILENAME-1); /* strncpy doesnt append the trailing NULL, of the string is too long. */ name[ MAXFILENAME ] = '\0'; if (name[len - 1] == '/') name[len - 1] = '\0'; /* not all systems allow stat'ing a file with / appended */ if (stat(name,&s)==0) { tm_t = s.st_mtime; ret = 1; } } filedate = localtime(&tm_t); tmzip->tm_sec = filedate->tm_sec; tmzip->tm_min = filedate->tm_min; tmzip->tm_hour = filedate->tm_hour; tmzip->tm_mday = filedate->tm_mday; tmzip->tm_mon = filedate->tm_mon ; tmzip->tm_year = filedate->tm_year; return ret; } #else uLong filetime(f, tmzip, dt) char *f; /* name of file to get info on */ tm_zip *tmzip; /* return value: access, modific. and creation times */ uLong *dt; /* dostime */ { return 0; } #endif #endif int check_exist_file(filename) const char* filename; { FILE* ftestexist; int ret = 1; ftestexist = fopen(filename,"rb"); if (ftestexist==NULL) ret = 0; else fclose(ftestexist); return ret; } void do_banner() { printf("MiniZip 1.01e-jg, demo of zLib + Zip package written by Gilles Vollant\n"); printf("minor updates, jg.\n"); printf("more info at http://www.winimage.com/zLibDll/minizip.html\n\n"); } void do_help() { printf("Usage : minizip [-o] [-a] [-0 to -9] [-p password] [-j] file.zip [files_to_add]\n\n" \ " -o Overwrite existing file.zip\n" \ " -a Append to existing file.zip\n" \ " -0 Store only\n" \ " -1 Compress faster\n" \ " -9 Compress better\n" \ " -j exclude path. store only the file name.\n\n"); } /* calculate the CRC32 of a file, because to encrypt a file, we need known the CRC32 of the file before */ int getFileCrc(const char* filenameinzip,void*buf,unsigned long size_buf,unsigned long* result_crc) { unsigned long calculate_crc=0; int err=ZIP_OK; FILE * fin = fopen(filenameinzip,"rb"); unsigned long size_read = 0; unsigned long total_read = 0; if (fin==NULL) { err = ZIP_ERRNO; } if (err == ZIP_OK) do { err = ZIP_OK; size_read = (int)fread(buf,1,size_buf,fin); if (size_read < size_buf) if (feof(fin)==0) { printf("error in reading %s\n",filenameinzip); err = ZIP_ERRNO; } if (size_read>0) calculate_crc = crc32(calculate_crc,buf,size_read); total_read += size_read; } while ((err == ZIP_OK) && (size_read>0)); if (fin) fclose(fin); *result_crc=calculate_crc; printf("file %s crc %lx\n",filenameinzip,calculate_crc); return err; } int main(argc,argv) int argc; char *argv[]; { int i; int opt_overwrite=0; int opt_compress_level=Z_DEFAULT_COMPRESSION; int opt_exclude_path=0; int zipfilenamearg = 0; char filename_try[MAXFILENAME+16]; int zipok; int err=0; int size_buf=0; void* buf=NULL; const char* password=NULL; do_banner(); if (argc==1) { do_help(); return 0; } else { for (i=1;i<argc;i++) { if ((*argv[i])=='-') { const char *p=argv[i]+1; while ((*p)!='\0') { char c=*(p++);; if ((c=='o') || (c=='O')) opt_overwrite = 1; if ((c=='a') || (c=='A')) opt_overwrite = 2; if ((c>='0') && (c<='9')) opt_compress_level = c-'0'; if ((c=='j') || (c=='J')) opt_exclude_path = 1; if (((c=='p') || (c=='P')) && (i+1<argc)) { password=argv[i+1]; i++; } } } else { if (zipfilenamearg == 0) { zipfilenamearg = i ; } } } } size_buf = WRITEBUFFERSIZE; buf = (void*)malloc(size_buf); if (buf==NULL) { printf("Error allocating memory\n"); return ZIP_INTERNALERROR; } if (zipfilenamearg==0) { zipok=0; } else { int i,len; int dot_found=0; zipok = 1 ; strncpy(filename_try, argv[zipfilenamearg],MAXFILENAME-1); /* strncpy doesnt append the trailing NULL, of the string is too long. */ filename_try[ MAXFILENAME ] = '\0'; len=(int)strlen(filename_try); for (i=0;i<len;i++) if (filename_try[i]=='.') dot_found=1; if (dot_found==0) strcat(filename_try,".zip"); if (opt_overwrite==2) { /* if the file don't exist, we not append file */ if (check_exist_file(filename_try)==0) opt_overwrite=1; } else if (opt_overwrite==0) if (check_exist_file(filename_try)!=0) { char rep=0; do { char answer[128]; int ret; printf("The file %s exists. Overwrite ? [y]es, [n]o, [a]ppend : ",filename_try); ret = scanf("%1s",answer); if (ret != 1) { exit(EXIT_FAILURE); } rep = answer[0] ; if ((rep>='a') && (rep<='z')) rep -= 0x20; } while ((rep!='Y') && (rep!='N') && (rep!='A')); if (rep=='N') zipok = 0; if (rep=='A') opt_overwrite = 2; } } if (zipok==1) { zipFile zf; int errclose; # ifdef USEWIN32IOAPI zlib_filefunc_def ffunc; fill_win32_filefunc(&ffunc); zf = zipOpen2(filename_try,(opt_overwrite==2) ? 2 : 0,NULL,&ffunc); # else zf = zipOpen(filename_try,(opt_overwrite==2) ? 2 : 0); # endif if (zf == NULL) { printf("error opening %s\n",filename_try); err= ZIP_ERRNO; } else printf("creating %s\n",filename_try); for (i=zipfilenamearg+1;(i<argc) && (err==ZIP_OK);i++) { if (!((((*(argv[i]))=='-') || ((*(argv[i]))=='/')) && ((argv[i][1]=='o') || (argv[i][1]=='O') || (argv[i][1]=='a') || (argv[i][1]=='A') || (argv[i][1]=='p') || (argv[i][1]=='P') || ((argv[i][1]>='0') || (argv[i][1]<='9'))) && (strlen(argv[i]) == 2))) { FILE * fin; int size_read; const char* filenameinzip = argv[i]; const char *savefilenameinzip; zip_fileinfo zi; unsigned long crcFile=0; zi.tmz_date.tm_sec = zi.tmz_date.tm_min = zi.tmz_date.tm_hour = zi.tmz_date.tm_mday = zi.tmz_date.tm_mon = zi.tmz_date.tm_year = 0; zi.dosDate = 0; zi.internal_fa = 0; zi.external_fa = 0; filetime(filenameinzip,&zi.tmz_date,&zi.dosDate); /* err = zipOpenNewFileInZip(zf,filenameinzip,&zi, NULL,0,NULL,0,NULL / * comment * /, (opt_compress_level != 0) ? Z_DEFLATED : 0, opt_compress_level); */ if ((password != NULL) && (err==ZIP_OK)) err = getFileCrc(filenameinzip,buf,size_buf,&crcFile); /*the path name saved, should not include a leading slash. */ /*if it did, windows/xp and dynazip couldn't read the zip file. */ savefilenameinzip = filenameinzip; while( savefilenameinzip[0] == '\\' || savefilenameinzip[0] == '/' ) { savefilenameinzip++; } /*should the zip file contain any path at all?*/ if( opt_exclude_path ) { const char *tmpptr; const char *lastslash = 0; for( tmpptr = savefilenameinzip; *tmpptr; tmpptr++) { if( *tmpptr == '\\' || *tmpptr == '/') { lastslash = tmpptr; } } if( lastslash != NULL ) { savefilenameinzip = lastslash+1; // base filename follows last slash. } } /**/ err = zipOpenNewFileInZip3(zf,savefilenameinzip,&zi, NULL,0,NULL,0,NULL /* comment*/, (opt_compress_level != 0) ? Z_DEFLATED : 0, opt_compress_level,0, /* -MAX_WBITS, DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY, */ -MAX_WBITS, DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY, password,crcFile); if (err != ZIP_OK) printf("error in opening %s in zipfile\n",filenameinzip); else { fin = fopen(filenameinzip,"rb"); if (fin==NULL) { err=ZIP_ERRNO; printf("error in opening %s for reading\n",filenameinzip); } } if (err == ZIP_OK) do { err = ZIP_OK; size_read = (int)fread(buf,1,size_buf,fin); if (size_read < size_buf) if (feof(fin)==0) { printf("error in reading %s\n",filenameinzip); err = ZIP_ERRNO; } if (size_read>0) { err = zipWriteInFileInZip (zf,buf,size_read); if (err<0) { printf("error in writing %s in the zipfile\n", filenameinzip); } } } while ((err == ZIP_OK) && (size_read>0)); if (fin) fclose(fin); if (err<0) err=ZIP_ERRNO; else { err = zipCloseFileInZip(zf); if (err!=ZIP_OK) printf("error in closing %s in the zipfile\n", filenameinzip); } } } errclose = zipClose(zf,NULL); if (errclose != ZIP_OK) printf("error in closing %s\n",filename_try); } else { do_help(); } free(buf); return 0; }
722,426
./openmeap/clients/c/openmeap-slic-core/3rd_party/minzip-1.01h/miniunz.c
/* miniunz.c Version 1.01h, December 28th, 2009 Copyright (C) 1998-2009 Gilles Vollant */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <time.h> #include <errno.h> #include <fcntl.h> #ifdef unix # include <unistd.h> # include <utime.h> #else # include <direct.h> # include <io.h> #endif #include "unzip.h" #define CASESENSITIVITY (0) #define WRITEBUFFERSIZE (8192) #define MAXFILENAME (256) #ifdef WIN32 #define USEWIN32IOAPI #include "iowin32.h" #endif /* mini unzip, demo of unzip package usage : Usage : miniunz [-exvlo] file.zip [file_to_extract] [-d extractdir] list the file in the zipfile, and print the content of FILE_ID.ZIP or README.TXT if it exists */ /* change_file_date : change the date/time of a file filename : the filename of the file where date/time must be modified dosdate : the new date at the MSDos format (4 bytes) tmu_date : the SAME new date at the tm_unz format */ void change_file_date(filename,dosdate,tmu_date) const char *filename; uLong dosdate; tm_unz tmu_date; { #ifdef WIN32 HANDLE hFile; FILETIME ftm,ftLocal,ftCreate,ftLastAcc,ftLastWrite; hFile = CreateFile(filename,GENERIC_READ | GENERIC_WRITE, 0,NULL,OPEN_EXISTING,0,NULL); GetFileTime(hFile,&ftCreate,&ftLastAcc,&ftLastWrite); DosDateTimeToFileTime((WORD)(dosdate>>16),(WORD)dosdate,&ftLocal); LocalFileTimeToFileTime(&ftLocal,&ftm); SetFileTime(hFile,&ftm,&ftLastAcc,&ftm); CloseHandle(hFile); #else #ifdef unix struct utimbuf ut; struct tm newdate; newdate.tm_sec = tmu_date.tm_sec; newdate.tm_min=tmu_date.tm_min; newdate.tm_hour=tmu_date.tm_hour; newdate.tm_mday=tmu_date.tm_mday; newdate.tm_mon=tmu_date.tm_mon; if (tmu_date.tm_year > 1900) newdate.tm_year=tmu_date.tm_year - 1900; else newdate.tm_year=tmu_date.tm_year ; newdate.tm_isdst=-1; ut.actime=ut.modtime=mktime(&newdate); utime(filename,&ut); #endif #endif } /* mymkdir and change_file_date are not 100 % portable As I don't know well Unix, I wait feedback for the unix portion */ int mymkdir(dirname) const char* dirname; { int ret=0; #ifdef WIN32 ret = mkdir(dirname); #else #ifdef unix ret = mkdir (dirname,0775); #endif #endif return ret; } int makedir (newdir) char *newdir; { char *buffer ; char *p; int len = (int)strlen(newdir); if (len <= 0) return 0; buffer = (char*)malloc(len+1); if (buffer==NULL) { printf("Error allocating memory\n"); return UNZ_INTERNALERROR; } strcpy(buffer,newdir); if (buffer[len-1] == '/') { buffer[len-1] = '\0'; } if (mymkdir(buffer) == 0) { free(buffer); return 1; } p = buffer+1; while (1) { char hold; while(*p && *p != '\\' && *p != '/') p++; hold = *p; *p = 0; if ((mymkdir(buffer) == -1) && (errno == ENOENT)) { printf("couldn't create directory %s\n",buffer); free(buffer); return 0; } if (hold == 0) break; *p++ = hold; } free(buffer); return 1; } void do_banner() { printf("MiniUnz 1.01b, demo of zLib + Unz package written by Gilles Vollant\n"); printf("more info at http://www.winimage.com/zLibDll/unzip.html\n\n"); } void do_help() { printf("Usage : miniunz [-e] [-x] [-v] [-l] [-o] [-p password] file.zip [file_to_extr.] [-d extractdir]\n\n" \ " -e Extract without pathname (junk paths)\n" \ " -x Extract with pathname\n" \ " -v list files\n" \ " -l list files\n" \ " -d directory to extract into\n" \ " -o overwrite files without prompting\n" \ " -p extract crypted file using password\n\n"); } int do_list(uf) unzFile uf; { uLong i; unz_global_info gi; int err; err = unzGetGlobalInfo (uf,&gi); if (err!=UNZ_OK) printf("error %d with zipfile in unzGetGlobalInfo \n",err); printf(" Length Method Size Ratio Date Time CRC-32 Name\n"); printf(" ------ ------ ---- ----- ---- ---- ------ ----\n"); for (i=0;i<gi.number_entry;i++) { char filename_inzip[256]; unz_file_info file_info; uLong ratio=0; const char *string_method; char charCrypt=' '; err = unzGetCurrentFileInfo(uf,&file_info,filename_inzip,sizeof(filename_inzip),NULL,0,NULL,0); if (err!=UNZ_OK) { printf("error %d with zipfile in unzGetCurrentFileInfo\n",err); break; } if (file_info.uncompressed_size>0) ratio = (file_info.compressed_size*100)/file_info.uncompressed_size; /* display a '*' if the file is crypted */ if ((file_info.flag & 1) != 0) charCrypt='*'; if (file_info.compression_method==0) string_method="Stored"; else if (file_info.compression_method==Z_DEFLATED) { uInt iLevel=(uInt)((file_info.flag & 0x6)/2); if (iLevel==0) string_method="Defl:N"; else if (iLevel==1) string_method="Defl:X"; else if ((iLevel==2) || (iLevel==3)) string_method="Defl:F"; /* 2:fast , 3 : extra fast*/ } else if (file_info.compression_method==Z_BZIP2ED) { string_method="BZip2 "; } else string_method="Unkn. "; printf("%7lu %6s%c%7lu %3lu%% %2.2lu-%2.2lu-%2.2lu %2.2lu:%2.2lu %8.8lx %s\n", file_info.uncompressed_size,string_method, charCrypt, file_info.compressed_size, ratio, (uLong)file_info.tmu_date.tm_mon + 1, (uLong)file_info.tmu_date.tm_mday, (uLong)file_info.tmu_date.tm_year % 100, (uLong)file_info.tmu_date.tm_hour,(uLong)file_info.tmu_date.tm_min, (uLong)file_info.crc,filename_inzip); if ((i+1)<gi.number_entry) { err = unzGoToNextFile(uf); if (err!=UNZ_OK) { printf("error %d with zipfile in unzGoToNextFile\n",err); break; } } } return 0; } int do_extract_currentfile(uf,popt_extract_without_path,popt_overwrite,password) unzFile uf; const int* popt_extract_without_path; int* popt_overwrite; const char* password; { char filename_inzip[256]; char* filename_withoutpath; char* p; int err=UNZ_OK; FILE *fout=NULL; void* buf; uInt size_buf; unz_file_info file_info; uLong ratio=0; err = unzGetCurrentFileInfo(uf,&file_info,filename_inzip,sizeof(filename_inzip),NULL,0,NULL,0); if (err!=UNZ_OK) { printf("error %d with zipfile in unzGetCurrentFileInfo\n",err); return err; } size_buf = WRITEBUFFERSIZE; buf = (void*)malloc(size_buf); if (buf==NULL) { printf("Error allocating memory\n"); return UNZ_INTERNALERROR; } p = filename_withoutpath = filename_inzip; while ((*p) != '\0') { if (((*p)=='/') || ((*p)=='\\')) filename_withoutpath = p+1; p++; } if ((*filename_withoutpath)=='\0') { if ((*popt_extract_without_path)==0) { printf("creating directory: %s\n",filename_inzip); mymkdir(filename_inzip); } } else { const char* write_filename; int skip=0; if ((*popt_extract_without_path)==0) write_filename = filename_inzip; else write_filename = filename_withoutpath; err = unzOpenCurrentFilePassword(uf,password); if (err!=UNZ_OK) { printf("error %d with zipfile in unzOpenCurrentFilePassword\n",err); } if (((*popt_overwrite)==0) && (err==UNZ_OK)) { char rep=0; FILE* ftestexist; ftestexist = fopen(write_filename,"rb"); if (ftestexist!=NULL) { fclose(ftestexist); do { char answer[128]; int ret; printf("The file %s exists. Overwrite ? [y]es, [n]o, [A]ll: ",write_filename); ret = scanf("%1s",answer); if (ret != 1) { exit(EXIT_FAILURE); } rep = answer[0] ; if ((rep>='a') && (rep<='z')) rep -= 0x20; } while ((rep!='Y') && (rep!='N') && (rep!='A')); } if (rep == 'N') skip = 1; if (rep == 'A') *popt_overwrite=1; } if ((skip==0) && (err==UNZ_OK)) { fout=fopen(write_filename,"wb"); /* some zipfile don't contain directory alone before file */ if ((fout==NULL) && ((*popt_extract_without_path)==0) && (filename_withoutpath!=(char*)filename_inzip)) { char c=*(filename_withoutpath-1); *(filename_withoutpath-1)='\0'; makedir(write_filename); *(filename_withoutpath-1)=c; fout=fopen(write_filename,"wb"); } if (fout==NULL) { printf("error opening %s\n",write_filename); } } if (fout!=NULL) { printf(" extracting: %s\n",write_filename); do { err = unzReadCurrentFile(uf,buf,size_buf); if (err<0) { printf("error %d with zipfile in unzReadCurrentFile\n",err); break; } if (err>0) if (fwrite(buf,err,1,fout)!=1) { printf("error in writing extracted file\n"); err=UNZ_ERRNO; break; } } while (err>0); if (fout) fclose(fout); if (err==0) change_file_date(write_filename,file_info.dosDate, file_info.tmu_date); } if (err==UNZ_OK) { err = unzCloseCurrentFile (uf); if (err!=UNZ_OK) { printf("error %d with zipfile in unzCloseCurrentFile\n",err); } } else unzCloseCurrentFile(uf); /* don't lose the error */ } free(buf); return err; } int do_extract(uf,opt_extract_without_path,opt_overwrite,password) unzFile uf; int opt_extract_without_path; int opt_overwrite; const char* password; { uLong i; unz_global_info gi; int err; FILE* fout=NULL; err = unzGetGlobalInfo (uf,&gi); if (err!=UNZ_OK) printf("error %d with zipfile in unzGetGlobalInfo \n",err); for (i=0;i<gi.number_entry;i++) { if (do_extract_currentfile(uf,&opt_extract_without_path, &opt_overwrite, password) != UNZ_OK) break; if ((i+1)<gi.number_entry) { err = unzGoToNextFile(uf); if (err!=UNZ_OK) { printf("error %d with zipfile in unzGoToNextFile\n",err); break; } } } return 0; } int do_extract_onefile(uf,filename,opt_extract_without_path,opt_overwrite,password) unzFile uf; const char* filename; int opt_extract_without_path; int opt_overwrite; const char* password; { int err = UNZ_OK; if (unzLocateFile(uf,filename,CASESENSITIVITY)!=UNZ_OK) { printf("file %s not found in the zipfile\n",filename); return 2; } if (do_extract_currentfile(uf,&opt_extract_without_path, &opt_overwrite, password) == UNZ_OK) return 0; else return 1; } int main(argc,argv) int argc; char *argv[]; { const char *zipfilename=NULL; const char *filename_to_extract=NULL; const char *password=NULL; char filename_try[MAXFILENAME+16] = ""; int i; int ret_value=0; int opt_do_list=0; int opt_do_extract=1; int opt_do_extract_withoutpath=0; int opt_overwrite=0; int opt_extractdir=0; const char *dirname=NULL; unzFile uf=NULL; do_banner(); if (argc==1) { do_help(); return 0; } else { for (i=1;i<argc;i++) { if ((*argv[i])=='-') { const char *p=argv[i]+1; while ((*p)!='\0') { char c=*(p++);; if ((c=='l') || (c=='L')) opt_do_list = 1; if ((c=='v') || (c=='V')) opt_do_list = 1; if ((c=='x') || (c=='X')) opt_do_extract = 1; if ((c=='e') || (c=='E')) opt_do_extract = opt_do_extract_withoutpath = 1; if ((c=='o') || (c=='O')) opt_overwrite=1; if ((c=='d') || (c=='D')) { opt_extractdir=1; dirname=argv[i+1]; } if (((c=='p') || (c=='P')) && (i+1<argc)) { password=argv[i+1]; i++; } } } else { if (zipfilename == NULL) zipfilename = argv[i]; else if ((filename_to_extract==NULL) && (!opt_extractdir)) filename_to_extract = argv[i] ; } } } if (zipfilename!=NULL) { # ifdef USEWIN32IOAPI zlib_filefunc_def ffunc; # endif strncpy(filename_try, zipfilename,MAXFILENAME-1); /* strncpy doesnt append the trailing NULL, of the string is too long. */ filename_try[ MAXFILENAME ] = '\0'; # ifdef USEWIN32IOAPI fill_win32_filefunc(&ffunc); uf = unzOpen2(zipfilename,&ffunc); # else uf = unzOpen(zipfilename); # endif if (uf==NULL) { strcat(filename_try,".zip"); # ifdef USEWIN32IOAPI uf = unzOpen2(filename_try,&ffunc); # else uf = unzOpen(filename_try); # endif } } if (uf==NULL) { printf("Cannot open %s or %s.zip\n",zipfilename,zipfilename); return 1; } printf("%s opened\n",filename_try); if (opt_do_list==1) ret_value = do_list(uf); else if (opt_do_extract==1) { if (opt_extractdir && chdir(dirname)) { printf("Error changing into %s, aborting\n", dirname); exit(-1); } if (filename_to_extract == NULL) ret_value = do_extract(uf,opt_do_extract_withoutpath,opt_overwrite,password); else ret_value = do_extract_onefile(uf,filename_to_extract, opt_do_extract_withoutpath,opt_overwrite,password); } unzClose(uf); return ret_value ; }
722,427
./openmeap/clients/c/openmeap-slic-core/3rd_party/minzip-1.01h/zip.c
/* zip.c -- IO on .zip files using zlib Version 1.01h, December 28th, 2009 27 Dec 2004 Rolf Kalbermatter Modification to zipOpen2 to support globalComment retrieval. Copyright (C) 1998-2009 Gilles Vollant Read zip.h for more info */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <time.h> #include "zlib.h" #include "zip.h" #ifdef STDC # include <stddef.h> # include <string.h> # include <stdlib.h> #endif #ifdef NO_ERRNO_H extern int errno; #else # include <errno.h> #endif #ifndef local # define local static #endif /* compile with -Dlocal if your debugger can't find static symbols */ #ifndef VERSIONMADEBY # define VERSIONMADEBY (0x0) /* platform depedent */ #endif #ifndef Z_BUFSIZE #define Z_BUFSIZE (16384) #endif #ifndef Z_MAXFILENAMEINZIP #define Z_MAXFILENAMEINZIP (256) #endif #ifndef ALLOC # define ALLOC(size) (malloc(size)) #endif #ifndef TRYFREE # define TRYFREE(p) {if (p) free(p);} #endif /* #define SIZECENTRALDIRITEM (0x2e) #define SIZEZIPLOCALHEADER (0x1e) */ /* I've found an old Unix (a SunOS 4.1.3_U1) without all SEEK_* defined.... */ #ifndef SEEK_CUR #define SEEK_CUR 1 #endif #ifndef SEEK_END #define SEEK_END 2 #endif #ifndef SEEK_SET #define SEEK_SET 0 #endif #ifndef DEF_MEM_LEVEL #if MAX_MEM_LEVEL >= 8 # define DEF_MEM_LEVEL 8 #else # define DEF_MEM_LEVEL MAX_MEM_LEVEL #endif #endif const char zip_copyright[] = " zip 1.01 Copyright 1998-2004 Gilles Vollant - http://www.winimage.com/zLibDll"; #define SIZEDATA_INDATABLOCK (4096-(4*4)) #define LOCALHEADERMAGIC (0x04034b50) #define CENTRALHEADERMAGIC (0x02014b50) #define ENDHEADERMAGIC (0x06054b50) #define FLAG_LOCALHEADER_OFFSET (0x06) #define CRC_LOCALHEADER_OFFSET (0x0e) #define SIZECENTRALHEADER (0x2e) /* 46 */ typedef struct linkedlist_datablock_internal_s { struct linkedlist_datablock_internal_s* next_datablock; uLong avail_in_this_block; uLong filled_in_this_block; uLong unused; /* for future use and alignement */ unsigned char data[SIZEDATA_INDATABLOCK]; } linkedlist_datablock_internal; typedef struct linkedlist_data_s { linkedlist_datablock_internal* first_block; linkedlist_datablock_internal* last_block; } linkedlist_data; typedef struct { z_stream stream; /* zLib stream structure for inflate */ int stream_initialised; /* 1 is stream is initialised */ uInt pos_in_buffered_data; /* last written byte in buffered_data */ uLong pos_local_header; /* offset of the local header of the file currenty writing */ char* central_header; /* central header data for the current file */ uLong size_centralheader; /* size of the central header for cur file */ uLong flag; /* flag of the file currently writing */ int method; /* compression method of file currenty wr.*/ int raw; /* 1 for directly writing raw data */ Byte buffered_data[Z_BUFSIZE];/* buffer contain compressed data to be writ*/ uLong dosDate; uLong crc32; int encrypt; #ifndef NOCRYPT unsigned long keys[3]; /* keys defining the pseudo-random sequence */ const unsigned long* pcrc_32_tab; int crypt_header_size; #endif } curfile_info; typedef struct { zlib_filefunc_def z_filefunc; voidpf filestream; /* io structore of the zipfile */ linkedlist_data central_dir;/* datablock with central dir in construction*/ int in_opened_file_inzip; /* 1 if a file in the zip is currently writ.*/ curfile_info ci; /* info on the file curretly writing */ uLong begin_pos; /* position of the beginning of the zipfile */ uLong add_position_when_writting_offset; uLong number_entry; #ifndef NO_ADDFILEINEXISTINGZIP char *globalcomment; #endif } zip_internal; #ifndef NOCRYPT #define INCLUDECRYPTINGCODE_IFCRYPTALLOWED #include "crypt.h" #endif local linkedlist_datablock_internal* allocate_new_datablock() { linkedlist_datablock_internal* ldi; ldi = (linkedlist_datablock_internal*) ALLOC(sizeof(linkedlist_datablock_internal)); if (ldi!=NULL) { ldi->next_datablock = NULL ; ldi->filled_in_this_block = 0 ; ldi->avail_in_this_block = SIZEDATA_INDATABLOCK ; } return ldi; } local void free_datablock(ldi) linkedlist_datablock_internal* ldi; { while (ldi!=NULL) { linkedlist_datablock_internal* ldinext = ldi->next_datablock; TRYFREE(ldi); ldi = ldinext; } } local void init_linkedlist(ll) linkedlist_data* ll; { ll->first_block = ll->last_block = NULL; } local void free_linkedlist(ll) linkedlist_data* ll; { free_datablock(ll->first_block); ll->first_block = ll->last_block = NULL; } local int add_data_in_datablock(ll,buf,len) linkedlist_data* ll; const void* buf; uLong len; { linkedlist_datablock_internal* ldi; const unsigned char* from_copy; if (ll==NULL) return ZIP_INTERNALERROR; if (ll->last_block == NULL) { ll->first_block = ll->last_block = allocate_new_datablock(); if (ll->first_block == NULL) return ZIP_INTERNALERROR; } ldi = ll->last_block; from_copy = (unsigned char*)buf; while (len>0) { uInt copy_this; uInt i; unsigned char* to_copy; if (ldi->avail_in_this_block==0) { ldi->next_datablock = allocate_new_datablock(); if (ldi->next_datablock == NULL) return ZIP_INTERNALERROR; ldi = ldi->next_datablock ; ll->last_block = ldi; } if (ldi->avail_in_this_block < len) copy_this = (uInt)ldi->avail_in_this_block; else copy_this = (uInt)len; to_copy = &(ldi->data[ldi->filled_in_this_block]); for (i=0;i<copy_this;i++) *(to_copy+i)=*(from_copy+i); ldi->filled_in_this_block += copy_this; ldi->avail_in_this_block -= copy_this; from_copy += copy_this ; len -= copy_this; } return ZIP_OK; } /****************************************************************************/ #ifndef NO_ADDFILEINEXISTINGZIP /* =========================================================================== Inputs a long in LSB order to the given file nbByte == 1, 2 or 4 (byte, short or long) */ local int ziplocal_putValue OF((const zlib_filefunc_def* pzlib_filefunc_def, voidpf filestream, uLong x, int nbByte)); local int ziplocal_putValue (pzlib_filefunc_def, filestream, x, nbByte) const zlib_filefunc_def* pzlib_filefunc_def; voidpf filestream; uLong x; int nbByte; { unsigned char buf[4]; int n; for (n = 0; n < nbByte; n++) { buf[n] = (unsigned char)(x & 0xff); x >>= 8; } if (x != 0) { /* data overflow - hack for ZIP64 (X Roche) */ for (n = 0; n < nbByte; n++) { buf[n] = 0xff; } } if (ZWRITE(*pzlib_filefunc_def,filestream,buf,nbByte)!=(uLong)nbByte) return ZIP_ERRNO; else return ZIP_OK; } local void ziplocal_putValue_inmemory OF((void* dest, uLong x, int nbByte)); local void ziplocal_putValue_inmemory (dest, x, nbByte) void* dest; uLong x; int nbByte; { unsigned char* buf=(unsigned char*)dest; int n; for (n = 0; n < nbByte; n++) { buf[n] = (unsigned char)(x & 0xff); x >>= 8; } if (x != 0) { /* data overflow - hack for ZIP64 */ for (n = 0; n < nbByte; n++) { buf[n] = 0xff; } } } /****************************************************************************/ local uLong ziplocal_TmzDateToDosDate(ptm,dosDate) const tm_zip* ptm; uLong dosDate; { uLong year = (uLong)ptm->tm_year; if (year>=1980) year-=1980; else if (year>=80) year-=80; return (uLong) (((ptm->tm_mday) + (32 * (ptm->tm_mon+1)) + (512 * year)) << 16) | ((ptm->tm_sec/2) + (32* ptm->tm_min) + (2048 * (uLong)ptm->tm_hour)); } /****************************************************************************/ local int ziplocal_getByte OF(( const zlib_filefunc_def* pzlib_filefunc_def, voidpf filestream, int *pi)); local int ziplocal_getByte(pzlib_filefunc_def,filestream,pi) const zlib_filefunc_def* pzlib_filefunc_def; voidpf filestream; int *pi; { unsigned char c; int err = (int)ZREAD(*pzlib_filefunc_def,filestream,&c,1); if (err==1) { *pi = (int)c; return ZIP_OK; } else { if (ZERROR(*pzlib_filefunc_def,filestream)) return ZIP_ERRNO; else return ZIP_EOF; } } /* =========================================================================== Reads a long in LSB order from the given gz_stream. Sets */ local int ziplocal_getShort OF(( const zlib_filefunc_def* pzlib_filefunc_def, voidpf filestream, uLong *pX)); local int ziplocal_getShort (pzlib_filefunc_def,filestream,pX) const zlib_filefunc_def* pzlib_filefunc_def; voidpf filestream; uLong *pX; { uLong x ; int i = 0; int err; err = ziplocal_getByte(pzlib_filefunc_def,filestream,&i); x = (uLong)i; if (err==ZIP_OK) err = ziplocal_getByte(pzlib_filefunc_def,filestream,&i); x += ((uLong)i)<<8; if (err==ZIP_OK) *pX = x; else *pX = 0; return err; } local int ziplocal_getLong OF(( const zlib_filefunc_def* pzlib_filefunc_def, voidpf filestream, uLong *pX)); local int ziplocal_getLong (pzlib_filefunc_def,filestream,pX) const zlib_filefunc_def* pzlib_filefunc_def; voidpf filestream; uLong *pX; { uLong x ; int i = 0; int err; err = ziplocal_getByte(pzlib_filefunc_def,filestream,&i); x = (uLong)i; if (err==ZIP_OK) err = ziplocal_getByte(pzlib_filefunc_def,filestream,&i); x += ((uLong)i)<<8; if (err==ZIP_OK) err = ziplocal_getByte(pzlib_filefunc_def,filestream,&i); x += ((uLong)i)<<16; if (err==ZIP_OK) err = ziplocal_getByte(pzlib_filefunc_def,filestream,&i); x += ((uLong)i)<<24; if (err==ZIP_OK) *pX = x; else *pX = 0; return err; } #ifndef BUFREADCOMMENT #define BUFREADCOMMENT (0x400) #endif /* Locate the Central directory of a zipfile (at the end, just before the global comment) Fix from Riccardo Cohen */ local uLong ziplocal_SearchCentralDir OF(( const zlib_filefunc_def* pzlib_filefunc_def, voidpf filestream)); local uLong ziplocal_SearchCentralDir(pzlib_filefunc_def,filestream) const zlib_filefunc_def* pzlib_filefunc_def; voidpf filestream; { unsigned char* buf; uLong uSizeFile; uLong uBackRead; uLong uMaxBack=0xffff; /* maximum size of global comment */ uLong uPosFound=0; if (ZSEEK(*pzlib_filefunc_def,filestream,0,ZLIB_FILEFUNC_SEEK_END) != 0) return 0; uSizeFile = ZTELL(*pzlib_filefunc_def,filestream); if (uMaxBack>uSizeFile) uMaxBack = uSizeFile; buf = (unsigned char*)ALLOC(BUFREADCOMMENT+4); if (buf==NULL) return 0; uBackRead = 4; while (uBackRead<uMaxBack) { uLong uReadSize,uReadPos ; int i; if (uBackRead+BUFREADCOMMENT>uMaxBack) uBackRead = uMaxBack; else uBackRead+=BUFREADCOMMENT; uReadPos = uSizeFile-uBackRead ; uReadSize = ((BUFREADCOMMENT+4) < (uSizeFile-uReadPos)) ? (BUFREADCOMMENT+4) : (uSizeFile-uReadPos); if (ZSEEK(*pzlib_filefunc_def,filestream,uReadPos,ZLIB_FILEFUNC_SEEK_SET)!=0) break; if (ZREAD(*pzlib_filefunc_def,filestream,buf,uReadSize)!=uReadSize) break; for (i=(int)uReadSize-3; (i--)>0;) if (((*(buf+i))==0x50) && ((*(buf+i+1))==0x4b) && ((*(buf+i+2))==0x05) && ((*(buf+i+3))==0x06)) { uPosFound = uReadPos+i; break; } if (uPosFound!=0) break; } TRYFREE(buf); return uPosFound; } #endif /* !NO_ADDFILEINEXISTINGZIP*/ /************************************************************/ extern zipFile ZEXPORT zipOpen2 (pathname, append, globalcomment, pzlib_filefunc_def) const char *pathname; int append; zipcharpc* globalcomment; zlib_filefunc_def* pzlib_filefunc_def; { zip_internal ziinit; zip_internal* zi; int err=ZIP_OK; if (pzlib_filefunc_def==NULL) fill_fopen_filefunc(&ziinit.z_filefunc); else ziinit.z_filefunc = *pzlib_filefunc_def; ziinit.filestream = (*(ziinit.z_filefunc.zopen_file)) (ziinit.z_filefunc.opaque, pathname, (append == APPEND_STATUS_CREATE) ? (ZLIB_FILEFUNC_MODE_READ | ZLIB_FILEFUNC_MODE_WRITE | ZLIB_FILEFUNC_MODE_CREATE) : (ZLIB_FILEFUNC_MODE_READ | ZLIB_FILEFUNC_MODE_WRITE | ZLIB_FILEFUNC_MODE_EXISTING)); if (ziinit.filestream == NULL) return NULL; if (append == APPEND_STATUS_CREATEAFTER) ZSEEK(ziinit.z_filefunc,ziinit.filestream,0,SEEK_END); ziinit.begin_pos = ZTELL(ziinit.z_filefunc,ziinit.filestream); ziinit.in_opened_file_inzip = 0; ziinit.ci.stream_initialised = 0; ziinit.number_entry = 0; ziinit.add_position_when_writting_offset = 0; init_linkedlist(&(ziinit.central_dir)); zi = (zip_internal*)ALLOC(sizeof(zip_internal)); if (zi==NULL) { ZCLOSE(ziinit.z_filefunc,ziinit.filestream); return NULL; } /* now we add file in a zipfile */ # ifndef NO_ADDFILEINEXISTINGZIP ziinit.globalcomment = NULL; if (append == APPEND_STATUS_ADDINZIP) { uLong byte_before_the_zipfile;/* byte before the zipfile, (>0 for sfx)*/ uLong size_central_dir; /* size of the central directory */ uLong offset_central_dir; /* offset of start of central directory */ uLong central_pos,uL; uLong number_disk; /* number of the current dist, used for spaning ZIP, unsupported, always 0*/ uLong number_disk_with_CD; /* number the the disk with central dir, used for spaning ZIP, unsupported, always 0*/ uLong number_entry; uLong number_entry_CD; /* total number of entries in the central dir (same than number_entry on nospan) */ uLong size_comment; central_pos = ziplocal_SearchCentralDir(&ziinit.z_filefunc,ziinit.filestream); /* disable to allow appending to empty ZIP archive if (central_pos==0) err=ZIP_ERRNO; */ if (ZSEEK(ziinit.z_filefunc, ziinit.filestream, central_pos,ZLIB_FILEFUNC_SEEK_SET)!=0) err=ZIP_ERRNO; /* the signature, already checked */ if (ziplocal_getLong(&ziinit.z_filefunc, ziinit.filestream,&uL)!=ZIP_OK) err=ZIP_ERRNO; /* number of this disk */ if (ziplocal_getShort(&ziinit.z_filefunc, ziinit.filestream,&number_disk)!=ZIP_OK) err=ZIP_ERRNO; /* number of the disk with the start of the central directory */ if (ziplocal_getShort(&ziinit.z_filefunc, ziinit.filestream,&number_disk_with_CD)!=ZIP_OK) err=ZIP_ERRNO; /* total number of entries in the central dir on this disk */ if (ziplocal_getShort(&ziinit.z_filefunc, ziinit.filestream,&number_entry)!=ZIP_OK) err=ZIP_ERRNO; /* total number of entries in the central dir */ if (ziplocal_getShort(&ziinit.z_filefunc, ziinit.filestream,&number_entry_CD)!=ZIP_OK) err=ZIP_ERRNO; if ((number_entry_CD!=number_entry) || (number_disk_with_CD!=0) || (number_disk!=0)) err=ZIP_BADZIPFILE; /* size of the central directory */ if (ziplocal_getLong(&ziinit.z_filefunc, ziinit.filestream,&size_central_dir)!=ZIP_OK) err=ZIP_ERRNO; /* offset of start of central directory with respect to the starting disk number */ if (ziplocal_getLong(&ziinit.z_filefunc, ziinit.filestream,&offset_central_dir)!=ZIP_OK) err=ZIP_ERRNO; /* zipfile global comment length */ if (ziplocal_getShort(&ziinit.z_filefunc, ziinit.filestream,&size_comment)!=ZIP_OK) err=ZIP_ERRNO; if ((central_pos<offset_central_dir+size_central_dir) && (err==ZIP_OK)) err=ZIP_BADZIPFILE; if (err!=ZIP_OK) { ZCLOSE(ziinit.z_filefunc, ziinit.filestream); return NULL; } if (size_comment>0) { ziinit.globalcomment = (char*)ALLOC(size_comment+1); if (ziinit.globalcomment) { size_comment = ZREAD(ziinit.z_filefunc, ziinit.filestream,ziinit.globalcomment,size_comment); ziinit.globalcomment[size_comment]=0; } } byte_before_the_zipfile = central_pos - (offset_central_dir+size_central_dir); ziinit.add_position_when_writting_offset = byte_before_the_zipfile; { uLong size_central_dir_to_read = size_central_dir; size_t buf_size = SIZEDATA_INDATABLOCK; void* buf_read = (void*)ALLOC(buf_size); if (ZSEEK(ziinit.z_filefunc, ziinit.filestream, offset_central_dir + byte_before_the_zipfile, ZLIB_FILEFUNC_SEEK_SET) != 0) err=ZIP_ERRNO; while ((size_central_dir_to_read>0) && (err==ZIP_OK)) { uLong read_this = SIZEDATA_INDATABLOCK; if (read_this > size_central_dir_to_read) read_this = size_central_dir_to_read; if (ZREAD(ziinit.z_filefunc, ziinit.filestream,buf_read,read_this) != read_this) err=ZIP_ERRNO; if (err==ZIP_OK) err = add_data_in_datablock(&ziinit.central_dir,buf_read, (uLong)read_this); size_central_dir_to_read-=read_this; } TRYFREE(buf_read); } ziinit.begin_pos = byte_before_the_zipfile; ziinit.number_entry = number_entry_CD; if (ZSEEK(ziinit.z_filefunc, ziinit.filestream, offset_central_dir+byte_before_the_zipfile,ZLIB_FILEFUNC_SEEK_SET)!=0) err=ZIP_ERRNO; } if (globalcomment) { *globalcomment = ziinit.globalcomment; } # endif /* !NO_ADDFILEINEXISTINGZIP*/ if (err != ZIP_OK) { # ifndef NO_ADDFILEINEXISTINGZIP TRYFREE(ziinit.globalcomment); # endif /* !NO_ADDFILEINEXISTINGZIP*/ TRYFREE(zi); return NULL; } else { *zi = ziinit; return (zipFile)zi; } } extern zipFile ZEXPORT zipOpen (pathname, append) const char *pathname; int append; { return zipOpen2(pathname,append,NULL,NULL); } extern int ZEXPORT zipOpenNewFileInZip4 (file, filename, zipfi, extrafield_local, size_extrafield_local, extrafield_global, size_extrafield_global, comment, method, level, raw, windowBits, memLevel, strategy, password, crcForCrypting, versionMadeBy, flagBase) zipFile file; const char* filename; const zip_fileinfo* zipfi; const void* extrafield_local; uInt size_extrafield_local; const void* extrafield_global; uInt size_extrafield_global; const char* comment; int method; int level; int raw; int windowBits; int memLevel; int strategy; const char* password; uLong crcForCrypting; uLong versionMadeBy; uLong flagBase; { zip_internal* zi; uInt size_filename; uInt size_comment; uInt i; int err = ZIP_OK; # ifdef NOCRYPT if (password != NULL) return ZIP_PARAMERROR; # endif if (file == NULL) return ZIP_PARAMERROR; if ((method!=0) && (method!=Z_DEFLATED)) return ZIP_PARAMERROR; zi = (zip_internal*)file; if (zi->in_opened_file_inzip == 1) { err = zipCloseFileInZip (file); if (err != ZIP_OK) return err; } if (filename==NULL) filename="-"; if (comment==NULL) size_comment = 0; else size_comment = (uInt)strlen(comment); size_filename = (uInt)strlen(filename); if (zipfi == NULL) zi->ci.dosDate = 0; else { if (zipfi->dosDate != 0) zi->ci.dosDate = zipfi->dosDate; else zi->ci.dosDate = ziplocal_TmzDateToDosDate(&zipfi->tmz_date,zipfi->dosDate); } zi->ci.flag = flagBase; if ((level==8) || (level==9)) zi->ci.flag |= 2; if ((level==2)) zi->ci.flag |= 4; if ((level==1)) zi->ci.flag |= 6; if (password != NULL) zi->ci.flag |= 1; zi->ci.crc32 = 0; zi->ci.method = method; zi->ci.encrypt = 0; zi->ci.stream_initialised = 0; zi->ci.pos_in_buffered_data = 0; zi->ci.raw = raw; zi->ci.pos_local_header = ZTELL(zi->z_filefunc,zi->filestream) ; zi->ci.size_centralheader = SIZECENTRALHEADER + size_filename + size_extrafield_global + size_comment; zi->ci.central_header = (char*)ALLOC((uInt)zi->ci.size_centralheader); ziplocal_putValue_inmemory(zi->ci.central_header,(uLong)CENTRALHEADERMAGIC,4); /* version info */ ziplocal_putValue_inmemory(zi->ci.central_header+4,(uLong)versionMadeBy,2); ziplocal_putValue_inmemory(zi->ci.central_header+6,(uLong)20,2); ziplocal_putValue_inmemory(zi->ci.central_header+8,(uLong)zi->ci.flag,2); ziplocal_putValue_inmemory(zi->ci.central_header+10,(uLong)zi->ci.method,2); ziplocal_putValue_inmemory(zi->ci.central_header+12,(uLong)zi->ci.dosDate,4); ziplocal_putValue_inmemory(zi->ci.central_header+16,(uLong)0,4); /*crc*/ ziplocal_putValue_inmemory(zi->ci.central_header+20,(uLong)0,4); /*compr size*/ ziplocal_putValue_inmemory(zi->ci.central_header+24,(uLong)0,4); /*uncompr size*/ ziplocal_putValue_inmemory(zi->ci.central_header+28,(uLong)size_filename,2); ziplocal_putValue_inmemory(zi->ci.central_header+30,(uLong)size_extrafield_global,2); ziplocal_putValue_inmemory(zi->ci.central_header+32,(uLong)size_comment,2); ziplocal_putValue_inmemory(zi->ci.central_header+34,(uLong)0,2); /*disk nm start*/ if (zipfi==NULL) ziplocal_putValue_inmemory(zi->ci.central_header+36,(uLong)0,2); else ziplocal_putValue_inmemory(zi->ci.central_header+36,(uLong)zipfi->internal_fa,2); if (zipfi==NULL) ziplocal_putValue_inmemory(zi->ci.central_header+38,(uLong)0,4); else ziplocal_putValue_inmemory(zi->ci.central_header+38,(uLong)zipfi->external_fa,4); ziplocal_putValue_inmemory(zi->ci.central_header+42,(uLong)zi->ci.pos_local_header- zi->add_position_when_writting_offset,4); for (i=0;i<size_filename;i++) *(zi->ci.central_header+SIZECENTRALHEADER+i) = *(filename+i); for (i=0;i<size_extrafield_global;i++) *(zi->ci.central_header+SIZECENTRALHEADER+size_filename+i) = *(((const char*)extrafield_global)+i); for (i=0;i<size_comment;i++) *(zi->ci.central_header+SIZECENTRALHEADER+size_filename+ size_extrafield_global+i) = *(comment+i); if (zi->ci.central_header == NULL) return ZIP_INTERNALERROR; /* write the local header */ err = ziplocal_putValue(&zi->z_filefunc,zi->filestream,(uLong)LOCALHEADERMAGIC,4); if (err==ZIP_OK) err = ziplocal_putValue(&zi->z_filefunc,zi->filestream,(uLong)20,2);/* version needed to extract */ if (err==ZIP_OK) err = ziplocal_putValue(&zi->z_filefunc,zi->filestream,(uLong)zi->ci.flag,2); if (err==ZIP_OK) err = ziplocal_putValue(&zi->z_filefunc,zi->filestream,(uLong)zi->ci.method,2); if (err==ZIP_OK) err = ziplocal_putValue(&zi->z_filefunc,zi->filestream,(uLong)zi->ci.dosDate,4); if (err==ZIP_OK) err = ziplocal_putValue(&zi->z_filefunc,zi->filestream,(uLong)0,4); /* crc 32, unknown */ if (err==ZIP_OK) err = ziplocal_putValue(&zi->z_filefunc,zi->filestream,(uLong)0,4); /* compressed size, unknown */ if (err==ZIP_OK) err = ziplocal_putValue(&zi->z_filefunc,zi->filestream,(uLong)0,4); /* uncompressed size, unknown */ if (err==ZIP_OK) err = ziplocal_putValue(&zi->z_filefunc,zi->filestream,(uLong)size_filename,2); if (err==ZIP_OK) err = ziplocal_putValue(&zi->z_filefunc,zi->filestream,(uLong)size_extrafield_local,2); if ((err==ZIP_OK) && (size_filename>0)) if (ZWRITE(zi->z_filefunc,zi->filestream,filename,size_filename)!=size_filename) err = ZIP_ERRNO; if ((err==ZIP_OK) && (size_extrafield_local>0)) if (ZWRITE(zi->z_filefunc,zi->filestream,extrafield_local,size_extrafield_local) !=size_extrafield_local) err = ZIP_ERRNO; zi->ci.stream.avail_in = (uInt)0; zi->ci.stream.avail_out = (uInt)Z_BUFSIZE; zi->ci.stream.next_out = zi->ci.buffered_data; zi->ci.stream.total_in = 0; zi->ci.stream.total_out = 0; zi->ci.stream.data_type = Z_BINARY; if ((err==ZIP_OK) && (zi->ci.method == Z_DEFLATED) && (!zi->ci.raw)) { zi->ci.stream.zalloc = (alloc_func)0; zi->ci.stream.zfree = (free_func)0; zi->ci.stream.opaque = (voidpf)0; if (windowBits>0) windowBits = -windowBits; err = deflateInit2(&zi->ci.stream, level, Z_DEFLATED, windowBits, memLevel, strategy); if (err==Z_OK) zi->ci.stream_initialised = 1; } # ifndef NOCRYPT zi->ci.crypt_header_size = 0; if ((err==Z_OK) && (password != NULL)) { unsigned char bufHead[RAND_HEAD_LEN]; unsigned int sizeHead; zi->ci.encrypt = 1; zi->ci.pcrc_32_tab = get_crc_table(); /*init_keys(password,zi->ci.keys,zi->ci.pcrc_32_tab);*/ sizeHead=crypthead(password,bufHead,RAND_HEAD_LEN,zi->ci.keys,zi->ci.pcrc_32_tab,crcForCrypting); zi->ci.crypt_header_size = sizeHead; if (ZWRITE(zi->z_filefunc,zi->filestream,bufHead,sizeHead) != sizeHead) err = ZIP_ERRNO; } # endif if (err==Z_OK) zi->in_opened_file_inzip = 1; return err; } extern int ZEXPORT zipOpenNewFileInZip2(file, filename, zipfi, extrafield_local, size_extrafield_local, extrafield_global, size_extrafield_global, comment, method, level, raw) zipFile file; const char* filename; const zip_fileinfo* zipfi; const void* extrafield_local; uInt size_extrafield_local; const void* extrafield_global; uInt size_extrafield_global; const char* comment; int method; int level; int raw; { return zipOpenNewFileInZip4 (file, filename, zipfi, extrafield_local, size_extrafield_local, extrafield_global, size_extrafield_global, comment, method, level, raw, -MAX_WBITS, DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY, NULL, 0, VERSIONMADEBY, 0); } extern int ZEXPORT zipOpenNewFileInZip3 (file, filename, zipfi, extrafield_local, size_extrafield_local, extrafield_global, size_extrafield_global, comment, method, level, raw, windowBits, memLevel, strategy, password, crcForCrypting) zipFile file; const char* filename; const zip_fileinfo* zipfi; const void* extrafield_local; uInt size_extrafield_local; const void* extrafield_global; uInt size_extrafield_global; const char* comment; int method; int level; int raw; int windowBits; int memLevel; int strategy; const char* password; uLong crcForCrypting; { return zipOpenNewFileInZip4 (file, filename, zipfi, extrafield_local, size_extrafield_local, extrafield_global, size_extrafield_global, comment, method, level, raw, windowBits, memLevel, strategy, password, crcForCrypting, VERSIONMADEBY, 0); } extern int ZEXPORT zipOpenNewFileInZip (file, filename, zipfi, extrafield_local, size_extrafield_local, extrafield_global, size_extrafield_global, comment, method, level) zipFile file; const char* filename; const zip_fileinfo* zipfi; const void* extrafield_local; uInt size_extrafield_local; const void* extrafield_global; uInt size_extrafield_global; const char* comment; int method; int level; { return zipOpenNewFileInZip4 (file, filename, zipfi, extrafield_local, size_extrafield_local, extrafield_global, size_extrafield_global, comment, method, level, 0, -MAX_WBITS, DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY, NULL, 0, VERSIONMADEBY, 0); } local int zipFlushWriteBuffer(zi) zip_internal* zi; { int err=ZIP_OK; if (zi->ci.encrypt != 0) { #ifndef NOCRYPT uInt i; int t; for (i=0;i<zi->ci.pos_in_buffered_data;i++) zi->ci.buffered_data[i] = zencode(zi->ci.keys, zi->ci.pcrc_32_tab, zi->ci.buffered_data[i],t); #endif } if (ZWRITE(zi->z_filefunc,zi->filestream,zi->ci.buffered_data,zi->ci.pos_in_buffered_data) !=zi->ci.pos_in_buffered_data) err = ZIP_ERRNO; zi->ci.pos_in_buffered_data = 0; return err; } extern int ZEXPORT zipWriteInFileInZip (file, buf, len) zipFile file; const void* buf; unsigned len; { zip_internal* zi; int err=ZIP_OK; if (file == NULL) return ZIP_PARAMERROR; zi = (zip_internal*)file; if (zi->in_opened_file_inzip == 0) return ZIP_PARAMERROR; zi->ci.stream.next_in = (Bytef*)buf; zi->ci.stream.avail_in = len; zi->ci.crc32 = crc32(zi->ci.crc32,buf,(uInt)len); while ((err==ZIP_OK) && (zi->ci.stream.avail_in>0)) { if (zi->ci.stream.avail_out == 0) { if (zipFlushWriteBuffer(zi) == ZIP_ERRNO) err = ZIP_ERRNO; zi->ci.stream.avail_out = (uInt)Z_BUFSIZE; zi->ci.stream.next_out = zi->ci.buffered_data; } if(err != ZIP_OK) break; if ((zi->ci.method == Z_DEFLATED) && (!zi->ci.raw)) { uLong uTotalOutBefore = zi->ci.stream.total_out; err=deflate(&zi->ci.stream, Z_NO_FLUSH); zi->ci.pos_in_buffered_data += (uInt)(zi->ci.stream.total_out - uTotalOutBefore) ; } else { uInt copy_this,i; if (zi->ci.stream.avail_in < zi->ci.stream.avail_out) copy_this = zi->ci.stream.avail_in; else copy_this = zi->ci.stream.avail_out; for (i=0;i<copy_this;i++) *(((char*)zi->ci.stream.next_out)+i) = *(((const char*)zi->ci.stream.next_in)+i); { zi->ci.stream.avail_in -= copy_this; zi->ci.stream.avail_out-= copy_this; zi->ci.stream.next_in+= copy_this; zi->ci.stream.next_out+= copy_this; zi->ci.stream.total_in+= copy_this; zi->ci.stream.total_out+= copy_this; zi->ci.pos_in_buffered_data += copy_this; } } } return err; } extern int ZEXPORT zipCloseFileInZipRaw (file, uncompressed_size, crc32) zipFile file; uLong uncompressed_size; uLong crc32; { zip_internal* zi; uLong compressed_size; int err=ZIP_OK; if (file == NULL) return ZIP_PARAMERROR; zi = (zip_internal*)file; if (zi->in_opened_file_inzip == 0) return ZIP_PARAMERROR; zi->ci.stream.avail_in = 0; if ((zi->ci.method == Z_DEFLATED) && (!zi->ci.raw)) while (err==ZIP_OK) { uLong uTotalOutBefore; if (zi->ci.stream.avail_out == 0) { if (zipFlushWriteBuffer(zi) == ZIP_ERRNO) err = ZIP_ERRNO; zi->ci.stream.avail_out = (uInt)Z_BUFSIZE; zi->ci.stream.next_out = zi->ci.buffered_data; } uTotalOutBefore = zi->ci.stream.total_out; err=deflate(&zi->ci.stream, Z_FINISH); zi->ci.pos_in_buffered_data += (uInt)(zi->ci.stream.total_out - uTotalOutBefore) ; } if (err==Z_STREAM_END) err=ZIP_OK; /* this is normal */ if ((zi->ci.pos_in_buffered_data>0) && (err==ZIP_OK)) if (zipFlushWriteBuffer(zi)==ZIP_ERRNO) err = ZIP_ERRNO; if ((zi->ci.method == Z_DEFLATED) && (!zi->ci.raw)) { int tmp_err=deflateEnd(&zi->ci.stream); if (err == ZIP_OK) err = tmp_err; zi->ci.stream_initialised = 0; } if (!zi->ci.raw) { crc32 = (uLong)zi->ci.crc32; uncompressed_size = (uLong)zi->ci.stream.total_in; } compressed_size = (uLong)zi->ci.stream.total_out; # ifndef NOCRYPT compressed_size += zi->ci.crypt_header_size; # endif ziplocal_putValue_inmemory(zi->ci.central_header+16,crc32,4); /*crc*/ ziplocal_putValue_inmemory(zi->ci.central_header+20, compressed_size,4); /*compr size*/ if (zi->ci.stream.data_type == Z_ASCII) ziplocal_putValue_inmemory(zi->ci.central_header+36,(uLong)Z_ASCII,2); ziplocal_putValue_inmemory(zi->ci.central_header+24, uncompressed_size,4); /*uncompr size*/ if (err==ZIP_OK) err = add_data_in_datablock(&zi->central_dir,zi->ci.central_header, (uLong)zi->ci.size_centralheader); free(zi->ci.central_header); if (err==ZIP_OK) { long cur_pos_inzip = ZTELL(zi->z_filefunc,zi->filestream); if (ZSEEK(zi->z_filefunc,zi->filestream, zi->ci.pos_local_header + 14,ZLIB_FILEFUNC_SEEK_SET)!=0) err = ZIP_ERRNO; if (err==ZIP_OK) err = ziplocal_putValue(&zi->z_filefunc,zi->filestream,crc32,4); /* crc 32, unknown */ if (err==ZIP_OK) /* compressed size, unknown */ err = ziplocal_putValue(&zi->z_filefunc,zi->filestream,compressed_size,4); if (err==ZIP_OK) /* uncompressed size, unknown */ err = ziplocal_putValue(&zi->z_filefunc,zi->filestream,uncompressed_size,4); if (ZSEEK(zi->z_filefunc,zi->filestream, cur_pos_inzip,ZLIB_FILEFUNC_SEEK_SET)!=0) err = ZIP_ERRNO; } zi->number_entry ++; zi->in_opened_file_inzip = 0; return err; } extern int ZEXPORT zipCloseFileInZip (file) zipFile file; { return zipCloseFileInZipRaw (file,0,0); } extern int ZEXPORT zipClose (file, global_comment) zipFile file; const char* global_comment; { zip_internal* zi; int err = 0; uLong size_centraldir = 0; uLong centraldir_pos_inzip; uInt size_global_comment; if (file == NULL) return ZIP_PARAMERROR; zi = (zip_internal*)file; if (zi->in_opened_file_inzip == 1) { err = zipCloseFileInZip (file); } #ifndef NO_ADDFILEINEXISTINGZIP if (global_comment==NULL) global_comment = zi->globalcomment; #endif if (global_comment==NULL) size_global_comment = 0; else size_global_comment = (uInt)strlen(global_comment); centraldir_pos_inzip = ZTELL(zi->z_filefunc,zi->filestream); if (err==ZIP_OK) { linkedlist_datablock_internal* ldi = zi->central_dir.first_block ; while (ldi!=NULL) { if ((err==ZIP_OK) && (ldi->filled_in_this_block>0)) if (ZWRITE(zi->z_filefunc,zi->filestream, ldi->data,ldi->filled_in_this_block) !=ldi->filled_in_this_block ) err = ZIP_ERRNO; size_centraldir += ldi->filled_in_this_block; ldi = ldi->next_datablock; } } free_linkedlist(&(zi->central_dir)); if (err==ZIP_OK) /* Magic End */ err = ziplocal_putValue(&zi->z_filefunc,zi->filestream,(uLong)ENDHEADERMAGIC,4); if (err==ZIP_OK) /* number of this disk */ err = ziplocal_putValue(&zi->z_filefunc,zi->filestream,(uLong)0,2); if (err==ZIP_OK) /* number of the disk with the start of the central directory */ err = ziplocal_putValue(&zi->z_filefunc,zi->filestream,(uLong)0,2); if (err==ZIP_OK) /* total number of entries in the central dir on this disk */ err = ziplocal_putValue(&zi->z_filefunc,zi->filestream,(uLong)zi->number_entry,2); if (err==ZIP_OK) /* total number of entries in the central dir */ err = ziplocal_putValue(&zi->z_filefunc,zi->filestream,(uLong)zi->number_entry,2); if (err==ZIP_OK) /* size of the central directory */ err = ziplocal_putValue(&zi->z_filefunc,zi->filestream,(uLong)size_centraldir,4); if (err==ZIP_OK) /* offset of start of central directory with respect to the starting disk number */ err = ziplocal_putValue(&zi->z_filefunc,zi->filestream, (uLong)(centraldir_pos_inzip - zi->add_position_when_writting_offset),4); if (err==ZIP_OK) /* zipfile comment length */ err = ziplocal_putValue(&zi->z_filefunc,zi->filestream,(uLong)size_global_comment,2); if ((err==ZIP_OK) && (size_global_comment>0)) if (ZWRITE(zi->z_filefunc,zi->filestream, global_comment,size_global_comment) != size_global_comment) err = ZIP_ERRNO; if (ZCLOSE(zi->z_filefunc,zi->filestream) != 0) if (err == ZIP_OK) err = ZIP_ERRNO; #ifndef NO_ADDFILEINEXISTINGZIP TRYFREE(zi->globalcomment); #endif TRYFREE(zi); return err; }
722,428
./openmeap/clients/c/openmeap-slic-core/3rd_party/minzip-1.01h/iowin32.c
/* iowin32.c -- IO base function header for compress/uncompress .zip files using zlib + zip or unzip API This IO API version uses the Win32 API (for Microsoft Windows) Version 1.01h, December 28th, 2009 Copyright (C) 1998-2009 Gilles Vollant */ #include <stdlib.h> #include "zlib.h" #include "ioapi.h" #include "iowin32.h" #ifndef INVALID_HANDLE_VALUE #define INVALID_HANDLE_VALUE (0xFFFFFFFF) #endif #ifndef INVALID_SET_FILE_POINTER #define INVALID_SET_FILE_POINTER ((DWORD)-1) #endif voidpf ZCALLBACK win32_open_file_func OF(( voidpf opaque, const char* filename, int mode)); uLong ZCALLBACK win32_read_file_func OF(( voidpf opaque, voidpf stream, void* buf, uLong size)); uLong ZCALLBACK win32_write_file_func OF(( voidpf opaque, voidpf stream, const void* buf, uLong size)); long ZCALLBACK win32_tell_file_func OF(( voidpf opaque, voidpf stream)); long ZCALLBACK win32_seek_file_func OF(( voidpf opaque, voidpf stream, uLong offset, int origin)); int ZCALLBACK win32_close_file_func OF(( voidpf opaque, voidpf stream)); int ZCALLBACK win32_error_file_func OF(( voidpf opaque, voidpf stream)); typedef struct { HANDLE hf; int error; } WIN32FILE_IOWIN; voidpf ZCALLBACK win32_open_file_func (opaque, filename, mode) voidpf opaque; const char* filename; int mode; { const char* mode_fopen = NULL; DWORD dwDesiredAccess,dwCreationDisposition,dwShareMode,dwFlagsAndAttributes ; HANDLE hFile = 0; voidpf ret=NULL; dwDesiredAccess = dwShareMode = dwFlagsAndAttributes = 0; if ((mode & ZLIB_FILEFUNC_MODE_READWRITEFILTER)==ZLIB_FILEFUNC_MODE_READ) { dwDesiredAccess = GENERIC_READ; dwCreationDisposition = OPEN_EXISTING; dwShareMode = FILE_SHARE_READ; } else if (mode & ZLIB_FILEFUNC_MODE_EXISTING) { dwDesiredAccess = GENERIC_WRITE | GENERIC_READ; dwCreationDisposition = OPEN_EXISTING; } else if (mode & ZLIB_FILEFUNC_MODE_CREATE) { dwDesiredAccess = GENERIC_WRITE | GENERIC_READ; dwCreationDisposition = CREATE_ALWAYS; } if ((filename!=NULL) && (dwDesiredAccess != 0)) hFile = CreateFile((LPCTSTR)filename, dwDesiredAccess, dwShareMode, NULL, dwCreationDisposition, dwFlagsAndAttributes, NULL); if (hFile == INVALID_HANDLE_VALUE) hFile = NULL; if (hFile != NULL) { WIN32FILE_IOWIN w32fiow; w32fiow.hf = hFile; w32fiow.error = 0; ret = malloc(sizeof(WIN32FILE_IOWIN)); if (ret==NULL) CloseHandle(hFile); else *((WIN32FILE_IOWIN*)ret) = w32fiow; } return ret; } uLong ZCALLBACK win32_read_file_func (opaque, stream, buf, size) voidpf opaque; voidpf stream; void* buf; uLong size; { uLong ret=0; HANDLE hFile = NULL; if (stream!=NULL) hFile = ((WIN32FILE_IOWIN*)stream) -> hf; if (hFile != NULL) if (!ReadFile(hFile, buf, size, &ret, NULL)) { DWORD dwErr = GetLastError(); if (dwErr == ERROR_HANDLE_EOF) dwErr = 0; ((WIN32FILE_IOWIN*)stream) -> error=(int)dwErr; } return ret; } uLong ZCALLBACK win32_write_file_func (opaque, stream, buf, size) voidpf opaque; voidpf stream; const void* buf; uLong size; { uLong ret=0; HANDLE hFile = NULL; if (stream!=NULL) hFile = ((WIN32FILE_IOWIN*)stream) -> hf; if (hFile !=NULL) if (!WriteFile(hFile, buf, size, &ret, NULL)) { DWORD dwErr = GetLastError(); if (dwErr == ERROR_HANDLE_EOF) dwErr = 0; ((WIN32FILE_IOWIN*)stream) -> error=(int)dwErr; } return ret; } long ZCALLBACK win32_tell_file_func (opaque, stream) voidpf opaque; voidpf stream; { long ret=-1; HANDLE hFile = NULL; if (stream!=NULL) hFile = ((WIN32FILE_IOWIN*)stream) -> hf; if (hFile != NULL) { DWORD dwSet = SetFilePointer(hFile, 0, NULL, FILE_CURRENT); if (dwSet == INVALID_SET_FILE_POINTER) { DWORD dwErr = GetLastError(); ((WIN32FILE_IOWIN*)stream) -> error=(int)dwErr; ret = -1; } else ret=(long)dwSet; } return ret; } long ZCALLBACK win32_seek_file_func (opaque, stream, offset, origin) voidpf opaque; voidpf stream; uLong offset; int origin; { DWORD dwMoveMethod=0xFFFFFFFF; HANDLE hFile = NULL; long ret=-1; if (stream!=NULL) hFile = ((WIN32FILE_IOWIN*)stream) -> hf; switch (origin) { case ZLIB_FILEFUNC_SEEK_CUR : dwMoveMethod = FILE_CURRENT; break; case ZLIB_FILEFUNC_SEEK_END : dwMoveMethod = FILE_END; break; case ZLIB_FILEFUNC_SEEK_SET : dwMoveMethod = FILE_BEGIN; break; default: return -1; } if (hFile != NULL) { DWORD dwSet = SetFilePointer(hFile, offset, NULL, dwMoveMethod); if (dwSet == INVALID_SET_FILE_POINTER) { DWORD dwErr = GetLastError(); ((WIN32FILE_IOWIN*)stream) -> error=(int)dwErr; ret = -1; } else ret=0; } return ret; } int ZCALLBACK win32_close_file_func (opaque, stream) voidpf opaque; voidpf stream; { int ret=-1; if (stream!=NULL) { HANDLE hFile; hFile = ((WIN32FILE_IOWIN*)stream) -> hf; if (hFile != NULL) { CloseHandle(hFile); ret=0; } free(stream); } return ret; } int ZCALLBACK win32_error_file_func (opaque, stream) voidpf opaque; voidpf stream; { int ret=-1; if (stream!=NULL) { ret = ((WIN32FILE_IOWIN*)stream) -> error; } return ret; } void fill_win32_filefunc (pzlib_filefunc_def) zlib_filefunc_def* pzlib_filefunc_def; { pzlib_filefunc_def->zopen_file = win32_open_file_func; pzlib_filefunc_def->zread_file = win32_read_file_func; pzlib_filefunc_def->zwrite_file = win32_write_file_func; pzlib_filefunc_def->ztell_file = win32_tell_file_func; pzlib_filefunc_def->zseek_file = win32_seek_file_func; pzlib_filefunc_def->zclose_file = win32_close_file_func; pzlib_filefunc_def->zerror_file = win32_error_file_func; pzlib_filefunc_def->opaque=NULL; }
722,429
./openmeap/clients/c/openmeap-slic-core/3rd_party/minzip-1.01h/mztools.c
/* Additional tools for Minizip Code: Xavier Roche '2004 License: Same as ZLIB (www.gzip.org) */ /* Code */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include "zlib.h" #include "unzip.h" #define READ_8(adr) ((unsigned char)*(adr)) #define READ_16(adr) ( READ_8(adr) | (READ_8(adr+1) << 8) ) #define READ_32(adr) ( READ_16(adr) | (READ_16((adr)+2) << 16) ) #define WRITE_8(buff, n) do { \ *((unsigned char*)(buff)) = (unsigned char) ((n) & 0xff); \ } while(0) #define WRITE_16(buff, n) do { \ WRITE_8((unsigned char*)(buff), n); \ WRITE_8(((unsigned char*)(buff)) + 1, (n) >> 8); \ } while(0) #define WRITE_32(buff, n) do { \ WRITE_16((unsigned char*)(buff), (n) & 0xffff); \ WRITE_16((unsigned char*)(buff) + 2, (n) >> 16); \ } while(0) extern int ZEXPORT unzRepair(file, fileOut, fileOutTmp, nRecovered, bytesRecovered) const char* file; const char* fileOut; const char* fileOutTmp; uLong* nRecovered; uLong* bytesRecovered; { int err = Z_OK; FILE* fpZip = fopen(file, "rb"); FILE* fpOut = fopen(fileOut, "wb"); FILE* fpOutCD = fopen(fileOutTmp, "wb"); if (fpZip != NULL && fpOut != NULL) { int entries = 0; uLong totalBytes = 0; char header[30]; char filename[256]; char extra[1024]; int offset = 0; int offsetCD = 0; while ( fread(header, 1, 30, fpZip) == 30 ) { int currentOffset = offset; /* File entry */ if (READ_32(header) == 0x04034b50) { unsigned int version = READ_16(header + 4); unsigned int gpflag = READ_16(header + 6); unsigned int method = READ_16(header + 8); unsigned int filetime = READ_16(header + 10); unsigned int filedate = READ_16(header + 12); unsigned int crc = READ_32(header + 14); /* crc */ unsigned int cpsize = READ_32(header + 18); /* compressed size */ unsigned int uncpsize = READ_32(header + 22); /* uncompressed sz */ unsigned int fnsize = READ_16(header + 26); /* file name length */ unsigned int extsize = READ_16(header + 28); /* extra field length */ filename[0] = extra[0] = '\0'; /* Header */ if (fwrite(header, 1, 30, fpOut) == 30) { offset += 30; } else { err = Z_ERRNO; break; } /* Filename */ if (fnsize > 0) { if (fread(filename, 1, fnsize, fpZip) == fnsize) { if (fwrite(filename, 1, fnsize, fpOut) == fnsize) { offset += fnsize; } else { err = Z_ERRNO; break; } } else { err = Z_ERRNO; break; } } else { err = Z_STREAM_ERROR; break; } /* Extra field */ if (extsize > 0) { if (fread(extra, 1, extsize, fpZip) == extsize) { if (fwrite(extra, 1, extsize, fpOut) == extsize) { offset += extsize; } else { err = Z_ERRNO; break; } } else { err = Z_ERRNO; break; } } /* Data */ { int dataSize = cpsize; if (dataSize == 0) { dataSize = uncpsize; } if (dataSize > 0) { char* data = malloc(dataSize); if (data != NULL) { if ((int)fread(data, 1, dataSize, fpZip) == dataSize) { if ((int)fwrite(data, 1, dataSize, fpOut) == dataSize) { offset += dataSize; totalBytes += dataSize; } else { err = Z_ERRNO; } } else { err = Z_ERRNO; } free(data); if (err != Z_OK) { break; } } else { err = Z_MEM_ERROR; break; } } } /* Central directory entry */ { char header[46]; char* comment = ""; int comsize = (int) strlen(comment); WRITE_32(header, 0x02014b50); WRITE_16(header + 4, version); WRITE_16(header + 6, version); WRITE_16(header + 8, gpflag); WRITE_16(header + 10, method); WRITE_16(header + 12, filetime); WRITE_16(header + 14, filedate); WRITE_32(header + 16, crc); WRITE_32(header + 20, cpsize); WRITE_32(header + 24, uncpsize); WRITE_16(header + 28, fnsize); WRITE_16(header + 30, extsize); WRITE_16(header + 32, comsize); WRITE_16(header + 34, 0); /* disk # */ WRITE_16(header + 36, 0); /* int attrb */ WRITE_32(header + 38, 0); /* ext attrb */ WRITE_32(header + 42, currentOffset); /* Header */ if (fwrite(header, 1, 46, fpOutCD) == 46) { offsetCD += 46; /* Filename */ if (fnsize > 0) { if (fwrite(filename, 1, fnsize, fpOutCD) == fnsize) { offsetCD += fnsize; } else { err = Z_ERRNO; break; } } else { err = Z_STREAM_ERROR; break; } /* Extra field */ if (extsize > 0) { if (fwrite(extra, 1, extsize, fpOutCD) == extsize) { offsetCD += extsize; } else { err = Z_ERRNO; break; } } /* Comment field */ if (comsize > 0) { if ((int)fwrite(comment, 1, comsize, fpOutCD) == comsize) { offsetCD += comsize; } else { err = Z_ERRNO; break; } } } else { err = Z_ERRNO; break; } } /* Success */ entries++; } else { break; } } /* Final central directory */ { int entriesZip = entries; char header[22]; char* comment = ""; // "ZIP File recovered by zlib/minizip/mztools"; int comsize = (int) strlen(comment); if (entriesZip > 0xffff) { entriesZip = 0xffff; } WRITE_32(header, 0x06054b50); WRITE_16(header + 4, 0); /* disk # */ WRITE_16(header + 6, 0); /* disk # */ WRITE_16(header + 8, entriesZip); /* hack */ WRITE_16(header + 10, entriesZip); /* hack */ WRITE_32(header + 12, offsetCD); /* size of CD */ WRITE_32(header + 16, offset); /* offset to CD */ WRITE_16(header + 20, comsize); /* comment */ /* Header */ if (fwrite(header, 1, 22, fpOutCD) == 22) { /* Comment field */ if (comsize > 0) { if ((int)fwrite(comment, 1, comsize, fpOutCD) != comsize) { err = Z_ERRNO; } } } else { err = Z_ERRNO; } } /* Final merge (file + central directory) */ fclose(fpOutCD); if (err == Z_OK) { fpOutCD = fopen(fileOutTmp, "rb"); if (fpOutCD != NULL) { int nRead; char buffer[8192]; while ( (nRead = (int)fread(buffer, 1, sizeof(buffer), fpOutCD)) > 0) { if ((int)fwrite(buffer, 1, nRead, fpOut) != nRead) { err = Z_ERRNO; break; } } fclose(fpOutCD); } } /* Close */ fclose(fpZip); fclose(fpOut); /* Wipe temporary file */ (void)remove(fileOutTmp); /* Number of recovered entries */ if (err == Z_OK) { if (nRecovered != NULL) { *nRecovered = entries; } if (bytesRecovered != NULL) { *bytesRecovered = totalBytes; } } } else { err = Z_STREAM_ERROR; } return err; }
722,430
./openmeap/clients/c/openmeap-slic-core/3rd_party/cJSON/test.c
/* Copyright (c) 2009 Dave Gamble Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include <stdio.h> #include <stdlib.h> #include "cJSON.h" /* Parse text to JSON, then render back to text, and print! */ void doit(char *text) { char *out;cJSON *json; json=cJSON_Parse(text); if (!json) {printf("Error before: [%s]\n",cJSON_GetErrorPtr());} else { out=cJSON_Print(json); cJSON_Delete(json); printf("%s\n",out); free(out); } } /* Read a file, parse, render back, etc. */ void dofile(char *filename) { FILE *f=fopen(filename,"rb");fseek(f,0,SEEK_END);long len=ftell(f);fseek(f,0,SEEK_SET); char *data=malloc(len+1);fread(data,1,len,f);fclose(f); doit(data); free(data); } /* Used by some code below as an example datatype. */ struct record {const char *precision;double lat,lon;const char *address,*city,*state,*zip,*country; }; /* Create a bunch of objects as demonstration. */ void create_objects() { cJSON *root,*fmt,*img,*thm,*fld;char *out;int i; /* declare a few. */ /* Here we construct some JSON standards, from the JSON site. */ /* Our "Video" datatype: */ root=cJSON_CreateObject(); cJSON_AddItemToObject(root, "name", cJSON_CreateString("Jack (\"Bee\") Nimble")); cJSON_AddItemToObject(root, "format", fmt=cJSON_CreateObject()); cJSON_AddStringToObject(fmt,"type", "rect"); cJSON_AddNumberToObject(fmt,"width", 1920); cJSON_AddNumberToObject(fmt,"height", 1080); cJSON_AddFalseToObject (fmt,"interlace"); cJSON_AddNumberToObject(fmt,"frame rate", 24); out=cJSON_Print(root); cJSON_Delete(root); printf("%s\n",out); free(out); /* Print to text, Delete the cJSON, print it, release the string. /* Our "days of the week" array: */ const char *strings[7]={"Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"}; root=cJSON_CreateStringArray(strings,7); out=cJSON_Print(root); cJSON_Delete(root); printf("%s\n",out); free(out); /* Our matrix: */ int numbers[3][3]={{0,-1,0},{1,0,0},{0,0,1}}; root=cJSON_CreateArray(); for (i=0;i<3;i++) cJSON_AddItemToArray(root,cJSON_CreateIntArray(numbers[i],3)); /* cJSON_ReplaceItemInArray(root,1,cJSON_CreateString("Replacement")); */ out=cJSON_Print(root); cJSON_Delete(root); printf("%s\n",out); free(out); /* Our "gallery" item: */ int ids[4]={116,943,234,38793}; root=cJSON_CreateObject(); cJSON_AddItemToObject(root, "Image", img=cJSON_CreateObject()); cJSON_AddNumberToObject(img,"Width",800); cJSON_AddNumberToObject(img,"Height",600); cJSON_AddStringToObject(img,"Title","View from 15th Floor"); cJSON_AddItemToObject(img, "Thumbnail", thm=cJSON_CreateObject()); cJSON_AddStringToObject(thm, "Url", "http:/*www.example.com/image/481989943"); cJSON_AddNumberToObject(thm,"Height",125); cJSON_AddStringToObject(thm,"Width","100"); cJSON_AddItemToObject(img,"IDs", cJSON_CreateIntArray(ids,4)); out=cJSON_Print(root); cJSON_Delete(root); printf("%s\n",out); free(out); /* Our array of "records": */ struct record fields[2]={ {"zip",37.7668,-1.223959e+2,"","SAN FRANCISCO","CA","94107","US"}, {"zip",37.371991,-1.22026e+2,"","SUNNYVALE","CA","94085","US"}}; root=cJSON_CreateArray(); for (i=0;i<2;i++) { cJSON_AddItemToArray(root,fld=cJSON_CreateObject()); cJSON_AddStringToObject(fld, "precision", fields[i].precision); cJSON_AddNumberToObject(fld, "Latitude", fields[i].lat); cJSON_AddNumberToObject(fld, "Longitude", fields[i].lon); cJSON_AddStringToObject(fld, "Address", fields[i].address); cJSON_AddStringToObject(fld, "City", fields[i].city); cJSON_AddStringToObject(fld, "State", fields[i].state); cJSON_AddStringToObject(fld, "Zip", fields[i].zip); cJSON_AddStringToObject(fld, "Country", fields[i].country); } /* cJSON_ReplaceItemInObject(cJSON_GetArrayItem(root,1),"City",cJSON_CreateIntArray(ids,4)); */ out=cJSON_Print(root); cJSON_Delete(root); printf("%s\n",out); free(out); } int main (int argc, const char * argv[]) { /* a bunch of json: */ char text1[]="{\n\"name\": \"Jack (\\\"Bee\\\") Nimble\", \n\"format\": {\"type\": \"rect\", \n\"width\": 1920, \n\"height\": 1080, \n\"interlace\": false,\"frame rate\": 24\n}\n}"; char text2[]="[\"Sunday\", \"Monday\", \"Tuesday\", \"Wednesday\", \"Thursday\", \"Friday\", \"Saturday\"]"; char text3[]="[\n [0, -1, 0],\n [1, 0, 0],\n [0, 0, 1]\n ]\n"; char text4[]="{\n \"Image\": {\n \"Width\": 800,\n \"Height\": 600,\n \"Title\": \"View from 15th Floor\",\n \"Thumbnail\": {\n \"Url\": \"http:/*www.example.com/image/481989943\",\n \"Height\": 125,\n \"Width\": \"100\"\n },\n \"IDs\": [116, 943, 234, 38793]\n }\n }"; char text5[]="[\n {\n \"precision\": \"zip\",\n \"Latitude\": 37.7668,\n \"Longitude\": -122.3959,\n \"Address\": \"\",\n \"City\": \"SAN FRANCISCO\",\n \"State\": \"CA\",\n \"Zip\": \"94107\",\n \"Country\": \"US\"\n },\n {\n \"precision\": \"zip\",\n \"Latitude\": 37.371991,\n \"Longitude\": -122.026020,\n \"Address\": \"\",\n \"City\": \"SUNNYVALE\",\n \"State\": \"CA\",\n \"Zip\": \"94085\",\n \"Country\": \"US\"\n }\n ]"; /* Process each json textblock by parsing, then rebuilding: */ doit(text1); doit(text2); doit(text3); doit(text4); doit(text5); /* Parse standard testfiles: /* dofile("../../tests/test1"); */ /* dofile("../../tests/test2"); */ /* dofile("../../tests/test3"); */ /* dofile("../../tests/test4"); */ /* dofile("../../tests/test5"); */ /* Now some samplecode for building objects concisely: */ create_objects(); return 0; }
722,431
./openmeap/clients/c/openmeap-slic-core/3rd_party/cJSON/cJSON.c
/* Copyright (c) 2009 Dave Gamble Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /* cJSON */ /* JSON parser in C. */ #include <string.h> #include <stdio.h> #include <math.h> #include <stdlib.h> #include <float.h> #include <limits.h> #include <ctype.h> #include "cJSON.h" static const char *ep; const char *cJSON_GetErrorPtr() {return ep;} static int cJSON_strcasecmp(const char *s1,const char *s2) { if (!s1) return (s1==s2)?0:1;if (!s2) return 1; for(; tolower(*s1) == tolower(*s2); ++s1, ++s2) if(*s1 == 0) return 0; return tolower(*(const unsigned char *)s1) - tolower(*(const unsigned char *)s2); } static void *(*cJSON_malloc)(size_t sz) = malloc; static void (*cJSON_free)(void *ptr) = free; static char* cJSON_strdup(const char* str) { size_t len; char* copy; len = strlen(str) + 1; if (!(copy = (char*)cJSON_malloc(len))) return 0; memcpy(copy,str,len); return copy; } void cJSON_InitHooks(cJSON_Hooks* hooks) { if (!hooks) { /* Reset hooks */ cJSON_malloc = malloc; cJSON_free = free; return; } cJSON_malloc = (hooks->malloc_fn)?hooks->malloc_fn:malloc; cJSON_free = (hooks->free_fn)?hooks->free_fn:free; } /* Internal constructor. */ static cJSON *cJSON_New_Item() { cJSON* node = (cJSON*)cJSON_malloc(sizeof(cJSON)); if (node) memset(node,0,sizeof(cJSON)); return node; } /* Delete a cJSON structure. */ void cJSON_Delete(cJSON *c) { cJSON *next; while (c) { next=c->next; if (!(c->type&cJSON_IsReference) && c->child) cJSON_Delete(c->child); if (!(c->type&cJSON_IsReference) && c->valuestring) cJSON_free(c->valuestring); if (c->string) cJSON_free(c->string); cJSON_free(c); c=next; } } /* Parse the input text to generate a number, and populate the result into item. */ static const char *parse_number(cJSON *item,const char *num) { double n=0,sign=1,scale=0;int subscale=0,signsubscale=1; /* Could use sscanf for this? */ if (*num=='-') sign=-1,num++; /* Has sign? */ if (*num=='0') num++; /* is zero */ if (*num>='1' && *num<='9') do n=(n*10.0)+(*num++ -'0'); while (*num>='0' && *num<='9'); /* Number? */ if (*num=='.' && num[1]>='0' && num[1]<='9') {num++; do n=(n*10.0)+(*num++ -'0'),scale--; while (*num>='0' && *num<='9');} /* Fractional part? */ if (*num=='e' || *num=='E') /* Exponent? */ { num++;if (*num=='+') num++; else if (*num=='-') signsubscale=-1,num++; /* With sign? */ while (*num>='0' && *num<='9') subscale=(subscale*10)+(*num++ - '0'); /* Number? */ } n=sign*n*pow(10.0,(scale+subscale*signsubscale)); /* number = +/- number.fraction * 10^+/- exponent */ item->valuedouble=n; item->valueint=(int)n; item->type=cJSON_Number; return num; } /* Render the number nicely from the given item into a string. */ static char *print_number(cJSON *item) { char *str; double d=item->valuedouble; if (fabs(((double)item->valueint)-d)<=DBL_EPSILON && d<=INT_MAX && d>=INT_MIN) { str=(char*)cJSON_malloc(21); /* 2^64+1 can be represented in 21 chars. */ if (str) sprintf(str,"%d",item->valueint); } else { str=(char*)cJSON_malloc(64); /* This is a nice tradeoff. */ if (str) { if (fabs(floor(d)-d)<=DBL_EPSILON) sprintf(str,"%.0f",d); else if (fabs(d)<1.0e-6 || fabs(d)>1.0e9) sprintf(str,"%e",d); else sprintf(str,"%f",d); } } return str; } /* Parse the input text into an unescaped cstring, and populate item. */ static const unsigned char firstByteMark[7] = { 0x00, 0x00, 0xC0, 0xE0, 0xF0, 0xF8, 0xFC }; static const char *parse_string(cJSON *item,const char *str) { const char *ptr=str+1;char *ptr2;char *out;int len=0;unsigned uc,uc2; if (*str!='\"') {ep=str;return 0;} /* not a string! */ while (*ptr!='\"' && *ptr && ++len) if (*ptr++ == '\\') ptr++; /* Skip escaped quotes. */ out=(char*)cJSON_malloc(len+1); /* This is how long we need for the string, roughly. */ if (!out) return 0; ptr=str+1;ptr2=out; while (*ptr!='\"' && *ptr) { if (*ptr!='\\') *ptr2++=*ptr++; else { ptr++; switch (*ptr) { case 'b': *ptr2++='\b'; break; case 'f': *ptr2++='\f'; break; case 'n': *ptr2++='\n'; break; case 'r': *ptr2++='\r'; break; case 't': *ptr2++='\t'; break; case 'u': /* transcode utf16 to utf8. */ sscanf(ptr+1,"%4x",&uc);ptr+=4; /* get the unicode char. */ if ((uc>=0xDC00 && uc<=0xDFFF) || uc==0) break; // check for invalid. if (uc>=0xD800 && uc<=0xDBFF) // UTF16 surrogate pairs. { if (ptr[1]!='\\' || ptr[2]!='u') break; // missing second-half of surrogate. sscanf(ptr+3,"%4x",&uc2);ptr+=6; if (uc2<0xDC00 || uc2>0xDFFF) break; // invalid second-half of surrogate. uc=0x10000 | ((uc&0x3FF)<<10) | (uc2&0x3FF); } len=4;if (uc<0x80) len=1;else if (uc<0x800) len=2;else if (uc<0x10000) len=3; ptr2+=len; switch (len) { case 4: *--ptr2 =((uc | 0x80) & 0xBF); uc >>= 6; case 3: *--ptr2 =((uc | 0x80) & 0xBF); uc >>= 6; case 2: *--ptr2 =((uc | 0x80) & 0xBF); uc >>= 6; case 1: *--ptr2 =(uc | firstByteMark[len]); } ptr2+=len; break; default: *ptr2++=*ptr; break; } ptr++; } } *ptr2=0; if (*ptr=='\"') ptr++; item->valuestring=out; item->type=cJSON_String; return ptr; } /* Render the cstring provided to an escaped version that can be printed. */ static char *print_string_ptr(const char *str) { const char *ptr;char *ptr2,*out;int len=0;unsigned char token; if (!str) return cJSON_strdup(""); ptr=str;while ((token=*ptr) && ++len) {if (strchr("\"\\\b\f\n\r\t",token)) len++; else if (token<32) len+=5;ptr++;} out=(char*)cJSON_malloc(len+3); if (!out) return 0; ptr2=out;ptr=str; *ptr2++='\"'; while (*ptr) { if ((unsigned char)*ptr>31 && *ptr!='\"' && *ptr!='\\') *ptr2++=*ptr++; else { *ptr2++='\\'; switch (token=*ptr++) { case '\\': *ptr2++='\\'; break; case '\"': *ptr2++='\"'; break; case '\b': *ptr2++='b'; break; case '\f': *ptr2++='f'; break; case '\n': *ptr2++='n'; break; case '\r': *ptr2++='r'; break; case '\t': *ptr2++='t'; break; default: sprintf(ptr2,"u%04x",token);ptr2+=5; break; /* escape and print */ } } } *ptr2++='\"';*ptr2++=0; return out; } /* Invote print_string_ptr (which is useful) on an item. */ static char *print_string(cJSON *item) {return print_string_ptr(item->valuestring);} /* Predeclare these prototypes. */ static const char *parse_value(cJSON *item,const char *value); static char *print_value(cJSON *item,int depth,int fmt); static const char *parse_array(cJSON *item,const char *value); static char *print_array(cJSON *item,int depth,int fmt); static const char *parse_object(cJSON *item,const char *value); static char *print_object(cJSON *item,int depth,int fmt); /* Utility to jump whitespace and cr/lf */ static const char *skip(const char *in) {while (in && *in && (unsigned char)*in<=32) in++; return in;} /* Parse an object - create a new root, and populate. */ cJSON *cJSON_Parse(const char *value) { cJSON *c=cJSON_New_Item(); ep=0; if (!c) return 0; /* memory fail */ if (!parse_value(c,skip(value))) {cJSON_Delete(c);return 0;} return c; } /* Render a cJSON item/entity/structure to text. */ char *cJSON_Print(cJSON *item) {return print_value(item,0,1);} char *cJSON_PrintUnformatted(cJSON *item) {return print_value(item,0,0);} /* Parser core - when encountering text, process appropriately. */ static const char *parse_value(cJSON *item,const char *value) { if (!value) return 0; /* Fail on null. */ if (!strncmp(value,"null",4)) { item->type=cJSON_NULL; return value+4; } if (!strncmp(value,"false",5)) { item->type=cJSON_False; return value+5; } if (!strncmp(value,"true",4)) { item->type=cJSON_True; item->valueint=1; return value+4; } if (*value=='\"') { return parse_string(item,value); } if (*value=='-' || (*value>='0' && *value<='9')) { return parse_number(item,value); } if (*value=='[') { return parse_array(item,value); } if (*value=='{') { return parse_object(item,value); } ep=value;return 0; /* failure. */ } /* Render a value to text. */ static char *print_value(cJSON *item,int depth,int fmt) { char *out=0; if (!item) return 0; switch ((item->type)&255) { case cJSON_NULL: out=cJSON_strdup("null"); break; case cJSON_False: out=cJSON_strdup("false");break; case cJSON_True: out=cJSON_strdup("true"); break; case cJSON_Number: out=print_number(item);break; case cJSON_String: out=print_string(item);break; case cJSON_Array: out=print_array(item,depth,fmt);break; case cJSON_Object: out=print_object(item,depth,fmt);break; } return out; } /* Build an array from input text. */ static const char *parse_array(cJSON *item,const char *value) { cJSON *child; if (*value!='[') {ep=value;return 0;} /* not an array! */ item->type=cJSON_Array; value=skip(value+1); if (*value==']') return value+1; /* empty array. */ item->child=child=cJSON_New_Item(); if (!item->child) return 0; /* memory fail */ value=skip(parse_value(child,skip(value))); /* skip any spacing, get the value. */ if (!value) return 0; while (*value==',') { cJSON *new_item; if (!(new_item=cJSON_New_Item())) return 0; /* memory fail */ child->next=new_item;new_item->prev=child;child=new_item; value=skip(parse_value(child,skip(value+1))); if (!value) return 0; /* memory fail */ } if (*value==']') return value+1; /* end of array */ ep=value;return 0; /* malformed. */ } /* Render an array to text */ static char *print_array(cJSON *item,int depth,int fmt) { char **entries; char *out=0,*ptr,*ret;int len=5; cJSON *child=item->child; int numentries=0,i=0,fail=0; /* How many entries in the array? */ while (child) numentries++,child=child->next; /* Allocate an array to hold the values for each */ entries=(char**)cJSON_malloc(numentries*sizeof(char*)); if (!entries) return 0; memset(entries,0,numentries*sizeof(char*)); /* Retrieve all the results: */ child=item->child; while (child && !fail) { ret=print_value(child,depth+1,fmt); entries[i++]=ret; if (ret) len+=strlen(ret)+2+(fmt?1:0); else fail=1; child=child->next; } /* If we didn't fail, try to malloc the output string */ if (!fail) out=(char*)cJSON_malloc(len); /* If that fails, we fail. */ if (!out) fail=1; /* Handle failure. */ if (fail) { for (i=0;i<numentries;i++) if (entries[i]) cJSON_free(entries[i]); cJSON_free(entries); return 0; } /* Compose the output array. */ *out='['; ptr=out+1;*ptr=0; for (i=0;i<numentries;i++) { strcpy(ptr,entries[i]);ptr+=strlen(entries[i]); if (i!=numentries-1) {*ptr++=',';if(fmt)*ptr++=' ';*ptr=0;} cJSON_free(entries[i]); } cJSON_free(entries); *ptr++=']';*ptr++=0; return out; } /* Build an object from the text. */ static const char *parse_object(cJSON *item,const char *value) { cJSON *child; if (*value!='{') {ep=value;return 0;} /* not an object! */ item->type=cJSON_Object; value=skip(value+1); if (*value=='}') return value+1; /* empty array. */ item->child=child=cJSON_New_Item(); if (!item->child) return 0; value=skip(parse_string(child,skip(value))); if (!value) return 0; child->string=child->valuestring;child->valuestring=0; if (*value!=':') {ep=value;return 0;} /* fail! */ value=skip(parse_value(child,skip(value+1))); /* skip any spacing, get the value. */ if (!value) return 0; while (*value==',') { cJSON *new_item; if (!(new_item=cJSON_New_Item())) return 0; /* memory fail */ child->next=new_item;new_item->prev=child;child=new_item; value=skip(parse_string(child,skip(value+1))); if (!value) return 0; child->string=child->valuestring;child->valuestring=0; if (*value!=':') {ep=value;return 0;} /* fail! */ value=skip(parse_value(child,skip(value+1))); /* skip any spacing, get the value. */ if (!value) return 0; } if (*value=='}') return value+1; /* end of array */ ep=value;return 0; /* malformed. */ } /* Render an object to text. */ static char *print_object(cJSON *item,int depth,int fmt) { char **entries=0,**names=0; char *out=0,*ptr,*ret,*str;int len=7,i=0,j; cJSON *child=item->child; int numentries=0,fail=0; /* Count the number of entries. */ while (child) numentries++,child=child->next; /* Allocate space for the names and the objects */ entries=(char**)cJSON_malloc(numentries*sizeof(char*)); if (!entries) return 0; names=(char**)cJSON_malloc(numentries*sizeof(char*)); if (!names) {cJSON_free(entries);return 0;} memset(entries,0,sizeof(char*)*numentries); memset(names,0,sizeof(char*)*numentries); /* Collect all the results into our arrays: */ child=item->child;depth++;if (fmt) len+=depth; while (child) { names[i]=str=print_string_ptr(child->string); entries[i++]=ret=print_value(child,depth,fmt); if (str && ret) len+=strlen(ret)+strlen(str)+2+(fmt?2+depth:0); else fail=1; child=child->next; } /* Try to allocate the output string */ if (!fail) out=(char*)cJSON_malloc(len); if (!out) fail=1; /* Handle failure */ if (fail) { for (i=0;i<numentries;i++) {if (names[i]) cJSON_free(names[i]);if (entries[i]) cJSON_free(entries[i]);} cJSON_free(names);cJSON_free(entries); return 0; } /* Compose the output: */ *out='{';ptr=out+1;if (fmt)*ptr++='\n';*ptr=0; for (i=0;i<numentries;i++) { if (fmt) for (j=0;j<depth;j++) *ptr++='\t'; strcpy(ptr,names[i]);ptr+=strlen(names[i]); *ptr++=':';if (fmt) *ptr++='\t'; strcpy(ptr,entries[i]);ptr+=strlen(entries[i]); if (i!=numentries-1) *ptr++=','; if (fmt) *ptr++='\n';*ptr=0; cJSON_free(names[i]);cJSON_free(entries[i]); } cJSON_free(names);cJSON_free(entries); if (fmt) for (i=0;i<depth-1;i++) *ptr++='\t'; *ptr++='}';*ptr++=0; return out; } /* Get Array size/item / object item. */ int cJSON_GetArraySize(cJSON *array) {cJSON *c=array->child;int i=0;while(c)i++,c=c->next;return i;} cJSON *cJSON_GetArrayItem(cJSON *array,int item) {cJSON *c=array->child; while (c && item>0) item--,c=c->next; return c;} cJSON *cJSON_GetObjectItem(cJSON *object,const char *string) {cJSON *c=object->child; while (c && cJSON_strcasecmp(c->string,string)) c=c->next; return c;} /* Utility for array list handling. */ static void suffix_object(cJSON *prev,cJSON *item) {prev->next=item;item->prev=prev;} /* Utility for handling references. */ static cJSON *create_reference(cJSON *item) {cJSON *ref=cJSON_New_Item();if (!ref) return 0;memcpy(ref,item,sizeof(cJSON));ref->string=0;ref->type|=cJSON_IsReference;ref->next=ref->prev=0;return ref;} /* Add item to array/object. */ void cJSON_AddItemToArray(cJSON *array, cJSON *item) {cJSON *c=array->child;if (!item) return; if (!c) {array->child=item;} else {while (c && c->next) c=c->next; suffix_object(c,item);}} void cJSON_AddItemToObject(cJSON *object,const char *string,cJSON *item) {if (!item) return; if (item->string) cJSON_free(item->string);item->string=cJSON_strdup(string);cJSON_AddItemToArray(object,item);} void cJSON_AddItemReferenceToArray(cJSON *array, cJSON *item) {cJSON_AddItemToArray(array,create_reference(item));} void cJSON_AddItemReferenceToObject(cJSON *object,const char *string,cJSON *item) {cJSON_AddItemToObject(object,string,create_reference(item));} cJSON *cJSON_DetachItemFromArray(cJSON *array,int which) {cJSON *c=array->child;while (c && which>0) c=c->next,which--;if (!c) return 0; if (c->prev) c->prev->next=c->next;if (c->next) c->next->prev=c->prev;if (c==array->child) array->child=c->next;c->prev=c->next=0;return c;} void cJSON_DeleteItemFromArray(cJSON *array,int which) {cJSON_Delete(cJSON_DetachItemFromArray(array,which));} cJSON *cJSON_DetachItemFromObject(cJSON *object,const char *string) {int i=0;cJSON *c=object->child;while (c && cJSON_strcasecmp(c->string,string)) i++,c=c->next;if (c) return cJSON_DetachItemFromArray(object,i);return 0;} void cJSON_DeleteItemFromObject(cJSON *object,const char *string) {cJSON_Delete(cJSON_DetachItemFromObject(object,string));} /* Replace array/object items with new ones. */ void cJSON_ReplaceItemInArray(cJSON *array,int which,cJSON *newitem) {cJSON *c=array->child;while (c && which>0) c=c->next,which--;if (!c) return; newitem->next=c->next;newitem->prev=c->prev;if (newitem->next) newitem->next->prev=newitem; if (c==array->child) array->child=newitem; else newitem->prev->next=newitem;c->next=c->prev=0;cJSON_Delete(c);} void cJSON_ReplaceItemInObject(cJSON *object,const char *string,cJSON *newitem){int i=0;cJSON *c=object->child;while(c && cJSON_strcasecmp(c->string,string))i++,c=c->next;if(c){newitem->string=cJSON_strdup(string);cJSON_ReplaceItemInArray(object,i,newitem);}} /* Create basic types: */ cJSON *cJSON_CreateNull() {cJSON *item=cJSON_New_Item();if(item)item->type=cJSON_NULL;return item;} cJSON *cJSON_CreateTrue() {cJSON *item=cJSON_New_Item();if(item)item->type=cJSON_True;return item;} cJSON *cJSON_CreateFalse() {cJSON *item=cJSON_New_Item();if(item)item->type=cJSON_False;return item;} cJSON *cJSON_CreateBool(int b) {cJSON *item=cJSON_New_Item();if(item)item->type=b?cJSON_True:cJSON_False;return item;} cJSON *cJSON_CreateNumber(double num) {cJSON *item=cJSON_New_Item();if(item){item->type=cJSON_Number;item->valuedouble=num;item->valueint=(int)num;}return item;} cJSON *cJSON_CreateString(const char *string) {cJSON *item=cJSON_New_Item();if(item){item->type=cJSON_String;item->valuestring=cJSON_strdup(string);}return item;} cJSON *cJSON_CreateArray() {cJSON *item=cJSON_New_Item();if(item)item->type=cJSON_Array;return item;} cJSON *cJSON_CreateObject() {cJSON *item=cJSON_New_Item();if(item)item->type=cJSON_Object;return item;} /* Create Arrays: */ cJSON *cJSON_CreateIntArray(int *numbers,int count) {int i;cJSON *n=0,*p=0,*a=cJSON_CreateArray();for(i=0;a && i<count;i++){n=cJSON_CreateNumber(numbers[i]);if(!i)a->child=n;else suffix_object(p,n);p=n;}return a;} cJSON *cJSON_CreateFloatArray(float *numbers,int count) {int i;cJSON *n=0,*p=0,*a=cJSON_CreateArray();for(i=0;a && i<count;i++){n=cJSON_CreateNumber(numbers[i]);if(!i)a->child=n;else suffix_object(p,n);p=n;}return a;} cJSON *cJSON_CreateDoubleArray(double *numbers,int count) {int i;cJSON *n=0,*p=0,*a=cJSON_CreateArray();for(i=0;a && i<count;i++){n=cJSON_CreateNumber(numbers[i]);if(!i)a->child=n;else suffix_object(p,n);p=n;}return a;} cJSON *cJSON_CreateStringArray(const char **strings,int count) {int i;cJSON *n=0,*p=0,*a=cJSON_CreateArray();for(i=0;a && i<count;i++){n=cJSON_CreateString(strings[i]);if(!i)a->child=n;else suffix_object(p,n);p=n;}return a;}
722,432
./openmeap/clients/c/openmeap-slic-core/3rd_party/digest-md5/md5.c
/* * This code implements the MD5 message-digest algorithm. * The algorithm is due to Ron Rivest. This code was * written by Colin Plumb in 1993, no copyright is claimed. * This code is in the public domain; do with it what you wish. * * Equivalent code is available from RSA Data Security, Inc. * This code has been tested against that, and is equivalent, * except that you don't need to include two pages of legalese * with every copy. * * To compute the message digest of a chunk of bytes, declare an * MD5Context structure, pass it to MD5Init, call MD5Update as * needed on buffers full of bytes, and then call MD5Final, which * will fill a supplied 16-byte array with the digest. */ /* This code was modified in 1997 by Jim Kingdon of Cyclic Software to not require an integer type which is exactly 32 bits. This work draws on the changes for the same purpose by Tatu Ylonen <ylo@cs.hut.fi> as part of SSH, but since I didn't actually use that code, there is no copyright issue. I hereby disclaim copyright in any changes I have made; this code remains in the public domain. */ /* Note regarding cvs_* namespace: this avoids potential conflicts with libraries such as some versions of Kerberos. No particular need to worry about whether the system supplies an MD5 library, as this file is only about 3k of object code. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include <string.h> /* for memcpy() and memset() */ #include "md5.h" /* Little-endian byte-swapping routines. Note that these do not depend on the size of datatypes such as cvs_uint32, nor do they require us to detect the endianness of the machine we are running on. It is possible they should be macros for speed, but I would be surprised if they were a performance bottleneck for MD5. */ static cvs_uint32 getu32 (addr) const unsigned char *addr; { return (((((unsigned long)addr[3] << 8) | addr[2]) << 8) | addr[1]) << 8 | addr[0]; } static void putu32 (data, addr) cvs_uint32 data; unsigned char *addr; { addr[0] = (unsigned char)data; addr[1] = (unsigned char)(data >> 8); addr[2] = (unsigned char)(data >> 16); addr[3] = (unsigned char)(data >> 24); } /* * Start MD5 accumulation. Set bit count to 0 and buffer to mysterious * initialization constants. */ void cvs_MD5Init (ctx) struct cvs_MD5Context *ctx; { ctx->buf[0] = 0x67452301; ctx->buf[1] = 0xefcdab89; ctx->buf[2] = 0x98badcfe; ctx->buf[3] = 0x10325476; ctx->bits[0] = 0; ctx->bits[1] = 0; } /* * Update context to reflect the concatenation of another buffer full * of bytes. */ void cvs_MD5Update (ctx, buf, len) struct cvs_MD5Context *ctx; unsigned char const *buf; unsigned len; { cvs_uint32 t; /* Update bitcount */ t = ctx->bits[0]; if ((ctx->bits[0] = (t + ((cvs_uint32)len << 3)) & 0xffffffff) < t) ctx->bits[1]++; /* Carry from low to high */ ctx->bits[1] += len >> 29; t = (t >> 3) & 0x3f; /* Bytes already in shsInfo->data */ /* Handle any leading odd-sized chunks */ if ( t ) { unsigned char *p = ctx->in + t; t = 64-t; if (len < t) { memcpy(p, buf, len); return; } memcpy(p, buf, t); cvs_MD5Transform (ctx->buf, ctx->in); buf += t; len -= t; } /* Process data in 64-byte chunks */ while (len >= 64) { memcpy(ctx->in, buf, 64); cvs_MD5Transform (ctx->buf, ctx->in); buf += 64; len -= 64; } /* Handle any remaining bytes of data. */ memcpy(ctx->in, buf, len); } /* * Final wrapup - pad to 64-byte boundary with the bit pattern * 1 0* (64-bit count of bits processed, MSB-first) */ void cvs_MD5Final (digest, ctx) unsigned char digest[16]; struct cvs_MD5Context *ctx; { unsigned count; unsigned char *p; /* Compute number of bytes mod 64 */ count = (ctx->bits[0] >> 3) & 0x3F; /* Set the first char of padding to 0x80. This is safe since there is always at least one byte free */ p = ctx->in + count; *p++ = 0x80; /* Bytes of padding needed to make 64 bytes */ count = 64 - 1 - count; /* Pad out to 56 mod 64 */ if (count < 8) { /* Two lots of padding: Pad the first block to 64 bytes */ memset(p, 0, count); cvs_MD5Transform (ctx->buf, ctx->in); /* Now fill the next block with 56 bytes */ memset(ctx->in, 0, 56); } else { /* Pad block to 56 bytes */ memset(p, 0, count-8); } /* Append length in bits and transform */ putu32(ctx->bits[0], ctx->in + 56); putu32(ctx->bits[1], ctx->in + 60); cvs_MD5Transform (ctx->buf, ctx->in); putu32(ctx->buf[0], digest); putu32(ctx->buf[1], digest + 4); putu32(ctx->buf[2], digest + 8); putu32(ctx->buf[3], digest + 12); memset(ctx, 0, sizeof(ctx)); /* In case it's sensitive */ } #ifndef ASM_MD5 /* The four core functions - F1 is optimized somewhat */ /* #define F1(x, y, z) (x & y | ~x & z) */ #define F1(x, y, z) (z ^ (x & (y ^ z))) #define F2(x, y, z) F1(z, x, y) #define F3(x, y, z) (x ^ y ^ z) #define F4(x, y, z) (y ^ (x | ~z)) /* This is the central step in the MD5 algorithm. */ #define MD5STEP(f, w, x, y, z, data, s) \ ( w += f(x, y, z) + data, w &= 0xffffffff, w = w<<s | w>>(32-s), w += x ) /* * The core of the MD5 algorithm, this alters an existing MD5 hash to * reflect the addition of 16 longwords of new data. MD5Update blocks * the data and converts bytes into longwords for this routine. */ void cvs_MD5Transform (buf, inraw) cvs_uint32 buf[4]; const unsigned char inraw[64]; { register cvs_uint32 a, b, c, d; cvs_uint32 in[16]; int i; for (i = 0; i < 16; ++i) in[i] = getu32 (inraw + 4 * i); a = buf[0]; b = buf[1]; c = buf[2]; d = buf[3]; MD5STEP(F1, a, b, c, d, in[ 0]+0xd76aa478, 7); MD5STEP(F1, d, a, b, c, in[ 1]+0xe8c7b756, 12); MD5STEP(F1, c, d, a, b, in[ 2]+0x242070db, 17); MD5STEP(F1, b, c, d, a, in[ 3]+0xc1bdceee, 22); MD5STEP(F1, a, b, c, d, in[ 4]+0xf57c0faf, 7); MD5STEP(F1, d, a, b, c, in[ 5]+0x4787c62a, 12); MD5STEP(F1, c, d, a, b, in[ 6]+0xa8304613, 17); MD5STEP(F1, b, c, d, a, in[ 7]+0xfd469501, 22); MD5STEP(F1, a, b, c, d, in[ 8]+0x698098d8, 7); MD5STEP(F1, d, a, b, c, in[ 9]+0x8b44f7af, 12); MD5STEP(F1, c, d, a, b, in[10]+0xffff5bb1, 17); MD5STEP(F1, b, c, d, a, in[11]+0x895cd7be, 22); MD5STEP(F1, a, b, c, d, in[12]+0x6b901122, 7); MD5STEP(F1, d, a, b, c, in[13]+0xfd987193, 12); MD5STEP(F1, c, d, a, b, in[14]+0xa679438e, 17); MD5STEP(F1, b, c, d, a, in[15]+0x49b40821, 22); MD5STEP(F2, a, b, c, d, in[ 1]+0xf61e2562, 5); MD5STEP(F2, d, a, b, c, in[ 6]+0xc040b340, 9); MD5STEP(F2, c, d, a, b, in[11]+0x265e5a51, 14); MD5STEP(F2, b, c, d, a, in[ 0]+0xe9b6c7aa, 20); MD5STEP(F2, a, b, c, d, in[ 5]+0xd62f105d, 5); MD5STEP(F2, d, a, b, c, in[10]+0x02441453, 9); MD5STEP(F2, c, d, a, b, in[15]+0xd8a1e681, 14); MD5STEP(F2, b, c, d, a, in[ 4]+0xe7d3fbc8, 20); MD5STEP(F2, a, b, c, d, in[ 9]+0x21e1cde6, 5); MD5STEP(F2, d, a, b, c, in[14]+0xc33707d6, 9); MD5STEP(F2, c, d, a, b, in[ 3]+0xf4d50d87, 14); MD5STEP(F2, b, c, d, a, in[ 8]+0x455a14ed, 20); MD5STEP(F2, a, b, c, d, in[13]+0xa9e3e905, 5); MD5STEP(F2, d, a, b, c, in[ 2]+0xfcefa3f8, 9); MD5STEP(F2, c, d, a, b, in[ 7]+0x676f02d9, 14); MD5STEP(F2, b, c, d, a, in[12]+0x8d2a4c8a, 20); MD5STEP(F3, a, b, c, d, in[ 5]+0xfffa3942, 4); MD5STEP(F3, d, a, b, c, in[ 8]+0x8771f681, 11); MD5STEP(F3, c, d, a, b, in[11]+0x6d9d6122, 16); MD5STEP(F3, b, c, d, a, in[14]+0xfde5380c, 23); MD5STEP(F3, a, b, c, d, in[ 1]+0xa4beea44, 4); MD5STEP(F3, d, a, b, c, in[ 4]+0x4bdecfa9, 11); MD5STEP(F3, c, d, a, b, in[ 7]+0xf6bb4b60, 16); MD5STEP(F3, b, c, d, a, in[10]+0xbebfbc70, 23); MD5STEP(F3, a, b, c, d, in[13]+0x289b7ec6, 4); MD5STEP(F3, d, a, b, c, in[ 0]+0xeaa127fa, 11); MD5STEP(F3, c, d, a, b, in[ 3]+0xd4ef3085, 16); MD5STEP(F3, b, c, d, a, in[ 6]+0x04881d05, 23); MD5STEP(F3, a, b, c, d, in[ 9]+0xd9d4d039, 4); MD5STEP(F3, d, a, b, c, in[12]+0xe6db99e5, 11); MD5STEP(F3, c, d, a, b, in[15]+0x1fa27cf8, 16); MD5STEP(F3, b, c, d, a, in[ 2]+0xc4ac5665, 23); MD5STEP(F4, a, b, c, d, in[ 0]+0xf4292244, 6); MD5STEP(F4, d, a, b, c, in[ 7]+0x432aff97, 10); MD5STEP(F4, c, d, a, b, in[14]+0xab9423a7, 15); MD5STEP(F4, b, c, d, a, in[ 5]+0xfc93a039, 21); MD5STEP(F4, a, b, c, d, in[12]+0x655b59c3, 6); MD5STEP(F4, d, a, b, c, in[ 3]+0x8f0ccc92, 10); MD5STEP(F4, c, d, a, b, in[10]+0xffeff47d, 15); MD5STEP(F4, b, c, d, a, in[ 1]+0x85845dd1, 21); MD5STEP(F4, a, b, c, d, in[ 8]+0x6fa87e4f, 6); MD5STEP(F4, d, a, b, c, in[15]+0xfe2ce6e0, 10); MD5STEP(F4, c, d, a, b, in[ 6]+0xa3014314, 15); MD5STEP(F4, b, c, d, a, in[13]+0x4e0811a1, 21); MD5STEP(F4, a, b, c, d, in[ 4]+0xf7537e82, 6); MD5STEP(F4, d, a, b, c, in[11]+0xbd3af235, 10); MD5STEP(F4, c, d, a, b, in[ 2]+0x2ad7d2bb, 15); MD5STEP(F4, b, c, d, a, in[ 9]+0xeb86d391, 21); buf[0] += a; buf[1] += b; buf[2] += c; buf[3] += d; } #endif #ifdef TEST /* Simple test program. Can use it to manually run the tests from RFC1321 for example. */ #include <stdio.h> int main (int argc, char **argv) { struct cvs_MD5Context context; unsigned char checksum[16]; int i; int j; if (argc < 2) { fprintf (stderr, "usage: %s string-to-hash\n", argv[0]); exit (1); } for (j = 1; j < argc; ++j) { printf ("MD5 (\"%s\") = ", argv[j]); cvs_MD5Init (&context); cvs_MD5Update (&context, argv[j], strlen (argv[j])); cvs_MD5Final (checksum, &context); for (i = 0; i < 16; i++) { printf ("%02x", (unsigned int) checksum[i]); } printf ("\n"); } return 0; } #endif /* TEST */
722,433
./openmeap/clients/c/openmeap-slic-core/3rd_party/digest-sha1/shatest.c
/* * shatest.c * * Copyright (C) 1998, 2009 * Paul E. Jones <paulej@packetizer.com> * All Rights Reserved * ***************************************************************************** * $Id: shatest.c 12 2009-06-22 19:34:25Z paulej $ ***************************************************************************** * * Description: * This file will exercise the SHA1 class and perform the three * tests documented in FIPS PUB 180-1. * * Portability Issues: * None. * */ #include <stdio.h> #include <string.h> #include "sha1.h" /* * Define patterns for testing */ #define TESTA "abc" #define TESTB_1 "abcdbcdecdefdefgefghfghighij" #define TESTB_2 "hijkijkljklmklmnlmnomnopnopq" #define TESTB TESTB_1 TESTB_2 #define TESTC "a" int main() { SHA1Context sha; int i; /* * Perform test A */ printf("\nTest A: 'abc'\n"); SHA1Reset(&sha); SHA1Input(&sha, (const unsigned char *) TESTA, strlen(TESTA)); if (!SHA1Result(&sha)) { fprintf(stderr, "ERROR-- could not compute message digest\n"); } else { printf("\t"); for(i = 0; i < 5 ; i++) { printf("%X ", sha.Message_Digest[i]); } printf("\n"); printf("Should match:\n"); printf("\tA9993E36 4706816A BA3E2571 7850C26C 9CD0D89D\n"); } /* * Perform test B */ printf("\nTest B:\n"); SHA1Reset(&sha); SHA1Input(&sha, (const unsigned char *) TESTB, strlen(TESTB)); if (!SHA1Result(&sha)) { fprintf(stderr, "ERROR-- could not compute message digest\n"); } else { printf("\t"); for(i = 0; i < 5 ; i++) { printf("%X ", sha.Message_Digest[i]); } printf("\n"); printf("Should match:\n"); printf("\t84983E44 1C3BD26E BAAE4AA1 F95129E5 E54670F1\n"); } /* * Perform test C */ printf("\nTest C: One million 'a' characters\n"); SHA1Reset(&sha); for(i = 1; i <= 1000000; i++) { SHA1Input(&sha, (const unsigned char *) TESTC, 1); } if (!SHA1Result(&sha)) { fprintf(stderr, "ERROR-- could not compute message digest\n"); } else { printf("\t"); for(i = 0; i < 5 ; i++) { printf("%X ", sha.Message_Digest[i]); } printf("\n"); printf("Should match:\n"); printf("\t34AA973C D4C4DAA4 F61EEB2B DBAD2731 6534016F\n"); } return 0; }
722,434
./openmeap/clients/c/openmeap-slic-core/3rd_party/digest-sha1/sha1.c
/* * sha1.c * * Copyright (C) 1998, 2009 * Paul E. Jones <paulej@packetizer.com> * All Rights Reserved * ***************************************************************************** * $Id: sha1.c 12 2009-06-22 19:34:25Z paulej $ ***************************************************************************** * * Description: * This file implements the Secure Hashing Standard as defined * in FIPS PUB 180-1 published April 17, 1995. * * The Secure Hashing Standard, which uses the Secure Hashing * Algorithm (SHA), produces a 160-bit message digest for a * given data stream. In theory, it is highly improbable that * two messages will produce the same message digest. Therefore, * this algorithm can serve as a means of providing a "fingerprint" * for a message. * * Portability Issues: * SHA-1 is defined in terms of 32-bit "words". This code was * written with the expectation that the processor has at least * a 32-bit machine word size. If the machine word size is larger, * the code should still function properly. One caveat to that * is that the input functions taking characters and character * arrays assume that only 8 bits of information are stored in each * character. * * Caveats: * SHA-1 is designed to work with messages less than 2^64 bits * long. Although SHA-1 allows a message digest to be generated for * messages of any number of bits less than 2^64, this * implementation only works with messages with a length that is a * multiple of the size of an 8-bit character. * */ #include "sha1.h" /* * Define the circular shift macro */ #define SHA1CircularShift(bits,word) \ ((((word) << (bits)) & 0xFFFFFFFF) | \ ((word) >> (32-(bits)))) /* Function prototypes */ void SHA1ProcessMessageBlock(SHA1Context *); void SHA1PadMessage(SHA1Context *); /* * SHA1Reset * * Description: * This function will initialize the SHA1Context in preparation * for computing a new message digest. * * Parameters: * context: [in/out] * The context to reset. * * Returns: * Nothing. * * Comments: * */ void SHA1Reset(SHA1Context *context) { context->Length_Low = 0; context->Length_High = 0; context->Message_Block_Index = 0; context->Message_Digest[0] = 0x67452301; context->Message_Digest[1] = 0xEFCDAB89; context->Message_Digest[2] = 0x98BADCFE; context->Message_Digest[3] = 0x10325476; context->Message_Digest[4] = 0xC3D2E1F0; context->Computed = 0; context->Corrupted = 0; } /* * SHA1Result * * Description: * This function will return the 160-bit message digest into the * Message_Digest array within the SHA1Context provided * * Parameters: * context: [in/out] * The context to use to calculate the SHA-1 hash. * * Returns: * 1 if successful, 0 if it failed. * * Comments: * */ int SHA1Result(SHA1Context *context) { if (context->Corrupted) { return 0; } if (!context->Computed) { SHA1PadMessage(context); context->Computed = 1; } return 1; } /* * SHA1Input * * Description: * This function accepts an array of octets as the next portion of * the message. * * Parameters: * context: [in/out] * The SHA-1 context to update * message_array: [in] * An array of characters representing the next portion of the * message. * length: [in] * The length of the message in message_array * * Returns: * Nothing. * * Comments: * */ void SHA1Input( SHA1Context *context, const unsigned char *message_array, unsigned length) { if (!length) { return; } if (context->Computed || context->Corrupted) { context->Corrupted = 1; return; } while(length-- && !context->Corrupted) { context->Message_Block[context->Message_Block_Index++] = (*message_array & 0xFF); context->Length_Low += 8; /* Force it to 32 bits */ context->Length_Low &= 0xFFFFFFFF; if (context->Length_Low == 0) { context->Length_High++; /* Force it to 32 bits */ context->Length_High &= 0xFFFFFFFF; if (context->Length_High == 0) { /* Message is too long */ context->Corrupted = 1; } } if (context->Message_Block_Index == 64) { SHA1ProcessMessageBlock(context); } message_array++; } } /* * SHA1ProcessMessageBlock * * Description: * This function will process the next 512 bits of the message * stored in the Message_Block array. * * Parameters: * None. * * Returns: * Nothing. * * Comments: * Many of the variable names in the SHAContext, especially the * single character names, were used because those were the names * used in the publication. * * */ void SHA1ProcessMessageBlock(SHA1Context *context) { const unsigned K[] = /* Constants defined in SHA-1 */ { 0x5A827999, 0x6ED9EBA1, 0x8F1BBCDC, 0xCA62C1D6 }; int t; /* Loop counter */ unsigned temp; /* Temporary word value */ unsigned W[80]; /* Word sequence */ unsigned A, B, C, D, E; /* Word buffers */ /* * Initialize the first 16 words in the array W */ for(t = 0; t < 16; t++) { W[t] = ((unsigned) context->Message_Block[t * 4]) << 24; W[t] |= ((unsigned) context->Message_Block[t * 4 + 1]) << 16; W[t] |= ((unsigned) context->Message_Block[t * 4 + 2]) << 8; W[t] |= ((unsigned) context->Message_Block[t * 4 + 3]); } for(t = 16; t < 80; t++) { W[t] = SHA1CircularShift(1,W[t-3] ^ W[t-8] ^ W[t-14] ^ W[t-16]); } A = context->Message_Digest[0]; B = context->Message_Digest[1]; C = context->Message_Digest[2]; D = context->Message_Digest[3]; E = context->Message_Digest[4]; for(t = 0; t < 20; t++) { temp = SHA1CircularShift(5,A) + ((B & C) | ((~B) & D)) + E + W[t] + K[0]; temp &= 0xFFFFFFFF; E = D; D = C; C = SHA1CircularShift(30,B); B = A; A = temp; } for(t = 20; t < 40; t++) { temp = SHA1CircularShift(5,A) + (B ^ C ^ D) + E + W[t] + K[1]; temp &= 0xFFFFFFFF; E = D; D = C; C = SHA1CircularShift(30,B); B = A; A = temp; } for(t = 40; t < 60; t++) { temp = SHA1CircularShift(5,A) + ((B & C) | (B & D) | (C & D)) + E + W[t] + K[2]; temp &= 0xFFFFFFFF; E = D; D = C; C = SHA1CircularShift(30,B); B = A; A = temp; } for(t = 60; t < 80; t++) { temp = SHA1CircularShift(5,A) + (B ^ C ^ D) + E + W[t] + K[3]; temp &= 0xFFFFFFFF; E = D; D = C; C = SHA1CircularShift(30,B); B = A; A = temp; } context->Message_Digest[0] = (context->Message_Digest[0] + A) & 0xFFFFFFFF; context->Message_Digest[1] = (context->Message_Digest[1] + B) & 0xFFFFFFFF; context->Message_Digest[2] = (context->Message_Digest[2] + C) & 0xFFFFFFFF; context->Message_Digest[3] = (context->Message_Digest[3] + D) & 0xFFFFFFFF; context->Message_Digest[4] = (context->Message_Digest[4] + E) & 0xFFFFFFFF; context->Message_Block_Index = 0; } /* * SHA1PadMessage * * Description: * According to the standard, the message must be padded to an even * 512 bits. The first padding bit must be a '1'. The last 64 * bits represent the length of the original message. All bits in * between should be 0. This function will pad the message * according to those rules by filling the Message_Block array * accordingly. It will also call SHA1ProcessMessageBlock() * appropriately. When it returns, it can be assumed that the * message digest has been computed. * * Parameters: * context: [in/out] * The context to pad * * Returns: * Nothing. * * Comments: * */ void SHA1PadMessage(SHA1Context *context) { /* * Check to see if the current message block is too small to hold * the initial padding bits and length. If so, we will pad the * block, process it, and then continue padding into a second * block. */ if (context->Message_Block_Index > 55) { context->Message_Block[context->Message_Block_Index++] = 0x80; while(context->Message_Block_Index < 64) { context->Message_Block[context->Message_Block_Index++] = 0; } SHA1ProcessMessageBlock(context); while(context->Message_Block_Index < 56) { context->Message_Block[context->Message_Block_Index++] = 0; } } else { context->Message_Block[context->Message_Block_Index++] = 0x80; while(context->Message_Block_Index < 56) { context->Message_Block[context->Message_Block_Index++] = 0; } } /* * Store the message length as the last 8 octets */ context->Message_Block[56] = (context->Length_High >> 24) & 0xFF; context->Message_Block[57] = (context->Length_High >> 16) & 0xFF; context->Message_Block[58] = (context->Length_High >> 8) & 0xFF; context->Message_Block[59] = (context->Length_High) & 0xFF; context->Message_Block[60] = (context->Length_Low >> 24) & 0xFF; context->Message_Block[61] = (context->Length_Low >> 16) & 0xFF; context->Message_Block[62] = (context->Length_Low >> 8) & 0xFF; context->Message_Block[63] = (context->Length_Low) & 0xFF; SHA1ProcessMessageBlock(context); }
722,435
./openmeap/clients/c/openmeap-slic-core/3rd_party/digest-sha1/sha.c
/* * sha.cpp * * Copyright (C) 1998, 2009 * Paul E. Jones <paulej@packetizer.com> * All Rights Reserved * ***************************************************************************** * $Id: sha.c 12 2009-06-22 19:34:25Z paulej $ ***************************************************************************** * * Description: * This utility will display the message digest (fingerprint) for * the specified file(s). * * Portability Issues: * None. */ #include <stdio.h> #include <string.h> #ifdef WIN32 #include <io.h> #endif #include <fcntl.h> #include "sha1.h" /* * Function prototype */ void usage(); /* * main * * Description: * This is the entry point for the program * * Parameters: * argc: [in] * This is the count of arguments in the argv array * argv: [in] * This is an array of filenames for which to compute message * digests * * Returns: * Nothing. * * Comments: * */ int main(int argc, char *argv[]) { SHA1Context sha; /* SHA-1 context */ FILE *fp; /* File pointer for reading files*/ char c; /* Character read from file */ int i; /* Counter */ int reading_stdin; /* Are we reading standard in? */ int read_stdin = 0; /* Have we read stdin? */ /* * Check the program arguments and print usage information if -? * or --help is passed as the first argument. */ if (argc > 1 && (!strcmp(argv[1],"-?") || !strcmp(argv[1],"--help"))) { usage(); return 1; } /* * For each filename passed in on the command line, calculate the * SHA-1 value and display it. */ for(i = 0; i < argc; i++) { /* * We start the counter at 0 to guarantee entry into the for * loop. So if 'i' is zero, we will increment it now. If there * is no argv[1], we will use STDIN below. */ if (i == 0) { i++; } if (argc == 1 || !strcmp(argv[i],"-")) { #ifdef WIN32 setmode(fileno(stdin), _O_BINARY); #endif fp = stdin; reading_stdin = 1; } else { if (!(fp = fopen(argv[i],"rb"))) { fprintf(stderr, "sha: unable to open file %s\n", argv[i]); return 2; } reading_stdin = 0; } /* * We do not want to read STDIN multiple times */ if (reading_stdin) { if (read_stdin) { continue; } read_stdin = 1; } /* * Reset the SHA-1 context and process input */ SHA1Reset(&sha); c = fgetc(fp); while(!feof(fp)) { SHA1Input(&sha, &c, 1); c = fgetc(fp); } if (!reading_stdin) { fclose(fp); } if (!SHA1Result(&sha)) { fprintf(stderr, "sha: could not compute message digest for %s\n", reading_stdin?"STDIN":argv[i]); } else { printf( "%08X %08X %08X %08X %08X - %s\n", sha.Message_Digest[0], sha.Message_Digest[1], sha.Message_Digest[2], sha.Message_Digest[3], sha.Message_Digest[4], reading_stdin?"STDIN":argv[i]); } } return 0; } /* * usage * * Description: * This function will display program usage information to the * user. * * Parameters: * None. * * Returns: * Nothing. * * Comments: * */ void usage() { printf("usage: sha <file> [<file> ...]\n"); printf("\tThis program will display the message digest\n"); printf("\tfor files using the Secure Hashing Algorithm (SHA-1).\n"); }
722,436
./comb/calc.c
/* Copyright 2012 William Hart. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY William Hart ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL William Hart OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include <stdio.h> #include "combinator.h" ast_t * eval(ast_t * a) { if (a == NULL) exception("missing operand\n"); switch (a->typ) { case T_INT: break; case T_ADD: eval(a->child); eval(a->child->next); a->l = a->child->l + a->child->next->l; break; case T_SUB: eval(a->child); eval(a->child->next); a->l = a->child->l - a->child->next->l; break; case T_MUL: eval(a->child); eval(a->child->next); a->l = a->child->l * a->child->next->l; break; case T_DIV: eval(a->child); eval(a->child->next); a->l = a->child->l / a->child->next->l; break; default: exception("Unknown tag in AST node\n"); } return a; } int main(void) { ast_t * a; input_t in = { NULL, 0, 0, 0 }; Combinator(Expr); Combinator(Term); Combinator(Factor); Combinator(Stmt); char * msg1 = "Error: \")\" expected!\n"; Factor = Or( Integer(), And( And( Match(T_NULL, "("), Expr ), Expect(T_NULL, ")", msg1) ) ); Term = Lloop( Factor, Or( Match(T_MUL, "*"), Match(T_DIV, "/") ) ); Expr = Lloop( Term, Or( Match(T_ADD, "+"), Match(T_SUB, "-") ) ); Stmt = And( Expr, Match(T_NULL, ";") ); printf("Welcome to Calc v1.0\n\n"); printf("> "); while (a = parse(&in, Stmt)) { printf("%ld\n", eval(a)->l); printf("\n> "); } return 0; }
722,437
./comb/combinator.c
/* Copyright 2012 William Hart. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY William Hart ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL William Hart OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include "combinator.h" void exception(char * err) { fprintf(stderr, err); abort(); } ast_t * new_ast(tag_t typ, ast_t * child, ast_t * next) { ast_t * ast = malloc(sizeof(ast_t)); ast->typ = typ; ast->child = child; ast->next = next; return ast; } char read1(input_t * in) { if (in->start < in->length) return in->input[in->start++]; if (in->alloc == in->length) { in->input = realloc(in->input, in->alloc + 50); in->alloc += 50; } in->start++; return in->input[in->length++] = getchar(); } void skip_whitespace(input_t * in) { char c; while ((c = read1(in)) == ' ' || c == '\n' || c == '\t') ; in->start--; } ast_t * match(input_t * in, tag_t tag, char * str) { int start = in->start; int i = 0, len = strlen(str); skip_whitespace(in); while (i < len && str[i] == read1(in)) i++; if (i != len) { in->start = start; return NULL; } return new_ast(tag, NULL, NULL); } ast_t * expect(input_t * in, tag_t tag, char * str, char * err) { ast_t * ast; if (!(ast = match(in, tag, str))) exception(err); return ast; } ast_t * parse(input_t * in, comb_t * c) { switch (c->type) { case C_COMB: return c->clos->comb(in, c->clos->cl1, c->clos->cl2); case C_MATCH: return match(in, c->tag, c->str); case C_EXPECT: return expect(in, c->tag, c->s2.str, c->s2.err); case C_LIT: return c->lit(in); case C_FORWARD: return parse(in, *c->forward); default: printf("tag = %d\n", c->type); exception("Unknown tag in parse()\n"); } } ast_t * comb_and(input_t * in, comb_t * c1, comb_t * c2) { ast_t * a1, * a2; int start = in->start; if ((a1 = parse(in, c1)) && (a2 = parse(in, c2))) { if (c1->tag != T_NULL) { if (c2->tag != T_NULL) { a1->next = a2; return a1; } else return a1; } if (c2->tag != T_NULL) return a2; } in->start = start; return NULL; } ast_t * comb_or(input_t * in, comb_t * c1, comb_t * c2) { ast_t * a; int start = in->start; if (a = parse(in, c1)) return a; in->start = start; if (a = parse(in, c2)) return a; in->start = start; return NULL; } ast_t * comb_laloop(input_t * in, comb_t * c1, comb_t * c2) { ast_t * a, * b, * t, *op; int start = in->start; if (a = parse(in, c1)) { start = in->start; while (op = parse(in, c2)) { b = parse(in, c1); a->next = b; op->child = a; a = op; start = in->start; } in->start = start; return a; } in->start = start; return NULL; } comb_t * Match(tag_t tag, char * str) { comb_t * c = malloc(sizeof(comb_t)); c->type = C_MATCH; c->tag = tag; c->str = str; return c; } comb_t * Expect(tag_t tag, char * str, char * err) { comb_t * c = malloc(sizeof(comb_t)); c->type = C_EXPECT; c->tag = tag; c->s2.str = str; c->s2.err = err; return c; } comb_t * Comb(ast_t * (*comb)(input_t *, struct comb_t *, struct comb_t *), comb_t * cl1, comb_t * cl2) { closure_t * clos = malloc(sizeof(closure_t)); clos->comb = comb; clos->cl1 = cl1; clos->cl2 = cl2; comb_t * c = malloc(sizeof(comb_t)); c->type = C_COMB; c->tag = T_COMB; c->clos = clos; return c; } #define str_insert(s, c) \ do { \ if (i == alloc) { \ s = realloc(s, alloc + 10); \ alloc += 10; \ } \ str[i++] = c; \ } while (0) ast_t * integer(input_t * in) { int start = in->start; char c; int i = 0, alloc = 0; char * str = NULL; ast_t * a; skip_whitespace(in); if ((c = read1(in)) >= '1' && c <= '9') { str_insert(str, c); start = in->start; while (isdigit(c = read1(in))) { str_insert(str, c); start = in->start; } in->start = start; str_insert(str, '\0'); a = new_ast(T_INT, NULL, NULL); a->l = atol(str); free(str); return a; } else if (c == '0') { str_insert(str, c); str_insert(str, '\0'); a = new_ast(T_INT, NULL, NULL); a->l = atol(str); free(str); return a; } in->start = start; return NULL; } comb_t * Integer() { comb_t * c = malloc(sizeof(comb_t)); c->type = C_LIT; c->tag = T_INT; c->lit = integer; return c; } comb_t * forward(comb_t ** comb) { comb_t * c = malloc(sizeof(comb_t)); c->type = C_FORWARD; c->tag = T_FORWARD; c->forward = comb; return c; }
722,438
./pcaputils/src/pcapdump.c
/* pcapdump.c - dump and filter pcaps Copyright (C) 2007 Robert S. Edmonds Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include <inttypes.h> #include <signal.h> #include <stdbool.h> #include <stdint.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/stat.h> #include <sys/types.h> #include <time.h> #include <unistd.h> #include <pcap.h> #include <util/daemon.h> #include <util/file.h> #include <util/net.h> #include <util/pcapnet.h> #include <util/util.h> #include <util/rng.h> #define FNAME_MAXLEN 512 /* globals */ static char *program_name = "pcapdump"; static cfgopt_t cfg[] = { pcapcfg_device, pcapcfg_readfile, pcapcfg_bpf, pcapcfg_snaplen, pcapcfg_promisc, pcapcfg_kickcmd, { 'u', "owner", CONFIG_STR, {}, "root", "output file owning user" }, { 'g', "group", CONFIG_STR, {}, "root", "output file owning group" }, { 'm', "mode", CONFIG_OCT, {}, "0600", "output file mode" }, { 't', "interval", CONFIG_DEC, {}, "86400", "output file rotation interval" }, { 'T', "duration", CONFIG_DEC, {}, NULL, "capture duration in seconds" }, { 'c', "count", CONFIG_DEC, {}, NULL, "packet count limit" }, { 'H', "headersonly", CONFIG_BOOL,{}, "0", "dump headers only" }, { 'S', "sample", CONFIG_DEC, {}, "0", "sample value" }, { 'R', "random", CONFIG_BOOL,{}, "0", "random sampling of packets" }, { 'w', "filefmt", CONFIG_STR, {}, NULL, "output file format" }, { 'P', "pidfile", CONFIG_STR, {}, NULL, "pid file" }, cfgopt_cfgfile, cfgopt_end }; static pcap_args_t pa; static bool check_interval = false; static bool headers_only = false; static bool reload_config = false; static bool stop_running = false; static char *pcapdump_filefmt; static int pcapdump_interval; static int last_ifdrop; static int64_t count_bytes; static int64_t count_packets; static int64_t pcapdump_packetlimit = -1; static int64_t pcapdump_duration = -1; static int64_t total_count_bytes; static int64_t total_count_dropped; static int64_t total_count_packets; static time_t time_lastdump; static time_t time_start; static bool pcapdump_sample_random = false; static int pcapdump_sample; static int pcapdump_sample_value; /* forward declarations */ static bool has_config_changed(void); static bool should_sample(void); static inline bool is_new_interval(time_t t); static void check_interval_and_reset(void); static void close_and_exit(void); static void daemonize(void); static void load_config(void); static void parse_args(int argc, char **argv); static void print_end_stats(void); static void process_packet(u_char *, const struct pcap_pkthdr *, const u_char *); static void reset_config(void); static void reset_dump(void); static void setup_signals(void); static void sigalarm_handler(int x __unused); static void sighup_handler(int x __unused); static void sigterm_handler(int x __unused); static void update_and_print_stats(void); static void usage(const char *msg); /* functions */ int main(int argc, char **argv){ struct timeval tv; gettimeofday(&tv, NULL); time_start = tv.tv_sec; setlinebuf(stderr); parse_args(argc, argv); daemonize(); reset_config(); setup_signals(); reset_dump(); for(;;){ pcapnet_packet_loop(&pa, process_packet); if(stop_running){ close_and_exit(); }else if(check_interval){ check_interval_and_reset(); }else if(reload_config){ reset_config(); reload_config = false; } else break; } return EXIT_SUCCESS; } static void daemonize(void){ cfgopt_t *cur = cfgopt_get(cfg, "pidfile"); if(cur && cur->val.str) util_daemonize(program_name, cur->val.str); } static void reset_config(void){ if(!pa.handle){ /* initial call to reset_config */ load_config(); pcapnet_init(&pa); cfgopt_print(cfg); }else{ /* called from signal handler */ if(has_config_changed()){ load_config(); pcapnet_reinit_device(&pa); } reset_dump(); } } static void load_config(void){ FREE(pa.dev); FREE(pa.bpf_string); FREE(pcapdump_filefmt); pa.dev = cfgopt_get_str_dup(cfg, "device"); pa.bpf_string = cfgopt_get_str_dup(cfg, "bpf"); pcapdump_filefmt = cfgopt_get_str_dup(cfg, "filefmt"); pa.promisc = cfgopt_get_bool(cfg, "promisc"); pa.snaplen = cfgopt_get_num(cfg, "snaplen"); pcapdump_interval = cfgopt_get_num(cfg, "interval"); pcapdump_packetlimit = cfgopt_get_num(cfg, "count"); pcapdump_duration = cfgopt_get_num(cfg, "duration"); } static bool has_config_changed(void){ char *configfile = cfgopt_get_str(cfg, "configfile"); if(configfile){ if(!cfgopt_load(cfg, configfile)) ERROR("configuration error, exiting"); } if( cfgopt_get_num(cfg, "interval") != pcapdump_interval || cfgopt_get_num(cfg, "duration") != pcapdump_duration || cfgopt_get_bool(cfg, "promisc") != pa.promisc || cfgopt_get_num(cfg, "snaplen") != pa.snaplen || strcmp(pa.bpf_string, cfgopt_get_str(cfg, "bpf")) != 0 || strcmp(pa.dev, cfgopt_get_str(cfg, "device")) != 0 || strcmp(pcapdump_filefmt,cfgopt_get_str(cfg, "filefmt")) != 0 ){ return true; }else{ return false; } } static void close_and_exit(void){ print_end_stats(); pcapnet_close(&pa); exit(EXIT_SUCCESS); } static void process_packet(u_char *user __unused, const struct pcap_pkthdr *hdr, const u_char *pkt){ if( pcapdump_packetlimit > 0 && total_count_packets + count_packets >= pcapdump_packetlimit ){ DEBUG("packet limit reached"); close_and_exit(); } if( pcapdump_duration > 0 && hdr->ts.tv_sec > (time_start + pcapdump_duration) ){ DEBUG("duration exceeded"); close_and_exit(); } if(is_new_interval(hdr->ts.tv_sec)) reset_dump(); if(pcapdump_sample > 0 && !should_sample()) return; if(unlikely(!headers_only)){ pcap_dump((u_char *) pa.dumper, hdr, pkt); ++count_packets; count_bytes += hdr->len; }else{ size_t len = hdr->caplen; const u_char *app = pcapnet_start_app_layer(pa.datalink, pkt, &len); u32 applen = app - pkt; if(app && applen <= (u32) pa.snaplen){ struct pcap_pkthdr newhdr = { .ts = hdr->ts, .caplen = applen, .len = hdr->len, }; pcap_dump((u_char *) pa.dumper, &newhdr, pkt); ++count_packets; count_bytes += applen; } } return; } static bool should_sample(void){ /* See RFC 5475 for a description of sampling techniques. Comments * in this function use the RFC terminology. */ if(!pcapdump_sample_random) { /* Systematic count-based sampling, section 5.1 */ if(--pcapdump_sample_value == 0){ pcapdump_sample_value = pcapdump_sample; return true; }else{ return false; } }else{ /* Uniform probabilistic sampling, section 5.2.2.1 */ if(rng_randint(0, pcapdump_sample - 1) == 0){ return true; }else{ return false; } } } static inline bool is_new_interval(time_t t){ if( (pcapdump_interval > 0) && (((t % pcapdump_interval == 0) && (t != time_lastdump)) || (t - time_lastdump > pcapdump_interval)) ) return true; else return false; } static void check_interval_and_reset(void){ check_interval = false; struct timeval tv; gettimeofday(&tv, NULL); if(is_new_interval(tv.tv_sec) && !reload_config) reset_dump(); if(pa.dev) alarm(1); } static void reset_dump(void){ if(pa.dumper) pcapnet_close_dump(&pa); char *fname; CALLOC(fname, FNAME_MAXLEN); struct timeval tv; gettimeofday(&tv, NULL); struct tm *the_time = gmtime(&tv.tv_sec); strftime(fname, FNAME_MAXLEN, pcapdump_filefmt, the_time); update_and_print_stats(); if(pcapdump_interval > 0) time_lastdump = tv.tv_sec - (tv.tv_sec % pcapdump_interval); int fd = creat_mog( fname, cfgopt_get_num(cfg, "mode"), cfgopt_get_str(cfg, "owner"), cfgopt_get_str(cfg, "group") ); pcapnet_init_dumpfd(&pa, fd); DEBUG("opened %s", fname); FREE(pa.fname_out); pa.fname_out = fname; } static void update_and_print_stats(void){ char *rate; struct pcap_stat stat; unsigned count_dropped; rate = human_readable_rate(count_packets, count_bytes, pcapdump_interval); if(pcap_stats(pa.handle, &stat) == 0){ count_dropped = stat.ps_drop - last_ifdrop; total_count_dropped = stat.ps_drop; last_ifdrop = stat.ps_drop; if(time_lastdump > 0 && pcapdump_interval > 0) DEBUG("%" PRIi64 " packets dumped (%u dropped) at %s", count_packets, count_dropped, rate ); } FREE(rate); total_count_packets += count_packets; total_count_bytes += count_bytes; count_packets = 0; count_bytes = 0; } static void print_end_stats(void){ char *rate; struct pcap_stat stat; struct timeval tv; gettimeofday(&tv, NULL); total_count_packets += count_packets; total_count_bytes += count_bytes; count_packets = 0; count_bytes = 0; rate = human_readable_rate(total_count_packets, total_count_bytes, tv.tv_sec - time_start); if(pcap_stats(pa.handle, &stat) == 0){ total_count_dropped += stat.ps_drop; if(time_lastdump > 0 && pcapdump_interval > 0) DEBUG("%" PRIi64 " total packets dumped (%" PRIi64 " dropped) at %s", total_count_packets, total_count_dropped, rate ); } FREE(rate); } static void setup_signals(void){ signal(SIGHUP, sighup_handler); siginterrupt(SIGHUP, 1); pcapnet_setup_signals(sigterm_handler); if(pa.dev && pcapdump_interval > 0){ signal(SIGALRM, sigalarm_handler); siginterrupt(SIGALRM, 1); alarm(1); } } static void sigalarm_handler(int x __unused){ check_interval = true; pcapnet_break_loop(&pa); } static void sighup_handler(int x __unused){ reload_config = true; pcapnet_break_loop(&pa); } static void sigterm_handler(int x __unused){ stop_running = true; pcapnet_break_loop(&pa); } static void parse_args(int argc, char **argv){ cfgopt_t *cur; cfgopt_parse_args(cfg, argc, argv); pcapnet_load_cfg(&pa, cfg); if(!pcapnet_are_packets_available(&pa)) usage("need to specify a packet capture source"); if(!cfgopt_is_present(cfg, "filefmt")) usage("need to specify output file format"); if((cur = cfgopt_get(cfg, "configfile")) && cur->val.str && cur->val.str[0] != '/') usage("use fully qualified config file path"); headers_only = cfgopt_get_bool(cfg, "headersonly"); pcapdump_sample = pcapdump_sample_value = cfgopt_get_num(cfg, "sample"); pcapdump_sample_random = cfgopt_get_bool(cfg, "random"); if(pcapdump_sample_random && (pcapdump_sample <= 0)) usage("random sampling requires a random value"); if(pcapdump_sample_random) rng_seed(false); cfgopt_free(cur); } static void usage(const char *msg){ fprintf(stderr, "Error: %s\n\n", msg); fprintf(stderr, "Usage: %s <options>\n", program_name); cfgopt_usage(cfg); exit(EXIT_FAILURE); }
722,439
./pcaputils/src/pcapip.c
/* pcapip.c - pcap IP filter Copyright (C) 2007 Robert S. Edmonds Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include <stdbool.h> #include <stdint.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <Judy.h> #include <pcap.h> #include <util/cfgopt.h> #include <util/net.h> #include <util/pcapnet.h> #include <util/scanfmt.h> #include <util/util.h> /* globals */ static char *program_name = "pcapip"; static cfgopt_t cfg[] = { pcapcfg_device, pcapcfg_bpf, pcapcfg_readfile, pcapcfg_writefile, pcapcfg_snaplen, pcapcfg_promisc, { 'l', "list", CONFIG_STR, {}, NULL, "file containing list of IP addresses" }, cfgopt_end }; static pcap_args_t pa; static void *pool = NULL; /* forward declarations */ static void parse_args(int argc, char **argv); static void process_packet(u_char *, const struct pcap_pkthdr *, const u_char *); static void read_ipfile(char *fname); static void sighandler(int x __unused); static void usage(const char *msg); /* functions */ int main(int argc, char **argv){ parse_args(argc, argv); read_ipfile(cfgopt_get_str(cfg, "list")); pcapnet_init(&pa); pcapnet_setup_signals(sighandler); pcapnet_packet_loop(&pa, process_packet); pcapnet_close(&pa); return EXIT_SUCCESS; } static void sighandler(int x __unused){ pcapnet_break_loop(&pa); } static void process_packet(u_char *user __unused, const struct pcap_pkthdr *hdr, const u_char *pkt){ int etype; size_t len = hdr->caplen; struct iphdr *ip_hdr = (struct iphdr *) pcapnet_start_network_header(pa.datalink, pkt, &etype, &len); if(ip_hdr == NULL) return; if(etype == ETHERTYPE_IP){ if(JudyLGet(pool, my_ntohl(ip_hdr->saddr), PJE0)){ pcap_dump((u_char *) pa.dumper, hdr, pkt); }else if(JudyLGet(pool, my_ntohl(ip_hdr->daddr), PJE0)){ pcap_dump((u_char *) pa.dumper, hdr, pkt); } } } static void read_ipfile(char *fname){ char *line = NULL; size_t len = 0; FILE *fp = fopen(fname, "r"); if(fp == NULL){ ERROR("unable to open file '%s'", fname); } while(getline(&line, &len, fp) != -1){ ipaddr_t addr; scan_ip4(line, (char *) &addr); addr = my_ntohl(addr); Word_t *val = (Word_t *)JudyLGet(pool, addr, PJE0); if(val == NULL){ val = (Word_t *)JudyLIns(&pool, addr, PJE0); } } FREE(line); } static void parse_args(int argc, char **argv){ cfgopt_parse_args(cfg, argc, argv); pcapnet_load_cfg(&pa, cfg); if(!pcapnet_are_packets_available(&pa)) usage("need to specify a packet capture source"); if(!cfgopt_is_present(cfg, "writefile")) usage("need to specify output file"); if(!cfgopt_is_present(cfg, "list")) usage("need to specify an IP list file"); } static void usage(const char *msg){ fprintf(stderr, "Error: %s\n\n", msg); fprintf(stderr, "Usage: %s <options>\n", program_name); cfgopt_usage(cfg); exit(EXIT_FAILURE); }
722,440
./pcaputils/src/pcappick.c
/* pcappick.c - pick a pcap frame Copyright (C) 2007 Robert S. Edmonds Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include <stdbool.h> #include <stdint.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <pcap.h> #include <util/cfgopt.h> #include <util/pcapnet.h> #include <util/util.h> /* globals */ static char *program_name = "pcappick"; static cfgopt_t cfg[] = { pcapcfg_device, pcapcfg_readfile, pcapcfg_writefile, pcapcfg_bpf, pcapcfg_snaplen, pcapcfg_promisc, { 'c', "count", CONFIG_DEC, {}, NULL, "frame number to pick" }, cfgopt_end }; static pcap_args_t pa; static uint64_t count_packet = 0; static uint64_t count_target = 0; /* forward declarations */ static void parse_args(int argc, char **argv); static void process_packet(u_char *, const struct pcap_pkthdr *, const u_char *); static void usage(const char *msg); /* functions */ int main(int argc, char **argv){ parse_args(argc, argv); pcapnet_init(&pa); pcapnet_packet_loop(&pa, process_packet); pcapnet_close(&pa); return EXIT_FAILURE; } static void process_packet(u_char *user __unused, const struct pcap_pkthdr *hdr, const u_char *pkt){ ++count_packet; if(count_packet == count_target){ pcap_dump((u_char *) pa.dumper, hdr, pkt); pcapnet_close(&pa); exit(EXIT_SUCCESS); } } static void parse_args(int argc, char **argv){ cfgopt_parse_args(cfg, argc, argv); pcapnet_load_cfg(&pa, cfg); if(!pcapnet_are_packets_available(&pa)) usage("need to specify a packet capture source"); if(!cfgopt_is_present(cfg, "count")) usage("need a frame number"); count_target = cfgopt_get_num(cfg, "count"); } static void usage(const char *msg){ fprintf(stderr, "Error: %s\n\n", msg); fprintf(stderr, "Usage: %s <options>\n", program_name); cfgopt_usage(cfg); exit(EXIT_FAILURE); }
722,441
./pcaputils/src/pcapuc.c
/* pcapuc.c - pcap IP address unique count Copyright (C) 2007 Robert S. Edmonds Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include <signal.h> #include <stdbool.h> #include <stdint.h> #include <stdlib.h> #include <string.h> #include <sys/socket.h> #include <unistd.h> #include <Judy.h> #include <pcap.h> #include <util/net.h> #include <util/pcapnet.h> #include <util/scanfmt.h> #include <util/util.h> /* globals */ static char *program_name = "pcapuc"; static bool count_src_only = false; static bool count_dst_only = false; static bool count_pairs_only = false; static bool count_summary_only = false; static cfgopt_t cfg[] = { pcapcfg_device, pcapcfg_readfile, pcapcfg_bpf, pcapcfg_promisc, { 'S', "countsrc", CONFIG_BOOL, { .boolean = &count_src_only }, "0", "count src addresses only" }, { 'D', "countdst", CONFIG_BOOL, { .boolean = &count_dst_only }, "0", "count dst addresses only" }, { 'P', "countpairs", CONFIG_BOOL, { .boolean = &count_pairs_only }, "0", "count (src, dst) sets only" }, { 'C', "countsum", CONFIG_BOOL, { .boolean = &count_summary_only },"0", "only output the summary count" }, cfgopt_end }; static pcap_args_t pa; static void *pool = NULL; /* forward declarations */ static void parse_args(int argc, char **argv); static void print_uniq(void); static void process_packet(u_char *, const struct pcap_pkthdr *, const u_char *); static void sighandler(int x __unused); static void usage(const char *msg); int main(int argc, char **argv){ parse_args(argc, argv); pcapnet_init(&pa); pcapnet_setup_signals(sighandler); pcapnet_packet_loop(&pa, process_packet); pcapnet_close(&pa); print_uniq(); return EXIT_SUCCESS; } static void process_packet(u_char *user __unused, const struct pcap_pkthdr *hdr, const u_char *pkt){ int etype; size_t len = hdr->caplen; struct iphdr *ip_hdr = (struct iphdr *) pcapnet_start_network_header(pa.datalink, pkt, &etype, &len); if(ip_hdr == NULL) return; if(etype == ETHERTYPE_IP){ if(count_src_only){ ipaddr_t addr = my_ntohl(ip_hdr->saddr); Word_t *val = (Word_t *) JudyLGet(pool, addr, PJE0); if(val == NULL){ val = (Word_t *) JudyLIns(&pool, addr, PJE0); *val = 1; }else{ *val += 1; } }else if(count_dst_only){ ipaddr_t addr = my_ntohl(ip_hdr->daddr); Word_t *val = (Word_t *) JudyLGet(pool, addr, PJE0); if(val == NULL){ val = (Word_t *) JudyLIns(&pool, addr, PJE0); *val = 1; }else{ *val += 1; } }else if(count_pairs_only){ ipaddr_t ip[2] = { my_ntohl(ip_hdr->saddr), my_ntohl(ip_hdr->daddr) }; if(ip[0] > ip[1]) SWAP(ip[0], ip[1]); void **val_ip0 = (void **) JudyLGet(pool, ip[0], PJE0); if(val_ip0 == NULL){ val_ip0 = (void **) JudyLIns(&pool, ip[0], PJE0); *val_ip0 = NULL; } Word_t *val_ip1 = (Word_t *) JudyLGet(*val_ip0, ip[1], PJE0); if(val_ip1 == NULL){ val_ip1 = (Word_t *) JudyLIns(val_ip0, ip[1], PJE0); *val_ip1 = 1; }else{ *val_ip1 += 1; } } } } static void print_uniq(void){ if(count_src_only || count_dst_only){ Word_t ip = 0; Word_t *val; if(count_summary_only){ uint64_t count = JudyLCount(pool, 0, -1, PJE0); printf("%" PRIu64 "\n", count); }else{ while((val = (Word_t *) JudyLNext(pool, &ip, PJE0)) != NULL){ char sip[INET_ADDRSTRLEN]; ipaddr_t ip_copy = my_htonl(ip); fmt_ip4(sip, (char *) &ip_copy); printf("%s\t%ld\n", sip, (long) *val); } } }else if(count_pairs_only){ Word_t ip[2] = { 0, 0 }; Word_t **val_ip0; Word_t *val_ip1; if(count_summary_only){ uint64_t count = 0; while((val_ip0 = (Word_t **) JudyLNext(pool, &ip[0], PJE0)) != NULL){ count += JudyLCount(*val_ip0, 0, -1, PJE0); } printf("%" PRIu64 "\n", count); }else{ uint64_t count = 0; while((val_ip0 = (Word_t **) JudyLNext(pool, &ip[0], PJE0)) != NULL){ while((val_ip1 = (Word_t *) JudyLNext(*val_ip0, &ip[1], PJE0)) != NULL){ ++count; char sip0[INET_ADDRSTRLEN]; char sip1[INET_ADDRSTRLEN]; ipaddr_t ip0 = my_htonl(ip[0]); ipaddr_t ip1 = my_htonl(ip[1]); fmt_ip4(sip0, (char *) &ip0); fmt_ip4(sip1, (char *) &ip1); printf("%s\t%s\t%ld\n", sip0, sip1, (long) *val_ip1); } ip[1] = 0; } } } } static void sighandler(int x __unused){ pcapnet_break_loop(&pa); } static void parse_args(int argc, char **argv){ cfgopt_parse_args(cfg, argc, argv); pcapnet_load_cfg(&pa, cfg); if(!pcapnet_are_packets_available(&pa)) usage("need to specify a packet capture source"); int c = count_src_only + count_dst_only + count_pairs_only; if(c > 1) usage("mutually exclusive options selecetd"); else if(c == 0) usage("select a counting mode"); } static void usage(const char *msg){ fprintf(stderr, "Error: %s\n\n", msg); fprintf(stderr, "Usage: %s <options>\n", program_name); cfgopt_usage(cfg); exit(EXIT_FAILURE); }
722,442
./pcaputils/util/uint.c
#include "uint.h" /* derived from public domain djbdns code */ void u16_pack(char s[2], u16 u) { s[0] = (char) (u & 255); s[1] = (char) (u >> 8); } void u16_pack_big(char s[2], u16 u) { s[1] = (char) (u & 255); s[0] = (char) (u >> 8); } void u16_unpack(const char s[2], u16 *u) { u16 result; result = (unsigned char) s[1]; result <<= 8; result += (unsigned char) s[0]; *u = result; } void u16_unpack_big(const char s[2], u16 *u) { u16 result; result = (unsigned char) s[0]; result <<= 8; result += (unsigned char) s[1]; *u = result; } void u32_pack(char s[4], u32 u) { s[0] = (char) (u & 255); u >>= 8; s[1] = (char) (u & 255); u >>= 8; s[2] = (char) (u & 255); s[3] = (char) (u >> 8); } void u32_pack_big(char s[4], u32 u) { s[3] = (char) (u & 255); u >>= 8; s[2] = (char) (u & 255); u >>= 8; s[1] = (char) (u & 255); s[0] = (char) (u >> 8); } void u32_unpack(const char s[4], u32 *u) { u32 result; result = (unsigned char) s[3]; result <<= 8; result += (unsigned char) s[2]; result <<= 8; result += (unsigned char) s[1]; result <<= 8; result += (unsigned char) s[0]; *u = result; } void u32_unpack_big(const char s[4], u32 *u) { u32 result; result = (unsigned char) s[0]; result <<= 8; result += (unsigned char) s[1]; result <<= 8; result += (unsigned char) s[2]; result <<= 8; result += (unsigned char) s[3]; *u = result; }
722,443
./pcaputils/util/file.c
/* file.c - abstractions for file manipulation Copyright (C) 2008 Robert S. Edmonds Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include <fcntl.h> #include <grp.h> #include <pwd.h> #include <sys/stat.h> #include <sys/types.h> #include <unistd.h> #include <util/file.h> #include <util/util.h> int creat_mog(const char *pathname, mode_t mode, const char *owner, const char *group){ uid_t uid; gid_t gid; int fd; struct group *gr; struct passwd *pw; pw = getpwnam(owner); gr = getgrnam(group); if(pw) uid = pw->pw_uid; else uid = geteuid(); if(gr) gid = gr->gr_gid; else gid = getegid(); if((fd = creat(pathname, mode)) == -1) ERROR("creat() failed: %s", strerror(errno)); if(geteuid() == 0) if(fchown(fd, uid, gid) != 0) ERROR("fchown() failed: %s", strerror(errno)); return fd; } int Open(const char *pathname, int flags){ int fd = open(pathname, flags); if(fd == -1) ERROR("unable to open(%s, %d): %s", pathname, flags, strerror(errno)); return fd; }
722,444
./pcaputils/util/checksum.c
#include "checksum.h" #include "net.h" #include "uint.h" #include "util.h" /* * This is a version of ip_compute_csum() optimized for IP headers, * which always checksum on 4 octet boundaries. * * By Jorge Cwik <jorge@laser.satlink.net>, adapted for linux by * Arnt Gulbrandsen. */ /** * ip_fast_csum - Compute the IPv4 header checksum efficiently. * iph: ipv4 header * ihl: length of header / 4 */ #if defined(__i386__) || defined(__amd64__) __inline u16 checksum_ip(const void *iph, unsigned ihl) { unsigned sum; asm( " movl (%1), %0\n" " subl $4, %2\n" " jbe 2f\n" " addl 4(%1), %0\n" " adcl 8(%1), %0\n" " adcl 12(%1), %0\n" "1: adcl 16(%1), %0\n" " lea 4(%1), %1\n" " decl %2\n" " jne 1b\n" " adcl $0, %0\n" " movl %0, %2\n" " shrl $16, %0\n" " addw %w2, %w0\n" " adcl $0, %0\n" " notl %0\n" "2:" /* Since the input registers which are loaded with iph and ihl are modified, we must also specify them as outputs, or gcc will assume they contain their original values. */ : "=r" (sum), "=r" (iph), "=r" (ihl) : "1" (iph), "2" (ihl) : "memory"); return (u16) sum; } #else __inline u16 checksum_ip(const void *iph, unsigned ihl) { return checksum_net(iph, 4 * ihl); } #endif __inline u16 checksum_net(const void *p, unsigned len) { unsigned sum = 0; u16 *ip = (u16 *) p; while(len > 1){ sum += *ip++; len -= 2; } while(sum >> 16) sum = (sum & 0xffff) + (sum >> 16); #if __BYTE_ORDER == __LITTLE_ENDIAN return (u16) (~sum); #else return my_bswap16((u16) (~sum)); #endif }
722,445
./pcaputils/util/util.c
#ifdef HAVE_EXECINFO_H # include <execinfo.h> #endif #include <stdbool.h> #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <util/util.h> bool util_flag_daemonized; bool util_flag_verbose; #ifdef HAVE_EXECINFO_H void util_print_backtrace(int x __unused){ #define NFRAMES 32 int nptrs; void *buf[NFRAMES]; fprintf(stderr, "what? alarms?! good lord, we're under electronic attack!\n"); nptrs = backtrace(buf, NFRAMES); backtrace_symbols_fd(buf, nptrs, STDERR_FILENO); abort(); } #else void util_print_backtrace(int x __unused) { abort(); } #endif
722,446
./pcaputils/util/daemon.c
/* daemon.c - functions for daemonizing Copyright (C) 2008 Robert S. Edmonds Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include <stdbool.h> #include <stdio.h> #include <sys/types.h> #include <syslog.h> #include <unistd.h> #include "daemon.h" #include "scanfmt.h" #include "util.h" void pidfile_create(const char *pidfile){ FILE *fp; pid_t pid; if(!pidfile) return; pid = getpid(); if(!(fp = fopen(pidfile, "w"))) ERROR("unable to open pidfile %s for writing: %s", pidfile, strerror(errno)); fprintf(fp, "%d\n", pid); fclose(fp); } void util_daemonize(char *program_name, char *pidfile){ if(daemon(0, 0) != 0) ERROR("%s", strerror(errno)); pidfile_create(pidfile); openlog(program_name, LOG_PID, LOG_DAEMON); util_flag_daemonized = true; } void envuidgid(void){ char *envuid; char *envgid; unsigned long uid; unsigned long gid; if((envgid = getenv("GID"))){ scan_ulong(envgid, &gid); if(-1 == setgid((gid_t) gid)) ERROR("unable to setgid(%s): %s", envgid, strerror(errno)); } if((envuid = getenv("UID"))){ scan_ulong(envuid, &uid); if(-1 == setuid((uid_t) uid)) ERROR("unable to setuid(%s): %s", envuid, strerror(errno)); } }
722,447
./pcaputils/util/socket.c
#include <stdbool.h> #include <sys/types.h> #include <sys/param.h> #include <sys/socket.h> #include <netinet/in.h> #include <errno.h> #include "byte.h" #include "socket.h" #include "uint.h" /* from libowfat */ /* Copyright (c) 2001 Felix von Leitner. All rights reserved. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License Version 2 as published by the Free Software Foundation. */ const char V4any[4]={0,0,0,0}; const char V4loopback[4]={127,0,0,1}; const char V4mappedprefix[12]={0,0,0,0,0,0,0,0,0,0,0xff,0xff}; const char V6loopback[16]={0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1}; const char V6any[16]={0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}; int socket_tcp6(void){ int s; s = socket(PF_INET6, SOCK_STREAM, 0); if(s == -1 && errno == EINVAL) s = socket(PF_INET, SOCK_STREAM, 0); return s; } int socket_tcp(void){ int s; s = socket(PF_INET, SOCK_STREAM, 0); if (s == -1) return -1; return s; } int socket_bind6(int s, const char ip[16], u16 port, u32 scope_id){ struct sockaddr_in6 sa; byte_zero(&sa, sizeof sa); sa.sin6_family = AF_INET6; u16_pack_big((char *) &sa.sin6_port, port); /* implicit: sa.sin6_flowinfo = 0; */ byte_copy((char *) &sa.sin6_addr, 16, ip); sa.sin6_scope_id = scope_id; return bind(s, (struct sockaddr *) &sa, sizeof sa); } int socket_bind6_reuse(int s, const char ip[16], u16 port, u32 scope_id){ int opt = 1; setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof opt); return socket_bind6(s, ip, port, scope_id); } int socket_listen(int s, unsigned backlog){ return listen(s, backlog); } int socket_accept6(int s, char ip[16], u16 *port, u32 *scope_id){ struct sockaddr_in6 sa; unsigned dummy = sizeof sa; int fd; fd = accept(s, (struct sockaddr *) &sa, &dummy); if(fd == -1) return -1; if(sa.sin6_family == AF_INET) { struct sockaddr_in *sa4 = (struct sockaddr_in *) &sa; byte_copy(ip, 12, V4mappedprefix); byte_copy(ip + 12, 4, (char *) &sa4->sin_addr); u16_unpack_big((char *) &sa4->sin_port, port); return fd; } byte_copy(ip, 16, (char *) &sa.sin6_addr); u16_unpack_big((char *) &sa.sin6_port, port); if(scope_id) *scope_id = sa.sin6_scope_id; return fd; } int socket_recv6(int s, char *buf, unsigned len, char ip[16], u16 *port, u32 *scope_id){ struct sockaddr_in6 sa; unsigned int dummy = sizeof sa; int r; byte_zero(&sa, dummy); r = recvfrom(s, buf, len, 0, (struct sockaddr *) &sa, &dummy); if(r == -1) return -1; byte_copy(ip, 16, (char *) &sa.sin6_addr); u16_unpack_big((char *) &sa.sin6_port, port); if(scope_id) *scope_id = sa.sin6_scope_id; return r; } int socket_bind4(int s, const char ip[4], u16 port){ struct sockaddr_in sa; byte_zero(&sa, sizeof sa); sa.sin_family = AF_INET; u16_pack_big((char *) &sa.sin_port,port); byte_copy((char *) &sa.sin_addr, 4, ip); return bind(s, (struct sockaddr *) &sa, sizeof sa); } int socket_bind4_reuse(int s, const char ip[4], u16 port){ int opt = 1; setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof opt); return socket_bind4(s, ip, port); } int socket_connect4(int s, const char ip[4], u16 port){ struct sockaddr_in sa; byte_zero(&sa, sizeof sa); sa.sin_family = AF_INET; u16_pack_big((char *) &sa.sin_port, port); byte_copy((char *) &sa.sin_addr, 4, ip); return connect(s, (struct sockaddr *) &sa, sizeof sa); } int socket_connect6(int s, const char ip[16], u16 port, u32 scope_id){ struct sockaddr_in6 sa; byte_zero(&sa, sizeof sa); sa.sin6_family = PF_INET6; u16_pack_big((char *) &sa.sin6_port, port); sa.sin6_flowinfo = 0; sa.sin6_scope_id = scope_id; byte_copy((char *) &sa.sin6_addr, 16, ip); return connect(s, (struct sockaddr *) &sa, sizeof sa); } int socket_udp6(void){ int s; s = socket(PF_INET6, SOCK_DGRAM, 0); if(s == -1){ if(errno == EINVAL) s = socket(PF_INET, SOCK_DGRAM, 0); } return s; } int socket_udp(void){ return socket(PF_INET, SOCK_DGRAM, 0); } int socket_send4(int s, const char *buf, int len, const char ip[4], u16 port){ struct sockaddr_in sa; byte_zero(&sa, sizeof(sa)); sa.sin_family = AF_INET; u16_pack_big((char *) &sa.sin_port, port); byte_copy((char *) &sa.sin_addr, 4, ip); return sendto(s, buf, len, 0, (struct sockaddr *) &sa, sizeof(sa)); } int socket_recv4(int s, char *buf, int len, char ip[4], u16 *port){ struct sockaddr_in sa; socklen_t dummy = sizeof(sa); int r; r = recvfrom(s, buf, len, 0, (struct sockaddr *) &sa, &dummy); if(r == -1) return -1; byte_copy(ip, 4, (char *) &sa.sin_addr); u16_unpack_big((char *) &sa.sin_port, port); return r; }
722,448
./pcaputils/util/ring.c
/* * Portable Audio I/O Library * Ring Buffer utility. * * Author: Phil Burk, http://www.softsynth.com * modified for SMP safety on Mac OS X by Bjorn Roche * modified for SMP safety on Linux by Leland Lucius * also, allowed for const where possible * * Note that this is safe only for a single-thread reader and a * single-thread writer. * * Copyright (c) 1999-2000 Ross Bencina and Phil Burk * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files * (the "Software"), to deal in the Software without restriction, * including without limitation the rights to use, copy, modify, merge, * publish, distribute, sublicense, and/or sell copies of the Software, * and to permit persons to whom the Software is furnished to do so, * subject to the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR * ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /* derived from http://www.portaudio.com/trac/browser/portaudio/branches/v19-devel/src/common/pa_ringbuffer.c */ #include <math.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include "ring.h" #include "util.h" ring_t *ring_new(size_t sz){ ring_t *rbuf = NULL; if( ((sz - 1) & sz) == 0){ NEW0(rbuf); MALLOC(rbuf->buffer, sz); rbuf->buffer_size = sz; ring_flush(rbuf); rbuf->big_mask = (2 * sz) - 1; rbuf->small_mask = sz - 1; }else{ ERROR("sz=%zd is not a power of 2", sz); } return rbuf; } size_t ring_read_bytes_avail(ring_t *rbuf){ ring_rmb(); return ( (rbuf->write_idx - rbuf->read_idx) & rbuf->big_mask ); } size_t ring_write_bytes_avail(ring_t *rbuf){ return rbuf->buffer_size - ring_read_bytes_avail(rbuf); } void ring_flush(ring_t *rbuf){ rbuf->write_idx = rbuf->read_idx = 0; } size_t ring_get_write_regions(ring_t *rbuf, size_t sz, void **dataPtr1, size_t *sizePtr1, void **dataPtr2, size_t *sizePtr2){ size_t index; size_t available = ring_write_bytes_avail(rbuf); if(sz > available) sz = available; index = rbuf->write_idx & rbuf->small_mask; if((index + sz) > rbuf->buffer_size) { size_t first_half = rbuf->buffer_size - index; *dataPtr1 = &rbuf->buffer[index]; *sizePtr1 = first_half; *dataPtr2 = &rbuf->buffer[0]; *sizePtr2 = sz - first_half; } else { *dataPtr1 = &rbuf->buffer[index]; *sizePtr1 = sz; *dataPtr2 = NULL; *sizePtr2 = 0; } return sz; } size_t ring_advance_write_idx(ring_t *rbuf, size_t sz){ ring_wmb(); return rbuf->write_idx = (rbuf->write_idx + sz) & rbuf->big_mask; } size_t ring_get_read_regions(ring_t *rbuf, size_t sz, void **dataPtr1, size_t *sizePtr1, void **dataPtr2, size_t *sizePtr2){ size_t index; size_t available = ring_read_bytes_avail(rbuf); if(sz > available) sz = available; index = rbuf->read_idx & rbuf->small_mask; if((index + sz) > rbuf->buffer_size) { size_t first_half = rbuf->buffer_size - index; *dataPtr1 = &rbuf->buffer[index]; *sizePtr1 = first_half; *dataPtr2 = &rbuf->buffer[0]; *sizePtr2 = sz - first_half; } else { *dataPtr1 = &rbuf->buffer[index]; *sizePtr1 = sz; *dataPtr2 = NULL; *sizePtr2 = 0; } return sz; } size_t ring_advance_read_idx(ring_t *rbuf, size_t sz){ ring_wmb(); return rbuf->read_idx = (rbuf->read_idx + sz) & rbuf->big_mask; } size_t ring_write(ring_t *rbuf, const void *data, size_t sz){ size_t size1, size2, num_written; void *data1, *data2; num_written = ring_get_write_regions(rbuf, sz, &data1, &size1, &data2, &size2); if(size2 > 0) { memcpy(data1, data, size1); data = ((char *) data) + size1; memcpy(data2, data, size2); } else { memcpy(data1, data, size1); } ring_advance_write_idx(rbuf, num_written); return num_written; } size_t ring_read(ring_t *rbuf, void *data, size_t sz){ size_t size1, size2, num_read; void *data1, *data2; num_read = ring_get_read_regions(rbuf, sz, &data1, &size1, &data2, &size2); if(size2 > 0) { memcpy(data, data1, size1); data = ((char *)data) + size1; memcpy(data, data2, size2); } else { memcpy(data, data1, size1); } ring_advance_read_idx(rbuf, num_read); return num_read; }
722,449
./pcaputils/util/pcapnet.c
/* pcapnet.c - libpcap abstraction layer Copyright (C) 2007 Robert S. Edmonds Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include <errno.h> #include <signal.h> #include <stdbool.h> #include <string.h> #include <sys/types.h> #include <sys/socket.h> #include <unistd.h> #include <pcap.h> #include "cfgopt.h" #include "net.h" #include "pcapnet.h" #include "util.h" /* functions */ void pcapnet_load_cfg(pcap_args_t *pa, cfgopt_t *cfg){ cfgopt_t *cur; char *str; if(!pa || !cfg) ERROR("pa or cfg null"); if((str = cfgopt_get_str(cfg, "device")) && str && str[0] != '\0') pa->dev = strdup(str); if((str = cfgopt_get_str(cfg, "inject")) && str && str[0] != '\0') pa->dev_out = strdup(str); if((str = cfgopt_get_str(cfg, "readfile")) && str && str[0] != '\0') pa->fname = strdup(str); if((str = cfgopt_get_str(cfg, "writefile")) && str && str[0] != '\0') pa->fname_out = strdup(str); if((str = cfgopt_get_str(cfg, "bpf")) && str && str[0] != '\0') pa->bpf_string = strdup(str); if((str = cfgopt_get_str(cfg, "kickcmd")) && str && str[0] != '\0') pa->kickcmd = strdup(str); if((cur = cfgopt_get(cfg, "snaplen")) && cur->val.num) pa->snaplen = *cur->val.num; if((cur = cfgopt_get(cfg, "promisc")) && cur->val.boolean) pa->promisc = *cur->val.boolean; } bool pcapnet_are_packets_available(pcap_args_t *pa){ if(!pa->fname && !pa->dev) return false; return true; } const u_char *pcapnet_start_network_header( int datalink, const u_char *orig_pkt, int *etype, /* modified */ size_t *len /* modified */ ){ const u_char *pkt = orig_pkt; switch(datalink){ case DLT_NULL: { if(*len < 4) return NULL; *len -= 4; pkt += 4; uint32_t x = *(const uint32_t *) pkt; if (x == PF_INET) *etype = ETHERTYPE_IP; else if(x == PF_INET6) *etype = ETHERTYPE_IPV6; break; } case DLT_LOOP: { if(*len < 4) return NULL; *len -= 4; pkt += 4; uint32_t x = my_ntohl(*(const uint32_t *) pkt); if (x == PF_INET) *etype = ETHERTYPE_IP; else if(x == PF_INET6) *etype = ETHERTYPE_IPV6; break; } case DLT_EN10MB: { if(*len < ETH_HLEN) return NULL; const struct ethhdr *ether = (const struct ethhdr *) pkt; *etype = my_ntohs(ether->type); *len -= ETH_HLEN; pkt += ETH_HLEN; if(*etype == ETHERTYPE_VLAN){ if(*len < 4) return NULL; *len -= 4; *etype = my_ntohs(*(const uint16_t *)(pkt + 2)); pkt += 4; } break; } case DLT_RAW: { if(*len < sizeof(struct iphdr)) return NULL; const struct iphdr *ip = (const struct iphdr *) pkt; if(ip->ihl == 4U){ *etype = ETHERTYPE_IP; }else if(ip->ihl == 6U){ *etype = ETHERTYPE_IPV6; }else{ return NULL; } break; } #ifdef DLT_LINUX_SLL case DLT_LINUX_SLL: { if(*len < 16) return NULL; *etype = my_ntohs(*(const uint16_t *)(pkt + 14)); *len -= 16; pkt += 16; break; } #endif } return pkt; } const u_char *pcapnet_start_transport_header( int datalink, const u_char *orig_pkt, size_t *len /* modified */, u8 *proto /* modified */ ){ int etype = 0; size_t net_len = *len; const u_char *pkt = pcapnet_start_network_header(datalink, orig_pkt, &etype, &net_len); if(!pkt) return NULL; switch(etype){ struct iphdr *ip; struct ip6hdr *ip6; case ETHERTYPE_IP: ip = (void *) pkt; if(*len < sizeof(struct iphdr) || *len < (4U * ip->ihl)) return NULL; *len -= 4 * ip->ihl; pkt += 4 * ip->ihl; *proto = ip->protocol; break; case ETHERTYPE_IPV6: ip6 = (void *) pkt; if(*len < sizeof(struct ip6hdr)) return NULL; *len -= sizeof(struct ip6hdr); pkt += sizeof(struct ip6hdr); *proto = ip6->ip6_nxt; break; default: return NULL; } switch(*proto){ case IPPROTO_TCP: if(*len < sizeof(struct tcphdr)) return NULL; case IPPROTO_UDP: if(*len < sizeof(struct udphdr)) return NULL; case IPPROTO_ICMPV6: case IPPROTO_ICMP: if(*len < ICMP_HLEN) return NULL; } return pkt; } const u_char *pcapnet_start_app_layer( int datalink, const u_char *orig_pkt, size_t *len /* modified */ ){ u8 proto; int etype = 0; size_t net_len = *len; const u_char *pkt = pcapnet_start_network_header(datalink, orig_pkt, &etype, &net_len); if(!pkt) return NULL; switch(etype){ struct iphdr *ip; struct ip6hdr *ip6; ip_header: case ETHERTYPE_IP: ip = (void *) pkt; if(*len < (unsigned) IP_MIN_HLEN || *len < (4U * ip->ihl)) return NULL; *len -= 4 * ip->ihl; pkt += 4 * ip->ihl; proto = ip->protocol; break; ipv6_header: case ETHERTYPE_IPV6: ip6 = (void *) pkt; if(*len < sizeof(struct ip6hdr)) return NULL; *len -= sizeof(struct ip6hdr); pkt += sizeof(struct ip6hdr); proto = ip6->ip6_nxt; break; default: return NULL; } switch(proto){ case IPPROTO_TCP: { struct tcphdr *tcp = (void *) pkt; if(*len < sizeof(struct tcphdr)) break; *len -= sizeof(struct tcphdr); pkt += sizeof(struct tcphdr); size_t option_octets = 4 * tcp->doff - sizeof(struct tcphdr); if(*len < option_octets) break; *len -= option_octets; pkt += option_octets; break; } case IPPROTO_UDP: if(*len < UDP_HLEN) break; *len -= UDP_HLEN; pkt += UDP_HLEN; break; case IPPROTO_ICMPV6: case IPPROTO_ICMP: if(*len < ICMP_HLEN) break; *len -= ICMP_HLEN; pkt += ICMP_HLEN; break; case IPPROTO_IPV6: goto ipv6_header; case IPPROTO_IPIP: goto ip_header; } return pkt; } void pcapnet_check_datalink_type(int dlt){ switch(dlt) { case DLT_NULL: case DLT_LOOP: case DLT_EN10MB: case DLT_RAW: #ifdef DLT_LINUX_SLL case DLT_LINUX_SLL: #endif break; default: ERROR("datalink type %s not supported", pcap_datalink_val_to_name(dlt)); } } void pcapnet_init(pcap_args_t *pa){ if(pa->dev && pa->fname) ERROR("cannot read packets from device and file simultaneously"); if(!(pa->dev || pa->fname)) ERROR("need a packet capture source"); if(pa->snaplen < 0 || pa->snaplen > 65536){ pa->snaplen = 1522; } if(pa->dev){ DEBUG("opening capture interface %s%s%s%s", pa->dev, pa->bpf_string ? " with filter '" : "", pa->bpf_string ? pa->bpf_string : "", pa->bpf_string ? "'" : "" ); pcapnet_init_device(&pa->handle, pa->dev, pa->snaplen, pa->to_ms, pa->promisc); pcapnet_init_bpf(pa); } if(pa->dev_out){ DEBUG("opening injection interface %s", pa->dev_out); if(pa->dev && strcmp(pa->dev, pa->dev_out) == 0){ pa->handle_out = pa->handle; }else{ pcapnet_init_device(&pa->handle_out, pa->dev_out, 1, 0, true); } } if(pa->fname){ pcapnet_init_file(&pa->handle, pa->fname); pcapnet_init_bpf(pa); DEBUG("reading from pcap file %s link-type %s%s%s%s", pa->fname, pcap_datalink_val_to_name(pcap_datalink(pa->handle)), pa->bpf_string ? " with filter '" : "", pa->bpf_string ? pa->bpf_string : "", pa->bpf_string ? "'" : "" ); } if(pa->fname_out){ pcapnet_init_dump(pa, pa->fname_out); } if(pa->handle){ pa->datalink = pcap_datalink(pa->handle); pcapnet_check_datalink_type(pa->datalink); } if(pa->handle_out){ pa->datalink_out = pcap_datalink(pa->handle_out); } } void pcapnet_reinit_device(pcap_args_t *pa){ if(pa->handle) pcap_close(pa->handle); pcapnet_init_device(&pa->handle, pa->dev, pa->snaplen, pa->to_ms, pa->promisc); pcapnet_init_bpf(pa); } void pcapnet_init_bpf(pcap_args_t *pa){ struct bpf_program pcap_filter; if(pa->bpf_string != NULL){ HENDEL_PCAPERR(pa->handle, pcap_compile(pa->handle, &pcap_filter, pa->bpf_string, 1, 0)); HENDEL_PCAPERR(pa->handle, pcap_setfilter(pa->handle, &pcap_filter)); pcap_freecode(&pcap_filter); } } void pcapnet_init_device(pcap_t **pcap, char *dev, int snaplen, int to_ms, bool promisc){ char pcap_errbuf[PCAP_ERRBUF_SIZE]; if(NULL == (*pcap = pcap_open_live(dev, snaplen, promisc, to_ms, pcap_errbuf))) ERROR("pcap_open_live failed: %s", pcap_errbuf); } void pcapnet_init_dump(pcap_args_t *pa, char *fname){ if(!fname) ERROR("filename is nil"); if(!pa->dumper){ if(!(pa->dumper = pcap_dump_open(pa->handle, fname))){ ERROR("pcap_dump_open: %s", pcap_geterr(pa->handle)); } }else{ ERROR("pcap dumper already initialized"); } } void pcapnet_init_dumpfd(pcap_args_t *pa, int fd){ if(!pa->dumper){ FILE *fp = fdopen(fd, "w"); if(!fp) ERROR("fdopen: %s", strerror(errno)); if(!(pa->dumper = pcap_dump_fopen(pa->handle, fp))){ ERROR("pcap_dump_fopen: %s", pcap_geterr(pa->handle)); } }else{ ERROR("pcap dumper already initialized"); } } void pcapnet_init_file(pcap_t **pcap, char *fname){ FILE *fp; char errbuf[PCAP_ERRBUF_SIZE]; if(strcmp(fname, "-") == 0) fp = fdopen(0, "r"); else fp = fopen(fname, "r"); if(fp == NULL) ERROR("f(d)open failed: %s", strerror(errno)); if(NULL == (*pcap = pcap_fopen_offline(fp, errbuf))) ERROR("pcap_fopen_offline failed: %s", errbuf); } void pcapnet_close(pcap_args_t *pa){ pcapnet_close_dump(pa); if(pa->handle_out){ pcap_close(pa->handle_out); pa->handle_out = NULL; } if(pa->handle){ pcap_close(pa->handle); pa->handle = NULL; } FREE(pa->dev); FREE(pa->dev_out); FREE(pa->fname); FREE(pa->fname_out); FREE(pa->kickcmd); } void pcapnet_close_dump(pcap_args_t *pa){ if(pa->dumper){ if(pa->fname_out) DEBUG("closing pcap file %s", pa->fname_out); pcap_dump_flush(pa->dumper); pcap_dump_close(pa->dumper); pa->dumper = NULL; if(pa->kickcmd != NULL && pa->fname_out != NULL){ char *cmd = NULL; if(asprintf(&cmd, "%s \"%s\" &", pa->kickcmd, pa->fname_out) < 0) ERROR("cannot initialize kick command string"); DEBUG("running '%s'", cmd); system(cmd); free(cmd); } } } void pcapnet_packet_loop(pcap_args_t *pa, pcap_handler cb){ if(!pa || !(pa->handle)) ERROR("pcap handle not initialized"); pcap_loop(pa->handle, -1, cb, (void *)pa); } void pcapnet_break_loop(pcap_args_t *pa){ if(!pa || !(pa->handle)) ERROR("pcap handle not initialized"); pcap_breakloop(pa->handle); } void pcapnet_setup_signals(void (*sighandler)(int)){ signal(SIGINT, sighandler); signal(SIGTERM, sighandler); siginterrupt(SIGINT, 1); siginterrupt(SIGTERM, 1); } void pcapnet_print_pkt(const struct pcap_pkthdr *hdr, const u_char *pkt){ int c = 0; for(unsigned i = 0 ; i < hdr->caplen ; ++i, ++c){ if(c == 25){ c = 0; fprintf(stderr, "\n"); } fprintf(stderr, "%2.x ", pkt[i]); } }
722,450
./pcaputils/util/byte.c
#include "byte.h" /* derived from public domain djbdns code */ unsigned int byte_chr(const char* s,unsigned int n,int c) { char ch; const char *t; ch = (char) c; t = s; for (;;) { if (!n) break; if (*t == ch) break; ++t; --n; if (!n) break; if (*t == ch) break; ++t; --n; if (!n) break; if (*t == ch) break; ++t; --n; if (!n) break; if (*t == ch) break; ++t; --n; } return t - s; } void byte_copy(void* To, unsigned int n, const void* From) { char *to=To; const char *from=From; for (;;) { if (!n) return; *to++ = *from++; --n; if (!n) return; *to++ = *from++; --n; if (!n) return; *to++ = *from++; --n; if (!n) return; *to++ = *from++; --n; } } void byte_copyr(void* To,unsigned int n, const void* From) { char *to=(char*)To+n; const char *from=(char*)From+n; for (;;) { if (!n) return; *--to = *--from; --n; if (!n) return; *--to = *--from; --n; if (!n) return; *--to = *--from; --n; if (!n) return; *--to = *--from; --n; } } int byte_diff(const void* S,unsigned int n, const void* T) { const char *s=S; const char *t=T; for (;;) { if (!n) return 0; if (*s != *t) break; ++s; ++t; --n; if (!n) return 0; if (*s != *t) break; ++s; ++t; --n; if (!n) return 0; if (*s != *t) break; ++s; ++t; --n; if (!n) return 0; if (*s != *t) break; ++s; ++t; --n; } return ((int)(unsigned int)(unsigned char) *s) - ((int)(unsigned int)(unsigned char) *t); } void byte_zero(void* S,unsigned int n) { char* s=S; for (;;) { if (!n) break; *s++ = 0; --n; if (!n) break; *s++ = 0; --n; if (!n) break; *s++ = 0; --n; if (!n) break; *s++ = 0; --n; } }
722,451
./pcaputils/util/cfgopt.c
/* cfgopt.c - unified config file / command line option parsing Copyright (C) 2008 Robert S. Edmonds Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include <getopt.h> #include <stdio.h> #include <string.h> #include "cfgopt.h" #include "scanfmt.h" #include "util.h" /* declarations */ static void cfgopt_load_value(cfgopt_t *cfg, char *value); /* functions */ bool cfgopt_load(cfgopt_t *cfg, char *fname){ FILE *fp; size_t len; char *line = NULL; bool success = true; if(!cfg || !fname) return false; if(!(fp = fopen(fname, "r"))) ERROR("fopen() failed: %s", strerror(errno)); while(getline(&line, &len, fp) != -1){ char *tok_key; char *tok_val; tok_key = strtok(line, "=\"\t\n"); if(!tok_key) continue; tok_val = strtok(NULL, "\"\t\n"); if(!tok_val){ DEBUG("null value for key='%s'", tok_key); continue; } cfgopt_t *cur = cfgopt_get(cfg, tok_key); if(!cur){ DEBUG("unknown configuration key '%s'", tok_key); success = false; continue; }else{ cfgopt_load_value(cur, tok_val); } FREE(line); } for(; cfg->type != CONFIG_END ; ++cfg) if(!cfg->val.str) cfgopt_load_value(cfg, cfg->default_value); FREE(line); fclose(fp); return success; } static void cfgopt_load_value(cfgopt_t *cfg, char *value){ if(!value) return; switch(cfg->type){ case CONFIG_STR: { cfg->val.str = strdup(value); break; } case CONFIG_DEC: case CONFIG_OCT: { int base = cfg->type == CONFIG_DEC ? 0 : 8; if(!cfg->val.num) NEW0(cfg->val.num); *cfg->val.num = strtoul(value, NULL, base); break; } case CONFIG_BOOL: { if(!cfg->val.boolean) NEW0(cfg->val.boolean); *cfg->val.boolean = (bool) strtoul(value, NULL, 0); break; } case CONFIG_IP: { char *ip; MALLOC(ip, 4); if(scan_ip4(value, ip) == 0) ERROR("invalid IPv4 literal: %s", value); cfg->val.ip = ip; break; } case CONFIG_IP6: { char *ip6; MALLOC(ip6, 16); if(scan_ip6(value, ip6) == 0) ERROR("invalid IPv6 literal: %s", value); cfg->val.ip6 = ip6; break; } case CONFIG_MAC: { char *mac; MALLOC(mac, 6); if(scan_mac(value, mac) != 6) ERROR("invalid MAC literal: %s", value); cfg->val.mac = mac; break; } case CONFIG_NONOPT: { if(!cfg->val.nonopt){ cfg->val.nonopt = strdup(value); }else{ size_t new_size = 2 + strlen(cfg->val.nonopt) + strlen(value); REALLOC(cfg->val.nonopt, new_size); strcat(cfg->val.nonopt, " "); strcat(cfg->val.nonopt, value); } break; } default: ERROR("invalid configuration type %d", (int) cfg->type); } } cfgopt_t *cfgopt_get(cfgopt_t *cfg, char *key){ for(; cfg->type != CONFIG_END ; ++cfg){ if(strcasecmp(cfg->key, key) == 0) return cfg; } return NULL; } char *cfgopt_get_str(cfgopt_t *cfg, char *key){ for(; cfg->type != CONFIG_END ; ++cfg){ if(strcasecmp(cfg->key, key) == 0){ if(cfg->type != CONFIG_STR) ERROR("key='%s' is not a CONFIG_STR", key); return cfg->val.str; } } return NULL; } char *cfgopt_get_str_dup(cfgopt_t *cfg, char *key){ for(; cfg->type != CONFIG_END ; ++cfg){ if(strcasecmp(cfg->key, key) == 0){ if(cfg->type != CONFIG_STR) ERROR("key='%s' is not a CONFIG_STR", key); if(cfg->val.str) return strdup(cfg->val.str); } } return NULL; } long cfgopt_get_num(cfgopt_t *cfg, char *key){ for(; cfg->type != CONFIG_END ; ++cfg){ if(strcasecmp(cfg->key, key) == 0){ if(cfg->type != CONFIG_DEC && cfg->type != CONFIG_OCT) ERROR("key='%s' is not a CONFIG_DEC or CONFIG_OCT", key); if(cfg->val.num) return *cfg->val.num; } } return 0; } bool cfgopt_get_bool(cfgopt_t *cfg, char *key){ for(; cfg->type != CONFIG_END ; ++cfg){ if(strcasecmp(cfg->key, key) == 0){ if(cfg->type != CONFIG_BOOL) ERROR("key='%s' is not a CONFIG_BOOL", key); if(cfg->val.boolean) return *cfg->val.boolean; } } return false; } char *cfgopt_get_ip(cfgopt_t *cfg, char *key){ for(; cfg->type != CONFIG_END ; ++cfg){ if(strcasecmp(cfg->key, key) == 0){ if(cfg->type != CONFIG_IP) ERROR("key='%s' is not a CONFIG_IP", key); if(cfg->val.ip) return cfg->val.ip; } } return NULL; } char *cfgopt_get_ip6(cfgopt_t *cfg, char *key){ for(; cfg->type != CONFIG_END ; ++cfg){ if(strcasecmp(cfg->key, key) == 0){ if(cfg->type != CONFIG_IP6) ERROR("key='%s' is not a CONFIG_IP6", key); return cfg->val.ip; } } return NULL; } char *cfgopt_get_mac(cfgopt_t *cfg, char *key){ for(; cfg->type != CONFIG_END ; ++cfg){ if(strcasecmp(cfg->key, key) == 0){ if(cfg->type != CONFIG_MAC) ERROR("key='%s' is not a CONFIG_MAC", key); return cfg->val.mac; } } return NULL; } char *cfgopt_get_nonopt(cfgopt_t *cfg){ for(; cfg->type != CONFIG_END ; ++cfg){ if(cfg->type == CONFIG_NONOPT) return cfg->val.nonopt; } return NULL; } void cfgopt_free(cfgopt_t *cfg){ for(; cfg->type != CONFIG_END ; ++cfg){ FREE(cfg->val.str); } } bool cfgopt_is_present(cfgopt_t *cfg, char *key){ for(; cfg->type != CONFIG_END ; ++cfg){ if((strcasecmp(cfg->key, key) == 0) && cfg->val.str) return true; } return false; } void cfgopt_print(cfgopt_t *cfg){ for(; cfg->type != CONFIG_END ; ++cfg){ switch(cfg->type){ case CONFIG_STR: if(cfg->val.str) DEBUG("key='%s', val='%s'", cfg->key, cfg->val.str); break; case CONFIG_BOOL: if(cfg->val.boolean) DEBUG("key='%s', val=%s", cfg->key, *cfg->val.boolean ? "true" : "false"); break; case CONFIG_DEC: if(cfg->val.num) DEBUG("key='%s', val=%ld", cfg->key, *cfg->val.num); break; case CONFIG_OCT: if(cfg->val.num) DEBUG("key='%s', val=%lo", cfg->key, *cfg->val.num); break; case CONFIG_IP: { char sip[FMT_IP4]; fmt_ip4(sip, cfg->val.ip); DEBUG("key='%s', val=%s", cfg->key, sip); break; } case CONFIG_IP6: { char sip[FMT_IP6]; fmt_ip6(sip, cfg->val.ip); DEBUG("key='%s', val=%s", cfg->key, sip); break; } case CONFIG_MAC: { char smac[FMT_MAC]; fmt_mac(smac, cfg->val.mac); DEBUG("key='%s', val=%s", cfg->key, smac); break; } case CONFIG_NONOPT: if(cfg->val.nonopt) DEBUG("nonopt='%s'", cfg->val.nonopt); break; default: break; } } } void cfgopt_usage(cfgopt_t *cfg){ for(; cfg->type != CONFIG_END ; ++cfg){ switch(cfg->type){ case CONFIG_STR: case CONFIG_DEC: case CONFIG_OCT: case CONFIG_IP: case CONFIG_IP6: case CONFIG_MAC: fprintf(stderr, "\t[ -%c <%s> %s %s%s%s]\n", cfg->cmd, cfg->key, cfg->help, cfg->default_value == NULL ? "" : "(default: ", cfg->default_value == NULL ? "" : cfg->default_value, cfg->default_value == NULL ? "" : ") " ); break; case CONFIG_BOOL: fprintf(stderr, "\t[ -%c %s %s%s%s]\n", cfg->cmd, cfg->help, cfg->default_value == NULL ? "" : "(default: ", cfg->default_value == NULL ? "" : cfg->default_value, cfg->default_value == NULL ? "" : ") " ); break; default: break; } } } void cfgopt_parse_args(cfgopt_t *cfg, int argc, char **argv){ int c; char *options; cfgopt_t *cur; CALLOC(options, 2 * cfgopt_len(cfg)); for(cur = cfg ; cur->type != CONFIG_END ; ++cur){ switch(cur->type){ case CONFIG_STR: case CONFIG_DEC: case CONFIG_OCT: case CONFIG_IP: case CONFIG_IP6: case CONFIG_MAC: strcat(options, &cur->cmd); strcat(options, ":"); break; case CONFIG_BOOL: strcat(options, &cur->cmd); break; default: break; } } for(cur = cfg ; cur->type != CONFIG_END ; ++cur) if(cur->type != CONFIG_NONOPT) cfgopt_load_value(cur, cur->default_value); while((c = getopt(argc, argv, options)) != EOF){ for(cur = cfg ; cur->type != CONFIG_END ; ++cur){ if(c == cur->cmd){ if(cur->type == CONFIG_BOOL){ if(cur->default_value && cur->default_value[0] == '0') cfgopt_load_value(cur, "1"); else if(cur->default_value && cur->default_value[0] == '1') cfgopt_load_value(cur, "0"); else cfgopt_load_value(cur, "1"); }else{ cfgopt_load_value(cur, optarg); } } } } for(cur = cfg ; cur->type != CONFIG_END; ++cur) if(cur->type == CONFIG_NONOPT) while(argv[optind] != '\0') cfgopt_load_value(cur, argv[optind++]); if((cur = cfgopt_get(cfg, "configfile")) && cur->val.str && !cfgopt_load(cfg, cur->val.str)) ERROR("configuration error, exiting"); FREE(options); } size_t cfgopt_len(cfgopt_t *cfg){ size_t len = 0; for(; cfg->type != CONFIG_END ; ++cfg) ++len; return len; }
722,452
./pcaputils/util/net.c
/* net.c - functions useful for programs which interact with the network Copyright (C) 2008 Robert S. Edmonds Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include <netinet/in.h> #include <errno.h> #include <netdb.h> #include <stdbool.h> #include <stdlib.h> #include <string.h> #include <sys/socket.h> #include <sys/types.h> #include "byte.h" #include "net.h" #include "scanfmt.h" #include "uint.h" #include "util.h" /* functions */ u32 my_bswap32(u32 x){ return ((x << 24) & 0xff000000 ) | ((x << 8) & 0x00ff0000 ) | ((x >> 8) & 0x0000ff00 ) | ((x >> 24) & 0x000000ff ); } u16 my_bswap16(u16 x){ return (u16) ((x & 0xff) << 8 | (x & 0xff00) >> 8); } ipaddr_range_t sips_to_range(char *sip0, char *sip1){ ipaddr_range_t ipr; scan_ip4(sip0, ipr.ip0); scan_ip4(sip1, ipr.ip1); return ipr; } char *human_readable_rate(u64 packets, u64 bytes, unsigned interval){ char prefix_packets[] = "\0\0"; char prefix_bytes[] = "\0\0"; char *str; CALLOC(str, 64); double div_packets = ((double) packets) / interval; double div_bytes = ((double) bytes) / interval; if(div_packets >= 1E9){ prefix_packets[0] = 'G'; div_packets /= 1E9; }else if(div_packets >= 1E6){ prefix_packets[0] = 'M'; div_packets /= 1E6; }else if(div_packets >= 1E3){ prefix_packets[0] = 'K'; div_packets /= 1E3; } if(div_bytes >= 1E9){ prefix_bytes[0] = 'G'; div_bytes /= 1E9; }else if(div_bytes >= 1E6){ prefix_bytes[0] = 'M'; div_bytes /= 1E6; }else if(div_bytes >= 1E3){ prefix_bytes[0] = 'K'; div_bytes /= 1E3; } snprintf(str, 64, "%.2f %spps, %.2f %sBps", div_packets, prefix_packets, div_bytes, prefix_bytes); return str; } u16 random_unprivileged_port(void){ long r = random(); r &= 0xffff; r |= 0x400; return (u16) r; } bool gai4(const char *hostname, char ip[4]){ struct addrinfo hints = { .ai_family = AF_INET, .ai_socktype = 0, .ai_protocol = 0 }; struct addrinfo *res; if(0 == getaddrinfo(hostname, NULL, &hints, &res)){ byte_copy(ip, 4, (char *) &((struct sockaddr_in *) res->ai_addr)->sin_addr.s_addr); freeaddrinfo(res); return true; }else{ DEBUG("getaddrinfo() returned: %s", strerror(errno)); } return false; } bool gai6(const char *hostname, char ip[16]){ struct addrinfo hints = { .ai_family = AF_INET6, .ai_socktype = 0, .ai_protocol = 0 }; struct addrinfo *res; if(0 == getaddrinfo(hostname, NULL, &hints, &res)){ byte_copy(ip, 16, (char *) &((struct sockaddr_in6 *) res->ai_addr)->sin6_addr); freeaddrinfo(res); return true; }else{ DEBUG("getaddrinfo() returned: %s", strerror(errno)); } return false; }
722,453
./pcaputils/util/rng.c
/* rng.c - randomization functions Copyright (C) 2008 Robert S. Edmonds Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include <fcntl.h> #include <stdlib.h> #include <sys/stat.h> #include <sys/types.h> #include <unistd.h> #include "rng.h" #include "util.h" void rng_seed(bool secure){ char *dev; int fd; unsigned seed; if(secure) dev = "/dev/random"; else dev = "/dev/urandom"; if((fd = open(dev, O_RDONLY)) != -1){ if(read(fd, &seed, sizeof(seed)) != sizeof(seed)) ERROR("unable to read %u bytes from %s", (unsigned) sizeof(seed), dev); }else{ ERROR("unable to open %s for reading: %s", dev, strerror(errno)); } srandom(seed); close(fd); } int rng_randint(int min, int max){ return (int) (((double) (max - min + 1)) * (rand() / (RAND_MAX + ((double) min)))); }
722,454
./pcaputils/util/server.c
/* server.c - functions useful for programs which provide network services Copyright (C) 2008 Robert S. Edmonds Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include "scanfmt.h" #include "server.h" #include "socket.h" #include "uint.h" #include "util.h" int setup_tcp_server_socket(const char ip[4], const char ip6[16], u16 port, int backlog){ char sip[FMT_IP6]; int fd; fd = socket_tcp6(); if(fd >= 0){ if(socket_bind6_reuse(fd, ip6, port, 0) == -1){ close(fd); fd = socket_tcp(); if(fd >= 0){ if(-1 == socket_bind4_reuse(fd, ip, port)) ERROR("unable to create server socket: %s", strerror(errno)); else{ fmt_ip4(sip, ip); DEBUG("bound TCP socket on %s:%hu", sip, port); } }else{ ERROR("unable to create TCP socket: %s", strerror(errno)); } }else{ fmt_ip6(sip, ip6); DEBUG("bound TCP socket on [%s]:%hu", sip, port); } if(socket_listen(fd, backlog) == -1) ERROR("listen() failed: %s", strerror(errno)); }else{ ERROR("unable to create TCP socket: %s", strerror(errno)); } return fd; } int setup_udp_server_socket(const char ip[4], const char ip6[16], u16 port){ char sip[FMT_IP6]; int fd; fd = socket_udp6(); if(fd >= 0){ if(socket_bind6(fd, ip6, port, 0) == -1){ close(fd); fd = socket_udp(); if(socket_bind4(fd, ip, port) == -1){ ERROR("unable to create server socket: %s", strerror(errno)); }else{ fmt_ip4(sip, ip); DEBUG("bound UDP socket on %s:%hu", sip, port); } }else{ fmt_ip6(sip, ip6); DEBUG("bound UDP socket on [%s]:%hu", sip, port); } }else{ ERROR("unable to create UDP socket: %s", strerror(errno)); } return fd; }
722,455
./pcaputils/util/scanfmt.c
#include <ctype.h> #include "socket.h" #include "scanfmt.h" unsigned fmt_mac(char *s, const char mac[6]){ unsigned i; unsigned len = 0; i = fmt_xlong(s, (unsigned long) (unsigned char) mac[0]); len += i; if(s) s += i; if(s) *s++ = ':'; ++len; i = fmt_xlong(s, (unsigned long) (unsigned char) mac[1]); len += i; if(s) s += i; if(s) *s++ = ':'; ++len; i = fmt_xlong(s, (unsigned long) (unsigned char) mac[2]); len += i; if(s) s += i; if(s) *s++ = ':'; ++len; i = fmt_xlong(s, (unsigned long) (unsigned char) mac[3]); len += i; if(s) s += i; if(s) *s++ = ':'; ++len; i = fmt_xlong(s, (unsigned long) (unsigned char) mac[4]); len += i; if(s) s += i; if(s) *s++ = ':'; ++len; i = fmt_xlong(s, (unsigned long) (unsigned char) mac[5]); len += i; if(s) s += i; *s = '\0'; return len; } unsigned scan_mac(const char *s, char mac[6]){ const char *tmp = s; unsigned len = 0; unsigned pos = 0; while(isxdigit(*tmp)){ mac[pos] = ((char) scan_fromhex(*tmp)) << 4 | ((char) scan_fromhex(*(tmp + 1))); ++pos; ++len; tmp += 2; if(*tmp == ':' || *tmp == '-' || *tmp == '.') ++tmp; } return len; } /* derived from public domain djbdns code */ unsigned fmt_ulong(char *s, unsigned long u) { unsigned len; unsigned long q; len = 1; q = u; while (q > 9) { ++len; q /= 10; } if (s) { s += len; do { *--s = '0' + (u % 10); u /= 10; } while(u); /* handles u == 0 */ } return len; } unsigned scan_ulong(const char *s, unsigned long *u) { unsigned pos = 0; unsigned long result = 0; unsigned long c; while ((c = (unsigned long) (unsigned char) (s[pos] - '0')) < 10) { result = result * 10 + c; ++pos; } *u = result; return pos; } unsigned fmt_xlong(char *s, unsigned long u) { unsigned len; unsigned long q; char c; len = 1; q = u; while (q > 15) { ++len; q /= 16; } if (s) { s += len; do { c = '0' + (u & 15); if (c > '0' + 9) c += 'a' - '0' - 10; *--s = c; u /= 16; } while(u); } return len; } unsigned scan_xlong(const char *src, unsigned long *dest) { const char *tmp=src; unsigned long l=0; unsigned char c; while ((c = (char) scan_fromhex(*tmp))<16) { l=(l<<4)+c; ++tmp; } *dest=l; return tmp-src; } int scan_fromhex(unsigned char c) { c-='0'; if (c<=9) return c; c&=~0x20; c-='A'-'0'; if (c<6) return c+10; return -1; } unsigned fmt_ip4(char *s,const char ip[4]) { unsigned i; unsigned len = 0; i = fmt_ulong(s,(unsigned long) (unsigned char) ip[0]); len += i; if (s) s += i; if (s) *s++ = '.'; ++len; i = fmt_ulong(s,(unsigned long) (unsigned char) ip[1]); len += i; if (s) s += i; if (s) *s++ = '.'; ++len; i = fmt_ulong(s,(unsigned long) (unsigned char) ip[2]); len += i; if (s) s += i; if (s) *s++ = '.'; ++len; i = fmt_ulong(s,(unsigned long) (unsigned char) ip[3]); len += i; if (s) s += i; *s = '\0'; return len; } unsigned scan_ip4(const char *s, char ip[4]) { unsigned i; unsigned len; unsigned long u; len = 0; i = scan_ulong(s,&u); if (!i) return 0; ip[0] = u; s += i; len += i; if (*s != '.') return 0; ++s; ++len; i = scan_ulong(s,&u); if (!i) return 0; ip[1] = u; s += i; len += i; if (*s != '.') return 0; ++s; ++len; i = scan_ulong(s,&u); if (!i) return 0; ip[2] = u; s += i; len += i; if (*s != '.') return 0; ++s; ++len; i = scan_ulong(s,&u); if (!i) return 0; ip[3] = u; s += i; len += i; return len; } /* functions from libowfat */ /* Copyright (c) 2001 Felix von Leitner. All rights reserved. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License Version 2 as published by the Free Software Foundation. */ unsigned fmt_ip6(char *s, const char ip[16]) { unsigned long len,temp, k, pos0=0,len0=0, pos1=0, compr=0; for (k=0; k<16; k+=2) { if (ip[k]==0 && ip[k+1]==0) { if (!compr) { compr=1; pos1=k; } if (k==14) { k=16; goto last; } } else if (compr) { last: if ((temp=k-pos1) > len0) { len0=temp; pos0=pos1; } compr=0; } } for (len=0,k=0; k<16; k+=2) { if (k==12 && ip6_isv4mapped(ip)) { len += fmt_ip4(s,ip+12); break; } if (pos0==k && len0) { if (k==0) { ++len; if (s) *s++ = ':'; } ++len; if (s) *s++ = ':'; k += len0-2; continue; } temp = ((unsigned long) (unsigned char) ip[k] << 8) + (unsigned long) (unsigned char) ip[k+1]; temp = fmt_xlong(s,temp); len += temp; if (s) s += temp; if (k<14) { ++len; if (s) *s++ = ':'; } } *s = '\0'; return len; } unsigned scan_ip6(const char *s, char ip[16]) { unsigned i; unsigned len=0; unsigned long u; char suffix[16]; unsigned prefixlen=0; unsigned suffixlen=0; if ((i=scan_ip4(s,ip+12))) { for (len=0; len<12; ++len) ip[len]=V4mappedprefix[len]; return i; } for (i=0; i<16; i++) ip[i]=0; for (;;) { if (*s == ':') { ++len; ++s; if (*s == ':') { /* Found "::", skip to part 2 */ ++len; ++s; break; } } i = scan_xlong(s,&u); if (!i) return 0; if (prefixlen==12 && s[i]=='.') { /* the last 4 bytes may be written as IPv4 address */ i=scan_ip4(s,ip+12); if (i) return i+len; else return 0; } ip[prefixlen++] = (u >> 8); ip[prefixlen++] = (u & 255); s += i; len += i; if (prefixlen==16) return len; } /* part 2, after "::" */ for (;;) { if (*s == ':') { if (suffixlen==0) break; s++; len++; } else if (suffixlen) break; i = scan_xlong(s,&u); if (!i) { if (suffixlen) --len; break; } if (suffixlen+prefixlen<=12 && s[i]=='.') { int j=scan_ip4(s,suffix+suffixlen); if (j) { suffixlen+=4; len+=j; break; } else prefixlen=12-suffixlen; /* make end-of-loop test true */ } suffix[suffixlen++] = (u >> 8); suffix[suffixlen++] = (u & 255); s += i; len += i; if (prefixlen+suffixlen==16) break; } for (i=0; i<suffixlen; i++) ip[16-suffixlen+i] = suffix[i]; return len; }
722,456
./pcaputils/util/rate.c
#include <stdlib.h> #include <sys/time.h> #include <time.h> #include <util/rate.h> #include <util/util.h> rate_t *rate_new(int call_rate){ rate_t *r; NEW0(r); r->call_rate = call_rate; r->gtod_rate = call_rate / 10; r->sleep_rate = call_rate / 100; r->ts.tv_sec = 0; r->ts.tv_nsec = 4E6; if(r->gtod_rate == 0) r->gtod_rate = 1; if(r->sleep_rate == 0) r->sleep_rate = 1; gettimeofday(&r->tv[0], NULL); return r; } void rate_free(rate_t **r){ FREE(*r); } void rate_call(rate_t *r, void (fn)(void *), void *data){ (r->call_no)++; (r->call_no_last)++; if(unlikely(r->call_no % r->sleep_rate == 0)){ nanosleep(&r->ts, NULL); } if(unlikely(r->call_no % r->gtod_rate == 0)){ gettimeofday(&r->tv[1], NULL); double d0 = r->tv[0].tv_sec + r->tv[0].tv_usec / 1E6; double d1 = r->tv[1].tv_sec + r->tv[1].tv_usec / 1E6; r->cur_rate = ((int) (r->call_no_last / (d1 - d0))); if(abs(r->cur_rate - r->call_rate) > 10){ if(r->cur_rate - r->call_rate > 0){ if(r->sleep_rate > 1){ int d = r->sleep_rate / 10; r->sleep_rate -= (d > 1 ? d : 1); VERBOSE("sleep_rate=%d", r->sleep_rate); } }else if (r->sleep_rate < 1E6){ int d = r->sleep_rate / 10; r->sleep_rate += (d > 1 ? d : 1); VERBOSE("sleep_rate=%d", r->sleep_rate); } } r->call_no_last = 0; r->tv[0] = r->tv[1]; } if(fn) fn(data); }