bool copyDirectory(const path& source, const path& destination) { if (!QDir().mkpath(toQString(destination))) { return false; } QDir srcDir(toQString(source)); for (const QFileInfo &info : srcDir.entryInfoList(QDir::Dirs | QDir::Files | QDir::NoDotAndDotDot)) { QString srcItemPath = toQString(source) + "/" + info.fileName(); QString dstItemPath = toQString(destination) + "/" + info.fileName(); if (info.isDir()) { if (!copyDirectory(toPath(srcItemPath), toPath(dstItemPath))) { return false; } } else if (info.isFile()) { if (!QFile::copy(srcItemPath, dstItemPath)) { return false; } } } return true; }
MHWD::STATUS Mhwd::installConfig(std::shared_ptr<Config> config) { std::string databaseDir; if ("USB" == config->type_) { databaseDir = MHWD_USB_DATABASE_DIR; } else { databaseDir = MHWD_PCI_DATABASE_DIR; } if (!runScript(config, MHWD::TRANSACTIONTYPE::INSTALL)) { return MHWD::STATUS::ERROR_SCRIPT_FAILED; } if (!copyDirectory(config->basePath_, databaseDir + "/" + config->name_)) { return MHWD::STATUS::ERROR_SET_DATABASE; } // Installed config vectors have to be updated manual with updateInstalledConfigData(Data*) return MHWD::STATUS::SUCCESS; }
bool copyDirFile(wxString& path, wxString& item, wxString& pathNew, void* parent, onThreadBeginCopyFileCallBackFunc onBeginCopyFile = NULL, onThreadEndCopyFileCallBackFunc onEndCopyFile = NULL) { wxString filePath = path + "\\" + item; bool blnIsDirectory = false; { wxDir dir; blnIsDirectory = dir.Exists(filePath); } if (blnIsDirectory) return copyDirectory(path, item, pathNew, parent, onBeginCopyFile, onEndCopyFile); wxFile file; if (file.Exists(filePath)) { bool blnCopy = false; int intCopy = COPY_FILE_OK; wxString itemNew = (path == pathNew ? "Copy of " + item : item); if (onBeginCopyFile) intCopy = onBeginCopyFile(parent, path + "\\" + item, pathNew + "\\" + itemNew); if (intCopy == COPY_FILE_OK) blnCopy = wxCopyFile(path + "\\" + item, pathNew + "\\" + itemNew, true); if (onEndCopyFile) onEndCopyFile(parent, blnCopy, path + "\\" + item, pathNew + "\\" + itemNew); return blnCopy; } return false; }
QMap< QString, QString> ConfigBase::exportDatas( const QString &directory ) { QDir copyDirectory( directory ); QFileInfo fi; const QFileInfoList fil = copyDirectory.entryInfoList( QDir::Dirs | QDir::Files , QDir::Name ); QListIterator< QFileInfo > it( fil ); QMap< QString, QString> zipData; while ( it.hasNext() ) { fi = it.next(); if ( fi.fileName() == "." || fi.fileName() == ".." ) { ; } else { if ( fi.isDir() && fi.isReadable() ) { exportDatas( fi.absoluteFilePath() ); } else if ( fi.isFile() && fi.isReadable() ) { zipData.insert( fi.absolutePath(), fi.fileName() ); } } } return zipData; }
int Server::copyInfo(string sessionFrom, string sessionTo) { std::stringstream source; source << "session/" << sessionFrom << "/"; std::stringstream destination; destination << "session/" << sessionTo << "/"; return copyDirectory(source.str().c_str(), destination.str().c_str(), PRIVILEGES); }
bool VUtils::copyDirectory(const QString &p_srcDirPath, const QString &p_destDirPath, bool p_isCut) { QString srcPath = QDir::cleanPath(p_srcDirPath); QString destPath = QDir::cleanPath(p_destDirPath); if (srcPath == destPath) { return true; } if (QFileInfo::exists(destPath)) { qWarning() << QString("target directory %1 already exists").arg(destPath); return false; } // QDir.rename() could not move directory across drives. // Make sure target directory exists. QDir destDir(destPath); if (!destDir.exists()) { if (!destDir.mkpath(destPath)) { qWarning() << QString("fail to create target directory %1").arg(destPath); return false; } } // Handle directory recursively. QDir srcDir(srcPath); Q_ASSERT(srcDir.exists() && destDir.exists()); QFileInfoList nodes = srcDir.entryInfoList(QDir::Dirs | QDir::Files | QDir::Hidden | QDir::NoSymLinks | QDir::NoDotAndDotDot); for (int i = 0; i < nodes.size(); ++i) { const QFileInfo &fileInfo = nodes.at(i); QString name = fileInfo.fileName(); if (fileInfo.isDir()) { if (!copyDirectory(srcDir.filePath(name), destDir.filePath(name), p_isCut)) { return false; } } else { Q_ASSERT(fileInfo.isFile()); if (!copyFile(srcDir.filePath(name), destDir.filePath(name), p_isCut)) { return false; } } } if (p_isCut) { if (!destDir.rmdir(srcPath)) { qWarning() << QString("fail to delete source directory %1 after cut").arg(srcPath); return false; } } return true; }
void copySysOSX(const char* projName) { #ifdef _DEBUG const char * appName = "MaratisPlayerDebug"; #else const char * appName = "MaratisPlayer"; #endif MWindow * window = MWindow::getInstance(); MEngine* engine = MEngine::getInstance(); MSystemContext* system = engine->getSystemContext(); char filename[256]; getLocalFilename(filename, system->getWorkingDirectory(), projName); if(char* ext = strstr(filename, ".mproj")) { MProject proj; if(proj.loadXML(projName)) { strcpy(ext, ".app"); char path[256]; char srcName[256]; char destName[256]; char appPath[256]; char level[256]; getLocalFilename(level, system->getWorkingDirectory(), proj.startLevel.c_str()); getGlobalFilename(appPath, getPubDir(), filename); sprintf(path, "../../../%s.app", appName); getGlobalFilename(srcName, window->getCurrentDirectory(), path); copyDirectory(srcName, appPath); strcpy(ext, ""); sprintf(srcName, "%s/Contents/MacOS/%s", appPath, appName); strcpy(ext, ".mproj"); embedProject(srcName, srcName, filename, level, proj.renderer.c_str()); chmod(srcName, 0777); // we need to put all data in app/Contents/Resources/ sprintf(destName, "%s/Contents/Resources", appPath); createDirectory(destName); s_dataDir = destName; } } }
void File::copyTo(const std::string& path) const { Path src(getPathImpl()); Path dest(path); File destFile(path); if ((destFile.exists() && destFile.isDirectory()) || dest.isDirectory()) { dest.makeDirectory(); dest.setFileName(src.getFileName()); } if (isDirectory()) copyDirectory(dest.toString()); else copyToImpl(dest.toString()); }
bool DirectoryUtilities::copyDirectory(const QString &sourceDirectoryPath, const QString &destinationDirectoryPath) { QDir sourceDirectory(sourceDirectoryPath), destinationDirectory(destinationDirectoryPath); QStringList files, directories; if (!sourceDirectory.exists()) { ERROR_LOG(QString("El directori origen %1 no existeix").arg(sourceDirectoryPath)); return false; } if (!destinationDirectory.exists()) { if (!destinationDirectory.mkdir(destinationDirectoryPath)) { ERROR_LOG("No s'ha pogut crear el directori " + destinationDirectoryPath); return false; } } // Copiem els fitxers del directori files = sourceDirectory.entryList(QDir::Files); for (int i = 0; i < files.count(); i++) { QString sourceFile = sourceDirectoryPath + QDir::separator() + files[i]; QString destinationFile = destinationDirectoryPath + QDir::separator() + files[i]; if (!QFile::copy(sourceFile, destinationFile)) { ERROR_LOG(QString("No s'ha pogut copiar l'arxiu %1 al seu destí %2").arg(sourceFile, destinationFile)); return false; } } // Copiem els subdirectoris directories = sourceDirectory.entryList(QDir::AllDirs | QDir::NoDotAndDotDot); for (int i = 0; i < directories.count(); i++) { QString sourceSubDirectory = sourceDirectoryPath + QDir::separator() + directories[i]; QString destinationSubDirectory = destinationDirectoryPath + QDir::separator() + directories[i]; if (!copyDirectory(sourceSubDirectory, destinationSubDirectory)) { return false; } } return true; }
JNIEXPORT jboolean JNICALL Java_com_five_onair_server_utils_FileUtils_copyDirectoryLikeRoot (JNIEnv *env, jclass m_class, jstring _from, jstring _dest){ // // char *from=NULL,*dest=NULL; // // strcpy(from, env->GetStringUTFChars(_from, NULL)); // strcpy(dest, env->GetStringUTFChars(_dest, NULL)); // // copyDirectory(from, dest); char * from,*dest; from = const_cast<char *>(env->GetStringUTFChars(_from, NULL)); dest = const_cast<char *>(env->GetStringUTFChars(_dest, NULL)); return copyDirectory(from, dest); }
bool copyDirectory(const fs::path& from, const fs::path& to) { if (!fs::exists(from) || !fs::is_directory(from)) return false; if (!fs::exists(to) && !fs::create_directories(to)) return false; fs::directory_iterator end; for (fs::directory_iterator it(from); it != end; ++it) { if (fs::is_regular_file(*it)) { if (!copyFile(*it, to / it->path().filename())) return false; } else if (fs::is_directory(*it)) { if (!copyDirectory(*it, to / it->path().filename())) return false; } } return true; }
bool FileTemplater::copyDirectory(const fs::path& source, const fs::path& destination) { try { // create directory if it doesn't exist if(!boost::filesystem::exists(destination) && !boost::filesystem::create_directory(destination)) { std::cerr << "Error! Unable to create destination directory: " << destination << std::endl; return false; } // iterate through directory for( boost::filesystem::directory_iterator file(source); file!=boost::filesystem::directory_iterator(); ++file) { // get current file boost::filesystem::path current(file->path()); if(boost::filesystem::is_directory(current)) { // directory, recursively call this function if(!copyDirectory(current, destination / current.filename())) { return false; } } else if (!copyFile(current, destination / current.filename())) { return false; } } } catch( boost::filesystem::filesystem_error const & e ) { std::cerr << "Error! " << e.what() << '\n'; } return true; }
QStringList ConfigBase::searchProfiles( const QString &directory ) { QDir copyDirectory( directory ); QFileInfo fi; const QFileInfoList fil = copyDirectory.entryInfoList( QDir::Files , QDir::Name ); QListIterator< QFileInfo > it( fil ); QStringList profiles; while ( it.hasNext() ) { fi = it.next(); if ( fi.fileName() == "." || fi.fileName() == ".." ) { ; } else { if ( fi.isFile() && fi.isReadable() && fi.suffix() == "conf" ) { profiles.append( fi.baseName() ); } } } return profiles; }
static int loadUrlImages(struct iurlinfo * ui) { char *stage2img; char tmpstr1[1024], tmpstr2[1024]; int rc; /* setupRamdisk();*/ /* grab the updates.img before netstg1.img so that we minimize our * ramdisk usage */ if (!loadSingleUrlImage(ui, "images/updates.img", "/tmp/ramfs/updates-disk.img", "/tmp/update-disk", "loop7", 1)) { copyDirectory("/tmp/update-disk", "/tmp/updates"); umountLoopback("/tmp/update-disk", "loop7"); unlink("/tmp/ramfs/updates-disk.img"); unlink("/tmp/update-disk"); } /* grab the product.img before netstg1.img so that we minimize our * ramdisk usage */ if (!loadSingleUrlImage(ui, "images/product.img", "/tmp/ramfs/product-disk.img", "/tmp/product-disk", "loop7", 1)) { copyDirectory("/tmp/product-disk", "/tmp/product"); umountLoopback("/tmp/product-disk", "loop7"); unlink("/tmp/ramfs/product-disk.img"); unlink("/tmp/product-disk"); } /* require 128MB for use of graphical stage 2 due to size of image */ if (totalMemory() < GUI_STAGE2_RAM) { stage2img = "minstg2.img"; logMessage(WARNING, "URLINSTALL falling back to non-GUI stage2 " "due to insufficient RAM"); } else { stage2img = "stage2.img"; } snprintf(tmpstr1, sizeof(tmpstr1), "images/%s", stage2img); snprintf(tmpstr2, sizeof(tmpstr2), "/tmp/ramfs/%s", stage2img); #ifdef ROCKS rc = loadSingleUrlImage(ui, tmpstr1, tmpstr2, "/mnt/runtime", "loop2", 0); #else rc = loadSingleUrlImage(ui, tmpstr1, tmpstr2, "/mnt/runtime", "loop0", 0); #endif /* ROCKS */ if (rc) { if (rc != 2) newtWinMessage(_("Error"), _("OK"), _("Unable to retrieve the install image.")); return 1; } #ifndef ROCKS /* * ROCKS - we don't want to check the stamp since we routinely rebuild * the distribution. */ /* now verify the stamp... */ if (!verifyStamp("/mnt/runtime")) { char * buf; buf = sdupprintf(_("The %s installation tree in that directory does " "not seem to match your boot media."), getProductName()); newtWinMessage(_("Error"), _("OK"), buf); umountLoopback("/mnt/runtime", "loop0"); return 1; } #endif /* ROCKS */ return 0; }
int main(int argc, char **argv) { pid_t installpid, childpid; int waitStatus; int fd = -1; int doShutdown =0; reboot_action shutdown_method = HALT; int isSerial = 0; int isDevelMode = 0; char * console = NULL; int doKill = 1; char * argvc[15]; char buf[1024]; char ** argvp = argvc; char twelve = 12; struct serial_struct si; int i, disable_keys; int ret; if (!strncmp(basename(argv[0]), "poweroff", 8)) { printf("Running poweroff...\n"); fd = getInitPid(); if (fd > 0) kill(fd, SIGUSR2); doExit(0); } else if (!strncmp(basename(argv[0]), "halt", 4)) { printf("Running halt...\n"); fd = getInitPid(); if (fd > 0) kill(fd, SIGUSR1); doExit(0); } else if (!strncmp(basename(argv[0]), "reboot", 6)) { printf("Running reboot...\n"); fd = getInitPid(); if (fd > 0) kill(fd, SIGINT); doExit(0); } /* turn off screen blanking */ printstr("\033[9;0]"); printstr("\033[8]"); umask(022); /* set up signal handler */ setupBacktrace(); printstr("\nGreetings.\n"); printf("anaconda installer init version %s starting\n", VERSION); printf("mounting /proc filesystem... "); fflush(stdout); if (mount("/proc", "/proc", "proc", 0, NULL)) fatal_error(1); printf("done\n"); /* check for development mode early */ int fdn; if ((fdn = open("/proc/cmdline", O_RDONLY, 0)) != -1) { /* get cmdline info */ int len = read(fdn, buf, sizeof(buf) - 1); char *develstart; close(fdn); /* check the arguments */ if (len > 0) { develstart = buf; while (develstart && (*develstart) != '\0') { /* strip spaces */ while(*develstart == ' ') develstart++; if(*develstart == '\0') break; /* not the word we are looking for */ if (strncmp(develstart, "devel", 5)) { develstart = strchr(develstart, ' '); continue; } /* is it isolated? */ if(((*(develstart+5)) == ' ' || (*(develstart+5)) == '\0')) { printf("Enabling development mode - cores will be dumped\n"); isDevelMode++; break; } /* Find next argument */ develstart = strchr(develstart, ' '); } } } /* these args are only for testing from commandline */ for (i = 1; i < argc; i++) { if (!strcmp (argv[i], "serial")) { isSerial = 1; break; } } printf("creating /dev filesystem... "); fflush(stdout); if (mount("/dev", "/dev", "tmpfs", 0, NULL)) fatal_error(1); createDevices(); printf("done\n"); printf("starting udev..."); fflush(stdout); if ((childpid = fork()) == 0) { execl("/sbin/udevd", "/sbin/udevd", "--daemon", NULL); fprintf(stderr, " exec of /sbin/udevd failed."); exit(1); } /* wait at least until the udevd process that we forked exits */ do { pid_t retpid; int waitstatus; retpid = wait(&waitstatus); if (retpid == -1) { if (errno == EINTR) continue; /* if the child exited before we called waitpid, we can get * ECHILD without anything really being wrong; we just lost * the race.*/ if (errno == ECHILD) break; printf("init: error waiting on udevd: %m\n"); exit(1); } else if ((retpid == childpid) && WIFEXITED(waitstatus)) { break; } } while (1); if (fork() == 0) { execl("/sbin/udevadm", "udevadm", "control", "--env=ANACONDA=1", NULL); fprintf(stderr, " exec of /sbin/udevadm failed."); exit(1); } printf("done\n"); printf("mounting /dev/pts (unix98 pty) filesystem... "); fflush(stdout); if (mount("/dev/pts", "/dev/pts", "devpts", 0, NULL)) fatal_error(1); printf("done\n"); printf("mounting /sys filesystem... "); fflush(stdout); if (mount("/sys", "/sys", "sysfs", 0, NULL)) fatal_error(1); printf("done\n"); /* if anaconda dies suddenly we are doomed, so at least make a coredump */ struct rlimit corelimit = { RLIM_INFINITY, RLIM_INFINITY}; ret = setrlimit(RLIMIT_CORE, &corelimit); if (ret) { perror("setrlimit failed - no coredumps will be available"); } doKill = getKillPolicy(); #if !defined(__s390__) && !defined(__s390x__) static struct termios orig_cmode; static int orig_flags; struct termios cmode, mode; int cfd; cfd = open("/dev/console", O_RDONLY); tcgetattr(cfd,&orig_cmode); orig_flags = fcntl(cfd, F_GETFL); close(cfd); cmode = orig_cmode; cmode.c_lflag &= (~ECHO); cfd = open("/dev/console", O_WRONLY); tcsetattr(cfd,TCSANOW,&cmode); close(cfd); /* handle weird consoles */ #if defined(__powerpc__) char * consoles[] = { "/dev/hvc0", /* hvc for JS20 */ "/dev/hvsi0", "/dev/hvsi1", "/dev/hvsi2", /* hvsi for POWER5 */ NULL }; #elif defined (__ia64__) char * consoles[] = { "/dev/ttySG0", "/dev/xvc0", "/dev/hvc0", NULL }; #elif defined (__i386__) || defined (__x86_64__) char * consoles[] = { "/dev/xvc0", "/dev/hvc0", NULL }; #else char * consoles[] = { NULL }; #endif for (i = 0; consoles[i] != NULL; i++) { if ((fd = open(consoles[i], O_RDWR)) >= 0 && !tcgetattr(fd, &mode) && !termcmp(&cmode, &mode)) { printf("anaconda installer init version %s using %s as console\n", VERSION, consoles[i]); isSerial = 3; console = strdup(consoles[i]); break; } close(fd); } cfd = open("/dev/console", O_WRONLY); tcsetattr(cfd,TCSANOW,&orig_cmode); close(cfd); if ((fd < 0) && (ioctl (0, TIOCLINUX, &twelve) < 0)) { isSerial = 2; if (ioctl(0, TIOCGSERIAL, &si) == -1) { isSerial = 0; } } if (isSerial && (isSerial != 3)) { char *device = "/dev/ttyS0"; printf("anaconda installer init version %s using a serial console\n", VERSION); if (isSerial == 2) device = "/dev/console"; fd = open(device, O_RDWR, 0); if (fd < 0) device = "/dev/tts/0"; if (fd < 0) { printf("failed to open %s\n", device); fatal_error(1); } setupTerminal(fd); } else if (isSerial == 3) { setupTerminal(fd); } else if (fd < 0) { fd = open("/dev/tty1", O_RDWR, 0); if (fd < 0) fd = open("/dev/vc/1", O_RDWR, 0); if (fd < 0) { printf("failed to open /dev/tty1 and /dev/vc/1"); fatal_error(1); } } setsid(); if (ioctl(0, TIOCSCTTY, NULL)) { printf("could not set new controlling tty\n"); } dup2(fd, 0); dup2(fd, 1); dup2(fd, 2); if (fd > 2) close(fd); #else dup2(0, 1); dup2(0, 2); #endif /* disable Ctrl+Z, Ctrl+C, etc ... but not in rescue mode */ disable_keys = 1; if (argc > 1) if (strstr(argv[1], "rescue")) disable_keys = 0; if (disable_keys) { tcgetattr(0, &ts); ts.c_iflag &= ~BRKINT; ts.c_iflag |= IGNBRK; ts.c_iflag &= ~ISIG; tcsetattr(0, TCSANOW, &ts); } ret = sethostname("localhost.localdomain", 21); /* the default domainname (as of 2.0.35) is "(none)", which confuses glibc */ ret = setdomainname("", 0); printf("trying to remount root filesystem read write... "); fflush(stdout); if (mount("/", "/", "ext2", MS_REMOUNT | MS_MGC_VAL, NULL)) { fatal_error(1); } printf("done\n"); /* we want our /tmp to be tmpfs, but we also want to let people hack * their initrds to add things like a ks.cfg, so this has to be a little * tricky */ rename("/tmp", "/oldtmp"); mkdir("/tmp", 0755); printf("mounting /tmp as tmpfs... "); fflush(stdout); if (mount("none", "/tmp", "tmpfs", 0, "size=250m")) fatal_error(1); printf("done\n"); copyDirectory("/oldtmp", "/tmp", copyErrorFn, copyErrorFn); unlink("/oldtmp"); /* Now we have some /tmp space set up, and /etc and /dev point to it. We should be in pretty good shape. */ startSyslog(); /* write out a pid file */ if ((fd = open("/var/run/init.pid", O_WRONLY|O_CREAT, 0644)) > 0) { char * buf = malloc(10); int ret; snprintf(buf, 9, "%d", getpid()); ret = write(fd, buf, strlen(buf)); close(fd); free(buf); } else { printf("unable to write init.pid (%d): %m\n", errno); sleep(2); } /* D-Bus */ if (fork() == 0) { execl("/sbin/dbus-uuidgen", "/sbin/dbus-uuidgen", "--ensure", NULL); fprintf(stderr, "exec of /sbin/dbus-uuidgen failed."); doExit(1); } if (fork() == 0) { execl("/sbin/dbus-daemon", "/sbin/dbus-daemon", "--system", NULL); fprintf(stderr, "exec of /sbin/dbus-daemon failed."); doExit(1); } sleep(2); /* Go into normal init mode - keep going, and then do a orderly shutdown when: 1) /bin/install exits 2) we receive a SIGHUP */ printf("running install...\n"); if (!(installpid = fork())) { /* child */ *argvp++ = "/sbin/loader"; if (isSerial == 3) { *argvp++ = "--virtpconsole"; *argvp++ = console; } if (isDevelMode) { *argvp++ = "--devel"; } *argvp++ = NULL; printf("running %s\n", argvc[0]); execve(argvc[0], argvc, env); shutDown(1, HALT); } /* signal handlers for halt/poweroff */ signal(SIGUSR1, sigUsr1Handler); signal(SIGUSR2, sigUsr2Handler); /* set up the ctrl+alt+delete handler to kill our pid, not pid 1 */ signal(SIGINT, sigintHandler); if ((fd = open("/proc/sys/kernel/cad_pid", O_WRONLY)) != -1) { char buf[7]; size_t count; sprintf(buf, "%d", getpid()); count = write(fd, buf, strlen(buf)); close(fd); /* if we succeeded in writing our pid, turn off the hard reboot ctrl-alt-del handler */ if (count == strlen(buf) && (fd = open("/proc/sys/kernel/ctrl-alt-del", O_WRONLY)) != -1) { int ret; ret = write(fd, "0", 1); close(fd); } } while (!doShutdown) { pid_t childpid; childpid = wait(&waitStatus); if (childpid == installpid) { doShutdown = 1; ioctl(0, VT_ACTIVATE, 1); } } #ifdef ROCKS /* * ignore child processes that throw error stati when * they terminate */ shutdown_method = REBOOT; #else if (!WIFEXITED(waitStatus) || (WIFEXITED(waitStatus) && WEXITSTATUS(waitStatus))) { /* Restore terminal */ cfd = open("/dev/console", O_RDONLY); tcsetattr(cfd, TCSANOW, &orig_cmode); fcntl(cfd, F_SETFL, orig_flags); close(cfd); shutdown_method = DELAYED_REBOOT; printf("install exited abnormally [%d/%d] ", WIFEXITED(waitStatus), WEXITSTATUS(waitStatus)); if (WIFSIGNALED(waitStatus)) { printf("-- received signal %d", WTERMSIG(waitStatus)); } printf("\n"); /* If debug mode was requested, spawn shell */ if(isDevelMode) { pid_t shellpid; printf("Development mode requested spawning shell...\n"); if ((shellpid = fork()) == 0) { execl("/sbin/bash", "/sbin/bash", NULL); } else if (shellpid > 0) { waitpid(shellpid, NULL, 0); } else { perror("Execution of debug shell failed."); } } } else { shutdown_method = REBOOT; } #endif #ifdef ROCKS while(dontReboot()) { sleep(10); } #endif shutDown(doKill, shutdown_method); return 0; }
// Slow but should be ok... bool AbstractRemoteConnection::moveDirectory(const QString &src, const QString &dest, bool recursive) { bool result = copyDirectory(src, dest, true); deleteDirectory(src, recursive); return result; }
bool FileTemplater::create() { // output files and output file iterator std::vector<std::ofstream*> outputFiles; for (std::list<std::string>::const_iterator it=m_dynamicFiles.begin(); it!=m_dynamicFiles.end(); ++it) { std::stringstream ss; ss << m_outputDirectory << *it << "." << m_fileExtension; std::ofstream* curFile = new std::ofstream(ss.str().c_str(), std::ofstream::out|std::ofstream::binary); if (!curFile->is_open()) { delete curFile; std::cerr << "Could not open '" << ss.str() << "'" << std::endl; return false; } else if (m_verbose) { std::cout << "Opened file: '" << ss.str() << "'" << std::endl; } outputFiles.push_back(curFile); } // step through 'file order' for (std::list<std::string>::const_iterator it=m_fileOrder.begin(); it!=m_fileOrder.end(); ++it) { if ((*it).empty()) { std::cout << "Ignoring empty file entry" << std::endl; } if ((*it).at(0)=='*') { // dynamic page, build file suffix from iterator std::string fileSuffix = (*it).substr(1); // get 2 iterators, 1 for input & 1 for output std::list<std::string>::const_iterator iIt = m_dynamicFiles.begin(); std::vector<std::ofstream*>::iterator oIt = outputFiles.begin(); for ( ; iIt!=m_dynamicFiles.end(); ++iIt, ++oIt) { std::stringstream ss; ss << m_inputDirectory << *iIt << fileSuffix; std::ifstream curFile(ss.str().c_str(), std::ifstream::in|std::ifstream::binary); if (curFile.is_open()) { if (m_verbose) { std::cout << "Opened dynamic file '" << ss.str() << "'" << std::endl; } appendSingleFile(*oIt, curFile); } else if (m_strict) { std::cerr << "Error, mode is set to strict and input file '" << ss.str() << "' does not exist" << std::endl; it = m_fileOrder.end(); break; } else if (m_verbose) { std::cout << "Skipping '" << ss.str() << "' as it does not exist" << std::endl; } } } else { std::stringstream ss; ss << m_inputDirectory << *it; std::ifstream curFile(ss.str().c_str(), std::ifstream::in|std::ifstream::binary); if (curFile.is_open()) { if (m_verbose) { std::cout << "Opened file '" << ss.str() << "'" << std::endl; } appendToAllFiles(outputFiles, curFile); { } } else { std::cerr << "Could not open required file '" << ss.str() << "'" << std::endl; break; } } } // copy additional files boost::filesystem::path sink(m_outputDirectory); for (std::list<std::string>::const_iterator it=m_additionalFiles.begin(); it!=m_additionalFiles.end(); ++it) { // build up full input file name std::stringstream ss; ss << m_inputDirectory << *it; // check if the file/directory exists boost::filesystem::path source(ss.str()); if (boost::filesystem::exists(source)) { if (boost::filesystem::is_directory(source)) { copyDirectory(source, sink / *it); } else { copyFile(source, sink / source.filename()); } } else { std::cout << "Additional file '" << ss.str() << "' does not exist. Skipping." << std::endl; } } if (m_verbose) { std::cout << "Closing files" << std::endl; } // finally, free data for (std::vector<std::ofstream*>::iterator it=outputFiles.begin(); it!=outputFiles.end(); ++it) { delete *it; } return true; }
char * mountNfsImage(struct installMethod * method, char * location, struct loaderData_s * loaderData) { char * host = NULL; char * directory = NULL; char * mountOpts = NULL; char * fullPath = NULL; char * url = NULL; enum { NFS_STAGE_NFS, NFS_STAGE_MOUNT, NFS_STAGE_DONE, NFS_STAGE_UPDATES } stage = NFS_STAGE_NFS; int rc; /* JKFIXME: ASSERT -- we have a network device setup when we get here */ while (stage != NFS_STAGE_DONE) { switch (stage) { case NFS_STAGE_NFS: logMessage(INFO, "going to do nfsGetSetup"); if (loaderData->method == METHOD_NFS && loaderData->stage2Data) { host = ((struct nfsInstallData *)loaderData->stage2Data)->host; directory = ((struct nfsInstallData *)loaderData->stage2Data)->directory; if (((struct nfsInstallData *) loaderData->stage2Data)->mountOpts == NULL) { mountOpts = strdup("ro"); } else { if (asprintf(&mountOpts, "ro,%s", ((struct nfsInstallData *) loaderData->stage2Data)->mountOpts) == -1) { logMessage(CRITICAL, "%s: %d: %m", __func__, __LINE__); abort(); } } logMessage(INFO, "host is %s, dir is %s, opts are '%s'", host, directory, mountOpts); if (!host || !directory) { logMessage(ERROR, "missing host or directory specification"); if (loaderData->inferredStage2) loaderData->invalidRepoParam = 1; loaderData->method = -1; break; } else { host = strdup(host); directory = strdup(directory); } } else { char *substr, *tmp; if (nfsGetSetup(&host, &directory) == LOADER_BACK) return NULL; /* If the user-provided URL points at a repo instead of a * stage2 image, fix that up now. */ substr = strstr(directory, ".img"); if (!substr || (substr && *(substr+4) != '\0')) { if (asprintf(&(loaderData->instRepo), "nfs:%s:%s", host, directory) == -1) { logMessage(CRITICAL, "%s: %d: %m", __func__, __LINE__); abort(); } if (asprintf(&tmp, "nfs:%s:%s/images/install.img", host, directory) == -1) { logMessage(CRITICAL, "%s: %d: %m", __func__, __LINE__); abort(); } setStage2LocFromCmdline(tmp, loaderData); free(host); free(directory); free(tmp); continue; } loaderData->invalidRepoParam = 1; } stage = NFS_STAGE_MOUNT; break; case NFS_STAGE_MOUNT: { char *buf; if (asprintf(&fullPath, "%s:%.*s", host, (int) (strrchr(directory, '/')-directory), directory) == -1) { logMessage(CRITICAL, "%s: %d: %m", __func__, __LINE__); abort(); } logMessage(INFO, "mounting nfs path %s", fullPath); if (FL_TESTING(flags)) { stage = NFS_STAGE_DONE; break; } stage = NFS_STAGE_NFS; if (!doPwMount(fullPath, "/mnt/stage2", "nfs", mountOpts, NULL)) { if (asprintf(&buf, "/mnt/stage2/%s", strrchr(directory, '/')) == -1) { logMessage(CRITICAL, "%s: %d: %m", __func__, __LINE__); abort(); } if (!access(buf, R_OK)) { logMessage(INFO, "can access %s", buf); rc = mountStage2(buf); if (rc == 0) { stage = NFS_STAGE_UPDATES; if (asprintf(&url, "nfs:%s:%s", host, directory) == -1) { logMessage(CRITICAL, "%s: %d: %m", __func__, __LINE__); abort(); } free(buf); break; } else { logMessage(WARNING, "unable to mount %s", buf); free(buf); break; } } else { logMessage(WARNING, "unable to access %s", buf); free(buf); umount("/mnt/stage2"); } } else { newtWinMessage(_("Error"), _("OK"), _("That directory could not be mounted from " "the server.")); if (loaderData->method >= 0) loaderData->method = -1; if (loaderData->inferredStage2) loaderData->invalidRepoParam = 1; break; } if (asprintf(&buf, _("That directory does not seem to " "contain a %s installation image."), getProductName()) == -1) { logMessage(CRITICAL, "%s: %d: %m", __func__, __LINE__); abort(); } newtWinMessage(_("Error"), _("OK"), buf); free(buf); if (loaderData->method >= 0) loaderData->method = -1; if (loaderData->inferredStage2) loaderData->invalidRepoParam = 1; break; } case NFS_STAGE_UPDATES: { char *buf; if (asprintf(&buf, "%.*s/RHupdates", (int) (strrchr(fullPath, '/')-fullPath), fullPath) == -1) { logMessage(CRITICAL, "%s: %d: %m", __func__, __LINE__); abort(); } logMessage(INFO, "mounting nfs path %s for updates", buf); if (!doPwMount(buf, "/tmp/update-disk", "nfs", mountOpts, NULL)) { logMessage(INFO, "Using RHupdates/ for NFS install"); copyDirectory("/tmp/update-disk", "/tmp/updates", NULL, NULL); umount("/tmp/update-disk"); unlink("/tmp/update-disk"); } else { logMessage(INFO, "No RHupdates/ directory found, skipping"); } stage = NFS_STAGE_DONE; break; } case NFS_STAGE_DONE: break; } } free(host); free(directory); if (fullPath) free(fullPath); return url; }
int main(int argc, char* argv[]) { if(!RTTRCONFIG.Init()) { std::cerr << "Failed to init program!" << std::endl; return 1; } if(argc <= 1 || argv[1] != std::string("interminal")) { try { const bfs::path tmpPath = "/tmp/rttr.command"; boost::nowide::ofstream file(tmpPath); file << "\"" << RTTRCONFIG.ExpandPath("<RTTR_BIN>/starter") << "\" interminal" << std::endl; file << "rm " << tmpPath << std::endl; file.close(); bfs::permissions(tmpPath, bfs::owner_all); bfs::current_path(RTTRCONFIG.ExpandPath("<RTTR_BIN>")); system("open rttr.terminal"); } catch(const std::exception& e) { std::cerr << "Error: " << e.what() << std::endl; } return 0; } if(!isS2Installed()) { const bfs::path S2CD = "/Volumes/S2_GOLD"; while(!bfs::is_directory(S2CD) && !isS2Installed()) { std::cerr << "Couldn't find data files for Settlers II" << std::endl; std::cerr << "Please copy the folders \"DATA\" and \"GFX\" from your Settlers II install to" << std::endl; std::cerr << "\"" << RTTRCONFIG.ExpandPath("<RTTR_GAME>") << "\" or" << std::endl; std::cerr << "insert the Settlers II Gold CD in your drive and hit \"Enter\"." << std::endl; std::cin.ignore(); } if(!isS2Installed()) { std::cout << "Copying files..." << std::endl; try { copyDirectory(S2CD / "DATA", RTTRCONFIG.ExpandPath("<RTTR_GAME>/DATA")); } catch(const std::runtime_error& e) { std::cerr << "Error copying DATA dir: " << e.what() << std::endl; return 1; } try { copyDirectory(S2CD / "GFX", RTTRCONFIG.ExpandPath("<RTTR_GAME>/GFX")); } catch(const std::runtime_error& e) { std::cerr << "Error copying GFX dir: " << e.what() << std::endl; return 1; } std::cout << "Done" << std::endl; } } if(argc <= 2 || argv[2] != std::string("noupdate")) { bfs::path updaterPath = RTTRCONFIG.ExpandPath("<RTTR_EXTRA_BIN>/s25update"); if(bfs::exists(updaterPath)) System::execute(updaterPath, "--dir \"../../../\" -v"); else std::cerr << "Updater not found at " << updaterPath << std::endl; } System::execute(RTTRCONFIG.ExpandPath("<RTTR_BIN>/s25client")); }
int main(int argc, char **argv) { pid_t installpid, childpid; int waitStatus; int fd = -1; int doReboot = 0; int doShutdown =0; int isSerial = 0; char * console = NULL; int noKill = 0; char * argvc[15]; char ** argvp = argvc; char twelve = 12; struct serial_struct si; int i, disable_keys; if (!strncmp(basename(argv[0]), "poweroff", 8)) { printf("Running poweroff...\n"); fd = getInitPid(); if (fd > 0) kill(fd, SIGUSR2); exit(0); } else if (!strncmp(basename(argv[0]), "halt", 4)) { printf("Running halt...\n"); fd = getInitPid(); if (fd > 0) kill(fd, SIGUSR1); exit(0); } else if (!strncmp(basename(argv[0]), "reboot", 6)) { printf("Running reboot...\n"); fd = getInitPid(); if (fd > 0) kill(fd, SIGINT); exit(0); } #if !defined(__s390__) && !defined(__s390x__) testing = (getppid() != 0) && (getppid() != 1); #endif if (!testing) { /* turn off screen blanking */ printstr("\033[9;0]"); printstr("\033[8]"); } else { printstr("(running in test mode).\n"); } umask(022); printstr("\nGreetings.\n"); printf("anaconda installer init version %s starting\n", VERSION); printf("mounting /proc filesystem... "); if (!testing) { if (mount("/proc", "/proc", "proc", 0, NULL)) fatal_error(1); } printf("done\n"); printf("creating /dev filesystem... "); if (!testing) { if (mount("/dev", "/dev", "tmpfs", 0, NULL)) fatal_error(1); createDevices(); } printf("done\n"); printf("mounting /dev/pts (unix98 pty) filesystem... "); if (!testing) { if (mount("/dev/pts", "/dev/pts", "devpts", 0, NULL)) fatal_error(1); } printf("done\n"); printf("mounting /sys filesystem... "); if (!testing) { if (mount("/sys", "/sys", "sysfs", 0, NULL)) fatal_error(1); } printf("done\n"); /* these args are only for testing from commandline */ for (i = 1; i < argc; i++) { if (!strcmp (argv[i], "serial")) { isSerial = 1; break; } } noKill = getNoKill(); #if !defined(__s390__) && !defined(__s390x__) static struct termios orig_cmode; struct termios cmode, mode; int cfd; cfd = open("/dev/console", O_RDONLY); tcgetattr(cfd,&orig_cmode); close(cfd); cmode = orig_cmode; cmode.c_lflag &= (~ECHO); cfd = open("/dev/console", O_WRONLY); tcsetattr(cfd,TCSANOW,&cmode); close(cfd); /* handle weird consoles */ #if defined(__powerpc__) char * consoles[] = { "/dev/hvc0", /* hvc for JS20 */ "/dev/hvsi0", "/dev/hvsi1", "/dev/hvsi2", /* hvsi for POWER5 */ NULL }; #elif defined (__ia64__) char * consoles[] = { "/dev/ttySG0", "/dev/xvc0", NULL }; #elif defined (__i386__) || defined (__x86_64__) char * consoles[] = { "/dev/xvc0", NULL }; #else char * consoles[] = { NULL }; #endif for (i = 0; consoles[i] != NULL; i++) { if ((fd = open(consoles[i], O_RDWR)) >= 0 && !tcgetattr(fd, &mode) && !termcmp(&cmode, &mode)) { printf("anaconda installer init version %s using %s as console\n", VERSION, consoles[i]); isSerial = 3; console = strdup(consoles[i]); break; } close(fd); } cfd = open("/dev/console", O_WRONLY); tcsetattr(cfd,TCSANOW,&orig_cmode); close(cfd); if ((fd < 0) && (ioctl (0, TIOCLINUX, &twelve) < 0)) { isSerial = 2; if (ioctl(0, TIOCGSERIAL, &si) == -1) { isSerial = 0; } } if (isSerial && (isSerial != 3)) { char *device = "/dev/ttyS0"; printf("anaconda installer init version %s using a serial console\n", VERSION); if (isSerial == 2) device = "/dev/console"; fd = open(device, O_RDWR, 0); if (fd < 0) device = "/dev/tts/0"; if (fd < 0) { printf("failed to open %s\n", device); fatal_error(1); } setupTerminal(fd); } else if (isSerial == 3) { setupTerminal(fd); } else if (fd < 0) { fd = open("/dev/tty1", O_RDWR, 0); if (fd < 0) fd = open("/dev/vc/1", O_RDWR, 0); if (fd < 0) { printf("failed to open /dev/tty1 and /dev/vc/1"); fatal_error(1); } } if (testing) exit(0); setsid(); if (ioctl(0, TIOCSCTTY, NULL)) { printf("could not set new controlling tty\n"); } dup2(fd, 0); dup2(fd, 1); dup2(fd, 2); if (fd > 2) close(fd); #else dup2(0, 1); dup2(0, 2); #endif /* disable Ctrl+Z, Ctrl+C, etc ... but not in rescue mode */ #ifdef SNAKES_ON_A_PLANE disable_keys = 0; #else disable_keys = 1; if (argc > 1) if (mystrstr(argv[1], "rescue")) disable_keys = 0; #endif if (disable_keys) { tcgetattr(0, &ts); ts.c_iflag &= ~BRKINT; ts.c_iflag |= IGNBRK; ts.c_iflag &= ~ISIG; tcsetattr(0, TCSANOW, &ts); } if (!testing) { int ret; ret = sethostname("localhost.localdomain", 21); /* the default domainname (as of 2.0.35) is "(none)", which confuses glibc */ ret = setdomainname("", 0); } printf("trying to remount root filesystem read write... "); if (mount("/", "/", "ext2", MS_REMOUNT | MS_MGC_VAL, NULL)) { fatal_error(1); } printf("done\n"); /* we want our /tmp to be ramfs, but we also want to let people hack * their initrds to add things like a ks.cfg, so this has to be a little * tricky */ if (!testing) { rename("/tmp", "/oldtmp"); mkdir("/tmp", 0755); printf("mounting /tmp as ramfs... "); if (mount("none", "/tmp", "ramfs", 0, NULL)) fatal_error(1); printf("done\n"); copyDirectory("/oldtmp", "/tmp"); unlink("/oldtmp"); } /* Now we have some /tmp space set up, and /etc and /dev point to it. We should be in pretty good shape. */ if (!testing) doklog("/dev/tty4"); /* write out a pid file */ if ((fd = open("/var/run/init.pid", O_WRONLY|O_CREAT, 0644)) > 0) { char * buf = malloc(10); int ret; snprintf(buf, 9, "%d", getpid()); ret = write(fd, buf, strlen(buf)); close(fd); free(buf); } else { printf("unable to write init.pid (%d): %s\n", errno, strerror(errno)); sleep(2); } /* Go into normal init mode - keep going, and then do a orderly shutdown when: 1) /bin/install exits 2) we receive a SIGHUP */ printf("running install...\n"); setsid(); #ifdef SNAKES_ON_A_PLANE printf("> Snakes on a Plane <\n"); /* hack to load core modules for debugging mode */ char * modvc[15]; char ** modvp = modvc; *modvp++ = "/bin/modprobe"; *modvp++ = "ehci-hcd"; *modvp++ = "uhci-hcd"; *modvp++ = "ohci-hcd"; *modvp++ = NULL; pid_t blah = fork(); int qux; if (blah == 0) { printf("loading core debugging modules...\n"); execve(modvc[0], modvc, env); } else { waitpid(blah, &qux, WNOHANG); } #endif if (!(installpid = fork())) { /* child */ #ifdef SNAKES_ON_A_PLANE *argvp++ = "/bin/strace"; #endif *argvp++ = "/sbin/loader"; if (isSerial == 3) { *argvp++ = "--virtpconsole"; *argvp++ = console; } *argvp++ = NULL; printf("running %s\n", argvc[0]); execve(argvc[0], argvc, env); shutDown(1, 0, 0); } /* signal handlers for halt/poweroff */ signal(SIGUSR1, sigUsr1Handler); signal(SIGUSR2, sigUsr2Handler); /* set up the ctrl+alt+delete handler to kill our pid, not pid 1 */ signal(SIGINT, sigintHandler); if ((fd = open("/proc/sys/kernel/cad_pid", O_WRONLY)) != -1) { char buf[7]; size_t count; sprintf(buf, "%d", getpid()); count = write(fd, buf, strlen(buf)); close(fd); /* if we succeeded in writing our pid, turn off the hard reboot ctrl-alt-del handler */ if (count == strlen(buf) && (fd = open("/proc/sys/kernel/ctrl-alt-del", O_WRONLY)) != -1) { int ret; ret = write(fd, "0", 1); close(fd); } } while (!doShutdown) { childpid = waitpid(-1, &waitStatus, 0); if (childpid == installpid) doShutdown = 1; } if (!WIFEXITED(waitStatus) || (WIFEXITED(waitStatus) && WEXITSTATUS(waitStatus))) { printf("install exited abnormally [%d/%d] ", WIFEXITED(waitStatus), WEXITSTATUS(waitStatus)); if (WIFSIGNALED(waitStatus)) { printf("-- received signal %d", WTERMSIG(waitStatus)); } printf("\n"); } else { doReboot = 1; } if (testing) exit(0); shutDown(noKill, doReboot, 0); return 0; }
/* Recursive -- copied (and tweaked)from loader2/method.c */ static int copyDirectory(char * from, char * to) { DIR * dir; struct dirent * ent; int fd, outfd; char buf[4096]; int i; struct stat sb; char filespec[256]; char filespec2[256]; char link[1024]; int ret; mkdir(to, 0755); if (!(dir = opendir(from))) { printf("Failed to read directory %s: %s", from, strerror(errno)); return 1; } errno = 0; while ((ent = readdir(dir))) { if (!strcmp(ent->d_name, ".") || !strcmp(ent->d_name, "..")) continue; sprintf(filespec, "%s/%s", from, ent->d_name); sprintf(filespec2, "%s/%s", to, ent->d_name); lstat(filespec, &sb); if (S_ISDIR(sb.st_mode)) { if (copyDirectory(filespec, filespec2)) return 1; } else if (S_ISLNK(sb.st_mode)) { i = readlink(filespec, link, sizeof(link) - 1); link[i] = '\0'; if (symlink(link, filespec2)) { printf("failed to symlink %s to %s: %s", filespec2, link, strerror(errno)); } } else { fd = open(filespec, O_RDONLY); if (fd == -1) { printf("failed to open %s: %s", filespec, strerror(errno)); return 1; } outfd = open(filespec2, O_RDWR | O_TRUNC | O_CREAT, 0644); if (outfd == -1) { printf("failed to create %s: %s", filespec2, strerror(errno)); } else { fchmod(outfd, sb.st_mode & 07777); while ((i = read(fd, buf, sizeof(buf))) > 0) ret = write(outfd, buf, i); close(outfd); } close(fd); } errno = 0; } closedir(dir); return 0; }
bool Mhwd::copyDirectory(const std::string& source, const std::string& destination) { struct stat filestatus; if (0 != lstat(destination.c_str(), &filestatus)) { if (!createDir(destination)) { return false; } } else if (S_ISREG(filestatus.st_mode)) { return false; } else if (S_ISDIR(filestatus.st_mode)) { if (!removeDirectory(destination)) { return false; } if (!createDir(destination)) { return false; } } struct dirent *dir; DIR *d = opendir(source.c_str()); if (!d) { return false; } else { bool success = true; while ((dir = readdir(d)) != nullptr) { std::string filename {dir->d_name}; if (("." == filename) || (".." == filename) || ("" == filename)) { continue; } else { std::string sourcePath {source + "/" + filename}; std::string destinationPath {destination + "/" + filename}; lstat(sourcePath.c_str(), &filestatus); if (S_ISREG(filestatus.st_mode)) { if (!copyFile(sourcePath, destinationPath)) { success = false; } } else if (S_ISDIR(filestatus.st_mode)) { if (!copyDirectory(sourcePath, destinationPath)) { success = false; } } } } closedir(d); return success; } }
static int loadUrlImages(struct iurlinfo * ui) { char *buf, *path, *dest, *slash; int rc; /* Figure out the path where updates.img and product.img files are * kept. Since ui->prefix points to a stage2 image file, we just need * to trim off the file name and look in the same directory. */ if ((slash = strrchr(ui->prefix, '/')) == NULL) return 0; if ((path = strndup(ui->prefix, slash - ui->prefix)) == NULL) path = ui->prefix; /* grab the updates.img before install.img so that we minimize our * ramdisk usage */ if (asprintf(&buf, "%s/%s", path, "updates.img") == -1) { logMessage(CRITICAL, "%s: %d: %m", __func__, __LINE__); abort(); } if (!loadSingleUrlImage(ui, buf, "/tmp/updates-disk.img", "/tmp/update-disk", "/dev/loop7", 1)) { copyDirectory("/tmp/update-disk", "/tmp/updates", copyWarnFn, copyErrorFn); umountLoopback("/tmp/update-disk", "/dev/loop7"); unlink("/tmp/updates-disk.img"); unlink("/tmp/update-disk"); } else if (!access("/tmp/updates-disk.img", R_OK)) { unpackCpioBall("/tmp/updates-disk.img", "/tmp/updates"); unlink("/tmp/updates-disk.img"); } free(buf); /* grab the product.img before install.img so that we minimize our * ramdisk usage */ if (asprintf(&buf, "%s/%s", path, "product.img") == -1) { logMessage(CRITICAL, "%s: %d: %m", __func__, __LINE__); abort(); } if (!loadSingleUrlImage(ui, buf, "/tmp/product-disk.img", "/tmp/product-disk", "/dev/loop7", 1)) { copyDirectory("/tmp/product-disk", "/tmp/product", copyWarnFn, copyErrorFn); umountLoopback("/tmp/product-disk", "/dev/loop7"); unlink("/tmp/product-disk.img"); unlink("/tmp/product-disk"); } free(buf); if (asprintf(&dest, "/tmp/install.img") == -1) { logMessage(CRITICAL, "%s: %d: %m", __func__, __LINE__); abort(); } rc = loadSingleUrlImage(ui, ui->prefix, dest, "/mnt/runtime", "/dev/loop0", 0); free(dest); if (rc) { if (rc != 2) newtWinMessage(_("Error"), _("OK"), _("Unable to retrieve the install image.")); return 1; } return 0; }
/* this copies the contents of the driver disk to a ramdisk and loads * the moduleinfo, etc. assumes a "valid" driver disk mounted at mntpt */ static int loadDriverDisk(struct loaderData_s *loaderData, char *mntpt) { moduleDeps *modDepsPtr = loaderData->modDepsPtr; moduleInfoSet modInfo = loaderData->modInfo; char file[200], dest[200]; char * title; struct moduleBallLocation * location; struct stat sb; static int disknum = 0; int version = 1; int fd, ret; /* check for both versions */ sprintf(file, "%s/rhdd", mntpt); if (access(file, R_OK)) { version = 0; sprintf(file, "%s/rhdd-6.1", mntpt); if (access(file, R_OK)) { /* this can't happen, we already verified it! */ return LOADER_BACK; } } stat(file, &sb); title = malloc(sb.st_size + 1); fd = open(file, O_RDONLY); ret = read(fd, title, sb.st_size); if (title[sb.st_size - 1] == '\n') sb.st_size--; title[sb.st_size] = '\0'; close(fd); sprintf(file, "/tmp/ramfs/DD-%d", disknum); mkdirChain(file); if (!FL_CMDLINE(flags)) { startNewt(); winStatus(40, 3, _("Loading"), _("Reading driver disk...")); } sprintf(dest, "/tmp/ramfs/DD-%d", disknum); copyDirectory(mntpt, dest); location = malloc(sizeof(struct moduleBallLocation)); location->title = strdup(title); location->path = sdupprintf("/tmp/ramfs/DD-%d/modules.cgz", disknum); location->version = version; char *fwdir = sdupprintf("/tmp/ramfs/DD-%d/firmware", disknum); if (!access(fwdir, R_OK|X_OK)) { add_fw_search_dir(loaderData, fwdir); stop_fw_loader(loaderData); start_fw_loader(loaderData); } free(fwdir); sprintf(file, "%s/modinfo", mntpt); readModuleInfo(file, modInfo, location, 1); sprintf(file, "%s/modules.dep", mntpt); mlLoadDeps(modDepsPtr, file); sprintf(file, "%s/modules.alias", mntpt); pciReadDrivers(file); if (!FL_CMDLINE(flags)) newtPopWindow(); disknum++; return 0; }
/* * Do the actual copy. This is called recursively from copyDirectory(). * * "dst" should only be a directory if "src" is also a directory. * * Returns 0 on success. */ static int copyFileRecursive(const char* src, const char* dst, bool isCmdLine, unsigned int options) { char* srcExe = NULL; char* dstExe = NULL; char* dstDir = NULL; struct stat srcStat; int retVal = 0; int statResult, statErrno; /* * Stat the source file. If it doesn't exist, fail. */ if (options & COPY_NO_DEREFERENCE) statResult = lstat(src, &srcStat); else statResult = stat(src, &srcStat); statErrno = errno; /* preserve across .exe attempt */ #ifdef WIN32_EXE /* * Here's the interesting part. Under Cygwin, if you have a file * called "foo.exe", stat("foo", ...) will succeed, but open("foo", ...) * will fail. We need to figure out what its name is supposed to be * so we can create the correct destination file. * * If we don't have the "-e" flag set, we want "acp foo bar" to fail, * not automatically find "foo.exe". That way, if we really were * trying to copy "foo", it doesn't grab something we don't want. */ if (isCmdLine && statResult == 0) { int tmpFd; tmpFd = open(src, O_RDONLY | O_BINARY, 0); if (tmpFd < 0) { statResult = -1; statErrno = ENOENT; } else { (void) close(tmpFd); } } /* * If we didn't find the file, try it again with ".exe". */ if (isCmdLine && statResult < 0 && statErrno == ENOENT && (options & COPY_TRY_EXE)) { srcExe = malloc(strlen(src) + 4 +1); strcpy(srcExe, src); strcat(srcExe, ".exe"); if (options & COPY_NO_DEREFERENCE) statResult = lstat(srcExe, &srcStat); else statResult = stat(srcExe, &srcStat); if (statResult == 0 && !S_ISREG(srcStat.st_mode)) statResult = -1; /* fail, use original statErrno below */ if (statResult == 0) { /* found a .exe, copy that instead */ dstExe = malloc(strlen(dst) + 4 +1); strcpy(dstExe, dst); strcat(dstExe, ".exe"); src = srcExe; dst = dstExe; } else { DBUG(("--- couldn't find '%s' either\n", srcExe)); } } #endif if (statResult < 0) { if (statErrno == ENOENT) fprintf(stderr, "acp: file '%s' does not exist\n", src); else fprintf(stderr, "acp: unable to stat '%s': %s\n", src, strerror(statErrno)); retVal = -1; goto bail; } /* * If "src" is a directory, ignore it if "recursive" isn't set. * * We want to create "dst" as a directory (or verify that it already * exists as a directory), and then copy its contents. */ if (S_ISDIR(srcStat.st_mode)) { if (!(options & COPY_RECURSIVE)) { fprintf(stderr, "acp: omitting directory '%s'\n", src); } else { retVal = copyDirectory(src, dst, &srcStat, options); } #ifdef HAVE_SYMLINKS } else if (S_ISLNK(srcStat.st_mode)) { retVal = copySymlink(src, dst, &srcStat, options); #endif } else if (S_ISREG(srcStat.st_mode)) { retVal = copyRegular(src, dst, &srcStat, options); } else { fprintf(stderr, "acp: skipping unusual file '%s' (mode=0%o)\n", src, srcStat.st_mode); retVal = -1; } bail: free(srcExe); free(dstExe); free(dstDir); return retVal; }