bool FileExists(const char * filePath) { FILE * fp = muscleFopen(filePath, "rb"); const bool ret = (fp != NULL); // gotta take this value before calling fclose(), or cppcheck complains if (fp) fclose(fp); return ret; }
status_t CopyFile(const char * oldPath, const char * newPath, bool allowCopyFolder) { if (strcmp(oldPath, newPath) == 0) return B_NO_ERROR; // Copying something onto itself is a no-op if (allowCopyFolder) { const FilePathInfo oldFPI(oldPath); if (oldFPI.IsDirectory()) return CopyDirectoryRecursive(oldPath, newPath); } FILE * fpIn = muscleFopen(oldPath, "rb"); if (fpIn == NULL) return B_ERROR; status_t ret = B_NO_ERROR; // optimistic default FILE * fpOut = muscleFopen(newPath, "wb"); if (fpOut) { while(1) { char buf[4*1024]; const size_t bytesRead = fread(buf, 1, sizeof(buf), fpIn); if ((bytesRead < sizeof(buf))&&(feof(fpIn) == false)) { ret = B_ERROR; break; } const size_t bytesWritten = fwrite(buf, 1, bytesRead, fpOut); if (bytesWritten < bytesRead) { ret = B_ERROR; break; } if (feof(fpIn)) break; } fclose(fpOut); } else ret = B_ERROR; fclose(fpIn); if ((fpOut)&&(ret != B_NO_ERROR)) (void) DeleteFile(newPath); // clean up on error return ret; }
float GetSystemMemoryUsagePercentage() { #if defined(__linux__) FILE * fpIn = muscleFopen("/proc/meminfo", "r"); if (fpIn) { double memTotal = -1.0, memFree = -1.0, buffered = -1.0, cached = -1.0; char buf[512]; while((fgets(buf, sizeof(buf), fpIn) != NULL)&&((memTotal<=0.0)||(memFree<0.0)||(buffered<0.0)||(cached<0.0))) { if (strncmp(buf, "MemTotal:", 9) == 0) memTotal = ParseMemValue(buf+9); else if (strncmp(buf, "MemFree:", 8) == 0) memFree = ParseMemValue(buf+8); else if (strncmp(buf, "Buffers:", 8) == 0) buffered = ParseMemValue(buf+8); else if (strncmp(buf, "Cached:", 7) == 0) cached = ParseMemValue(buf+7); } fclose(fpIn); if ((memTotal > 0.0)&&(memFree >= 0.0)&&(buffered >= 0.0)&&(cached >= 0.0)) { const double memUsed = memTotal-(memFree+buffered+cached); return (float) (memUsed/memTotal); } } #elif defined(__APPLE__) FILE * fpIn = popen("/usr/bin/vm_stat", "r"); if (fpIn) { double pagesUsed = 0.0, totalPages = 0.0; char buf[512]; while(fgets(buf, sizeof(buf), fpIn) != NULL) { if (strncmp(buf, "Pages", 5) == 0) { const double val = ParseMemValue(buf); if (val >= 0.0) { if ((strncmp(buf, "Pages wired", 11) == 0)||(strncmp(buf, "Pages active", 12) == 0)) pagesUsed += val; totalPages += val; } } else if (strncmp(buf, "Mach Virtual Memory Statistics", 30) != 0) break; // Stop at "Translation Faults", we don't care about anything at or below that } pclose(fpIn); if (totalPages > 0.0) return (float) (pagesUsed/totalPages); } #elif defined(WIN32) && !defined(__MINGW32__) MEMORYSTATUSEX stat; memset(&stat, 0, sizeof(stat)); stat.dwLength = sizeof(stat); GlobalMemoryStatusEx(&stat); return ((float)stat.dwMemoryLoad)/100.0f; #endif return -1.0f; }
status_t TarFileWriter :: SetFile(const char * outputFileName, bool append) { (void) Close(); _writerIO.Reset(); if (outputFileName) { if (append == false) (void) DeleteFile(outputFileName); FILE * fpOut = muscleFopen(outputFileName, append?"ab":"wb"); if (fpOut) { _writerIO.SetRef(newnothrow FileDataIO(fpOut)); if (_writerIO()) return B_NO_ERROR; else {fclose(fpOut); WARN_OUT_OF_MEMORY;} } return B_ERROR; } else return B_NO_ERROR; }
App::App(void) : BApplication(STR_MUSCLE_DEAMON_NAME) , maxBytes(MUSCLE_NO_LIMIT) , maxNodesPerSession(MUSCLE_NO_LIMIT) , maxReceiveRate(MUSCLE_NO_LIMIT) , maxSendRate(MUSCLE_NO_LIMIT) , maxCombinedRate(MUSCLE_NO_LIMIT) , maxMessageSize(MUSCLE_NO_LIMIT) , maxSessions(MUSCLE_NO_LIMIT) , maxSessionsPerHost(MUSCLE_NO_LIMIT) , fprivateKeyFilePath(NULL) , retVal(0) , okay(true) { CompleteSetupSystem css; TCHECKPOINT; #ifdef MUSCLE_ENABLE_MEMORY_TRACKING printf("MUSCLE_ENABLE_MEMORY_TRACKING\n"); // Set up memory allocation policies for our server. These policies will make sure // that the server can't allocate more than a specified amount of memory, and if it tries, // some emergency callbacks will be called to free up cached info. FunctionCallback fcb(AbstractObjectRecycler::GlobalFlushAllCachedObjects); MemoryAllocatorRef nullRef; AutoCleanupProxyMemoryAllocator cleanupAllocator(nullRef); cleanupAllocator.GetCallbacksQueue().AddTail(GenericCallbackRef(&fcb, false)); UsageLimitProxyMemoryAllocator usageLimitAllocator(MemoryAllocatorRef(&cleanupAllocator, false)); SetCPlusPlusGlobalMemoryAllocator(MemoryAllocatorRef(&usageLimitAllocator, false)); SetCPlusPlusGlobalMemoryAllocator(MemoryAllocatorRef()); // unset, so that none of our allocator objects will be used after they are gone if ((maxBytes != MUSCLE_NO_LIMIT) && (&usageLimitAllocator)) usageLimitAllocator.SetMaxNumBytes(maxBytes); #endif TCHECKPOINT; server.GetAddressRemappingTable() = tempRemaps; if (maxNodesPerSession != MUSCLE_NO_LIMIT) server.GetCentralState().AddInt32(PR_NAME_MAX_NODES_PER_SESSION, maxNodesPerSession); for (MessageFieldNameIterator iter = tempPrivs.GetFieldNameIterator(); iter.HasData(); iter++) tempPrivs.CopyName(iter.GetFieldName(), server.GetCentralState()); // If the user asked for bandwidth limiting, create Policy objects to handle that. AbstractSessionIOPolicyRef inputPolicyRef, outputPolicyRef; if (maxCombinedRate != MUSCLE_NO_LIMIT) { inputPolicyRef.SetRef(newnothrow RateLimitSessionIOPolicy(maxCombinedRate)); outputPolicyRef = inputPolicyRef; if (inputPolicyRef()) LogTime(MUSCLE_LOG_INFO, "Limiting aggregate I/O bandwidth to %.02f kilobytes/second.\n", ((float)maxCombinedRate/1024.0f)); else { WARN_OUT_OF_MEMORY; okay = false; } } else { if (maxReceiveRate != MUSCLE_NO_LIMIT) { inputPolicyRef.SetRef(newnothrow RateLimitSessionIOPolicy(maxReceiveRate)); if (inputPolicyRef()) LogTime(MUSCLE_LOG_INFO, "Limiting aggregate receive bandwidth to %.02f kilobytes/second.\n", ((float)maxReceiveRate/1024.0f)); else { WARN_OUT_OF_MEMORY; okay = false; } } if (maxSendRate != MUSCLE_NO_LIMIT) { outputPolicyRef.SetRef(newnothrow RateLimitSessionIOPolicy(maxSendRate)); if (outputPolicyRef()) LogTime(MUSCLE_LOG_INFO, "Limiting aggregate send bandwidth to %.02f kilobytes/second.\n", ((float)maxSendRate/1024.0f)); else { WARN_OUT_OF_MEMORY; okay = false; } } } // Set up the Session Factory. This factory object creates the new StorageReflectSessions // as needed when people connect, and also has a filter to keep out the riff-raff. StorageReflectSessionFactory factory; factory.SetMaxIncomingMessageSize(maxMessageSize); FilterSessionFactory filter(ReflectSessionFactoryRef(&factory, false), maxSessionsPerHost, maxSessions); filter.SetInputPolicy(inputPolicyRef); filter.SetOutputPolicy(outputPolicyRef); for (int b=bans.GetNumItems()-1; ((okay)&&(b>=0)); b--) if (filter.PutBanPattern(bans[b]()) != B_NO_ERROR) okay = false; for (int a=requires.GetNumItems()-1; ((okay)&&(a>=0)); a--) if (filter.PutRequirePattern(requires[a]()) != B_NO_ERROR) okay = false; #ifdef MUSCLE_ENABLE_SSL ByteBufferRef optCryptoBuf; if (fprivateKeyFilePath) { FileDataIO fdio(muscleFopen(fprivateKeyFilePath->Cstr(), "rb")); ByteBufferRef fileData = GetByteBufferFromPool((uint32)fdio.GetLength()); if ((fdio.GetFile())&&(fileData())&&(fdio.ReadFully(fileData()->GetBuffer(), fileData()->GetNumBytes()) == fileData()->GetNumBytes())) { LogTime(MUSCLE_LOG_INFO, "Using private key file [%s] to authenticate with connecting clients\n", fprivateKeyFilePath->Cstr()); server.SetSSLPrivateKey(fileData); } else { LogTime(MUSCLE_LOG_CRITICALERROR, "Couldn't load private key file [%s] (file not found?)\n", fprivateKeyFilePath->Cstr()); okay = false; } } #else if (fprivateKeyFilePath) { LogTime(MUSCLE_LOG_CRITICALERROR, "Can't loadp private key file [%s], SSL support is not compiled in!\n", fprivateKeyFilePath->Cstr()); okay = false; } #endif // Set up ports. We allow multiple ports, mostly just to show how it can be done; // they all get the same set of ban/require patterns (since they all do the same thing anyway). if (listenPorts.IsEmpty()) listenPorts.PutWithDefault(IPAddressAndPort(invalidIP, DEFAULT_MUSCLED_PORT)); for (HashtableIterator<IPAddressAndPort, Void> iter(listenPorts); iter.HasData(); iter++) { const IPAddressAndPort & iap = iter.GetKey(); if (server.PutAcceptFactory(iap.GetPort(), ReflectSessionFactoryRef(&filter, false), iap.GetIPAddress()) != B_NO_ERROR) { if (iap.GetIPAddress() == invalidIP) LogTime(MUSCLE_LOG_CRITICALERROR, "Error adding port %u, aborting.\n", iap.GetPort()); else LogTime(MUSCLE_LOG_CRITICALERROR, "Error adding port %u to interface %s, aborting.\n", iap.GetPort(), Inet_NtoA(iap.GetIPAddress())()); okay = false; break; } } if (okay) { retVal = (server.ServerProcessLoop() == B_NO_ERROR) ? 0 : 10; if (retVal > 0) LogTime(MUSCLE_LOG_CRITICALERROR, "Server process aborted!\n"); else LogTime(MUSCLE_LOG_INFO, "Server process exiting.\n"); } else LogTime(MUSCLE_LOG_CRITICALERROR, "Error occurred during setup, aborting!\n"); server.Cleanup(); }
MessageRef ReadZipFile(const char * fileName, bool loadData) { FileDataIO fio(muscleFopen(fileName, "rb")); return ReadZipFile(fio, loadData); }
status_t WriteZipFile(const char * fileName, const Message & msg, int compressionLevel, uint64 fileCreationTime) { FileDataIO fio(muscleFopen(fileName, "wb")); return WriteZipFile(fio, msg, compressionLevel, fileCreationTime); }