File::File(QString fileName, QMap<QByteArray, QByteArray> *hashToBlock, QMap<QByteArray, QByteArray> *blockToHash) { this->fileName = fileName; if (parseFile() == 0) { qDebug() << "Opened file " << fileName << " with size " << this->fileSize; blocklist = hashFile(contents, BLOCK_SIZE, hashToBlock, blockToHash); qDebug() << "Calculated blocklist"; fileID = hashFile(blocklist, BLOCK_SIZE, hashToBlock, blockToHash); qDebug() << "FileID for " << fileName << " is " << fileID.toHex(); } }
void main(int argc,char **argv) { // printf("%i\n",sizeof(long)); hashFile(argv[1],&alen,&ahashes); hashFile(argv[2],&blen,&bhashes); exit(0); }
// |---[ Kernel ]-------------------- kernel device::buildKernel(const std::string &filename, const std::string &kernelName, const occa::properties &props) const { occa::properties allProps = props + kernelProperties(); allProps["mode"] = mode(); hash_t kernelHash = (hash() ^ occa::hash(allProps) ^ hashFile(filename)); // Check cache first kernel &cachedKernel = dHandle->getCachedKernel(kernelHash, kernelName); if (cachedKernel.isInitialized()) { return cachedKernel; } const std::string realFilename = io::filename(filename); const std::string hashDir = io::hashDir(realFilename, kernelHash); cachedKernel = dHandle->buildKernel(realFilename, kernelName, kernelHash, allProps); return cachedKernel; }
/********************************************************************* ** This function will add weather record into binary file. False adding weather will be terminated and proper messages will be printed. Adding result will be returned as a number(BADLINE, GOODADD, BADFILE). *********************************************************************/ int addRecordsToDB(FILE *fp) { // prompt the user to enter name of the file printf("Enter file name: "); char fileName[MAXFILENAME]; gets(fileName); // enter nothing, return BLANK if (fileName[0] == '\0') { return BLANK; } // file name format check // open file if ((fp = openWeatherFile(fileName)) == NULL) { printf("Batch insertion file could not be opened!\n"); return BADFILE; } // input string's according file not valid, return BADLINE "Batch insertion file could not be opened!" // hash hashFile(fp); // inout file open successfully, but bucket overflow, return BADFILE, "Bucket overflow! Record for INPUT,INPUT rejected!" // file valid, good file, check if the record is duplicate, print no duplicate message // return GOODADD // close file }
char* stringify(int param) { char * buffer = (char *) malloc(10000 * sizeof(char)); char * hash = (char *) malloc(32); memset(hash,0,sizeof(hash)); memset(buffer,0,sizeof(buffer)); DIR *dp; struct dirent *ep; dp = opendir("./"); int i; int counter = 0; if (dp != NULL) { while (ep = readdir (dp)){ if((strcmp(ep->d_name, ".") == 0 ) || (strcmp(ep->d_name, "..") == 0)){ //printf("fail\n"); } else{ if(param == 1){ //buffer = (char *) realloc(buffer, strlen(buffer)+strlen(ep->d_name)); strncat(buffer, ep->d_name, sizeof(ep->d_name)); strncat(buffer, ";", sizeof(char)); } else if(param == 2){ //buffer = (char *) realloc(buffer, counter + 32 ); //strncat(buffer,hashFile(ep->d_name), 32); hash = hashFile(ep->d_name); for(i = 0; i < 32; i++){ buffer[counter] = hash[i]; counter++; } //printf("buffer: "); //for(i = 0; i < 160; i++) printf("%02x", (unsigned char) buffer[i]); //printf("\n"); //strncat(buffer, ";", sizeof(char)); } else{ perror("Please provide either argument 1 or 2"); } } } (void) closedir (dp); } else perror("Coudln't open"); //Terminate string if(param ==1){ buffer[strlen(buffer)-1]=0; } //buffer = realloc(buffer, strlen(buffer)+1); return buffer; }
DWORD CDX9ShaderLoader::OnLoadFile(DWORD size, void *params) { VERIFY_MESSAGE_SIZE(size, sizeof(TCHAR *)); TCHAR *pFileName = (TCHAR *)params; StdString szFileName(pFileName); szFileName.MakeSafeFileName(); CHashString hashFile(szFileName); map<DWORD, bool>::iterator mapIter = m_mFileLoaded.find(hashFile.GetUniqueID()); // if the file is not loaded yet, load it; otherwise do nothing if (mapIter == m_mFileLoaded.end()) { CHashString hszTypeName; //check filetype if( _tcsstr( szFileName, _T(".psh") ) ) { hszTypeName.Init( _T("CPixelShader") ); } else { hszTypeName.Init( _T("CVertexShader") ); } CREATEOBJECTPARAMS cop; cop.parentName = NULL; cop.typeName = &hszTypeName; cop.name = &hashFile; static DWORD msgHash_CreateObject = CHashString(_T("CreateObject")).GetUniqueID(); DWORD retval = m_ToolBox->SendMessage(msgHash_CreateObject, sizeof(CREATEOBJECTPARAMS), &cop, NULL, NULL); INITOBJECTPARAMS iop; iop.name = &hashFile; if( retval == MSG_HANDLED ) { static DWORD msgHash_InitObject = CHashString(_T("InitObject")).GetUniqueID(); retval = m_ToolBox->SendMessage(msgHash_InitObject, sizeof(INITOBJECTPARAMS), &iop, NULL, NULL); } ADDSHADERTOMANAGER astom; astom.m_Name = &hashFile; astom.m_CompType = &hszTypeName; if( retval == MSG_HANDLED ) { static DWORD msgHash_AddShader = CHashString(_T("AddShader")).GetUniqueID(); retval = m_ToolBox->SendMessage(msgHash_AddShader, sizeof(ADDSHADERTOMANAGER), &astom, NULL, NULL); } m_mFileLoaded.insert(pair<DWORD, bool>(hashFile.GetUniqueID(), true)); } return MSG_HANDLED_STOP; }
void NotaryPage::calculateNotaryID() { std::string fileName = ui->sendNotaryEntry->text().toStdString(); std::string fileHash = hashFile(fileName); // Warn if file is NULL if (fileHash == "") { QMessageBox::warning(this, tr("Notarize File"), tr("Unable to open file for hashing."), QMessageBox::Ok, QMessageBox::Ok); return; } ui->notaryIDEdit->setText(QString::fromStdString(fileHash)); }
void createIndex(Hashmap *map, DIR *directory) { if (directory == NULL) { printf("ERROR"); } struct dirent *ent; while ((ent = readdir(directory)) != NULL) { if (strcmp(ent->d_name, ".") == 0 || strcmp(ent->d_name, "..") == 0) { continue; } FILE *file = fopen(ent->d_name, "r"); exitIfError(ferror(file), "opening file during indexing"); char *hash = hashFile(file); exitIfError(fclose(file) == EOF, "closing file during indexing"); putInHashmap(map, hash, ent->d_name); } }
int main(int argc, char *argv[]) { stunHash(); for (int i = 1; i < argc; ++i) { QString path = QString::fromLocal8Bit(argv[i]); QFileInfo info(path); QTime t; t.start(); QByteArray result = hashFile(path); int ms = t.elapsed(); if (ms > 0) qDebug() << info.fileName() << result.toHex() << ms/1000.0 << "s" << (double(info.size()) / (1000.0 * ms)) << "MB/s"; } return 0; }
bool Cache::isCached(QString path, QString &code) { QString hash = hashFile(path); QSqlQuery query(db); if (!tryInsert(path, hash)) { query.exec("SELECT GenCode FROM MedusaCache WHERE Hash='" + hash + "'"); query.next(); if (query.isValid()) { code = query.value(0).toString(); return true; } else return changed(path, hash, code) ? false : true; } else return false; }
SHashedImage::SHashedImage(struct picture *picture) : QImage() { QUrl url = QUrl::fromUserInput(QString(picture->filename)); if(url.isLocalFile()) load(url.toLocalFile()); if (isNull()) { // Hash lookup. load(fileFromHash(picture->hash)); if (!isNull()) { QtConcurrent::run(updateHash, picture); } else { QtConcurrent::run(loadPicture, picture); } } else { QByteArray hash = hashFile(url.toLocalFile()); free(picture->hash); picture->hash = strdup(hash.toHex().data()); } }
void Scanner::scanRecursive(QDir &d, ReleaseFileList &r, QStack<QString> &dirname) { QDirIterator it(d); static QString pathDelim="/"; while (it.hasNext()) { it.next(); QFileInfo info = it.fileInfo(); if (info.isDir()) { if (info.fileName()[0]=='.') { continue; } QDir nd(info.filePath()); dirname.push(info.fileName()); scanRecursive(nd, r,dirname); dirname.pop(); } else { QFile file(info.filePath()); ReleaseFile rf; if (file.open(QIODevice::ReadOnly) <0) { throw 2; } rf.sha = hashFile(file); dirname.push( info.fileName() ); rf.name = qstackJoin( dirname, pathDelim); rf.size = info.size(); rf.exec = info.isExecutable(); r.push_back(rf); dirname.pop(); file.close(); } } }
int scan_path( char path[ PATH_MAX ], uint32_t tablevel ) { struct stat64 statdir, statfile; struct dirent *entry; DIR *dir; char fname[ PATH_MAX ], hash[ HASH_LEN ]; uint32_t len; int ret; struct hash_node *node; // add / at end of path len = strlen( path ); if( len == 0 || len > PATH_MAX ) { fprintf( stderr, "Got a bad path: |%s|\n", path ); return 1; } if( path[len-1] != '/' ) { strncpy( fname, path, sizeof( fname )); if( snprintf( path, PATH_MAX, "%s/", fname ) >= PATH_MAX ) { fprintf( stderr, "Path is to long: %s\n", path ); return 1; } } // try to stat if( scanlinks ) { // stat64 follows the symlink, thus our link check is always false if( stat64( path, &statdir ) != 0 ) { NORMAL( fprintf( stderr, "Path %s does not exist: %s\n", path, strerror( errno ))); return errno; } } else { if( lstat64( path, &statdir ) != 0 ) { NORMAL( fprintf( stderr, "Path %s does not exist: %s\n", path, strerror( errno ))); return errno; } } // make sure this is a directory if( !S_ISDIR( statdir.st_mode ) || S_ISLNK( statdir.st_mode )) { NORMAL( fprintf( stderr, "%s is not a directory\n", path )); if( S_ISLNK( statdir.st_mode )) NORMAL( fprintf( stderr, "Scanning links is disabled by defaults\n" )); return errno; } // open the directory if(( dir = opendir( path )) == NULL ) { NORMAL( fprintf( stderr, "Failed to open %s: %s\n", path, strerror( errno ))); return errno; } while(( entry = readdir( dir ))) { // skip . and .. if( strcmp( entry->d_name, "." ) == 0 || strcmp( entry->d_name, ".." ) == 0 ) { continue; } // build full file name // path is checked if it has a / at the end if( snprintf( fname, sizeof( fname ), "%s%s", path, entry->d_name ) >= sizeof( fname )) { fprintf( stderr, "File name is to long: %s\n", fname ); closedir( dir ); return 1; } // try to stat if( scanlinks ) { // stat64 follows the symlink, thus our link check is always false if( stat64( fname, &statfile ) != 0 ) { NORMAL( fprintf( stderr, "Failed to stat %s: %s\n", fname, strerror( errno ))); continue; } } else { if( lstat64( fname, &statfile ) != 0 ) { NORMAL( fprintf( stderr, "Failed to stat %s: %s\n", fname, strerror( errno ))); continue; } } if( S_ISREG( statfile.st_mode ) && !S_ISLNK( statfile.st_mode )) { VERBOSE( ptabs( tablevel ); printf( "%-30s %-10lld", entry->d_name, statfile.st_size ); fflush( stdout ); ); // get the files hash code if(( ret = hashFile( fname, hash )) != 0 ) { continue; } //VERBOSE( printf( " %s ", hash )); if(( node = find( hash )) == NULL ) { VERBOSE( printf( "Unmatched\n" )); add( hash, fname, statfile.st_ino ); } else { if( statfile.st_ino == node->inode ) { VERBOSE( printf( "Matched - Already Hardlink\n" )); } else { if( !verbose ) NORMAL( printf( "%s is ", fname )); NORMAL( printf( "Matched - Making Hardlink of %s: ", node->fname ); fflush( stdout)); if( !dryrun ) { if( unlink( fname ) != 0 ) { NORMAL( printf( "failed %s\n", strerror( errno ))); continue; } if( link( node->fname, fname ) != 0 ) { NORMAL( printf( "failed %s\n", strerror( errno ))); continue; } NORMAL( printf( "done\n")); } else { NORMAL( printf( "skipped\n")); } } } } else if ( S_ISDIR( statfile.st_mode ) && !S_ISLNK( statfile.st_mode )) {
/// \brief Adds a texture to the manager and returns a pointer to the object. If object already /// exists, increments its internal reference count and returns the object. Takes /// a structure of type TEXTUREOBJECTPARAMS DWORD CTextureManager::OnAddTexture(DWORD size, void *params) { //maybe change this to a loader? But texture objects should not exist in the hierarchy. //get the param structure TEXTUREOBJECTPARAMS *texObjParams; IBaseTextureObject * currentTexture = NULL; TEXTURENAMEMAP::iterator cur; texObjParams = (TEXTUREOBJECTPARAMS *)params; VERIFY_MESSAGE_SIZE(sizeof(TEXTUREOBJECTPARAMS), size); //look for it if( texObjParams->Name != NULL ) { // convert to safe file name StdString szFileName = texObjParams->Name->GetString(); szFileName.MakeSafeFileName(); CHashString hashFile(szFileName); //do we have it in the mapping already? TEXTURENAMEMAP::iterator itr = m_TextureNameMap.find( hashFile.GetUniqueID() ); if (itr != m_TextureNameMap.end()) currentTexture = itr->second; if( currentTexture != NULL ) { currentTexture->IncrementRefCount(); } else { if (texObjParams->bLoad) { if (m_currentTexMemArea == TEX_MEM_VIDEO) { //new texture //check extension if( _tcsstr( hashFile.GetString(), ".hdr" )!= NULL ) { static CHashString texName(_T("CDX9TextureObject")); currentTexture = (ITextureObject*)CreateTextureObject( &hashFile, &texName); assert( currentTexture ); currentTexture->SetTextureName( &hashFile ); currentTexture->LoadFromFile(hashFile.GetString() ); }else if( _tcsstr( hashFile.GetString(), ".ant" )!= NULL ) { static CHashString aniTexObj(_T("CAnimatedTextureObject") ); currentTexture = CreateTextureObject( &hashFile, &aniTexObj); currentTexture->LoadFromFile(hashFile.GetString() ); }else if( _tcsstr( hashFile.GetString(), _T(".dds") ) != NULL ) { //we can automatically load cubemap textures if it is a cubemap texture currentTexture = LoadCubeDDSTexture( &hashFile ); } } // use the internal loader as it deals with a lot of issues // (ie. linear vs. tiled texture alignments/restrictions) for us. // and gets around the bug in DevIL on small mip levels of textures if( !currentTexture ) { static CHashString DX9TexObj(_T("CDX9TextureObject")); currentTexture = CreateTextureObject( &hashFile, &DX9TexObj); currentTexture->SetTextureName( &hashFile ); if (!currentTexture->LoadFromFile( hashFile.GetString() )) { DeleteTextureObject( currentTexture ); currentTexture = NULL; } } //try loading file by extension if( !currentTexture ) { currentTexture = LoadTextureByExtension( &hashFile ); } if( !currentTexture ) { // log message about creating or allocating memory m_ToolBox->Log( LOGERROR, _T("Could not create texture %s\n"), hashFile.GetString() ); return MSG_ERROR; } } else { currentTexture = texObjParams->TextureObjectInterface; currentTexture->IncrementRefCount(); } //add to internal list m_TextureNameMap[hashFile.GetUniqueID()] = currentTexture; } //set the return value texObjParams->TextureObjectInterface = currentTexture; } else //No name/filename specified, return nothing { texObjParams->TextureObjectInterface = NULL; } return MSG_HANDLED_PROCEED; }
int main(int argc, char *argv[]) { //QMultiHash<QString, StringPair> hashTable; QHash<QString, QSet<QString> > predictTable; QHash<StringPair, ulong> countTable; QVector<QString> tagsV; QHash<ulong, QVector<StringPair> > hashTb; tagsV.clear(); QFile fin(argv[1]); QTextStream out(stdout); QTextStream err(stderr); if (argc != 3) { out << "Usage: genhashtable dictfile.txt hashtablefile.txt" << endl; return 0; } if (!fin.open(QIODevice::ReadOnly | QIODevice::Text)) { err << "ERROR: input file not found" << endl; return 1; } QTextStream sfin(&fin); sfin.setCodec("UTF-8"); out.setCodec("UTF-8"); QString line = sfin.readLine(); QStringList lineParts; bool isfirst = false; QString form, normalForm, tags; while (!line.isNull()) { lineParts = line.split(QRegExp("[\t ]"), QString::SkipEmptyParts); if (isfirst) { if (!(lineParts.size() < 2 || lineParts[1].startsWith("VERB,") || lineParts[1].startsWith("PRTF,") || lineParts[1].startsWith("PRTS,") || lineParts[1].startsWith("GRND,"))) { normalForm = lineParts[0]; } isfirst = false; } if (lineParts.size() > 2 && lineParts[1].startsWith("INFN,")) { normalForm = lineParts[0]; } if (lineParts.size() < 1) { line = sfin.readLine(); continue; } if (lineParts.size() == 1) { isfirst = true; line = sfin.readLine(); continue; } form = lineParts[0]; QChar yo = QString::fromUtf8("Ё")[0]; QChar ye = QString::fromUtf8("Е")[0]; form.replace(yo, ye, Qt::CaseInsensitive); tags = lineParts[1]; if (lineParts.size() == 3) { tags += ("," + lineParts[2]); } if (tagsV.indexOf(tags) == -1) { tagsV.append(tags); } hashTb[tagsV.indexOf(tags)].append(StringPair(normalForm, form)); //hashTable.insert(form, StringPair(normalForm, tags)); predictTable[form.right(3)].insert(tags); ++countTable[StringPair(form.right(3), tags)]; line = sfin.readLine(); } fin.close(); //out << "Table size: " << hashTable.size() << endl; QString result(""); for (int i = 0; i < tagsV.size(); ++i) { result += ("& " + tagsV[i] + " "); for (int j = 0; j < hashTb[i].size(); ++j) { result += (hashTb[i][j].first + " " + hashTb[i][j].second + " "); } } result += "\n----------"; for (QHash<QString, QSet<QString> >::const_iterator itr = predictTable.begin(); itr != predictTable.end(); ++itr) { for (QSet<QString>::const_iterator jtr = itr.value().begin(); jtr != itr.value().end(); ++jtr) { result += (" " + itr.key() + " " + *jtr); } } result += "\n----------"; for (QHash<StringPair, ulong>::const_iterator itr = countTable.begin(); itr != countTable.end(); ++itr) { result += (" " + itr.key().first + " " + itr.key().second + " " + QString::number(itr.value())); } result += "\n----------"; QFile hashFile(argv[2]); hashFile.open(QIODevice::WriteOnly); QTextCodec *cp1251 = QTextCodec::codecForName("CP1251"); hashFile.write(qCompress(cp1251->fromUnicode(result))); hashFile.flush(); hashFile.close(); return 0; }
std::string getMd5(const boost::filesystem::path& path) { MD5 algorithm; hashFile(path, algorithm); return algorithm.getHash(); }
std::string getCrc(const boost::filesystem::path& path) { CRC32 algorithm; hashFile(path, algorithm); return algorithm.getHash(); }
int walk_recur(char *dname, regex_t *reg, int spec, void (*hashFile)(char *file)) { struct dirent *dent; DIR *dir; struct stat st; char fn[FILENAME_MAX]; int res = WALK_OK; int len = (int)strlen(dname); if (len >= FILENAME_MAX - 1) return WALK_NAMETOOLONG; strcpy(fn, dname); fn[len++] = '/'; if (!(dir = opendir(dname))) { warn("can't open %s", dname); return WALK_BADIO; } errno = 0; while ((dent = readdir(dir))) { if (!(spec & WS_DOTFILES) && dent->d_name[0] == '.') continue; if (!strcmp(dent->d_name, ".") || !strcmp(dent->d_name, "..")) continue; strncpy(fn + len, dent->d_name, FILENAME_MAX - len); if (lstat(fn, &st) == -1) { warn("Can't stat %s", fn); res = WALK_BADIO; continue; } /* don't follow symlink unless told so */ if (S_ISLNK(st.st_mode) && !(spec & WS_FOLLOWLINK)) continue; /* will be false for symlinked dirs */ if (S_ISDIR(st.st_mode)) { /* recursively follow dirs */ if ((spec & WS_RECURSIVE)) walk_recur(fn, reg, spec,hashFile); if (!(spec & WS_MATCHDIRS)) continue; } //printf("%s\n",fn); if(S_ISREG(st.st_mode)){ printf("Considering file %s\n",fn); hashFile(fn); //printf("ISRED IS %d \n",S_IFREG); } /* pattern match */ if (!regexec(reg, fn, 0, 0, 0)){ // puts(fn); } } if (dir) closedir(dir); return res ? res : errno ? WALK_BADIO : WALK_OK; }
int main() { struct sockaddr_in server; struct sockaddr_in dest; int socket_fd, client_fd,num; socklen_t size; SSL_CTX *ctx; /******* START SSL ***************/ /* http://mooon.blog.51cto.com/1246491/909932 */ /* SSL Libraries Init */ SSL_library_init(); /* add all SSL algorithms */ OpenSSL_add_all_algorithms(); /* add all SSL ciphers */ OpenSSL_add_all_ciphers(); /* add all digests */ OpenSSL_add_all_digests(); /* load all SSL errors */ SSL_load_error_strings(); /* Build SSL_CTX -> SSL Content Text * SSLv2_server_method() or SSLv3_server_method() relative to SSL V2 * and SSL V3 */ ctx = SSL_CTX_new(SSLv23_server_method()); if(ctx == NULL){ ERR_print_errors_fp(stdout); exit(EXIT_FAILURE); } /* Load the server certificate into the SSL_CTX structure */ if(SSL_CTX_use_certificate_file(ctx,RSA_SERVER_CERT,SSL_FILETYPE_PEM) <= 0){ ERR_print_errors_fp(stdout); exit(EXIT_FAILURE); } /* Load the private-key corresponding to the server certificate */ if(SSL_CTX_use_PrivateKey_file(ctx,RSA_SERVER_KEY,SSL_FILETYPE_PEM) <= 0){ ERR_print_errors_fp(stdout); exit(EXIT_FAILURE); } /* Check if the server certificate and private-key matches */ if(!SSL_CTX_check_private_key(ctx)){ ERR_print_errors_fp(stdout); exit(EXIT_FAILURE); } /*********** END SSL ****************/ int yes =1; /* Open a socket to listen */ if ((socket_fd = socket(AF_INET, SOCK_STREAM, 0))== -1) { fprintf(stderr, "Socket failure!!\n"); exit(EXIT_FAILURE); } if (setsockopt(socket_fd, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(int)) == -1) { perror("setsockopt"); exit(EXIT_FAILURE); } /* init memory for server and dest */ memset(&server, 0, sizeof(server)); memset(&dest,0,sizeof(dest)); server.sin_family = AF_INET; //same to PF_INET server.sin_port = htons(PORT); server.sin_addr.s_addr = INADDR_ANY; /* BIND SOCKET */ if ((bind(socket_fd, (struct sockaddr *)&server, sizeof(struct sockaddr )))== -1) { //sizeof(struct sockaddr) fprintf(stderr, "Binding Failure\n"); exit(EXIT_FAILURE); } /* START LISTENING */ if ((listen(socket_fd, BACKLOG))== -1){ fprintf(stderr, "Listening Failure\n"); exit(EXIT_FAILURE); } while(1) { SSL *ssl; size = sizeof(struct sockaddr_in); /* Waiting for client to connect */ if ((client_fd = accept(socket_fd, (struct sockaddr *)&dest, &size))==-1 ) { perror("accept"); continue; //exit(EXIT_FAILURE); } else{ printf("Server got connection from client %s, port %d, socket %d\n", inet_ntoa(dest.sin_addr),ntohs(dest.sin_port),client_fd); } /* /connection complete */ /* create a new ssl based on ctx */ ssl = SSL_new(ctx); /* add socket : client_fd to SSL */ SSL_set_fd(ssl,client_fd); /* Build up SSL connection */ if(SSL_accept(ssl) == -1){ perror("accept"); SSL_shutdown(ssl); SSL_free(ssl); close(client_fd); continue; //exit(EXIT_FAILURE); } /******* START PROCESSING DATA *************/ /* read header - then do action based on header parsing */ char header_buf[HEADER_SIZE]; int len = HEADER_SIZE; if ((num = recv_all(ssl, (unsigned char *)header_buf, &len))== -1) { printf("Read header failed\n"); perror("recv"); SSL_shutdown(ssl); SSL_free(ssl); close(client_fd); continue; //exit(EXIT_FAILURE); } char *hr = NULL; hr = malloc(3); SSL_read(ssl, hr, sizeof(hr)); if(strcmp("100",hr)){ printf("Header receiving failed\n"); SSL_write(ssl,"-1",strlen("-1")); /* Close SSL Connection */ SSL_shutdown(ssl); /* Release SSL */ SSL_free(ssl); //Close Connection Socket close(client_fd); continue; } else{ printf("Header received successfully\n"); } /* unpack header string */ header h; if (unpack_header_string(header_buf, &h) == -1) { fprintf(stderr, "[SERVER] Could not unpack header information from client\n"); h.action = FAIL_ERROR; //exit(EXIT_FAILURE); } if (h.action == FAIL_ERROR) { printf("Header action is FAIL ERROR\n"); SSL_write(ssl,"-1",strlen("-1")); /* Close SSL Connection */ SSL_shutdown(ssl); /* Release SSL */ SSL_free(ssl); //Close Connection Socket close(client_fd); continue; } //inform client header unpacked successfully SSL_write(ssl,"100",strlen("100")); printf("Header unpacked successfully\n"); // header part end // if client requests to uplaod file if (h.action == ADD_FILE) { char *target = NULL; target = malloc(BLOCK_SIZE); sprintf(target, "%s/%s", SERVER_FILE_DIR, h.file_name); printf("[SERVER] Adding file %s\n", target); receive_file(ssl, target, h.file_size); free(target); } else if (h.action == FETCH_FILE) { char *target = NULL; target = malloc(BLOCK_SIZE); sprintf(target, "%s/%s", SERVER_FILE_DIR, h.file_name); printf("[SERVER] Fetching file %s\n", target); FILE *fp; if (!(fp = fopen(target, "r"))) { perror("fopen"); /* Close SSL Connection */ SSL_shutdown(ssl); /* Release SSL */ SSL_free(ssl); //Close Connection Socket close(client_fd); continue; //exit(EXIT_FAILURE); } free(target); // get file's protection rating to compare to // client's requested circumference int protectionRating = getProtectionRating(h.file_name); header h_send; if (protectionRating >= h.circ) { h_send.action = ADD_FILE; } else { h_send.action = FAIL_ERROR; // client will fail out } h_send.file_size = get_file_size(fp); h_send.file_name = h.file_name; h_send.certificate = " "; send_header(ssl, h_send); if (protectionRating >= h.circ) send_file(ssl, fp); fclose(fp); } else if (h.action == UPLOAD_CERT) { char target[MAXSIZE]; sprintf(target, "%s/%s_crt.pem", SERVER_CERT_DIR, h.file_name); printf("Receiving cert and storing: %s\n", target); receive_file(ssl, target, h.file_size); }// if client requests to list files else if (h.action == LIST_FILE) { char **files; size_t count; unsigned int i; count = file_list(SERVER_FILE_DIR, &files); for (i = 0; i < count; i++) { char *send_str = NULL; send_str = malloc(MAXSIZE); int protectionRating = getProtectionRating(files[i]); if (protectionRating >= h.circ) { sprintf(send_str, "Protected (c = %i): %s",protectionRating,files[i]); } else { sprintf(send_str, "Unprotected (c = %i): %s",protectionRating,files[i]); } send_message(ssl, send_str); free(send_str); } printf("File list transmitting completed.\n"); close(client_fd); printf("Client connection closed.\n"); } /* if client requires to vouch a file * https://gitorious.org/random_play/random_play/source/b9f19d4d9e8d4a9ba0ef55a6b0e2113d1c6a5587:openssl_sign.c */ else if (h.action == VOUCH_FILE){ // vouch for this file const char *clearTextFileName = h.file_name; int isCertFile = isNameCertFile(clearTextFileName); // vouch using this certificate char *certificate_file_name = h.certificate; char *cert_loc = NULL; cert_loc = malloc(MAXSIZE); sprintf(cert_loc, "%s/%s", SERVER_CERT_DIR, certificate_file_name); if (!check_if_file_exists(cert_loc)) { char *message = NULL; message = malloc(MAXSIZE); sprintf(message, "Unable to locate %s certificate on the server. Please upload using -a\n", cert_loc); SSL_write(ssl, message,strlen(message)); free(message); /* Close SSL Connection */ SSL_shutdown(ssl); /* Release SSL */ SSL_free(ssl); //Close Connection Socket close(client_fd); continue; // should notify client here somehow } else{ char *message = NULL; message = malloc(MAXSIZE); sprintf(message, "Located %s certificate on the server. \n", cert_loc); SSL_write(ssl, message,strlen(message)); free(message); } free(cert_loc); char *target = NULL; target = malloc(MAXSIZE); if (isCertFile) { sprintf(target, "%s/%s", SERVER_CERT_DIR, h.file_name); } else { sprintf(target, "%s/%s", SERVER_FILE_DIR, h.file_name); } unsigned char *md5Value = NULL; md5Value = malloc(MD5_DIGEST_LENGTH); if(hashFile(md5Value, (const char *)target)!=0){ printf("Couldn't open file"); free(target); /* Close SSL Connection */ SSL_shutdown(ssl); /* Release SSL */ SSL_free(ssl); //Close Connection Socket close(client_fd); continue; } free(target); send_message(ssl, (char *)md5Value); unsigned char signature[MAXSIZE]; SSL_read(ssl, signature, 128); char *sig_name = NULL; sig_name = malloc(MAXSIZE); // keep certificate signatures with certificates if (isCertFile) { sprintf(sig_name, "%s/%s_%s.sig", SERVER_CERT_DIR, clearTextFileName, certificate_file_name); } else { sprintf(sig_name, "%s/%s_%s.sig", SERVER_SIG_DIR, clearTextFileName, certificate_file_name); } if (writeSig(signature, sig_name) != 0) { fprintf(stderr, "Could not save signature file\n"); free(sig_name); SSL_write(ssl,"-1",strlen("-1")); /* Close SSL Connection */ SSL_shutdown(ssl); /* Release SSL */ SSL_free(ssl); //Close Connection Socket close(client_fd); continue; //exit(EXIT_FAILURE); } else{ printf("Sig loc: %s\n", sig_name); SSL_write(ssl,"100",strlen("100")); } free(sig_name); } else if (h.action == VERIFY_FILE){ // test verification of signature files char signatoryCertName[MAXSIZE]; sprintf( signatoryCertName, "%s_crt.pem", h.certificate ); const char *clearText = h.file_name; if(!verifySig(signatoryCertName,clearText)){ printf("Verify failed\n"); } } else if (h.action == FIND_ISSUER){ char certPath[MAXSIZE]; sprintf( certPath, "%s", h.certificate ); } else if (h.action == TEST_RINGOFTRUST) { ringOfTrust(h.file_name); } /********** END DATA PROCESSING **************/ free(h.certificate); free(h.file_name); /* Close SSL Connection */ SSL_shutdown(ssl); /* Release SSL */ SSL_free(ssl); //Close Connection Socket close(client_fd); } //Outer While /* Close listening socket */ close(socket_fd); /* Release CTX */ SSL_CTX_free(ctx); return 0; } //End of main