/* Add an MD5 checksum entry for a file or link */ void add_cksum(Package *pkg, PackingList p, const char *fname) { char *cp = NULL, buf[33]; if (issymlink(fname)) { int len; char lnk[FILENAME_MAX]; if ((len = readlink(fname, lnk, FILENAME_MAX)) > 0) cp = MD5Data((unsigned char *)lnk, len, buf); } else if (isfile(fname)) { /* Don't record MD5 checksum for device nodes and such */ cp = MD5File(fname, buf); } if (cp != NULL) { PackingList tmp = new_plist_entry(); tmp->name = copy_string(strconcat("MD5:", cp)); tmp->type = PLIST_COMMENT; tmp->next = p->next; tmp->prev = p; p->next = tmp; if (pkg->tail == p) pkg->tail = tmp; } }
void Del (const char *dir1, const char *dir2, const char *name, struct dirent *de) { damage++; change++; if (de->d_type == DT_DIR) { char *p = alloca(strlen(name)+strlen(de->d_name)+2); strcpy(p, name); strcat(p, de->d_name); strcat(p, "/"); DoDir(dir1, dir2, p); printf("CTMDR %s%s\n", name, de->d_name); fprintf(logf, "CTMDR %s%s\n", name, de->d_name); if (verbose > 1) { fprintf(stderr, "CTMDR %s%s\n", name, de->d_name); } s_del_dirs++; } else if (de->d_type == DT_REG) { char *buf1 = alloca(strlen(dir1) + strlen(name) + strlen(de->d_name) + 3); char *m1, md5_1[33]; strcpy(buf1, dir1); strcat(buf1, "/"); strcat(buf1, name); strcat(buf1, "/"); strcat(buf1, de->d_name); m1 = MD5File(buf1, md5_1); printf("CTMFR %s%s %s\n", name, de->d_name, m1); fprintf(logf, "CTMFR %s%s %s\n", name, de->d_name, m1); if (verbose > 1) { fprintf(stderr, "CTMFR %s%s\n", name, de->d_name); } s_del_files++; s_del_bytes += StatFile(buf1)->st_size; } }
int main(int argc, char *argv[]) { char *md5sum = NULL, buf[65]; if (argc < 3) { fprintf(stderr, "USAGE: %s <correct MD5 sum> <file>\n", argv[0]); return -1; } if (strlen(argv[1]) != 32) fprintf(stderr, "WARNING: MD5 hash size is wrong.\n"); md5sum = MD5File(argv[2], buf); if (!md5sum) { perror("Could not obtain MD5 sum"); return -1; } if (!strcasecmp(md5sum, argv[1])) { fprintf(stderr, "%s: OK\n", argv[2]); return 0; } else { fprintf(stderr, "%s: FAILED. Checksum is %s\n", argv[2], md5sum); return -1; } }
/*----------------------------------------------------------------------*/ int ReadFileData(char* szIni, int num_files) { char szBase[]="file_"; char szFile[16]; int x=0; int n=0; num_files++; for(x=0;x<num_files;x++) { sprintf(szFile,"%s%d",szBase,x+1); n=ReadIniArg(szIni,szFile,"filename", watch_list[x].szFile, BUF_LEN); if(n=0) return -1; n=ReadIniArg(szIni,szFile,"script", watch_list[x].szCommand, BUF_LEN); if(n==0) return -1; MD5File(watch_list[x].szFile,watch_list[x].szMD5); #ifdef DEBUG_PRINT printf("%d: %s [%s] {%s}\n", x, watch_list[x].szFile, watch_list[x].szCommand, watch_list[x].szMD5); #endif } return x+1; }
void cfgutils_rpc_check_hash(rpc_t* rpc, void* ctx) { char tmp[MD5_LEN]; memset(tmp, 0, MD5_LEN); if (!hash_file) { rpc->fault(ctx, 500, "No hash file"); return; } if (MD5File(tmp, hash_file) != 0) { LM_ERR("could not hash the config file"); rpc->fault(ctx, 500, "Failed to hash the file"); return; } if (strncmp(config_hash, tmp, MD5_LEN) == 0) { if (rpc->rpl_printf(ctx, "Identical hash") < 0) { rpc->fault(ctx, 500, "Faiure building the response"); return; } } else { if (rpc->rpl_printf(ctx, "Different hash") < 0) { rpc->fault(ctx, 500, "Faiure building the response"); return; } } }
int main(void) { printf("MD5 Key of the phrase 'md5Test' = <%s>\n", MD5String("md5Test")); printf("MD5 Key of the file 'md5.cpp' = <%s>\n", MD5File("md5.cpp")); return 0; }
/* Show files that don't match the recorded checksum */ int show_cksum(const char *title, Package *plist) { PackingList p; const char *dir = "."; char *prefix = NULL; char tmp[FILENAME_MAX]; int errcode = 0; if (!Quiet) { printf("%s%s", InfoPrefix, title); fflush(stdout); } for (p = plist->head; p != NULL; p = p->next) if (p->type == PLIST_CWD) { if (!prefix) prefix = p->name; if (p->name == NULL) dir = prefix; else dir = p->name; } else if (p->type == PLIST_FILE) { snprintf(tmp, FILENAME_MAX, "%s/%s", elide_root(dir), p->name); if (!fexists(tmp)) { warnx("%s doesn't exist", tmp); errcode = 1; } else if (p->next && p->next->type == PLIST_COMMENT && (strncmp(p->next->name, "MD5:", 4) == 0)) { char *cp = NULL, buf[33]; /* * For packing lists whose version is 1.1 or greater, the md5 * hash for a symlink is calculated on the string returned * by readlink(). */ if (issymlink(tmp) && verscmp(plist, 1, 0) > 0) { int len; char linkbuf[FILENAME_MAX]; if ((len = readlink(tmp, linkbuf, FILENAME_MAX)) > 0) cp = MD5Data((unsigned char *)linkbuf, len, buf); } else if (isfile(tmp) || verscmp(plist, 1, 1) < 0) cp = MD5File(tmp, buf); if (cp != NULL) { /* Mismatch? */ if (strcmp(cp, p->next->name + 4)) printf("%s fails the original MD5 checksum\n", tmp); else if (Verbose) printf("%s matched the original MD5 checksum\n", tmp); } } } return (errcode); }
LUA_STRING Crypto::MD5FileLua(const char* path) { unsigned char buffer[MD5_BUFFER_LENGTH]; MD5File(path, buffer); LuaStack* stack = LuaEngine::getInstance()->getLuaStack(); stack->clean(); char* hex = bin2hex(buffer, MD5_BUFFER_LENGTH); stack->pushString(hex); delete[] hex; return 1; }
int main(int argc,char*argv[]) { std::set<std::string> stFiles; FindAllFiles(stFiles,"C:\\Program Files (x86)\\Electronic Arts\\Battlefield 2142"); std::ofstream ofs("checksums.txt"); for (std::set<std::string>::iterator it=stFiles.begin();it!=stFiles.end();++it) { ofs << MD5File(it->c_str()) << '\t' << *it << std::endl; } ofs.close(); return 0; }
void main(void) { unsigned char digest[16]; //存放结果 //第一种用法: MD5_CTX md5c; MD5Init(&md5c); //初始化 MD5UpdaterString(&md5c, "你要测试的字符串"); MD5FileUpdateFile(&md5c, "你要测试的文件路径"); MD5Final(digest, &md5c); //第二种用法: MDString("你要测试的字符串", digest); //直接输入字符串并得出结果 //第三种用法: MD5File("你要测试的文件路径", digest); //直接输入文件路径并得出结果 }
void CSettingDlg::OnBrowserAvatarFile() { TCHAR szFiles[MAX_BUF] = {0}; TCHAR szFilter[] = _T("图像文件(*.bmp;*.jpg;*.jpeg;*.gif;*.png)\0*.bmp;*.jpg;*.jpeg;*.gif;*.png\0\0"); OPENFILENAME ofn; ZeroMemory(&ofn, sizeof(ofn)); ofn.Flags = OFN_OVERWRITEPROMPT | OFN_HIDEREADONLY | OFN_PATHMUSTEXIST | OFN_ALLOWMULTISELECT | OFN_EXPLORER; ofn.lStructSize = sizeof(ofn); ofn.hwndOwner = m_hWnd; ofn.lpstrFile = szFiles; ofn.nMaxFile = sizeof(szFiles); ofn.lpstrFilter = szFilter; ofn.nFilterIndex = 1; ofn.lpstrFileTitle = NULL; ofn.nMaxFileTitle = 0; ofn.lpstrInitialDir = NULL; ofn.lpstrDefExt = NULL; if (GetOpenFileName(&ofn) == FALSE) { return; } TCHAR szMd5[MAX_MD5] = {0}; TCHAR szAvatarFile[MAX_NAMEBUF] = {0}; TCHAR szAvatarPath[MAX_PATH] = {0}; Config* pCfg = Singleton<Config>::getInstance(); if (!MD5File(szMd5, ofn.lpstrFile)) { return ; } wsprintf(szAvatarFile, _T("%s%s"), szMd5, ::PathFindExtension(ofn.lpstrFile)); wsprintf(szAvatarPath, _T("%s%s"), pCfg->szAvatarSaveDir, szAvatarFile); if (!::CopyFile(ofn.lpstrFile, szAvatarPath, FALSE)) { return ; } m_pLabelAvatar->SetBkImage(szAvatarPath); m_pLabelAvatar->SetUserData(szAvatarPath); m_bPersonalChange = TRUE; }
static int chkmd5(FILE * fp, const char *path) { char buf[298]; /* "MD5 (NAMESIZE = MDSUMLEN" */ char name[NAMESIZE + 1]; char sum[MDSUMLEN + 1], chk[MDSUMLEN + 1]; const char *dname; char *s; int rval, error, c, fd; char ch; rval = 0; while (fgets(buf, sizeof(buf), fp)) { dname = NULL; error = 0; if (((c = sscanf(buf, "MD5 (%256s = %32s%c", name, sum, &ch)) != 3 && (!feof(fp) || c != 2)) || (c == 3 && ch != '\n') || (s = strrchr(name, ')')) == NULL || strlen(sum) != MDSUMLEN) error = E_BADMD5; else { *s = 0; if ((dname = distname(path, name, NULL)) == NULL) error = E_NAME; else if (opt_exist) { if ((fd = open(dname, O_RDONLY)) == -1) error = E_ERRNO; else if (close(fd)) err(2, "%s", dname); } else if (!MD5File(dname, chk)) error = E_ERRNO; else if (strcmp(chk, sum)) error = E_CHKSUM; } if (opt_ignore && error == E_ERRNO && errno == ENOENT) continue; if (error || opt_all) rval |= report(path, dname, error); if (isfatal(error)) break; } return rval; }
static char * digest_file(const char *name) { switch (digesttype) { case DIGEST_MD5: return (MD5File(name, NULL)); case DIGEST_RIPEMD160: return (RIPEMD160_File(name, NULL)); case DIGEST_SHA1: return (SHA1_File(name, NULL)); case DIGEST_SHA256: return (SHA256_File(name, NULL)); case DIGEST_SHA512: return (SHA512_File(name, NULL)); default: return (NULL); } }
char * doMD5File(const char *filename, char *buf, int is_target) { if (SummaryOpt) { struct stat st; if (stat(filename, &st) == 0) { uint64_t size = st.st_size; if (is_target) CountTargetReadBytes += size; else CountSourceReadBytes += size; } } #ifdef WITH_LIBMD return MD5File(filename, buf); #else return md5_file(filename, buf); #endif }
int doTest(const char *ext, int width, int align, int height, enum BMPPF pf, enum BMPORN orientation) { char filename[80], *md5sum, md5buf[65]; int pitch=BMPPAD(width*bmp_ps[pf], align), loadWidth=0, loadHeight=0, retval=0; unsigned char *buf=NULL; char *md5ref=!stricmp(ext, "ppm")? "c0c9f772b464d1896326883a5c79c545": "b03eec1eaaad38fed9cab5082bf37e52"; if((buf=(unsigned char *)malloc(pitch*height))==NULL) _throw("Could not allocate memory"); initBuf(buf, width, pitch, height, pf, orientation); snprintf(filename, 80, "bmptest_%s_%d_%s.%s", pfStr[pf], align, orientation==BMPORN_TOPDOWN? "td":"bu", ext); if(bmp_save(filename, buf, width, pitch, height, pf, orientation)==-1) _throw(bmp_geterr()); md5sum=MD5File(filename, md5buf); if(stricmp(md5sum, md5ref)) _throwmd5(filename, md5sum, md5ref); free(buf); buf=NULL; if(bmp_load(filename, &buf, &loadWidth, align, &loadHeight, pf, orientation)==-1) _throw(bmp_geterr()); if(width!=loadWidth || height!=loadHeight) { printf("\n Image dimensions of %s are bogus\n", filename); retval=-1; goto bailout; } if(!cmpBuf(buf, width, pitch, height, pf, orientation)) { printf("\n Pixel data in %s is bogus\n", filename); retval=-1; goto bailout; } unlink(filename); bailout: if(buf) free(buf); return retval; }
static int mod_init(void) { if (!hash_file) { LM_INFO("no hash_file given, disable hash functionality\n"); } else { if (MD5File(config_hash, hash_file) != 0) { LM_ERR("could not hash the config file\n"); return -1; } LM_DBG("config file hash is %.*s", MD5_LEN, config_hash); } if (initial > 100) { LM_ERR("invalid probability <%d>\n", initial); return -1; } LM_DBG("initial probability %d percent\n", initial); probability=(int *) shm_malloc(sizeof(int)); if (!probability) { LM_ERR("no shmem available\n"); return -1; } *probability = initial; if (lock_pool_size < 1) { LM_ERR("Invalid lock size parameter (%d)!\n", lock_pool_size); return -1; } if (create_dynamic_locks() != 0) { LM_ERR("Failed to create dynamic locks\n"); return -1; } LM_INFO("module initialized, pid [%d]\n", getpid()); return 0; }
static struct mi_root* mi_check_hash(struct mi_root* cmd, void* param ) { struct mi_root* rpl_tree= NULL; struct mi_node* node= NULL; char tmp[MD5_LEN]; memset(tmp, 0, MD5_LEN); if (!hash_file) { LM_INFO("no hash_file given, disable hash functionality\n"); rpl_tree = init_mi_tree(404, "Functionality disabled\n", 23); } else { if (MD5File(tmp, hash_file) != 0) { LM_ERR("could not hash the config file"); rpl_tree = init_mi_tree( 500, MI_INTERNAL_ERR_S, MI_INTERNAL_ERR_LEN ); return rpl_tree; } if (strncmp(config_hash, tmp, MD5_LEN) == 0) { rpl_tree = init_mi_tree( 200, MI_OK_S, MI_OK_LEN ); if(rpl_tree == NULL) return 0; node = addf_mi_node_child( &rpl_tree->node, 0, 0, 0, "The actual config file hash is identical to the stored one.\n"); } else { rpl_tree = init_mi_tree( 400, "Error", 5 ); if(rpl_tree == NULL) return 0; node = addf_mi_node_child( &rpl_tree->node, 0, 0, 0, "The actual config file hash is not identical to the stored one.\n"); } if(node == NULL) goto error; } return rpl_tree; error: free_mi_tree(rpl_tree); return 0; }
mi_response_t *mi_check_hash(const mi_params_t *params, struct mi_handler *async_hdl) { char tmp[MD5_LEN]; memset(tmp, 0, MD5_LEN); if (!hash_file) { LM_INFO("no hash_file given, disable hash functionality\n"); return init_mi_error(404, MI_SSTR("Functionality disabled")); } else { if (MD5File(tmp, hash_file) != 0) { LM_ERR("could not hash the config file"); return init_mi_error(500, MI_SSTR("Internal error")); } if (strncmp(config_hash, tmp, MD5_LEN) == 0) return init_mi_result_string(MI_SSTR("The actual config file hash " "is identical to the stored one.")); else return init_mi_error(400, MI_SSTR("The actual config file hash is not " "identical to the stored one.")); } }
/* * Check a list for files that require preconversion */ void check_list(package_t *pkg, const char *PkgName) { struct stat st; plist_t *tmp; plist_t *p; char buf[ChecksumHeaderLen + LegibleChecksumLen]; char target[MaxPathSize + SymlinkHeaderLen]; char name[MaxPathSize]; char *cwd = NULL; char *srcdir = NULL; int dirc; int cc; /* Open Package Database for writing */ if (update_pkgdb && !pkgdb_open(ReadWrite)) err(EXIT_FAILURE, "can't open pkgdb"); for (dirc = 0, p = pkg->head; p; p = p->next) { switch (p->type) { case PLIST_CWD: cwd = p->name; break; case PLIST_IGNORE: p = p->next; break; case PLIST_SRC: srcdir = p->name; break; case PLIST_DIR_RM: dirc++; break; case PLIST_FILE: /* * pkgdb handling - usually, we enter files * into the pkgdb as soon as they hit the disk, * but as they are present before pkg_create * starts, it's ok to do this somewhere here */ if (cwd == NULL) errx(2, "file without preceding @cwd found"); if (update_pkgdb) { char *s, t[MaxPathSize]; (void) snprintf(t, sizeof(t), "%s%s%s", cwd, (strcmp(cwd, "/") == 0) ? "" : "/", p->name); s = pkgdb_retrieve(t); if (s && PlistOnly) warnx("Overwriting %s - " "pkg %s bogus/conflicting?", t, s); else { pkgdb_store(t, PkgName); } } /* prepend DESTDIR if set? - HF */ (void) snprintf(name, sizeof(name), "%s%s%s", cwd, (strcmp(cwd, "/") == 0) ? "" : "/", p->name); if (lstat(name, &st) < 0) { warnx("can't stat `%s'", name); continue; } switch (st.st_mode & S_IFMT) { case S_IFDIR: p->type = PLIST_DIR_RM; dirc++; continue; case S_IFLNK: if (RelativeLinks) { CheckSymlink(name, cwd, strlen(cwd)); } (void) strlcpy(target, SYMLINK_HEADER, sizeof(target)); if ((cc = readlink(name, &target[SymlinkHeaderLen], sizeof(target) - SymlinkHeaderLen - 1)) < 0) { warnx("can't readlink `%s'", name); continue; } target[SymlinkHeaderLen + cc] = 0x0; tmp = new_plist_entry(); tmp->name = xstrdup(target); tmp->type = PLIST_COMMENT; tmp->next = p->next; tmp->prev = p; if (p == pkg->tail) { pkg->tail = tmp; } p->next = tmp; p = tmp; break; case S_IFCHR: warnx("Warning - char special device `%s' in PLIST", name); break; case S_IFBLK: warnx("Warning - block special device `%s' in PLIST", name); break; default: (void) strlcpy(buf, CHECKSUM_HEADER, sizeof(buf)); if (MD5File(name, &buf[ChecksumHeaderLen]) != (char *) NULL) { tmp = new_plist_entry(); tmp->name = xstrdup(buf); tmp->type = PLIST_COMMENT; /* PLIST_MD5 - HF */ tmp->next = p->next; tmp->prev = p; if (p == pkg->tail) { pkg->tail = tmp; } p->next = tmp; p = tmp; } break; } break; default: break; } } if (update_pkgdb) { pkgdb_close(); } if (ReorderDirs && dirc > 0) { reorder(pkg, dirc); } }
/* * Check a list for files that require preconversion */ void check_list(package_t *pkg, const char *PkgName) { struct stat st; plist_t *tmp; plist_t *p; char buf[ChecksumHeaderLen + LegibleChecksumLen]; char target[MaxPathSize + SymlinkHeaderLen]; char name[MaxPathSize]; char *cwd = NULL; char *pkgname = NULL; int cc; for (p = pkg->head; p; p = p->next) { switch (p->type) { case PLIST_CWD: cwd = p->name; break; case PLIST_NAME: pkgname = p->name; break; case PLIST_IGNORE: p = p->next; break; case PLIST_PKGDIR: if (cwd == NULL) errx(2, "@pkgdir without preceding @cwd found"); if (pkgname == NULL) errx(2, "@pkgdir without preceding @name found"); break; case PLIST_FILE: if (cwd == NULL) errx(2, "file without preceding @cwd found"); (void) snprintf(name, sizeof(name), "%s%s%s", cwd, (strcmp(cwd, "/") == 0) ? "" : "/", p->name); if (lstat(name, &st) < 0) { warnx("can't stat `%s'", name); continue; } switch (st.st_mode & S_IFMT) { case S_IFDIR: warnx("Warning - directory `%s' in PLIST", name); break; case S_IFLNK: if (RelativeLinks) { CheckSymlink(name, cwd, strlen(cwd)); } (void) strlcpy(target, SYMLINK_HEADER, sizeof(target)); if ((cc = readlink(name, &target[SymlinkHeaderLen], sizeof(target) - SymlinkHeaderLen - 1)) < 0) { warnx("can't readlink `%s'", name); continue; } target[SymlinkHeaderLen + cc] = 0x0; tmp = new_plist_entry(); tmp->name = xstrdup(target); tmp->type = PLIST_COMMENT; tmp->next = p->next; tmp->prev = p; if (p == pkg->tail) { pkg->tail = tmp; } p->next = tmp; p = tmp; break; case S_IFCHR: warnx("Warning - char special device `%s' in PLIST", name); break; case S_IFBLK: warnx("Warning - block special device `%s' in PLIST", name); break; default: (void) strlcpy(buf, CHECKSUM_HEADER, sizeof(buf)); if (MD5File(name, &buf[ChecksumHeaderLen]) != (char *) NULL) { tmp = new_plist_entry(); tmp->name = xstrdup(buf); tmp->type = PLIST_COMMENT; /* PLIST_MD5 - HF */ tmp->next = p->next; tmp->prev = p; if (p == pkg->tail) { pkg->tail = tmp; } p->next = tmp; p = tmp; } break; } break; default: break; } } }
void CFileUpLoad::ThreadProcMain() { USES_CONVERSION; RESTART: if (m_uThreadType == 1) { while(m_bConnect == FALSE) { if (m_bStop) goto END; DWORD dwTimeLatest=0; DWORD dwTimeWait=0; dwTimeLatest = GetTickCount(); dwTimeWait = dwTimeLatest - staticTimer; if (dwTimeWait > 3000) { staticTimer = dwTimeLatest; if (m_pITcpClient) { m_pITcpClient->ReleaseConnections(); m_pITcpClient = NULL; } TRACE(_T("connect server(%s): %s:%d\n"), A2T(m_strSendExtType.c_str()), m_strAddr, m_usPort); m_pITcpClient = CreateTcpClient(*this, T2A(m_strAddr), m_usPort); if (m_pITcpClient == NULL) { m_nConnectFails++; //TRACE0("\nconect to File Server failed!\n"); if (m_UpLoadAddrList.size() > 1 && m_nConnectFails >= 3) { bool bFindAddr = false; std::list<pstUpLoadAddr>::iterator itAddr = m_UpLoadAddrList.begin(); for (; itAddr != m_UpLoadAddrList.end(); itAddr++) { if ((*itAddr)->strIP == T2A(m_strAddr) && m_usPort == (*itAddr)->nPort) { bFindAddr = true; pstUpLoadAddr pUpLoadAddr = *itAddr; m_UpLoadAddrList.erase(itAddr); m_UpLoadAddrList.push_back(pUpLoadAddr); //将此地址移动到最后 break; } } if (!bFindAddr) { pstUpLoadAddr pUpLoadAddr = new stUpLoadAddr; pUpLoadAddr->nPort = m_usPort; pUpLoadAddr->strIP = T2A(m_strAddr); m_UpLoadAddrList.push_back(pUpLoadAddr); //将此地址移动到最后 } //切换ip地址 std::list<pstUpLoadAddr>::iterator itFirstAddr = m_UpLoadAddrList.begin(); std::string strLog = Poco::format("切换文件连接地址%s:%d==>%s:%d(%s)", std::string(T2A(m_strAddr)), (int)m_usPort, (*itFirstAddr)->strIP, (*itFirstAddr)->nPort, m_strSendExtType); g_pLogger->information(strLog); TRACE("%s\n", strLog.c_str()); m_strAddr = A2T((*itFirstAddr)->strIP.c_str()); m_usPort = (*itFirstAddr)->nPort; m_nConnectFails = 0; } g_bFileConnect = false; Sleep(100); continue; } else { TRACE("\nconect to File Server Success!(%s)\n", m_strSendExtType.c_str()); char szLog[300] = { 0 }; sprintf_s(szLog, "连接文件服务器成功(%s)(%s:%d)[%s]", m_strSendExtType.c_str(), T2A(m_strAddr), m_usPort, g_strFileVersion.c_str()); g_pLogger->information(szLog); m_bConnect = TRUE; m_uThreadType = 2; g_bFileConnect = true; m_nConnectFails = 0; goto RESTART; } } else Sleep(300); } } else if (m_uThreadType == 2) { while (m_bUpLoad) { if (!m_bConnect) { m_uThreadType = 1; g_bFileConnect = false; goto RESTART; } bool bFindTask = false; std::list<stUpLoadAns*>::iterator it = m_listFile.begin(); for (; it != m_listFile.end(); it++) { if (m_bStop) goto END; stUpLoadAns* pTask = *it; if (pTask->bUpload == FALSE) { if (_taccess(pTask->strPath, 0) != 0) //_access(T2A(pTask->strPath), 0) != 0 { continue; } bFindTask = true; (reinterpret_cast<pSENDTASK>(pTask->pTask))->fSendPercent = 0; (reinterpret_cast<pSENDTASK>(pTask->pTask))->nSendState = 1; char *szFileBuff = NULL; std::string strAnsName = T2A(pTask->strAnsName); DWORD Length = 0; try { CFile MyFileSend(pTask->strPath, CFile::modeRead); Length = MyFileSend.GetLength(); szFileBuff = new char[Length]; MyFileSend.Seek(0, CFile::begin); MyFileSend.Read(szFileBuff, Length); MyFileSend.Close(); } catch (CMemoryException* e) { (reinterpret_cast<pSENDTASK>(pTask->pTask))->fSendPercent = 0; (reinterpret_cast<pSENDTASK>(pTask->pTask))->nSendState = 3; std::stringstream ssTmpLog; ssTmpLog << "上传文件(" << strAnsName << ")[" << pTask->strPath << "]时内存申请失败,需要重新尝试。"; g_pLogger->information(ssTmpLog.str()); Sleep(500); continue; } catch (CFileException* e) { (reinterpret_cast<pSENDTASK>(pTask->pTask))->fSendPercent = 0; (reinterpret_cast<pSENDTASK>(pTask->pTask))->nSendState = 3; CString strErr = _T(""); e->GetErrorMessage((LPTSTR)(LPCTSTR)strErr, 1024); std::stringstream ssTmpLog; ssTmpLog << "上传文件(" << strAnsName << ")[" << pTask->strPath << "]时发生文件异常,需要重新尝试。" << strErr; g_pLogger->information(ssTmpLog.str()); Sleep(500); continue; } catch (...) { (reinterpret_cast<pSENDTASK>(pTask->pTask))->fSendPercent = 0; (reinterpret_cast<pSENDTASK>(pTask->pTask))->nSendState = 3; std::stringstream ssTmpLog; ssTmpLog << "上传文件(" << strAnsName << ")[" << pTask->strPath << "]时发生未知异常,需要重新尝试。"; g_pLogger->information(ssTmpLog.str()); Sleep(500); continue; } TRACE0("start send ans file\n"); char szLog[300] = { 0 }; sprintf_s(szLog, "开始上传文件(%s): %s", T2A(pTask->strAnsName), g_strFileVersion.c_str()); g_pLogger->information(szLog); //上传文件 ST_CMD_HEADER stHead; stHead.usCmd = REQUEST_UPLOADANS; stHead.uPackSize = sizeof(ST_FILE_INFO)+Length; ST_FILE_INFO stAnsInfo; strcpy(stAnsInfo.szFileName, T2A(pTask->strAnsName)); char *pMd5 = MD5File(T2A(pTask->strPath)); memcpy(stAnsInfo.szMD5, pMd5, LEN_MD5); stAnsInfo.dwFileLen = Length; memcpy(m_szSendBuf, &stHead, HEAD_SIZE); memcpy(m_szSendBuf + HEAD_SIZE, &stAnsInfo, sizeof(ST_FILE_INFO)); RESENDHEAD: ResetEvent(m_hSendReadyEvent); ResetEvent(m_hSendDoneEvent); if (!m_bConnect) { delete szFileBuff; delete pMd5; m_uThreadType = 1; g_bFileConnect = false; break; } if (m_bStop) { sprintf_s(szLog, "发送文件(%s)时检测到系统退出标志,停止发送数据", T2A(pTask->strAnsName)); g_pLogger->information(szLog); (reinterpret_cast<pSENDTASK>(pTask->pTask))->fSendPercent = 0; delete szFileBuff; delete pMd5; break; } if (!sendData(m_szSendBuf, HEAD_SIZE + sizeof(ST_FILE_INFO), pTask)) { std::string strLog = "sendData失败,需要重连"; g_pLogger->information(strLog); (reinterpret_cast<pSENDTASK>(pTask->pTask))->fSendPercent = 0; delete szFileBuff; delete pMd5; m_bConnect = FALSE; break; } // DWORD dwResult1 = WaitForSingleObject(m_hSendReadyEvent, INFINITE); bool bRecvResult = false; //接收服务器是否接收完成数据的结果命令 DWORD dwResult1 = WaitForSingleObject(m_hSendReadyEvent, 5 * 1000); switch (dwResult1) { case WAIT_OBJECT_0: bRecvResult = true; break; case WAIT_TIMEOUT: sprintf_s(szLog, "文件头数据发送完成,接收服务器回复命令失败(%s)失败(5s超时), 需要重传", T2A(pTask->strAnsName)); g_pLogger->information(szLog); break; } if (!bRecvResult) { (reinterpret_cast<pSENDTASK>(pTask->pTask))->fSendPercent = 0; m_bConnect = FALSE; goto RESENDHEAD; } ResetEvent(m_hSendReadyEvent); if (m_bReadyOK == FALSE) { sprintf_s(szLog, "上传文件(%s)的反馈信息失败,重传", T2A(pTask->strAnsName)); g_pLogger->information(szLog); (reinterpret_cast<pSENDTASK>(pTask->pTask))->fSendPercent = 0; m_bConnect = FALSE; goto RESENDHEAD; } if (!sendData(szFileBuff, Length, pTask)) { std::string strLog = "sendData失败2,需要重连"; g_pLogger->information(strLog); (reinterpret_cast<pSENDTASK>(pTask->pTask))->fSendPercent = 0; delete szFileBuff; delete pMd5; m_bConnect = FALSE; break; } // DWORD dwResult = WaitForSingleObject(m_hSendDoneEvent, INFINITE); bRecvResult = false; //接收服务器是否接收完成数据的结果命令 DWORD dwResult = WaitForSingleObject(m_hSendDoneEvent, g_nReUploadWaitTime * 1000); switch (dwResult) { case WAIT_OBJECT_0: bRecvResult = true; break; case WAIT_TIMEOUT: sprintf_s(szLog, "文件数据发送完成,接收服务器回复命令失败(%s)失败(%ds超时)", T2A(pTask->strAnsName), g_nReUploadWaitTime); g_pLogger->information(szLog); break; } if (!bRecvResult) { (reinterpret_cast<pSENDTASK>(pTask->pTask))->fSendPercent = 0; m_bConnect = FALSE; goto RESENDHEAD; } ResetEvent(m_hSendDoneEvent); if (m_bSendOK == FALSE) { sprintf_s(szLog, "上传文件(%s)失败,重传", T2A(pTask->strAnsName)); g_pLogger->information(szLog); (reinterpret_cast<pSENDTASK>(pTask->pTask))->fSendPercent = 0; m_bConnect = FALSE; goto RESENDHEAD; } pTask->bUpload = TRUE; (reinterpret_cast<pSENDTASK>(pTask->pTask))->fSendPercent = 100.0; (reinterpret_cast<pSENDTASK>(pTask->pTask))->nSendState = 2; delete szFileBuff; delete pMd5; TRACE0("end send ans file\n"); if(m_pNotifyObj) m_pNotifyObj->SendFileComplete(stAnsInfo.szFileName, T2A(pTask->strPath)); bFindTask = false; } } if (!bFindTask) Sleep(1000); } } END: return; }
int compare(char *name, NODE *s, FTSENT *p) { u_int32_t len, val; int fd, label; char *cp, *tab = ""; label = 0; switch(s->type) { case F_BLOCK: if (!S_ISBLK(p->fts_statp->st_mode)) goto typeerr; break; case F_CHAR: if (!S_ISCHR(p->fts_statp->st_mode)) goto typeerr; break; case F_DIR: if (!S_ISDIR(p->fts_statp->st_mode)) goto typeerr; break; case F_FIFO: if (!S_ISFIFO(p->fts_statp->st_mode)) goto typeerr; break; case F_FILE: if (!S_ISREG(p->fts_statp->st_mode)) goto typeerr; break; case F_LINK: if (!S_ISLNK(p->fts_statp->st_mode)) goto typeerr; break; case F_SOCK: if (!S_ISSOCK(p->fts_statp->st_mode)) { typeerr: LABEL; (void)printf("\ttype (%s, %s)\n", ftype(s->type), inotype(p->fts_statp->st_mode)); } break; } /* Set the uid/gid first, then set the mode. */ if (s->flags & (F_UID | F_UNAME) && s->st_uid != p->fts_statp->st_uid) { LABEL; (void)printf("%suser (%u, %u", tab, s->st_uid, p->fts_statp->st_uid); if (uflag) if (chown(p->fts_accpath, s->st_uid, -1)) (void)printf(", not modified: %s)\n", strerror(errno)); else (void)printf(", modified)\n"); else (void)printf(")\n"); tab = "\t"; } if (s->flags & (F_GID | F_GNAME) && s->st_gid != p->fts_statp->st_gid) { LABEL; (void)printf("%sgid (%u, %u", tab, s->st_gid, p->fts_statp->st_gid); if (uflag) if (chown(p->fts_accpath, -1, s->st_gid)) (void)printf(", not modified: %s)\n", strerror(errno)); else (void)printf(", modified)\n"); else (void)printf(")\n"); tab = "\t"; } if (s->flags & F_MODE && s->st_mode != (p->fts_statp->st_mode & MBITS)) { if (lflag) { mode_t tmode, mode; tmode = s->st_mode; mode = p->fts_statp->st_mode & MBITS; /* * if none of the suid/sgid/etc bits are set, * then if the mode is a subset of the target, * skip. */ if (!((tmode & ~(S_IRWXU|S_IRWXG|S_IRWXO)) || (mode & ~(S_IRWXU|S_IRWXG|S_IRWXO)))) if ((mode | tmode) == tmode) goto skip; } LABEL; (void)printf("%spermissions (%#o, %#o", tab, s->st_mode, p->fts_statp->st_mode & MBITS); if (uflag) if (chmod(p->fts_accpath, s->st_mode)) (void)printf(", not modified: %s)\n", strerror(errno)); else (void)printf(", modified)\n"); else (void)printf(")\n"); tab = "\t"; skip: ; } if (s->flags & F_NLINK && s->type != F_DIR && s->st_nlink != p->fts_statp->st_nlink) { LABEL; (void)printf("%slink count (%u, %u)\n", tab, s->st_nlink, p->fts_statp->st_nlink); tab = "\t"; } if (s->flags & F_SIZE && s->st_size != p->fts_statp->st_size) { LABEL; (void)printf("%ssize (%qd, %qd)\n", tab, s->st_size, p->fts_statp->st_size); tab = "\t"; } /* * XXX * Since utimes(2) only takes a timeval, there's no point in * comparing the low bits of the timespec nanosecond field. This * will only result in mismatches that we can never fix. * * Doesn't display microsecond differences. */ if (s->flags & F_TIME) { struct timeval tv[2]; TIMESPEC_TO_TIMEVAL(&tv[0], &s->st_mtimespec); TIMESPEC_TO_TIMEVAL(&tv[1], &p->fts_statp->st_mtimespec); if (tv[0].tv_sec != tv[1].tv_sec || tv[0].tv_usec != tv[1].tv_usec) { LABEL; (void)printf("%smodification time (%.24s, ", tab, ctime(&s->st_mtimespec.tv_sec)); (void)printf("%.24s", ctime(&p->fts_statp->st_mtimespec.tv_sec)); if (tflag) { tv[1] = tv[0]; if (utimes(p->fts_accpath, tv)) (void)printf(", not modified: %s)\n", strerror(errno)); else (void)printf(", modified)\n"); } else (void)printf(")\n"); tab = "\t"; } } if (s->flags & F_CKSUM) { if ((fd = open(p->fts_accpath, MTREE_O_FLAGS, 0)) < 0) { LABEL; (void)printf("%scksum: %s: %s\n", tab, p->fts_accpath, strerror(errno)); tab = "\t"; } else if (crc(fd, &val, &len)) { (void)close(fd); LABEL; (void)printf("%scksum: %s: %s\n", tab, p->fts_accpath, strerror(errno)); tab = "\t"; } else { (void)close(fd); if (s->cksum != val) { LABEL; (void)printf("%scksum (%u, %u)\n", tab, s->cksum, val); } tab = "\t"; } } if (s->flags & F_MD5) { char *new_digest, buf[MD5_DIGEST_STRING_LENGTH]; new_digest = MD5File(p->fts_accpath, buf); if (!new_digest) { LABEL; printf("%sMD5File: %s: %s\n", tab, p->fts_accpath, strerror(errno)); tab = "\t"; } else if (strcmp(new_digest, s->md5digest)) { LABEL; printf("%sMD5 (%s, %s)\n", tab, s->md5digest, new_digest); tab = "\t"; } } if (s->flags & F_RMD160) { char *new_digest, buf[RMD160_DIGEST_STRING_LENGTH]; new_digest = RMD160File(p->fts_accpath, buf); if (!new_digest) { LABEL; printf("%sRMD160File: %s: %s\n", tab, p->fts_accpath, strerror(errno)); tab = "\t"; } else if (strcmp(new_digest, s->rmd160digest)) { LABEL; printf("%sRMD160 (%s, %s)\n", tab, s->rmd160digest, new_digest); tab = "\t"; } } if (s->flags & F_SHA1) { char *new_digest, buf[SHA1_DIGEST_STRING_LENGTH]; new_digest = SHA1File(p->fts_accpath, buf); if (!new_digest) { LABEL; printf("%sSHA1File: %s: %s\n", tab, p->fts_accpath, strerror(errno)); tab = "\t"; } else if (strcmp(new_digest, s->sha1digest)) { LABEL; printf("%sSHA1 (%s, %s)\n", tab, s->sha1digest, new_digest); tab = "\t"; } } if (s->flags & F_SHA256) { char *new_digest, buf[SHA256_DIGEST_STRING_LENGTH]; new_digest = SHA256File(p->fts_accpath, buf); if (!new_digest) { LABEL; printf("%sSHA256File: %s: %s\n", tab, p->fts_accpath, strerror(errno)); tab = "\t"; } else if (strcmp(new_digest, s->sha256digest)) { LABEL; printf("%sSHA256 (%s, %s)\n", tab, s->sha256digest, new_digest); tab = "\t"; } } if (s->flags & F_SLINK && strcmp(cp = rlink(name), s->slink)) { LABEL; (void)printf("%slink ref (%s, %s)\n", tab, cp, s->slink); } if (s->flags & F_FLAGS && s->file_flags != p->fts_statp->st_flags) { char *db_flags = NULL; char *cur_flags = NULL; if ((db_flags = fflagstostr(s->file_flags)) == NULL || (cur_flags = fflagstostr(p->fts_statp->st_flags)) == NULL) { LABEL; (void)printf("%sflags: %s %s\n", tab, p->fts_accpath, strerror(errno)); tab = "\t"; free(db_flags); free(cur_flags); } else { LABEL; REPLACE_COMMA(db_flags); REPLACE_COMMA(cur_flags); printf("%sflags (%s, %s", tab, (*db_flags == '\0') ? "-" : db_flags, (*cur_flags == '\0') ? "-" : cur_flags); tab = "\t"; if (uflag) if (chflags(p->fts_accpath, s->file_flags)) (void)printf(", not modified: %s)\n", strerror(errno)); else (void)printf(", modified)\n"); else (void)printf(")\n"); tab = "\t"; free(db_flags); free(cur_flags); } } return (label); }
/* * Delete the results of a package installation. * * This is here rather than in the pkg_delete code because pkg_add needs to * run it too in cases of failure. */ int delete_package(Boolean ign_err, Boolean nukedirs, Package *pkg) { PackingList p; const char *Where = ".", *last_file = ""; Boolean fail = SUCCESS; Boolean preserve; char tmp[FILENAME_MAX], *name = NULL; char *prefix = NULL; preserve = find_plist_option(pkg, "preserve") ? TRUE : FALSE; for (p = pkg->head; p; p = p->next) { switch (p->type) { case PLIST_NAME: name = p->name; break; case PLIST_IGNORE: p = p->next; break; case PLIST_CWD: if (!prefix) prefix = p->name; Where = (p->name == NULL) ? prefix : p->name; if (Verbose) printf("Change working directory to %s\n", Where); break; case PLIST_UNEXEC: format_cmd(tmp, FILENAME_MAX, p->name, Where, last_file); if (Verbose) printf("Execute '%s'\n", tmp); if (!Fake && system(tmp)) { warnx("unexec command for '%s' failed", tmp); fail = FAIL; } break; case PLIST_FILE: last_file = p->name; if (*p->name == '/') strlcpy(tmp, p->name, FILENAME_MAX); else sprintf(tmp, "%s/%s", Where, p->name); if (isdir(tmp) && fexists(tmp) && !issymlink(tmp)) { warnx("cannot delete specified file '%s' - it is a directory!\n" "this packing list is incorrect - ignoring delete request", tmp); } else { if (p->next && p->next->type == PLIST_COMMENT && !strncmp(p->next->name, "MD5:", 4)) { char *cp = NULL, buf[33]; /* * For packing lists whose version is 1.1 or greater, the md5 * hash for a symlink is calculated on the string returned * by readlink(). */ if (issymlink(tmp) && verscmp(pkg, 1, 0) > 0) { int len; char linkbuf[FILENAME_MAX]; if ((len = readlink(tmp, linkbuf, FILENAME_MAX)) > 0) cp = MD5Data((unsigned char *)linkbuf, len, buf); } else if (isfile(tmp) || verscmp(pkg, 1, 1) < 0) cp = MD5File(tmp, buf); if (cp != NULL) { /* Mismatch? */ if (strcmp(cp, p->next->name + 4)) { warnx("'%s' fails original MD5 checksum - %s", tmp, Force ? "deleted anyway." : "not deleted."); if (!Force) { fail = FAIL; continue; } } } } if (Verbose) printf("Delete file %s\n", tmp); if (!Fake) { if (delete_hierarchy(tmp, ign_err, nukedirs)) fail = FAIL; if (preserve && name) { char tmp2[FILENAME_MAX]; if (make_preserve_name(tmp2, FILENAME_MAX, name, tmp)) { if (fexists(tmp2)) { if (rename(tmp2, tmp)) warn("preserve: unable to restore %s as %s", tmp2, tmp); } } } } } break; case PLIST_DIR_RM: sprintf(tmp, "%s/%s", Where, p->name); if (!isdir(tmp) && fexists(tmp)) { warnx("cannot delete specified directory '%s' - it is a file!\n" "this packing list is incorrect - ignoring delete request", tmp); } else { if (Verbose) printf("Delete directory %s\n", tmp); if (!Fake && delete_hierarchy(tmp, ign_err, FALSE)) { warnx("unable to completely remove directory '%s'", tmp); fail = FAIL; } } last_file = p->name; break; default: break; } } return fail; }
/*----------------------------------------------------------------------*/ int main(int argc,char *argv[]) { int fd,wd,x; ssize_t len,i; struct inotify_event equeue[QUEUE_LEN]; struct watch_list_t* pwatch_list = watch_list; char szCommand[BUF_LEN]; char szMessage[BUF_LEN]; char* szFile=NULL; char szBuffer[BUF_LEN]; int num_watch_files=0; int nDiff=0; char szMD5new[BUF_LEN]; int sleep_time=60; if(argc>1) { szFile=argv[1]; } else { printf("Use: %s [ini filename]\n",argv[0]); exit(-1); } #ifdef DAEMONIZE daemon(); #endif /* get the number of files to watch */ x=ReadIniArg(szFile, FILEWATCH,"num_files",szBuffer,BUF_LEN); if(x) { num_watch_files=atoi(szBuffer); } /* get the sleep time */ x=ReadIniArg(szFile, FILEWATCH,"sleep_time",szBuffer,BUF_LEN); if(x) { sleep_time=atoi(szBuffer); } sprintf(szMessage,"watching %d files every %d seconds", num_watch_files,sleep_time); locallog(szMessage); /* set up the basic paramters */ ReadFileData(szFile,num_watch_files); memset(equeue,0,sizeof(struct inotify_event)*QUEUE_LEN); fd=inotify_init(); if(fd==-1) { perror("inotify_init"); exit(EXIT_FAILURE); } /* do the work */ for(x=0;x<num_watch_files;x++) { watch_list[x].wd=inotify_add_watch(fd, watch_list[x].szFile, IN_CLOSE_WRITE); sprintf(szMessage,"watching %s",watch_list[x].szFile); locallog(szMessage); } #ifdef EVENT_QUEUE_METHOD while(1) { len = read (fd,equeue,QUEUE_LEN); i=0; while(i<len) { struct inotify_event *event = (struct inotify_event*) &equeue[i]; if(event->mask && IN_CLOSE_WRITE) { print_event(event); for(x=0;x<MAX_WATCH_FILES;x++) { if(event->wd == watch_list[x].wd) { sprintf(szMessage,"file %s closed",watch_list[x].szFile); locallog(szMessage); /* check the MD5 to see if the file changed */ MD5File(watch_list[x].szFile,szMD5new); nDiff=strcmp(watch_list[x].szMD5,szMD5new); if(nDiff) { DoFileCommand(x); strcpy(watch_list[x].szMD5,szMD5new); } } } } i++; } sleep(2); } inotify_rm_watch(fd); #endif #ifdef POLLING_METHOD while(1) { sleep(sleep_time); for(x=0;x<num_watch_files;x++) { /* check the MD5 to see if the file changed */ MD5File(watch_list[x].szFile,szMD5new); nDiff=strcmp(watch_list[x].szMD5,szMD5new); if(nDiff) { DoFileCommand(x); strcpy(watch_list[x].szMD5,szMD5new); sprintf(szMessage,"file %s new MD5: %s", watch_list[x].szFile, watch_list[x].szMD5); locallog(szMessage); } } } #endif }
static void statf(int indent, FTSENT *p) { struct group *gr; struct passwd *pw; u_int32_t len, val; int fd, offset; char *name, *escaped_name; size_t esc_len; esc_len = p->fts_namelen * 4 + 1; escaped_name = malloc(esc_len); if (escaped_name == NULL) error("statf: %s", strerror(errno)); strnvis(escaped_name, p->fts_name, esc_len, VIS_WHITE | VIS_OCTAL | VIS_GLOB); if (iflag || S_ISDIR(p->fts_statp->st_mode)) offset = printf("%*s%s", indent, "", escaped_name); else offset = printf("%*s %s", indent, "", escaped_name); free(escaped_name); if (offset > (INDENTNAMELEN + indent)) offset = MAXLINELEN; else offset += printf("%*s", (INDENTNAMELEN + indent) - offset, ""); if (!S_ISREG(p->fts_statp->st_mode) && !dflag) output(indent, &offset, "type=%s", inotype(p->fts_statp->st_mode)); if (p->fts_statp->st_uid != uid) { if (keys & F_UNAME) { if ((pw = getpwuid(p->fts_statp->st_uid)) != NULL) { output(indent, &offset, "uname=%s", pw->pw_name); } else { error("could not get uname for uid=%u", p->fts_statp->st_uid); } } if (keys & F_UID) output(indent, &offset, "uid=%u", p->fts_statp->st_uid); } if (p->fts_statp->st_gid != gid) { if (keys & F_GNAME) { if ((gr = getgrgid(p->fts_statp->st_gid)) != NULL) { output(indent, &offset, "gname=%s", gr->gr_name); } else { error("could not get gname for gid=%u", p->fts_statp->st_gid); } } if (keys & F_GID) output(indent, &offset, "gid=%u", p->fts_statp->st_gid); } if (keys & F_MODE && (p->fts_statp->st_mode & MBITS) != mode) output(indent, &offset, "mode=%#o", p->fts_statp->st_mode & MBITS); if (keys & F_NLINK && p->fts_statp->st_nlink != 1) output(indent, &offset, "nlink=%u", p->fts_statp->st_nlink); if (keys & F_SIZE && S_ISREG(p->fts_statp->st_mode)) output(indent, &offset, "size=%qd", p->fts_statp->st_size); if (keys & F_TIME) output(indent, &offset, "time=%lld.%ld", (long long)p->fts_statp->st_mtimespec.tv_sec, p->fts_statp->st_mtimespec.tv_nsec); if (keys & F_CKSUM && S_ISREG(p->fts_statp->st_mode)) { if ((fd = open(p->fts_accpath, MTREE_O_FLAGS, 0)) < 0 || crc(fd, &val, &len)) error("%s: %s", p->fts_accpath, strerror(errno)); (void)close(fd); output(indent, &offset, "cksum=%u", val); } if (keys & F_MD5 && S_ISREG(p->fts_statp->st_mode)) { char *md5digest, buf[MD5_DIGEST_STRING_LENGTH]; md5digest = MD5File(p->fts_accpath,buf); if (!md5digest) error("%s: %s", p->fts_accpath, strerror(errno)); else output(indent, &offset, "md5digest=%s", md5digest); } if (keys & F_RMD160 && S_ISREG(p->fts_statp->st_mode)) { char *rmd160digest, buf[RMD160_DIGEST_STRING_LENGTH]; rmd160digest = RMD160File(p->fts_accpath,buf); if (!rmd160digest) error("%s: %s", p->fts_accpath, strerror(errno)); else output(indent, &offset, "rmd160digest=%s", rmd160digest); } if (keys & F_SHA1 && S_ISREG(p->fts_statp->st_mode)) { char *sha1digest, buf[SHA1_DIGEST_STRING_LENGTH]; sha1digest = SHA1File(p->fts_accpath,buf); if (!sha1digest) error("%s: %s", p->fts_accpath, strerror(errno)); else output(indent, &offset, "sha1digest=%s", sha1digest); } if (keys & F_SHA256 && S_ISREG(p->fts_statp->st_mode)) { char *sha256digest, buf[SHA256_DIGEST_STRING_LENGTH]; sha256digest = SHA256File(p->fts_accpath,buf); if (!sha256digest) error("%s: %s", p->fts_accpath, strerror(errno)); else output(indent, &offset, "sha256digest=%s", sha256digest); } if (keys & F_SLINK && (p->fts_info == FTS_SL || p->fts_info == FTS_SLNONE)) { name = rlink(p->fts_accpath); esc_len = strlen(name) * 4 + 1; escaped_name = malloc(esc_len); if (escaped_name == NULL) error("statf: %s", strerror(errno)); strnvis(escaped_name, name, esc_len, VIS_WHITE | VIS_OCTAL); output(indent, &offset, "link=%s", escaped_name); free(escaped_name); } if (keys & F_FLAGS && !S_ISLNK(p->fts_statp->st_mode)) { char *file_flags; file_flags = fflagstostr(p->fts_statp->st_flags); if (file_flags == NULL) error("%s", strerror(errno)); if (*file_flags != '\0') output(indent, &offset, "flags=%s", file_flags); else output(indent, &offset, "flags=none"); free(file_flags); } (void)putchar('\n'); }
static void statf(FTSENT *p) { u_int32_t len, val; int fd, indent; const char *name; #if !defined(NO_MD5) || !defined(NO_RMD160) || !defined(NO_SHA1) || !defined(NO_SHA2) char *digestbuf; #endif indent = printf("%s%s", S_ISDIR(p->fts_statp->st_mode) ? "" : " ", vispath(p->fts_name)); if (indent > INDENTNAMELEN) indent = MAXLINELEN; else indent += printf("%*s", INDENTNAMELEN - indent, ""); if (!S_ISREG(p->fts_statp->st_mode)) output(&indent, "type=%s", inotype(p->fts_statp->st_mode)); if (keys & (F_UID | F_UNAME) && p->fts_statp->st_uid != uid) { if (keys & F_UNAME && (name = user_from_uid(p->fts_statp->st_uid, 1)) != NULL) output(&indent, "uname=%s", name); else /* if (keys & F_UID) */ output(&indent, "uid=%u", p->fts_statp->st_uid); } if (keys & (F_GID | F_GNAME) && p->fts_statp->st_gid != gid) { if (keys & F_GNAME && (name = group_from_gid(p->fts_statp->st_gid, 1)) != NULL) output(&indent, "gname=%s", name); else /* if (keys & F_GID) */ output(&indent, "gid=%u", p->fts_statp->st_gid); } if (keys & F_MODE && (p->fts_statp->st_mode & MBITS) != mode) output(&indent, "mode=%#o", p->fts_statp->st_mode & MBITS); if (keys & F_DEV && (S_ISBLK(p->fts_statp->st_mode) || S_ISCHR(p->fts_statp->st_mode))) output(&indent, "device=%#llx", (long long)p->fts_statp->st_rdev); if (keys & F_NLINK && p->fts_statp->st_nlink != 1) output(&indent, "nlink=%u", p->fts_statp->st_nlink); if (keys & F_SIZE && S_ISREG(p->fts_statp->st_mode)) output(&indent, "size=%lld", (long long)p->fts_statp->st_size); if (keys & F_TIME) #if defined(BSD4_4) && !defined(HAVE_NBTOOL_CONFIG_H) output(&indent, "time=%ld.%ld", (long)p->fts_statp->st_mtimespec.tv_sec, p->fts_statp->st_mtimespec.tv_nsec); #else output(&indent, "time=%ld.%ld", (long)p->fts_statp->st_mtime, (long)0); #endif if (keys & F_CKSUM && S_ISREG(p->fts_statp->st_mode)) { if ((fd = open(p->fts_accpath, O_RDONLY, 0)) < 0 || crc(fd, &val, &len)) mtree_err("%s: %s", p->fts_accpath, strerror(errno)); close(fd); output(&indent, "cksum=%lu", (long)val); } #ifndef NO_MD5 if (keys & F_MD5 && S_ISREG(p->fts_statp->st_mode)) { if ((digestbuf = MD5File(p->fts_accpath, NULL)) == NULL) mtree_err("%s: MD5File failed: %s", p->fts_accpath, strerror(errno)); output(&indent, "md5=%s", digestbuf); free(digestbuf); } #endif /* ! NO_MD5 */ #ifndef NO_RMD160 if (keys & F_RMD160 && S_ISREG(p->fts_statp->st_mode)) { if ((digestbuf = RMD160File(p->fts_accpath, NULL)) == NULL) mtree_err("%s: RMD160File failed: %s", p->fts_accpath, strerror(errno)); output(&indent, "rmd160=%s", digestbuf); free(digestbuf); } #endif /* ! NO_RMD160 */ #ifndef NO_SHA1 if (keys & F_SHA1 && S_ISREG(p->fts_statp->st_mode)) { if ((digestbuf = SHA1File(p->fts_accpath, NULL)) == NULL) mtree_err("%s: SHA1File failed: %s", p->fts_accpath, strerror(errno)); output(&indent, "sha1=%s", digestbuf); free(digestbuf); } #endif /* ! NO_SHA1 */ #ifndef NO_SHA2 if (keys & F_SHA256 && S_ISREG(p->fts_statp->st_mode)) { if ((digestbuf = SHA256_File(p->fts_accpath, NULL)) == NULL) mtree_err("%s: SHA256_File failed: %s", p->fts_accpath, strerror(errno)); output(&indent, "sha256=%s", digestbuf); free(digestbuf); } if (keys & F_SHA384 && S_ISREG(p->fts_statp->st_mode)) { if ((digestbuf = SHA384_File(p->fts_accpath, NULL)) == NULL) mtree_err("%s: SHA384_File failed: %s", p->fts_accpath, strerror(errno)); output(&indent, "sha384=%s", digestbuf); free(digestbuf); } if (keys & F_SHA512 && S_ISREG(p->fts_statp->st_mode)) { if ((digestbuf = SHA512_File(p->fts_accpath, NULL)) == NULL) mtree_err("%s: SHA512_File failed: %s", p->fts_accpath, strerror(errno)); output(&indent, "sha512=%s", digestbuf); free(digestbuf); } #endif /* ! NO_SHA2 */ if (keys & F_SLINK && (p->fts_info == FTS_SL || p->fts_info == FTS_SLNONE)) output(&indent, "link=%s", vispath(rlink(p->fts_accpath))); #if HAVE_STRUCT_STAT_ST_FLAGS if (keys & F_FLAGS && p->fts_statp->st_flags != flags) output(&indent, "flags=%s", flags_to_string(p->fts_statp->st_flags, "none")); #endif putchar('\n'); }
/* * Delete the results of a package installation. * * This is here rather than in the pkg_delete code because pkg_add needs to * run it too in cases of failure. */ int delete_package(Boolean ign_err, package_t *pkg, Boolean NoDeleteFiles, const char *destdir) { plist_t *p; const char *last_file = ""; int fail = SUCCESS; Boolean preserve; char tmp[MaxPathSize]; const char *prefix = NULL, *name = NULL; if (!pkgdb_open(ReadWrite)) { err(EXIT_FAILURE, "cannot open pkgdb"); } preserve = find_plist_option(pkg, "preserve") ? TRUE : FALSE; for (p = pkg->head; p; p = p->next) { switch (p->type) { case PLIST_NAME: name = p->name; break; case PLIST_CWD: if (prefix == NULL) prefix = p->name; break; default: break; } } if (name == NULL || prefix == NULL) errx(EXIT_FAILURE, "broken PLIST"); /* * Remove database entries first, directory removal is done * in the main loop below. */ for (p = pkg->head; p; p = p->next) { if (p->type == PLIST_PKGDIR) delete_pkgdir(name, prefix, p->name); } for (p = pkg->head; p; p = p->next) { switch (p->type) { case PLIST_NAME: /* Handled already */ break; case PLIST_PKGDIR: case PLIST_DIR_RM: (void) snprintf(tmp, sizeof(tmp), "%s/%s", prefix, p->name); if (has_pkgdir(tmp)) continue; (void) snprintf(tmp, sizeof(tmp), "%s%s%s/%s", destdir ? destdir : "", destdir ? "/" : "", prefix, p->name); if (!fexists(tmp)) { if (p->type == PLIST_PKGDIR) warnx("Directory `%s' disappeared, skipping", tmp); } else if (!isdir(tmp)) { warnx("attempting to delete a file `%s' as a directory\n" "this packing list is incorrect - ignoring delete request", tmp); } else if (delete_with_parents(tmp, ign_err, TRUE)) fail = FAIL; break; case PLIST_IGNORE: p = p->next; break; case PLIST_UNEXEC: if (NoDeleteFiles) break; format_cmd(tmp, sizeof(tmp), p->name, prefix, last_file); printf("Executing `%s'\n", tmp); if (!Fake && system(tmp)) { warnx("unexec command for `%s' failed", tmp); fail = FAIL; } break; case PLIST_FILE: last_file = p->name; (void) snprintf(tmp, sizeof(tmp), "%s%s%s/%s", destdir ? destdir : "", destdir ? "/" : "", prefix, p->name); if (isdir(tmp)) { warnx("attempting to delete directory `%s' as a file\n" "this packing list is incorrect - ignoring delete request", tmp); } else { int restored = 0; /* restored from preserve? */ if (p->next && p->next->type == PLIST_COMMENT) { if (strncmp(p->next->name, CHECKSUM_HEADER, ChecksumHeaderLen) == 0) { char *cp, buf[LegibleChecksumLen]; if ((cp = MD5File(tmp, buf)) != NULL) { /* Mismatch? */ if (strcmp(cp, p->next->name + ChecksumHeaderLen) != 0) { printf("original MD5 checksum failed, %s: %s\n", Force ? "deleting anyway" : "not deleting", tmp); if (!Force) { fail = FAIL; goto pkgdb_cleanup; } } } } else if (strncmp(p->next->name, SYMLINK_HEADER, SymlinkHeaderLen) == 0) { char buf[MaxPathSize + SymlinkHeaderLen]; int cc; (void) strlcpy(buf, SYMLINK_HEADER, sizeof(buf)); if ((cc = readlink(tmp, &buf[SymlinkHeaderLen], sizeof(buf) - SymlinkHeaderLen - 1)) < 0) { warn("can't readlink `%s'", tmp); goto pkgdb_cleanup; } buf[SymlinkHeaderLen + cc] = 0x0; if (strcmp(buf, p->next->name) != 0) { if ((cc = readlink(&buf[SymlinkHeaderLen], &buf[SymlinkHeaderLen], sizeof(buf) - SymlinkHeaderLen)) < 0) { printf("symlink %s is not same as recorded value, %s: %s\n", buf, Force ? "deleting anyway" : "not deleting", tmp); if (!Force) { fail = FAIL; goto pkgdb_cleanup; } } buf[SymlinkHeaderLen + cc] = 0x0; if (strcmp(buf, p->next->name) != 0) { printf("symlink %s is not same as recorded value, %s: %s\n", buf, Force ? "deleting anyway" : "not deleting", tmp); if (!Force) { fail = FAIL; goto pkgdb_cleanup; } } } } } if (Verbose && !NoDeleteFiles) printf("Delete file %s\n", tmp); if (!Fake && !NoDeleteFiles) { if (delete_with_parents(tmp, ign_err, FALSE)) fail = FAIL; if (preserve && name) { char tmp2[MaxPathSize]; if (make_preserve_name(tmp2, MaxPathSize, name, tmp)) { if (fexists(tmp2)) { if (rename(tmp2, tmp)) warn("preserve: unable to restore %s as %s", tmp2, tmp); else restored = 1; } } } } pkgdb_cleanup: if (!Fake) { if (!restored) { errno = 0; if (pkgdb_remove(tmp) && errno) perror("pkgdb_remove"); } } } break; default: break; } } pkgdb_close(); return fail; }
static void statf(int indent, FTSENT *p) { struct group *gr; struct passwd *pw; uint32_t val; off_t len; int fd, offset; char *fflags; char *escaped_name; escaped_name = calloc(1, p->fts_namelen * 4 + 1); if (escaped_name == NULL) errx(1, "statf(): calloc() failed"); strvis(escaped_name, p->fts_name, VIS_WHITE | VIS_OCTAL | VIS_GLOB); if (iflag || S_ISDIR(p->fts_statp->st_mode)) offset = printf("%*s%s", indent, "", escaped_name); else offset = printf("%*s %s", indent, "", escaped_name); free(escaped_name); if (offset > (INDENTNAMELEN + indent)) offset = MAXLINELEN; else offset += printf("%*s", (INDENTNAMELEN + indent) - offset, ""); if (!S_ISREG(p->fts_statp->st_mode) && !dflag) output(indent, &offset, "type=%s", inotype(p->fts_statp->st_mode)); if (p->fts_statp->st_uid != uid) { if (keys & F_UNAME) { pw = getpwuid(p->fts_statp->st_uid); if (pw != NULL) output(indent, &offset, "uname=%s", pw->pw_name); else if (wflag) warnx("Could not get uname for uid=%u", p->fts_statp->st_uid); else errx(1, "Could not get uname for uid=%u", p->fts_statp->st_uid); } if (keys & F_UID) output(indent, &offset, "uid=%u", p->fts_statp->st_uid); } if (p->fts_statp->st_gid != gid) { if (keys & F_GNAME) { gr = getgrgid(p->fts_statp->st_gid); if (gr != NULL) output(indent, &offset, "gname=%s", gr->gr_name); else if (wflag) warnx("Could not get gname for gid=%u", p->fts_statp->st_gid); else errx(1, "Could not get gname for gid=%u", p->fts_statp->st_gid); } if (keys & F_GID) output(indent, &offset, "gid=%u", p->fts_statp->st_gid); } if (keys & F_MODE && (p->fts_statp->st_mode & MBITS) != mode) output(indent, &offset, "mode=%#o", p->fts_statp->st_mode & MBITS); if (keys & F_NLINK && p->fts_statp->st_nlink != 1) output(indent, &offset, "nlink=%u", p->fts_statp->st_nlink); if (keys & F_SIZE) output(indent, &offset, "size=%jd", (intmax_t)p->fts_statp->st_size); if (keys & F_TIME) output(indent, &offset, "time=%ld.%ld", (long)p->fts_statp->st_mtimespec.tv_sec, p->fts_statp->st_mtimespec.tv_nsec); if (keys & F_CKSUM && S_ISREG(p->fts_statp->st_mode)) { if ((fd = open(p->fts_accpath, O_RDONLY, 0)) < 0 || crc(fd, &val, &len)) err(1, "%s", p->fts_accpath); (void)close(fd); output(indent, &offset, "cksum=%lu", (unsigned long)val); } #ifdef ENABLE_MD5 if (keys & F_MD5 && S_ISREG(p->fts_statp->st_mode)) { char *digest, buf[33]; digest = MD5File(p->fts_accpath, buf); if (!digest) err(1, "%s", p->fts_accpath); output(indent, &offset, "md5digest=%s", digest); } #endif /* ENABLE_MD5 */ #ifdef ENABLE_SHA1 if (keys & F_SHA1 && S_ISREG(p->fts_statp->st_mode)) { char *digest, buf[41]; digest = SHA1_File(p->fts_accpath, buf); if (!digest) err(1, "%s", p->fts_accpath); output(indent, &offset, "sha1digest=%s", digest); } #endif /* ENABLE_SHA1 */ #ifdef ENABLE_RMD160 if (keys & F_RMD160 && S_ISREG(p->fts_statp->st_mode)) { char *digest, buf[41]; digest = RIPEMD160_File(p->fts_accpath, buf); if (!digest) err(1, "%s", p->fts_accpath); output(indent, &offset, "ripemd160digest=%s", digest); } #endif /* ENABLE_RMD160 */ #ifdef ENABLE_SHA256 if (keys & F_SHA256 && S_ISREG(p->fts_statp->st_mode)) { char *digest, buf[65]; digest = SHA256_File(p->fts_accpath, buf); if (!digest) err(1, "%s", p->fts_accpath); output(indent, &offset, "sha256digest=%s", digest); } #endif /* ENABLE_SHA256 */ if (keys & F_SLINK && (p->fts_info == FTS_SL || p->fts_info == FTS_SLNONE)) { char visbuf[MAXPATHLEN * 4]; char *s = rlink(p->fts_accpath); strvis(visbuf, s, VIS_WHITE | VIS_OCTAL); output(indent, &offset, "link=%s", visbuf); } if (keys & F_FLAGS && p->fts_statp->st_flags != flags) { fflags = flags_to_string(p->fts_statp->st_flags); output(indent, &offset, "flags=%s", fflags); free(fflags); } (void)putchar('\n'); }
static int mod_init(void) { /* Register RPC commands */ if (rpc_register_array(rpc_cmds)!=0) { LM_ERR("failed to register RPC commands\n"); return -1; } if(register_mi_mod(exports.name, mi_cmds)!=0) { LM_ERR("failed to register MI commands\n"); return -1; } if (!hash_file) { LM_INFO("no hash_file given, disable hash functionality\n"); } else { if (MD5File(config_hash, hash_file) != 0) { LM_ERR("could not hash the config file"); return -1; } LM_DBG("config file hash is %.*s", MD5_LEN, config_hash); } if (initial_prob > 100) { LM_ERR("invalid probability <%d>\n", initial_prob); return -1; } LM_DBG("initial probability %d percent\n", initial_prob); probability=(int *) shm_malloc(sizeof(int)); if (!probability) { LM_ERR("no shmem available\n"); return -1; } *probability = initial_prob; gflags=(unsigned int *) shm_malloc(sizeof(unsigned int)); if (!gflags) { LM_ERR(" no shmem available\n"); return -1; } *gflags=initial_gflags; gflags_lock = lock_alloc(); if (gflags_lock==0) { LM_ERR("cannot allocate gflgas lock\n"); return -1; } if (lock_init(gflags_lock)==NULL) { LM_ERR("cannot initiate gflags lock\n"); lock_dealloc(gflags_lock); return -1; } if(_cfg_lock_size>0 && _cfg_lock_size<=10) { _cfg_lock_size = 1<<_cfg_lock_size; _cfg_lock_set = lock_set_alloc(_cfg_lock_size); if(_cfg_lock_set==NULL || lock_set_init(_cfg_lock_set)==NULL) { LM_ERR("cannot initiate lock set\n"); return -1; } } return 0; }
bool DownloadAndApplyPatch(std::string targetDirectory, std::string versionFile, uint64_t currentVersion) { for (unsigned int patchIndex = 0; patchIndex < g_BestPatchPath.size(); ++patchIndex) { const Patch& patch = g_Patches[g_BestPatchPath[patchIndex]]; std::string updatesDirectory = "updates/"; // Create the updates directory. No problem if the directory already exists. errno = 0; ZPatcher::CreateDirectoryTree(updatesDirectory); if (errno != 0 && errno != EEXIST) { ZPatcher::Log(ZPatcher::LOG_FATAL, "An error occurred while attempting to create the directory structure: %s", updatesDirectory.c_str(), strerror(errno)); return false; } // Split the filename from the URL size_t length = patch.fileURL.find_last_of('/'); if (length == std::string::npos) { fprintf(stderr, "Invalid Update URL.\n"); // This is bad! Our URL is malformed (no slashes in it!) return false; } std::string urlBase = std::string(patch.fileURL, 0, length + 1); std::string fileName = std::string(patch.fileURL, length + 1, std::string::npos); std::string localFullPath = (updatesDirectory + fileName); bool MD5Matches = false; while (!MD5Matches) { // Check if the target file already exists. errno = 0; #ifdef _WIN32 int fileExists = _access(localFullPath.c_str(), 0); // Will return Zero if file exists #else int fileExists = access(localFullPath.c_str(), F_OK); // Will return Zero if file exists #endif // _WIN32 // If the file exists, check if it match the required MD5. If not, re-download the file. bool downloadFile = true; if (fileExists == 0) { fprintf(stdout, "\nChecking if MD5 of the file %s matches the required by the patch...\n", fileName.c_str()); std::string fileMD5 = MD5File(localFullPath); fprintf(stdout, "Required MD5:\t%s\n", patch.fileMD5.c_str()); fprintf(stdout, "File MD5:\t%s\n", fileMD5.c_str()); if (_stricmp(fileMD5.c_str(), patch.fileMD5.c_str()) == 0) { fprintf(stdout, "Matches!\n"); downloadFile = false; MD5Matches = true; } else { fprintf(stdout, "Does not match! :(\n"); downloadFile = true; } } // Should we download the file? :) if (downloadFile) { SimpleDownloadFile(patch.fileURL, updatesDirectory); fprintf(stdout, "\n"); } } // If we got here, the file is downloaded and the MD5 Matches fprintf(stdout, "\nApplying patch: %s \n", fileName.c_str()); ZPatcher::InitLogSystem("./"); if (ZPatcher::ApplyPatchFile(localFullPath, targetDirectory, currentVersion)) { SaveTargetNewVersion(versionFile, patch.targetBuildNumber); if (!SaveTargetNewVersion(versionFile, patch.targetBuildNumber)) { ZPatcher::DestroyLogSystem(); system("pause"); return false; } currentVersion = patch.targetBuildNumber; ZPatcher::DestroyLogSystem(); } else { ZPatcher::DestroyLogSystem(); system("pause"); return false; } ////////////////////////////////////////////////////////////////////////// // HACK! HACK! HACK! HACK! HACK! // TODO: Rewrite this function so that this horrendous hack isn't here! bool shouldRestart = false; if (!SelfUpdate(shouldRestart)) return false; else if (shouldRestart) exit(EXIT_SUCCESS); ////////////////////////////////////////////////////////////////////////// } return true; }