void saveRBC( matrix *R, rep *ri, char *filename ){ size_t i; unint nr = R->r; FILE *fp = fopen(filename, "wb"); if( !fp ){ fprintf(stderr, "unable to open output file\n"); exit(1); } safeWrite( &nr, sizeof(unint), 1, fp ); for( i=0; i<nr; i++ ){ unint len = ri[i].len; safeWrite( &len, sizeof(unint), 1, fp ); safeWrite( ri[i].lr, sizeof(unint), len, fp ); safeWrite( ri[i].dists, sizeof(real), len, fp ); safeWrite( &(ri[i].start), sizeof(unint), 1, fp ); safeWrite( &(ri[i].radius), sizeof(real), 1, fp ); } safeWrite( &(R->r), sizeof(unint), 1, fp ); safeWrite( &(R->c), sizeof(unint), 1, fp ); safeWrite( R->mat, sizeof(real), sizeOfMat(*R), fp ); fclose(fp); }
void Encrypt(PK0304* le, AE_EXTRA* ae, char* password) { char *salt, *key1, *key2, *check, digest[40]; u32 key_len = KeySize*2 + 2; u32 dig_len = 40; salt = BUF; key1 = salt+SaltSize; key2 = key1+KeySize; check = key2+KeySize; /* Gets a random salt (8-16 byte) */ sprng_read(salt, SaltSize, 0); /* Generates 2 keys for AES and HMAC, plus 2-byte password verification value */ if (pkcs_5_alg2(password, strlen(password), salt, SaltSize, 1000, 0, key1, &key_len) != CRYPT_OK) Z_ERROR("Failed to derive encryption keys"); // dump("salt", salt, SaltSize); // dump("key", key1, KeySize); if (ctr_start(0, IV, key1, KeySize, 0, CTR_COUNTER_LITTLE_ENDIAN, &ctr) != CRYPT_OK) Z_ERROR("Failed to setup AES CTR encoder"); #ifdef GLADMAN_HMAC hmac_sha1_begin(&hmac); hmac_sha1_key(key2, KeySize, &hmac); #else if (hmac_init(&hmac, 0, key2, KeySize) != CRYPT_OK) Z_ERROR("Failed to setup HMAC-SHA1"); #endif if (AE2) le->Crc32 = 0; le->Flag |= 1; le->CompMethod = 99; le->ExtraLen += 11; le->CompSize += SaltSize + 12; /* variable salt, fixed password check and hmac */ safeWrite(ZOUT, le, sizeof(PK0304)); fileCopy(ZOUT, ZIN, le->NameLen+le->ExtraLen-11); safeWrite(ZOUT, ae, 11); safeWrite(ZOUT, salt, SaltSize); safeWrite(ZOUT, check, 2); /* encrypt contents */ fileFilter(ZOUT, ZIN, le->CompSize-SaltSize-12); #ifdef GLADMAN_HMAC hmac_sha1_end(digest, dig_len, &hmac); #else if (hmac_done(&hmac, digest, &dig_len) != CRYPT_OK) Z_ERROR("Failed to computate HMAC"); #endif safeWrite(ZOUT, digest, 10); ctr_done(&ctr); }
void relay(int sock) { /* Read from socket, echo to stdout. Read from input, echo to sock. When eof(input) shutdown that direction of sock. If read on sock fails, assume it is because self process did a shutdown; then stop waiting for output from him and also stop relaying input to him. */ trace("Starting to relay.\n"); if (fork()) { char ch; for (;;) { char buf[BUFSIZ]; int count = read(sock, buf, sizeof(buf)); if (count <= 0) break; write(1, buf, count); } trace("read failed - assuming shutdown"); /* Now exit, thereby terminating parent (and child). */ } else { int ich; /* int to be able to distinguish EOF. */ while((ich = getchar()) != EOF) { char ch = ich; safeWrite(sock, &ch, sizeof(ch)); } shutdown(sock, 1); } }
int _evlWriteTemplate(const template_t *t, const char *path) { tfile_t *tf; size_t fileSize; int fd; int nBytes; tf = allocTfile(path, 1000); writeTemplate(t, tf); fileSize = tf->tf_next - tf->tf_buf; fd = open(path, O_WRONLY|O_CREAT|O_TRUNC, 0644); if (fd < 0) { perror(path); freeTfile(tf); return -1; } nBytes = safeWrite(fd, tf->tf_buf, fileSize); assert(nBytes == fileSize); freeTfile(tf); (void) close(fd); return 0; }
float* saveMatrix(const char* filename, float* buf, size_t height, size_t width) { int fd = safeOpen(filename, O_WRONLY|O_CREAT, 0777); size_t count = width * height * sizeof(float); ssize_t num = safeWrite(fd, buf, count, "save matrix"); close(fd); return buf; }
static int flushGrain(StreamOptimizedDiskInfo *sodi) { int ret; uint32_t oldLoc; if (sodi->writer.grainBufferNr == ~0ULL) { return 0; } if (sodi->writer.grainBufferValidEnd == 0) { return 0; } ret = fillGrain(sodi); if (ret) { return ret; } oldLoc = __le32_to_cpu(sodi->writer.gtInfo.gt[sodi->writer.grainBufferNr]); if (oldLoc != 0) { fprintf(stderr, "Cannot update already written grain\n"); return -1; } if (!isZeroed(sodi->writer.grainBuffer, sodi->writer.grainBufferValidEnd)) { size_t dataLen; uint32_t rem; SparseGrainLBAHeaderOnDisk *grainHdr = sodi->writer.zlibBuffer.grainHdr; sodi->writer.gtInfo.gt[sodi->writer.grainBufferNr] = __cpu_to_le32(sodi->writer.curSP); if (deflateReset(&sodi->writer.zstream) != Z_OK) { fprintf(stderr, "DeflateReset failed\n"); return -1; } sodi->writer.zstream.next_in = sodi->writer.grainBuffer; sodi->writer.zstream.avail_in = sodi->writer.grainBufferValidEnd; sodi->writer.zstream.next_out = sodi->writer.zlibBuffer.data + sizeof *grainHdr; sodi->writer.zstream.avail_out = sodi->writer.zlibBufferSize - sizeof *grainHdr; if (deflate(&sodi->writer.zstream, Z_FINISH) != Z_STREAM_END) { fprintf(stderr, "Deflate failed\n"); return -1; } dataLen = sodi->writer.zstream.next_out - sodi->writer.zlibBuffer.data; grainHdr->lba = sodi->writer.grainBufferNr * sodi->diskHdr.grainSize; grainHdr->cmpSize = __cpu_to_le32(dataLen - sizeof *grainHdr); rem = dataLen & (VMDK_SECTOR_SIZE - 1); if (rem != 0) { rem = VMDK_SECTOR_SIZE - rem; memset(sodi->writer.zstream.next_out, 0, rem); dataLen += rem; } if (!safeWrite(sodi->writer.fd, grainHdr, dataLen)) { return -1; } sodi->writer.curSP += dataLen / VMDK_SECTOR_SIZE; } return 0; }
static int StreamOptimizedClose(DiskInfo *self) { StreamOptimizedDiskInfo *sodi = getSODI(self); uint32_t cid; char *descFile; SparseExtentHeaderOnDisk onDisk; if (flushGrain(sodi)) { goto failAll; } writeEOS(&sodi->writer); if (lseek(sodi->writer.fd, sodi->writer.gdOffset * VMDK_SECTOR_SIZE, SEEK_SET) == -1) { goto failAll; } if (!safeWrite(sodi->writer.fd, sodi->writer.gtInfo.gd, (sodi->writer.gtInfo.GDsectors + sodi->writer.gtInfo.GTsectors * sodi->writer.gtInfo.GTs) * VMDK_SECTOR_SIZE)) { goto failAll; } do { cid = mrand48(); /* * Do not accept 0xFFFFFFFF and 0xFFFFFFFE. They may be interpreted by * some software as no parent, or disk full of zeroes. */ } while (cid == 0xFFFFFFFFU || cid == 0xFFFFFFFEU); descFile = makeDiskDescriptorFile(sodi->writer.fileName, sodi->diskHdr.capacity, cid); if (pwrite(sodi->writer.fd, descFile, strlen(descFile), sodi->diskHdr.descriptorOffset * VMDK_SECTOR_SIZE) != (ssize_t)strlen(descFile)) { free(descFile); goto failAll; } free(descFile); /* * Write everything out as it should be, except that file signature is * vmdk, rather than VMDK. Then flush everything to the media, and finally * rewrite header with proper VMDK signature. */ setSparseExtentHeader(&onDisk, &sodi->diskHdr, true); if (pwrite(sodi->writer.fd, &onDisk, sizeof onDisk, 0) != sizeof onDisk) { goto failAll; } if (fsync(sodi->writer.fd) != 0) { goto failAll; } setSparseExtentHeader(&onDisk, &sodi->diskHdr, false); if (pwrite(sodi->writer.fd, &onDisk, sizeof onDisk, 0) != sizeof onDisk) { goto failAll; } if (fsync(sodi->writer.fd) != 0) { goto failAll; } return StreamOptimizedFinalize(sodi); failAll: StreamOptimizedAbort(&sodi->hdr); return -1; }
static bool writeSpecial(SparseVmdkWriter *writer, uint32_t marker, SectorType length) { SparseSpecialLBAHeaderOnDisk *specialHdr = writer->zlibBuffer.specialHdr; memset(writer->zlibBuffer.data, 0, VMDK_SECTOR_SIZE); specialHdr->lba = __cpu_to_le64(length); specialHdr->type = __cpu_to_le32(marker); return safeWrite(writer->fd, specialHdr, VMDK_SECTOR_SIZE); }
void finMachineSimple(int from1, char *nom1, int status, int from2, int to2, int pid2, char *nom2, FILE *logFile){ int nbRead; char *coup1 = malloc(513 * sizeof(char)); char *coup2 = malloc(513 * sizeof(char)); struct rusage infoFils; double uFils1, sFils1, uFils2, sFils2; printf("Les %s ont termine de jouer: %d!\n",nom1,WEXITSTATUS(status)); getrusage(RUSAGE_CHILDREN,&infoFils); /* on recupere des secondes et des micro secondes pour le temps CPU passe * en calculs utilisateurs et en appel de fonctions systeme du fils 1 */ sFils1 = ((double) infoFils.ru_stime.tv_sec) + ((double) infoFils.ru_stime.tv_usec)/1000000; uFils1 = ((double) infoFils.ru_utime.tv_sec) + ((double) infoFils.ru_utime.tv_usec)/1000000; printf("Les %s ont utilise %lf sec de systeme et %lf de temps utilisateur\n", nom1,sFils1,uFils1); nbRead = read(from1,coup1,512); if (nbRead > 0){ coup1[nbRead] = '\0'; printf("Les %s ont un dernier message: %s",nom1,coup1); safeWrite(to2,coup1); if (logFile != NULL){ fprintf(logFile,coup1); fflush(logFile); } } sleep(1); /* on attend une seconde que l'autre ait aussi termine ! */ if (waitpid(pid2,&status,WNOHANG) == 0){ printf("Cependant, les %s n'ont pas termine de jouer ... tant pis.\n",nom2); /* on les tue */ kill(pid2,SIGKILL); waitpid(pid2,&status,WNOHANG); } else { printf("Les %s on aussi termine: %d!\n",nom2,WEXITSTATUS(status)); } getrusage(RUSAGE_CHILDREN,&infoFils); /* idem, sauf qu'on recupere la somme du fils 1 et du fils 2 ... */ sFils2 = ((double) infoFils.ru_stime.tv_sec) + ((double) infoFils.ru_stime.tv_usec)/1000000; uFils2 = ((double) infoFils.ru_utime.tv_sec) + ((double) infoFils.ru_utime.tv_usec)/1000000; /* idem, sauf qu'on recupere la somme du fils 1 et du fils 2 */ sFils2 = sFils2 - sFils1; uFils2 = uFils2 - uFils1; printf("Les %s ont utilise %lf sec de systeme et %lf de temps utilisateur\n", nom2,sFils2,uFils2); nbRead = read(from2,coup2,512); if(nbRead > 0){ coup2[nbRead] = '\0'; printf("Les %s ont un dernier message: %s",nom2,coup2); if (logFile != NULL){ fprintf(logFile,coup2); fflush(logFile); } } }
void _fileCopy(FILE* fOut, FILE* fIn, u32 n, char filtering) { #ifndef DOS_16 #define BLOCK 64*1024 #else #define BLOCK 1*1024 #endif if (!IoBuF) { IoBuF = (char*) xmalloc(BLOCK); } while (n > BLOCK) { safeRead(IoBuF, fIn, BLOCK); if (filtering) filter(IoBuF, BLOCK); safeWrite(fOut, IoBuF, BLOCK); n -= BLOCK; } safeRead(IoBuF, fIn, n); if (filtering) filter(IoBuF, n); safeWrite(fOut, IoBuF, n); }
int joueMM(int taille, char *p1, char *p2, char *log){ FILE *logFile = NULL; if (log != NULL){ printf("fichier d'enregistrement: %s\n",log); logFile = fopen(log,"w"); } int versProgrammeA[2], versProgrammeB[2]; int deProgrammeA[2], deProgrammeB[2]; pipe(versProgrammeA); pipe(deProgrammeA); int pidA = fork(); if (pidA == -1){ perror("Fork n'a pas reussi"); return(-1); } else if (pidA == 0){ /* fils A: les blancs */ dup2(versProgrammeA[0],STDIN_FILENO); dup2(deProgrammeA[1],STDOUT_FILENO); close(versProgrammeA[1]); close(deProgrammeA[0]); fclose(logFile); char t[40]; sprintf(t,"%d",taille); execlp(p1,p1,t,"grilleOn","ia","B",(char *) NULL); perror("Pas reussi a executer le programme A. Desole"); return -4; } else { /* pere */ pipe(versProgrammeB); pipe(deProgrammeB); close(versProgrammeA[0]); close(deProgrammeA[1]); int pidB = fork(); if (pidB == -1){ perror("Fork 2 n'a pas reussi"); return -1; /* le fils A est tue quand le pere meurt */ } else if (pidB == 0) { /* fils B: les noirs */ close(versProgrammeA[1]); close(deProgrammeA[0]); close(versProgrammeB[1]); close(deProgrammeB[0]); fclose(logFile); dup2(versProgrammeB[0],STDIN_FILENO); dup2(deProgrammeB[1],STDOUT_FILENO); char t[40]; sprintf(t,"%d",taille); execlp(p2,p2,t,"grilleOff","ia","N",(char *) NULL); perror("Pas reussi a executer le programme B. Desole"); return -5; } else { /* le pere */ close(versProgrammeB[0]); close(deProgrammeB[1]); char *coupBlanc = malloc(513 * sizeof(char)); char *coupNoir = malloc(513 * sizeof(char)); int nbRead; int status; int changed; int i=0; do { changed = waitpid(pidA,&status,WNOHANG); if (changed == 0) { nbRead = read(deProgrammeA[0],coupBlanc,512); coupBlanc[nbRead] = '\0'; if (nbRead >= 5){ printf("Les blancs declarent: %s",coupBlanc); } else { /* un coup legal: colonne, ligne, \n et \0 */ printf("Les blancs jouent: %s",coupBlanc); } safeWrite(versProgrammeB[1],coupBlanc); if (logFile != NULL){ fprintf(logFile,coupBlanc); fflush(logFile); } changed = waitpid(pidB,&status,WNOHANG); if (changed == 0){ nbRead = read(deProgrammeB[0],coupNoir,512); coupNoir[nbRead] = '\0'; if (nbRead >= 5){ printf("Les noirs declarent: %s",coupNoir); } else { /* un coup legal: colonne, ligne, \n et \0 */ printf("Les noirs jouent: %s",coupNoir); } /* tester si on peut ecrire avant de le faire ! Sinon ca plante */ safeWrite(versProgrammeA[1],coupNoir); if (logFile != NULL){ fprintf(logFile,coupNoir); fflush(logFile); } } else { finMachineSimple(deProgrammeB[0],"noirs",status,deProgrammeA[0],versProgrammeA[1],pidA,"blancs",logFile); } } else { finMachineSimple(deProgrammeA[0],"blancs",status,deProgrammeB[0],versProgrammeB[1],pidB,"noirs",logFile); } } while (changed == 0); free(coupNoir); free(coupBlanc); if (logFile != NULL){ fprintf(logFile,"\n---- partie terminee ----\n "); fflush(logFile); fclose(logFile); } close(versProgrammeA[1]); close(deProgrammeA[0]); close(versProgrammeB[1]); close(deProgrammeB[0]); return 0; } // fin second fork } // fin premier fork }
// Parameters: lpszProjectDirectory ignored if this lang file already exists // otherwise, it tells us where to put it (and create a directory for it if needed) BOOL CCarlaLanguage::save(LPCTSTR lpszProjectDirectory) { notifyIfNotConsistent(); // jdh 17 Sept 2001 added // if we haven't saved this file before, determine where to put it if(m_mfs.m_sCtrlFilesDirectory.GetLength() ==0 ) m_mfs.m_sCtrlFilesDirectory = getLanguageDirectory(lpszProjectDirectory ); else if(m_mfs.m_sCtrlFilesDirectory != getLanguageDirectory(lpszProjectDirectory)) { // we get this when the whole project has been moved. m_mfs.m_sCtrlFilesDirectory = getLanguageDirectory(lpszProjectDirectory); } CSafeStream safeWrite(getFilePath()); ofstream& fout = safeWrite.openStream(); if(!fout.is_open()) { CString s(_T("Couldn't save the language file: ")); s += getFilePath(); MessageBox( NULL, s, NULL, MB_ICONERROR | MB_OK); return FALSE; } USES_CONVERSION_U8; fout << "\\id This file contains information about a CarlaStudio language.\n"; fout << "\\co You should normally not attempt to edit this file.\n"; fout << "\\formatversion 1\n"; fout << "\\name " << T2CU8(m_sName) << "\n"; fout << "\\abrev " << T2CU8(m_sAbrev) << "\n"; //outputBool(fout, "CopyItxToSrcDir", m_bCopyInterlinearToSrcDir); //outputBool(fout, "LeaveNonGoalFilesInTemp", m_bLeaveNonGoalsInTempDir); //fout << "\\outputProcessingFlags " << m_dwOutputProcessingFlags << '\n'; m_pDoc->writeParams(fout); m_displayInfo.write(fout); fout << "\\interface "; if(m_pDoc->m_pCurrentInterface == m_pDoc->m_pCarlaMenuInterface) fout << "carlaMenuStyle\n"; else fout << "funtionalStyle\n"; if(m_pFilesWiz) // added mar 11 99 for beta 7 { if(!m_pFilesWiz->m_analysisPage.m_sCommentChar.IsEmpty()) // rde270 the comment char is limited to ANSI m_commonModel.m_cCommentChar = (char)m_pFilesWiz->m_analysisPage.m_sCommentChar.GetAt(0); } fout << "\\commentChar " << m_commonModel.m_cCommentChar << "\n"; // added feb 99 #define WRITEPREFS(M,LIST) fout << "\\"<<M<<" "<< T2CU8(LIST.getPrefsField()) <<'\n'; WRITEPREFS("adhocPairsPrefs",m_analysisModel.adhocPairs); WRITEPREFS("rtCatPairsPrefs",m_analysisModel.compoundRootCatPairs); WRITEPREFS("ftestPrefs",m_analysisModel.finalTests); WRITEPREFS("ptestPrefs",m_analysisModel.prefixTests); WRITEPREFS("stestPrefs",m_analysisModel.suffixTests); WRITEPREFS("itestPrefs",m_analysisModel.infixTests); WRITEPREFS("ntestPrefs",m_analysisModel.interfixTests); WRITEPREFS("rttestPrefs",m_analysisModel.rootTests); WRITEPREFS("mccPrefs",m_analysisModel.generalMCCs); WRITEPREFS("apPrefs",m_commonModel.m_allomorphProperties); WRITEPREFS("mpPrefs",m_commonModel.m_morphemeProperties); WRITEPREFS("catPrefs",m_commonModel.m_categories); WRITEPREFS("cclPrefs",m_commonModel.categoryClasses); WRITEPREFS("mclPrefs",m_commonModel.morphemeClasses); WRITEPREFS("sclPrefs",m_commonModel.stringClasses); WRITEPREFS("pclPrefs",m_commonModel.punctuationClasses);// 1.06 hab WRITEPREFS("textInOrthoPrefs",m_textInModel.m_orthoChanges); WRITEPREFS("textOutOrthoPrefs",m_textOutModel.m_orthoChanges); WRITEPREFS("dictOrthoPrefs",m_dictOrthoModel.m_orthoChanges); WRITEPREFS("phonrulPrefs",m_phonruleModel.m_rules); #ifndef hab17a1 WRITEPREFS("sampleLexChangePrefs",m_stampSynthesisModel.m_lexChanges); #endif // hab17a1 WRITEPREFS("sampleSoundPrefs",m_stampSynthesisModel.m_regSoundChanges); WRITEPREFS("sampleTestPrefs",m_stampSynthesisModel.m_tests); WRITEPREFS("sentAdjPrefs",m_sentransGlossAdjustmentModel.m_rules); WRITEPREFS("sentAnaAdjPrefs",m_sentransAnaAdjustmentModel.m_rules);// JDH 6/2/99 WRITEPREFS("sentDisamPrefs",m_sentransDisambigModel.m_rules); fout << "\\DisplayFlags " << m_wDisplayFlags << "\n"; // jdh 11/9/99 // If needed, finish conversion from CARLA MENU if(m_sTempConvertFromDirectory.GetLength() >0) // will be "" after first save { LOG(_T("--------BEGIN CARLMENU CONVERSION FOR ")); LOG(getName()); LOG (_T("\r\n")); LOG (_T("Copying control files...\r\n")); convertFromCarla(); // first time, just copy over the files LOG (_T("Loading control files...\r\n")); loadControlFiles(TRUE, FALSE); LOG(_T("--------FINISHED CARLMENU CONVERSION FOR ")); LOG(getName()); LOG (_T("\r\n")); } else if(m_pFilesWiz) { LOG(_T("--------BEGIN FROM-FILES CREATION\r\n")); convertFromFiles(); loadControlFiles(FALSE, TRUE); LOG(_T("--------FINISHED FROM-FILES CREATION\r\n")); } // this is here as a convenient place to fix new lang wizards (from files or from scratch) // that can't conveniently change the maxes according to what kind of dicts were chosen if(!m_mfs.getUsingUnifiedDicts()) { if(m_mfs.getPrefixDictPathD().IsEmpty()) m_analysisModel.maxPrefixes=0; if(m_mfs.getSuffixDictPathD().IsEmpty()) m_analysisModel.maxSuffixes=0; if(m_mfs.getInfixDictPathD().IsEmpty()) m_analysisModel.maxInfixes=0; } if(m_pAnalysisSequence) m_pAnalysisSequence->writeToFile(fout); for(int i=0; i<m_pTransferSequences.GetSize(); i++) m_pTransferSequences[i]->writeToFile(fout); if(m_pSynthesisSequence) m_pSynthesisSequence->writeToFile(fout); if(m_pInterlinearSequence) m_pInterlinearSequence->writeToFile(fout); writeControlFiles(); m_mfs.writeToStream(fout); // must be *after* call to convertFromFiles() safeWrite.close(); return TRUE; }
int sendEmail(const int socketFd, const unsigned char *fromMail, const unsigned char *toMail, const unsigned char *textMail, const int textLen) { char readData[SMTP_MTU] = {0}; char writeData[SMTP_MTU] = {0}; /* Send: MAIL FROM */ memset(&writeData, 0, SMTP_MTU); sprintf(writeData, "MAIL FROM: <%s>\r\n", fromMail); safeWrite(socketFd, writeData, strlen(writeData)); /* Recv: MAIL FROM */ memset(&readData, 0, SMTP_MTU); safeRead(socketFd, readData, SMTP_MTU); SMTP_Print6("[%s][%d]recv: %s\r\n", __FILE__, __LINE__, readData); recvStatus(readData); /* Send: RCPT TO */ memset(&writeData, 0, SMTP_MTU); sprintf(writeData, "RCPT TO: <%s>\r\n", toMail); safeWrite(socketFd, writeData, strlen(writeData)); /* Recv: RCPT TO */ memset(&readData, 0, SMTP_MTU); safeRead(socketFd, readData, SMTP_MTU); SMTP_Print6("[%s][%d]recv: %s\r\n", __FILE__, __LINE__, readData); recvStatus(readData); /* Send: DATA */ memset(&writeData, 0, SMTP_MTU); safeWrite(socketFd, "DATA\r\n", strlen("DATA\r\n")); /* Recv: DATA */ memset(&readData, 0, SMTP_MTU); safeRead(socketFd, readData, SMTP_MTU); SMTP_Print6("[%s][%d]recv: %s\r\n", __FILE__, __LINE__, readData); recvStatus(readData); /* Send: MAIL TEXT */ safeWrite(socketFd, textMail, textLen); /* Recv: MAIL TEXT */ memset(&readData, 0, SMTP_MTU); safeRead(socketFd, readData, SMTP_MTU); SMTP_Print6("[%s][%d]recv: %s\r\n", __FILE__, __LINE__, readData); recvStatus(readData); /* Send: QUIT */ memset(&writeData, 0, SMTP_MTU); safeWrite(socketFd, "QUIT\r\n", strlen("QUIT\r\n")); /* Recv: QUIT */ memset(&readData, 0, SMTP_MTU); safeRead(socketFd, readData, SMTP_MTU); SMTP_Print6("[%s][%d]recv: %s\r\n", __FILE__, __LINE__, readData); recvStatus(readData); return 0; }
int authEmail(const int socketFd, const unsigned char *mailAddr, const unsigned char *mailPasswd) { int outSize = 0, stringLen; char readData[SMTP_MTU] = {0}; char writeData[SMTP_MTU] = {0}; char userName[MAX_EMAIL_LEN] = {0}; char userPasswd[MAX_EMAIL_LEN] = {0}; memset(&readData, 0, SMTP_MTU); safeRead(socketFd, readData, SMTP_MTU); SMTP_Print6("[%s][%d]recv: %s\r\n", __FILE__, __LINE__, readData); /* Send: EHLO */ safeWrite(socketFd, "EHLO Here\r\n", strlen("EHLO Here\r\n")); /* Recv: EHLO */ memset(&readData, 0, SMTP_MTU); safeRead(socketFd, readData, SMTP_MTU); SMTP_Print6("[%s][%d]recv: %s\r\n", __FILE__, __LINE__, readData); recvStatus(readData); /* Send: AUTH LOGIN */ safeWrite(socketFd, "AUTH LOGIN\r\n", strlen("AUTH LOGIN\r\n")); /* Recv: AUTH LOGIN */ memset(&readData, 0, SMTP_MTU); safeRead(socketFd, readData, SMTP_MTU); SMTP_Print6("[%s][%d]recv: %s\r\n", __FILE__, __LINE__, readData); recvStatus(readData); /* Send: username */ memset(&userName, 0, MAX_EMAIL_LEN); memset(&writeData, 0, SMTP_MTU); stringCut((unsigned char*)mailAddr, NULL, "@", userName); outSize = BASE64_SIZE(strlen(userName)); base64_encode(writeData, outSize, userName, strlen(userName)); strcat(writeData, "\r\n"); safeWrite(socketFd, writeData, strlen(writeData)); /* Recv: username */ memset(&readData, 0, SMTP_MTU); safeRead(socketFd, readData, SMTP_MTU); SMTP_Print6("[%s][%d]recv: %s\r\n", __FILE__, __LINE__, readData); recvStatus(readData); /* Send: passwd */ memset(&userPasswd, 0, MAX_EMAIL_LEN); strcpy(userPasswd, mailPasswd); memset(&writeData, 0, SMTP_MTU); outSize = BASE64_SIZE(strlen(userPasswd)); base64_encode(writeData, outSize, userPasswd, strlen(userPasswd)); strcat(writeData, "\r\n"); safeWrite(socketFd, writeData, strlen(writeData)); /* Recv: passwd */ memset(&readData, 0, SMTP_MTU); safeRead(socketFd, readData, SMTP_MTU); SMTP_Print6("[%s][%d]recv: %s\r\n", __FILE__, __LINE__, readData); recvStatus(readData); return 0; }
int sendEmail(const ACE_HANDLE socketFd, const unsigned char *fromMail, const unsigned char *toMail, const unsigned char *textMail, const int textLen) { char readData[SMTP_MTU] = {0}; char writeData[SMTP_MTU] = {0}; /* Send: MAIL FROM */ ACE_OS::memset(&writeData, 0, SMTP_MTU); ACE_OS::sprintf(writeData, "MAIL FROM: <%s>\r\n", fromMail); safeWrite(socketFd, writeData, strlen(writeData)); /* Recv: MAIL FROM */ ACE_OS::memset(&readData, 0, SMTP_MTU); safeRead(socketFd, readData, SMTP_MTU); //SMTP_Print6("[%s][%d]recv: %s\r\n", __FILE__, __LINE__, readData); recvStatus(readData); /* Send: RCPT TO */ ACE_OS::memset(&writeData, 0, SMTP_MTU); ACE_OS::sprintf(writeData, "RCPT TO: <%s>\r\n", toMail); safeWrite(socketFd, writeData, strlen(writeData)); /* Recv: RCPT TO */ ACE_OS::memset(&readData, 0, SMTP_MTU); safeRead(socketFd, readData, SMTP_MTU); //SMTP_Print6("[%s][%d]recv: %s\r\n", __FILE__, __LINE__, readData); recvStatus(readData); /* Send: DATA */ ACE_OS::memset(&writeData, 0, SMTP_MTU); char szDATA[50] = {'\0'}; ACE_OS::sprintf(szDATA, "DATA\r\n"); safeWrite(socketFd, szDATA, ACE_OS::strlen("DATA\r\n")); /* Recv: DATA */ ACE_OS::memset(&readData, 0, SMTP_MTU); safeRead(socketFd, readData, SMTP_MTU); //SMTP_Print6("[%s][%d]recv: %s\r\n", __FILE__, __LINE__, readData); recvStatus(readData); /* Send: MAIL TEXT */ safeWrite(socketFd, (char* )textMail, textLen); /* Recv: MAIL TEXT */ ACE_OS::memset(&readData, 0, SMTP_MTU); safeRead(socketFd, readData, SMTP_MTU); //SMTP_Print6("[%s][%d]recv: %s\r\n", __FILE__, __LINE__, readData); recvStatus(readData); /* Send: QUIT */ ACE_OS::memset(&writeData, 0, SMTP_MTU); char szQUIT[50] = {'\0'}; ACE_OS::sprintf(szQUIT, "QUIT\r\n"); safeWrite(socketFd, szQUIT, ACE_OS::strlen("QUIT\r\n")); /* Recv: QUIT */ ACE_OS::memset(&readData, 0, SMTP_MTU); safeRead(socketFd, readData, SMTP_MTU); recvStatus(readData); return 0; }
int authEmail(const ACE_HANDLE socketFd, const unsigned char *mailAddr, const unsigned char *mailPasswd) { int outSize = 0; char readData[SMTP_MTU] = {0}; char writeData[SMTP_MTU] = {0}; char userName[MAX_EMAIL_LEN] = {0}; char userPasswd[MAX_EMAIL_LEN] = {0}; ACE_OS::memset(&readData, 0, SMTP_MTU); safeRead(socketFd, readData, SMTP_MTU); //SMTP_Print6("[%s][%d]recv: %s\r\n", __FILE__, __LINE__, readData); /* Send: EHLO */ char szRELO[50] = {'\0'}; ACE_OS::sprintf(szRELO, "EHLO Here\r\n"); safeWrite(socketFd, szRELO, ACE_OS::strlen("EHLO Here\r\n")); /* Recv: EHLO */ ACE_OS::memset(&readData, 0, SMTP_MTU); safeRead(socketFd, readData, SMTP_MTU); //SMTP_Print6("[%s][%d]recv: %s\r\n", __FILE__, __LINE__, readData); recvStatus(readData); /* Send: AUTH LOGIN */ char szLOGIN[50] = {'\0'}; ACE_OS::sprintf(szLOGIN, "AUTH LOGIN\r\n"); safeWrite(socketFd, szLOGIN, ACE_OS::strlen("AUTH LOGIN\r\n")); /* Recv: AUTH LOGIN */ ACE_OS::memset(&readData, 0, SMTP_MTU); safeRead(socketFd, readData, SMTP_MTU); //SMTP_Print6("[%s][%d]recv: %s\r\n", __FILE__, __LINE__, readData); recvStatus(readData); /* Send: username */ ACE_OS::memset(&userName, 0, MAX_EMAIL_LEN); ACE_OS::memset(&writeData, 0, SMTP_MTU); stringCut((unsigned char*)mailAddr, NULL, (char* )"@", userName); outSize = BASE64_SIZE(strlen(userName)); base64_encode(writeData, outSize, (const unsigned char *)userName, strlen(userName)); ACE_OS::strcat(writeData, "\r\n"); safeWrite(socketFd, writeData, strlen(writeData)); /* Recv: username */ ACE_OS::memset(&readData, 0, SMTP_MTU); safeRead(socketFd, readData, SMTP_MTU); //SMTP_Print6("[%s][%d]recv: %s\r\n", __FILE__, __LINE__, readData); recvStatus(readData); /* Send: passwd */ ACE_OS::memset(&userPasswd, 0, MAX_EMAIL_LEN); ACE_OS::strcpy((char* )userPasswd, (char* )mailPasswd); ACE_OS::memset(&writeData, 0, SMTP_MTU); outSize = BASE64_SIZE(strlen(userPasswd)); base64_encode(writeData, outSize, (const unsigned char *)userPasswd, strlen(userPasswd)); ACE_OS::strcat(writeData, "\r\n"); safeWrite(socketFd, writeData, strlen(writeData)); /* Recv: passwd */ ACE_OS::memset(&readData, 0, SMTP_MTU); safeRead(socketFd, readData, SMTP_MTU); //SMTP_Print6("[%s][%d]recv: %s\r\n", __FILE__, __LINE__, readData); recvStatus(readData); return 0; }
/*********************************************************** * Make fits and plots of time and ADC histograms ************************************************************/ void timefit( const char *rootfile, const char *cham, const char *flag ) { int region = 0; int startflag=0; int makeplots=0; int tubeplots=0; int mlplots=0; int mzplots=0; int logy=0; // parse flag for( int i=0; flag[i]!='\0'; i++ ) { if( flag[i] == 'S' ) startflag=1; else if( flag[i] == 'P' ) makeplots=1; else if( flag[i] == 'L' ) logy=1; else if( flag[i] == 'T' ) tubeplots=1; else if( flag[i] == 'M' ) mlplots=1; else if( flag[i] == 'Z' ) mzplots=1; } c1 = new TCanvas("c1","chamberplot",800,600); if( logy ) c1->SetLogy(1); gStyle->SetStatW(0.48); gStyle->SetStatX(0.98); gStyle->SetStatY(0.90); gStyle->SetStatH(0.35); gStyle->SetTitleH(0.1); gStyle->SetTitleX(0.5); // Reset chamber loop limits if chamber specified int imin=0, imax=MAXCHAMBERS; if( cham[0] != '\0' ) { if( cham[0] == 'R' ) { region = atoi(&cham[1]); } else { int idx = MDTindex( cham ); if( idx == -1 ) { printf("ERROR: Unknown chamber %s\n",cham); return; } else { imin = idx; imax = idx+1; if( startflag ) imax = MAXCHAMBERS; } } } // Open ROOT file TFile *f = new TFile(rootfile); if( f && f->IsZombie() ) { printf("Error with ROOT file %s\n",rootfile); f->Close(); return; } printf("Opened input ROOT file %s\n",rootfile); // Loop over chamber folders and fit histograms if( makeplots ) { // Set global style options gStyle->SetStatX(0.94); //set statbox x location gStyle->SetStatW(0.3); //set statbox width gStyle->SetStatH(0.2); //set statbox height - fonts scale with size gStyle->SetTitleX(0.5); gStyle->SetTitleY(1.05); gStyle->SetTitleH(0.2); gStyle->SetTitleW(0.95); for( int i=imin; i<imax; i++ ) { // If only doing a specific region check if chamber is in it. if( region && chamber_regions[i] != region ) continue; TH1F *chamber_dtime_h1 = (TH1F *) f->Get(Form("%s/%s_dTime",chlist[i].hardname,chlist[i].hardname)); if( chamber_dtime_h1 ) { chamber_dtime_h1->Draw(); c1->Print(Form("%s_dTime.png",chlist[i].hardname)); } } return; } // Open ROOT file for refit histograms // Long winded way of removing path on input ROOT file name char newrootfile[100],pname[80]; int ilen = strlen(rootfile); int ibeg=0; for( int ii=ilen; ii>=0; ii-- ) { if( rootfile[ii] == '/' ) { ibeg=ii+1; break; } } sprintf(fname,"%s",&rootfile[ibeg]); ilen = strlen(fname); fname[ilen-5] = '\0'; //remove .root ending if( cham[0] != '\0' && cham[0] != 'R' ) { sprintf(newrootfile,"%s_fit_%s.root",fname,cham); } else { sprintf(newrootfile,"%s_fit.root",fname); } TFile *froot = new TFile(newrootfile,"recreate"); if( froot && froot->IsZombie() ) { printf("Error opening ROOT file for new fits %s\n",newrootfile); froot->Close(); return; } printf("Opened ROOT file for new fits %s\n",newrootfile); // Save general histograms char genhist[16][20] = { "chamber_hits", "Trk_Author", "Trk_Tracks", "track_hits", "track_chambers", "segment_hits", "segment_hits_comb", "Trk_Momentum", "Trk_Pt", "Trk_Phi", "Trk_Eta", "Trk_Eta_Phi", "Trk_P_Phi", "Trk_P_Eta", "Trk_Pt_Phi", "Trk_Pt_Eta" }; for( int ih=0; ih<16; ih++ ) { TH1F *h1 = (TH1F *) f->Get(genhist[ih]); safeWrite( h1 ); } // Open stats file if( cham[0] != '\0' && cham[0] != 'R' ) { fout.open(Form("%s_timefitstats_%s.txt",fname,cham),std::fstream::out); } else { fout.open(Form("%s_timefitstats.txt",fname),std::fstream::out); } if( fout.is_open() == 0 ) { printf("ERROR: cannot open stats file %s_timefitstats\n",fname); return; } // Print header of stats file // 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 fout << "chamber type Events T0 T0_Err T0_Slope T0_Slope_Err Background Background_Err T0_#chi^{2} Tmax Tmax_Err Tmax_Slope Tmax_Slope_Err Tmax_#chi^{2} ADC_peak ADC_peak_Err ADC_width ADC_width_Err ADC_skew ADC_skew_Err ADC_#chi^{2}\n"; fout << "units x x [ns] [ns] [ns] [ns] x x x [ns] [ns] [ns] [ns] x [ns] [ns] [ns] [ns] x x x\n"; fout << "min x 0 -10 0 2 0 0 0 0 720 0 1 0 0 110 0 25 0 1.4 0 0\n"; fout << "max x 0 80 0 5 0 30 0 70 800 0 18 0 10 150 0 40 0 2.6 0 10\n"; // Loop over chamber folders and fit histograms for( int i=imin; i<imax; i++ ) { // If only doing a specific region check if chamber is in it. if( region && chamber_regions[i] != region ) continue; f->cd(); //init arrays // Store chamber fit results in chamdata. These are used to set // initial values of parameters for ML and mezzcard fits. float chamdata[NDATA] = {-1}; char chamber[10]; sprintf(chamber,"%s",chlist[i].hardname); sprintf(pname,"%s/%s",chamber,chamber); // Fit chamber-level T0 TH1F *chamber_time_h1 = (TH1F *) f->Get(Form("%s_Time",pname)); if( FitTdcHist(chamber_time_h1,chamdata,0,1) ) continue; TH1F *T0_Chamber_h1=0, *T0_ML_h1=0, *T0_Mezz_h1=0, *T0_Mezzcard_h1=0, *T0_MezzTube_h1=0, *T0_Tube_h1=0; int nml = chlist[i].num_ml; int nmezz = MDTmaxmezz(chamber); //includes non-existant mezzcards in cutouts, if any int tottubes = 24*nmezz; //includes non-existant tubes in cutouts, if any int tubes = chlist[i].ntl_ml1; if( chlist[i].ntl_ml2 > chlist[i].ntl_ml1 ) tubes = chlist[i].ntl_ml2; int layers = chlist[i].nly_ml1; if( chlist[i].nly_ml2 > chlist[i].nly_ml1 ) layers = chlist[i].nly_ml2; T0_Chamber_h1 = make_h1(Form("%s_T0_Chamber_h1",chamber),Form("%s Chamber T0",chamber), 1,1.,tottubes+1,"tube","T0 [ns]"); T0_Chamber_h1->SetBinContent(1,chamdata[1]); T0_Chamber_h1->SetBinError(1,chamdata[2]); TH1F *chamber_ADC_h1 = (TH1F *) f->Get(Form("%s_ADC",pname)); FitAdcHist(chamber_ADC_h1,chamdata,1); fout << chamber << " CHM" << Form(" %.0f",chamdata[0]); for( int k=1; k<NDATA; k++ ) fout << Form(" %.2f",chamdata[k]); fout << "\n"; // Fit multilayer data TH1F *ml_time_h1[2] = {}; TH1F *ml_ADC_h1[2] = {}; T0_ML_h1 = make_h1(Form("%s_T0_ML_h1",chamber),Form("%s ML T0",chamber), nml,1.,tottubes+1,"tube","T0 [ns]"); for( int m=0; m<nml; m++ ) { float data[NDATA] = {-1}; ml_time_h1[m] = (TH1F *) f->Get(Form("%s_Time_ML%i",pname,m+1)); if( FitTdcHist(ml_time_h1[m],data,chamdata,mlplots) ) continue; T0_ML_h1->SetBinContent(1+m,data[1]); T0_ML_h1->SetBinError(1+m,data[2]); ml_ADC_h1[m] = (TH1F *) f->Get(Form("%s_ADC_ML%i",pname,m+1)); FitAdcHist(ml_ADC_h1[m],data,mlplots); fout << chamber << " ML" << m+1 << Form(" %.0f",data[0]); for( int k=1; k<NDATA; k++ ) fout << Form(" %.2f",data[k]); fout << "\n"; } // These plot both ML histograms on same plot TdcMLPlot(ml_time_h1); AdcMLPlot(ml_ADC_h1); // Fit mezzcard data int mezzstep = 8; //number of tubes/layer in a mezzcard if( chlist[i].nly_ml1 == 4 ) mezzstep = 6; int mezzbins = tottubes/mezzstep; T0_Mezz_h1 = make_h1(Form("%s_T0_Mezz_h1",chamber),Form("%s Mezz T0",chamber), mezzbins,1.,tottubes+1,"tube","T0 [ns]"); T0_Mezzcard_h1 = make_h1(Form("%s_T0_Mezzcard_h1",chamber),Form("%s Mezz T0",chamber), nmezz, 0.,nmezz,"Mezzcard","T0 [ns]"); TH1F *mezz_time_h1[26] = {}; TH1F *mezz_ADC_h1[26] = {}; for( int m=0; m<nmezz; m++ ) { float data[NDATA] = {-1}; mezz_time_h1[m] = (TH1F *) f->Get(Form("%s_Time_Mezz%i",pname,m)); if( FitTdcHist(mezz_time_h1[m],data,chamdata,mzplots) ) continue; T0_Mezzcard_h1->SetBinContent(m+1,data[1]); T0_Mezzcard_h1->SetBinError(m+1,data[2]); mezz_ADC_h1[m] = (TH1F *) f->Get(Form("%s_ADC_Mezz%i",pname,m)); FitAdcHist(mezz_ADC_h1[m],data,mzplots); fout << chamber << " MZ" << m << Form(" %.0f",data[0]); for( int k=1; k<NDATA; k++ ) fout << Form(" %.2f",data[k]); fout << "\n"; } // Look for tube-level histogram if processing by region TH1F *tube_time_h1[2][4][78] = {}; TH1F *tube_ADC_h1[2][4][78] = {}; TH1F *tube_T0_h1=0, *tube_T0slope_h1=0, *tube_Tmax_h1=0, *tube_TmaxSlope_h1=0; TH1F *tube_ADCpeak_h1=0, *tube_ADCwidth_h1=0; TH2F *tube_T0_map_h2=0, *tube_T0slope_map_h2=0, *tube_Tmax_map_h2=0, *tube_TmaxSlope_map_h2=0; TH2F *tube_ADCpeak_map_h2=0, *tube_ADCwidth_map_h2=0; //Only look for tube histograms if individual chamber or region selected if( cham[0] != '\0' ) { T0_Tube_h1 = make_h1(Form("%s_T0_Tube_h1",chamber),Form("%s Tube T0",chamber), tottubes,1.,tottubes+1,"tube","T0 [ns]"); T0_MezzTube_h1 = make_h1(Form("%s_T0_MezzcTube_h1",chamber),Form("%s Tube T0 per Mezzcard",chamber), tottubes, 0.,nmezz,"Mezzcard","T0 [ns]"); tube_T0_h1 = make_h1(Form("%s_tube_T0",chamber),Form("%s Tube T0",chamber), 100,-10.,90.,"T0 [ns]"); tube_T0_map_h2 = make_h2(Form("%s_T0_map",chamber),Form("%s T0 Map",chamber), tubes,1.,1+tubes,2*layers+1,1.,2*layers+2,"tube number","layer"); tube_T0slope_h1 = make_h1(Form("%s_tube_T0slope",chamber),Form("%s Tube T0slope",chamber), 100,0.,5.,"T0slope [ns]"); tube_T0slope_map_h2 = make_h2(Form("%s_T0slope_map",chamber),Form("%s T0slope Map",chamber), tubes,1.,1+tubes,2*layers+1,1.,2*layers+2,"tube number","layer"); tube_Tmax_h1 = make_h1(Form("%s_tube_Tmax",chamber),Form("%s Tube Tmax",chamber), 100,700.,800.,"Tmax [ns]"); tube_Tmax_map_h2 = make_h2(Form("%s_Tmax_map",chamber),Form("%s Tmax Map",chamber), tubes,1.,1+tubes,2*layers+1,1.,2*layers+2,"tube number","layer"); tube_TmaxSlope_h1 = make_h1(Form("%s_tube_TmaxSlope",chamber),Form("%s Tube TmaxSlope",chamber), 100,0.,10.,"TmaxSlope [ns]"); tube_TmaxSlope_map_h2 = make_h2(Form("%s_TmaxSlope_map",chamber),Form("%s TmaxSlope Map",chamber), tubes,1.,1+tubes,2*layers+1,1.,2*layers+2,"tube number","layer"); tube_ADCpeak_h1 = make_h1(Form("%s_tube_ADCpeak",chamber),Form("%s Tube ADCpeak",chamber), 100,90.,190.,"ADCpeak [ns]"); tube_ADCpeak_map_h2 = make_h2(Form("%s_ADCpeak_map",chamber),Form("%s ADCpeak Map",chamber), tubes,1.,1+tubes,2*layers+1,1,2*layers+2,"tube number","layer"); tube_ADCwidth_h1 = make_h1(Form("%s_tube_ADCwidth",chamber),Form("%s Tube ADCwidth",chamber), 100,10.,60.,"ADCwidth [ns]"); tube_ADCwidth_map_h2 = make_h2(Form("%s_ADCwidth_map",chamber),Form("%s ADCwidth Map",chamber), tubes,1.,1+tubes,2*layers+1,1,2*layers+2,"tube number","layer"); int mezztube[26] = {}; //to track tube within mezzcard int tubenum = 0; for( int m=0; m<nml; m++ ) { for( int l=0; l<layers; l++ ) { for( int t=0; t<tubes; t++ ) { tubenum++; float data[NDATA] = {-1}; int mllt = 1000*m + 100*l + t + 1101; tube_time_h1[m][l][t] = (TH1F *) f->Get(Form("%s_Time_%i",pname,mllt)); if( FitTdcHist( tube_time_h1[m][l][t],data,chamdata,tubeplots) ) continue; // int tb = MLLT2T(chamber,mllt) + 1; //MLL2T numbering starts at 0 // printf("mllt=%i tb=%i tubenum=%i\n",mllt,tb,tubenum); T0_Tube_h1->SetBinContent(tubenum,data[1]); T0_Tube_h1->SetBinError(tubenum,data[2]); int mz = MLLT2M(chamber,mllt); //mezzcard of tube mezztube[mz]++; //number of tube within mezzcard [1..24] int ibin = mz*24 + mezztube[mz]; T0_MezzTube_h1->SetBinContent(ibin,data[1]); T0_MezzTube_h1->SetBinError(ibin,data[2]); tube_ADC_h1[m][l][t] = (TH1F *) f->Get(Form("%s_ADC_%i",pname,mllt)); FitAdcHist(tube_ADC_h1[m][l][t],data,tubeplots); if( data[0] == 0. ) continue; fout << chamber << " TB" << mllt << Form(" %.0f",data[0]); for( int k=1; k<NDATA; k++ ) fout << Form(" %.2f",data[k]); fout << "\n"; int tt = t + 1; int ll = l + m + m*chlist[i].nly_ml1 + 1; tube_T0_h1->Fill(data[1]); tube_T0slope_h1->Fill(data[3]); tube_Tmax_h1->Fill(data[8]); tube_TmaxSlope_h1->Fill(data[10]); tube_ADCpeak_h1->Fill(data[13]); tube_ADCwidth_h1->Fill(data[15]); tube_T0_map_h2->Fill(tt,ll,data[1]); tube_T0slope_map_h2->Fill(tt,ll,data[3]); tube_Tmax_map_h2->Fill(tt,ll,data[8]); tube_TmaxSlope_map_h2->Fill(tt,ll,data[10]); tube_ADCpeak_map_h2->Fill(tt,ll,data[13]); tube_ADCwidth_map_h2->Fill(tt,ll,data[15]); // Fill mezzcard T0 vs tube histogram if( tubenum%mezzstep == 0 ) { ibin = tubenum/mezzstep; T0_Mezz_h1->SetBinContent(ibin,T0_Mezzcard_h1->GetBinContent(mz+1)); T0_Mezz_h1->SetBinError(ibin,T0_Mezzcard_h1->GetBinError(mz+1)); } } //end loop over tubes } //end loop over layers } //end loop over ml plotmap(tube_T0_h1,tube_T0_map_h2,0); plotmap(tube_T0slope_h1,tube_T0slope_map_h2); plotmap(tube_Tmax_h1,tube_Tmax_map_h2); plotmap(tube_TmaxSlope_h1,tube_TmaxSlope_map_h2); plotmap(tube_ADCpeak_h1,tube_ADCpeak_map_h2); plotmap(tube_ADCwidth_h1,tube_ADCwidth_map_h2); plott0s(tube_T0_h1,T0_Chamber_h1,T0_ML_h1,T0_Mezz_h1,T0_Tube_h1); plott0s2(tube_T0_h1, T0_Mezzcard_h1, T0_MezzTube_h1); } //end if region //Save fitted histograms to refit ROOT file froot->cd(); if( chamber_time_h1 == 0 ) continue; froot->mkdir(chamber); froot->cd(chamber); // Save misc chamber histograms in original file char mischist[4][10] = { "Momentum", "Pt", "Mezz_Hits", "dTime" }; for( int ih=0; ih<4; ih++ ) { TH1F *h1 = (TH1F *) f->Get(Form("%s_%s",pname,mischist[ih])); safeWrite( h1 ); } safeWrite( chamber_time_h1 ); safeWrite( chamber_ADC_h1 ); safeWrite( T0_Chamber_h1 ); safeWrite( T0_ML_h1 ); safeWrite( T0_Mezz_h1 ); safeWrite( T0_Mezzcard_h1 ); safeWrite( T0_MezzTube_h1 ); safeWrite( T0_Tube_h1 ); for( int m=0; m<nml; m++ ) { safeWrite( ml_time_h1[m] ); safeWrite( ml_ADC_h1[m] ); } for( int m=0; m<nmezz; m++ ) { safeWrite( mezz_time_h1[m] ); safeWrite( mezz_ADC_h1[m] ); } if( cham[0] != '\0' ) { safeWrite( T0_Tube_h1 ); safeWrite( tube_T0_h1 ); safeWrite( tube_T0slope_h1 ); safeWrite( tube_Tmax_h1 ); safeWrite( tube_TmaxSlope_h1 ); safeWrite( tube_ADCpeak_h1 ); safeWrite( tube_ADCwidth_h1 ); safeWrite( tube_T0_map_h2 ); safeWrite( tube_T0slope_map_h2 ); safeWrite( tube_Tmax_map_h2 ); safeWrite( tube_TmaxSlope_map_h2 ); safeWrite( tube_ADCpeak_map_h2 ); safeWrite( tube_ADCwidth_map_h2 ); for( int m=0; m<nml; m++ ) { for( int l=0; l<layers; l++ ) { for( int t=0; t<tubes; t++ ) { safeWrite( tube_time_h1[m][l][t] ); safeWrite( tube_ADC_h1[m][l][t] ); } //end loop over tubes } //end loop over layers } //end loop over ml } //end if region } //end loop over chambers // Close the ROOT file of refit histograms froot->Close(); f->Close(); return; } //end timefit()
void Decrypt(PK0304 *le, char *password) { char *salt, *key1, *key2, *check, digest[40]; u32 key_len, dig_len = 40, start, xlen; AE_EXTRA ae; start = ftell(ZIN); /* Searches for AE-1 header */ fseek(ZIN, le->NameLen, SEEK_CUR); for(xlen=le->ExtraLen; xlen;) { safeRead(&ae, ZIN, 4); xlen -= (4 + ae.Size); if (ae.Sig == 0x9901) { safeRead(&ae.Version, ZIN, 7); continue; } fseek(ZIN, ae.Size, SEEK_CUR); } if (ae.Sig != 0x9901) Z_ERROR("Fatal! Can't find AE extra header!"); if (ae.Strength < 1 || ae.Strength > 3) Z_ERROR("Bad encryption strength"); SaltSize = KS[ae.Strength].Salt; KeySize = KS[ae.Strength].Key; salt = BUF; key1 = salt+SaltSize; key2 = key1+KeySize; check = key2+KeySize; key_len = KeySize*2+2; /* Loads salt and password check value, and regenerates original crypto material */ fseek(ZIN, start+le->NameLen+le->ExtraLen, SEEK_SET); safeRead(salt, ZIN, SaltSize); safeRead(check+2, ZIN, 2); point1: if (pkcs_5_alg2(password, strlen(password), salt, SaltSize, 1000, 0, key1, &key_len) != CRYPT_OK) Z_ERROR("Failed to derive encryption keys"); if (memcmp(check, check+2, 2)) { printf("\nCan't decrypt data: try another password.\nNew password: "******"\n"); goto point1; } if (ctr_start(0, IV, key1, KeySize, 0, CTR_COUNTER_LITTLE_ENDIAN, &ctr) != CRYPT_OK) Z_ERROR("Failed to setup AES CTR decoder"); #ifdef GLADMAN_HMAC hmac_sha1_begin(&hmac); hmac_sha1_key(key2, KeySize, &hmac); #else if (hmac_init(&hmac, 0, key2, KeySize) != CRYPT_OK) Z_ERROR("Failed to setup HMAC-SHA1"); #endif /* Adjusts local header */ le->Flag ^= 1; le->CompMethod = ae.CompMethod; le->ExtraLen -= 11; le->CompSize -= (SaltSize + 12); /* Writes local header and copies extra, except 0x9901 */ safeWrite(ZOUT, le, sizeof(PK0304)); fseek(ZIN, start, SEEK_SET); fileCopy(ZOUT, ZIN, le->NameLen); for(xlen=le->ExtraLen+11; xlen;) { safeRead(&ae, ZIN, 4); xlen -= (4 + ae.Size); if (ae.Sig == 0x9901) { safeRead(&ae.Version, ZIN, 7); continue; } safeWrite(ZOUT, &ae, 4); fileCopy(ZOUT, ZIN, ae.Size); } fseek(ZIN, SaltSize+2, SEEK_CUR); fileFilter(ZOUT, ZIN, le->CompSize); #ifdef GLADMAN_HMAC hmac_sha1_end(digest, dig_len, &hmac); #else if (hmac_done(&hmac, digest, &dig_len) != CRYPT_OK) Z_ERROR("Failed to computate HMAC"); #endif /* Retrieves and checks HMACs */ safeRead(digest+10, ZIN, 10); if (memcmp(digest, digest+10, 10)) printf(" authentication failed, contents were lost!"); ctr_done(&ctr); }
int main(int argc,char** argv) { char pm, operation=-1, found=1, pw1[128], pw2[128], ae1[15], ae2[15]; u32 i; PK0102 ce; PK0304 le; PK0506 ed; for (pm=1; pm < argc; pm++) { char opt; if (argv[pm][0] != '/') continue; if (argv[pm][1] == '?') { printf( "Encrypts or decrypts an archive following WinZip(R) 9 specifications.\n\n" \ "ZAES /D | /E:keysize [/2] archive.zip\n\n" \ " /D decrypts AES encrypted entries\n" \ " /E:keysize encrypts with 128, 192 or 256-bit keys (keysize 1, 2 or 3)\n" \ " /2 AE-2 format (sets CRC-32 to zero)\n"); return 1; } opt = toupper(argv[pm][1]); if (opt== 'E') { Mode = atol(&argv[pm][3]); operation = 0; filter = encrypt_authenticate; if (Mode < 1 || Mode > 3) Z_ERROR("Bad encryption mode specified!"); SaltSize = KS[Mode].Salt; KeySize = KS[Mode].Key; found++; continue; } if (opt== 'D') { operation = 1; filter = authenticate_decrypt; found++; continue; } if (opt== '2') { AE2 = 1; found++; printf("WARNING: according to AE-2 specifications, CRC-32 will be set to zero\n"\ "in encrypted entries. Reverting to original archive after decryption will\n"\ "be impossible with this utility!\n"); continue; } } argv+=found; argc-=found; if (operation == -1) Z_ERROR("You must specify /E or /D switch!\nTry ZAES /?"); if (argc < 1) Z_ERROR("You must give a ZIP archive to process!"); register_prng(&sprng_desc); register_cipher(&aes_desc); register_hash(&sha1_desc); //~ printf("DEBUG: sha1 id=%d, aes id=%d\n", find_hash("sha1"), find_cipher("aes")); if ( (ZIN=fopen(argv[0],"rb")) == 0 || (ZIN2=fopen(argv[0],"rb")) == 0 ) Z_ERROR("Can't open input ZIP archive"); if ( (ZOUT=topen(ae1)) == 0 || (ZTMP=topen(ae2)) == 0) Z_ERROR("Can't open temporary output files"); setvbuf(ZIN , 0, _IOFBF, BLOCK); setvbuf(ZOUT, 0, _IOFBF, BLOCK); /* assumiamo uno ZIP senza commento! */ fseek(ZIN2,-22,SEEK_END); safeRead(&ed, ZIN2, sizeof(PK0506)); if (ed.Sig != 0x06054B50) #ifdef HANDLE_COMMENT { fseek(ZIN2, -0xFFFF, SEEK_END); fread(p, 1, 4, ZIN2); #else Z_ERROR("End directory marker not found!"); #endif /* verifica un minimo di coerenza nella ENDDIR */ if (ed.Disk != 0) Z_ERROR("Can't process a spanned archive"); while(1) { printf("Enter password: "******"\rFor your safety, please use a password of 8 characters or more.\n"); continue; } if (operation) { printf("\n"); break; } printf("\rVerify password: "******"Passwords don't match!\n"); continue; } printf("\n"); break; } #define PUTN(x) { fileCopy(stdout, ZIN, x.NameLen); fseek(ZIN, -x.NameLen, SEEK_CUR); } fseek(ZIN2, ed.Offset, SEEK_SET); for (i=0; i < ed.Total; i++) { safeRead(&ce, ZIN2, sizeof(PK0102)); if (ce.Sig != 0x02014B50) Z_ERROR("Expected central directory marker not found"); /* Assume i dati corretti dalla LE */ fseek(ZIN, ce.Offset, SEEK_SET); safeRead(&le, ZIN, sizeof(PK0304)); if (le.Sig != 0x04034B50) Z_ERROR("Expected local entry marker not found"); if ( ((le.Flag & 1) && !operation) || /* doesn't encrypt already encrypted */ (!(le.Flag & 1) && operation) || /* doesn't decrypt already decrypted */ ((le.Flag & 1) && operation && le.CompMethod != 99) || /* doesn't decrypt not AES encrypted */ !le.CompSize ) { ce.Offset = ftell(ZOUT); safeWrite(ZOUT, &le, sizeof(PK0304)); printf(" copying: "); PUTN(le); fileCopy(ZOUT, ZIN, le.NameLen+le.ExtraLen+le.CompSize); printf("\n"); safeWrite(ZTMP, &ce, sizeof(PK0102)); fileCopy(ZTMP, ZIN2, ce.NameLen+ce.ExtraLen); continue; } if (!operation) { AE_EXTRA ae = {0x9901, 7, AE2+1, 0x4541, Mode, 0}; ae.CompMethod = ce.CompMethod; ce.CompMethod = 99; if (AE2) ce.Crc32 = 0; ce.Flag |= 1; ce.ExtraLen += 11; ce.CompSize += SaltSize + 12; /* variable salt, fixed password check and hmac */ ce.Offset = ftell(ZOUT); safeWrite(ZTMP, &ce, sizeof(PK0102)); fileCopy(ZTMP, ZIN2, ce.NameLen+ce.ExtraLen-11); safeWrite(ZTMP, &ae, 11); printf(" encrypting: "); PUTN(le); Encrypt(&le, &ae, pw1); printf("\n"); } else { ce.Offset = ftell(ZOUT); printf(" decrypting: "); PUTN(le); Decrypt(&le, pw1); /* Decrypts contents */ printf("\n"); ce.CompMethod = le.CompMethod; if (AE2) ce.Crc32 = 0; ce.Flag ^= 1; ce.ExtraLen -= 11; ce.CompSize = le.CompSize; safeWrite(ZTMP, &ce, sizeof(PK0102)); /* Copy the extra data (may be LE != CE) */ fileCopy(ZTMP, ZIN2, ce.NameLen); for(ce.ExtraLen+=11; ce.ExtraLen;) { u16 u[2]; safeRead(u, ZIN2, 4); ce.ExtraLen -= (4 + u[1]); if (u[0] == 0x9901) { fseek(ZIN2, u[1], SEEK_CUR); continue; } safeWrite(ZTMP, u, 4); fileCopy(ZTMP, ZIN2, u[1]); } } } ed.Offset = ftell(ZOUT); /* new central directory start */ ed.Size = ftell(ZTMP); /* new central directory size */ fseek(ZTMP, 0, SEEK_SET); fclose(ZIN); fclose(ZIN2); /* Copies central directory */ fileCopy(ZOUT, ZTMP, ed.Size); safeWrite(ZOUT, &ed, sizeof(PK0506)); fclose(ZTMP); fclose(ZOUT); remove(ae2); if (remove(argv[0])) { printf("Can't remove old archive; new one is in file '%s'\n", ae1); } else if (rename(ae1, argv[0])) { printf("Can't rename old archive; new one is in file '%s'\n", ae1); } memset(&BUF, 0, sizeof(BUF)); memset(&ctr, 0, sizeof(ctr)); memset(pw1, 0, 128); memset(pw2, 0, 128); return 0; }