void DolphinTabPage::slotViewActivated() { const DolphinView* oldActiveView = activeViewContainer()->view(); // Set the view, which was active before, to inactive // and update the active view type. if (m_splitViewEnabled) { activeViewContainer()->setActive(false); m_primaryViewActive = !m_primaryViewActive; } else { m_primaryViewActive = true; } const DolphinView* newActiveView = activeViewContainer()->view(); if (newActiveView != oldActiveView) { disconnect(oldActiveView, SIGNAL(urlChanged(QUrl)), this, SIGNAL(activeViewUrlChanged(QUrl))); disconnect(oldActiveView, SIGNAL(redirection(QUrl,QUrl)), this, SLOT(slotViewUrlRedirection(QUrl,QUrl))); connect(newActiveView, SIGNAL(urlChanged(QUrl)), this, SIGNAL(activeViewUrlChanged(QUrl))); connect(newActiveView, SIGNAL(redirection(QUrl,QUrl)), this, SLOT(slotViewUrlRedirection(QUrl,QUrl))); } emit activeViewUrlChanged(activeViewContainer()->url()); emit activeViewChanged(activeViewContainer()); }
void exececho(Cmd c, int inPipeId, int outPipeId) { int newfd; if(c->next == NULL) { redirection(c, inPipeId, outPipeId); for (int i = 1; c->args[i] != NULL; i++ ) printf("%s ", c->args[i]); putchar('\n'); } else { if(fork() == 0) { redirection(c, inPipeId, outPipeId); for (int i = 1; c->args[i] != NULL; i++ ) printf("%s ", c->args[i]); putchar('\n'); exit(0); } else { close((pipes+(2*outPipeId))[1]); wait(); } } }
int main(int argc, char **argv) { int a; // Счётчик аргументов for (a = 1; a < argc; ++a) { int fd = open(argv[a], O_RDONLY); if (fd < 0) { printerr(argv[a]); } else { switch (redirection(fd, 1)) { case -1: printerr("Read error: "); break; case -2: printerr("Write error: "); break; case 0: default: break; } fd = close(fd); if (fd < 0) { printerr(argv[a]); } } } if ((a == 1) && (redirection(0, 1) != 0)) { printerr("Error in stdin! "); } return 0; }
void backstage(char *command, char *args[], int size){ int i = 0, j; pid_t pid; int cnt = 0; //查看是否存在& for(i = 0; i < size; i++) if(strcmp(args[i], "&") == 0) break; //若没有,则直接调用judge_utility if(i == size){ redirection(command, args, size); return; } //若有,则创建子进程 pid = fork(); while(pid < 0){ //若创建子进程失败,则不断创建 pid = fork(); cnt++; if(cnt >= 100) break; } if(cnt >= 100){//创建子进程失败 printf("创建子进程失败!\n"); return; } if(pid == 0){ jobID++; //在子进程中调用功能函数 printf("[%d]%d\n", jobID, getpid()); redirection(command, args, i); printf("[%d]\tDone\t%s", jobID, command); //调用完成 for(j = 0; j < i; j++) printf(" %s", args[j]); printf("\n"); jobID--; //子进程完成后结束该进程 exit(0); }else{ if(i == size - 1) return; else{ //截取字符串后递归调用该函数 backstage(args[i + 1], args + i + 2, size - i - 2); return; } } }
void execcommand(Cmd c, int inPipeId, int outPipeId) { char cwd[100]; pid_t pid; pid = fork(); int status; if( pid == 0) { redirection(c, inPipeId, outPipeId); //printf("TP"); //if((c->args+1) != NULL) //fprintf(std_out, "The command and arguments are: %s: %s\n", c->args[0], c->args[1]); //flushall(); if(execvp(c->args[0], c->args) < 0) perror(""); //else //execvp(c->args[0]); //fprintf(stdout,"Processed Here\n"); fflush(stdout); _exit(0); } else { close((pipes+(2*outPipeId))[1]); while(wait(&status) != pid); } }
void RemoteProtocol::listDir(const KURL &url) { kdDebug(1220) << "RemoteProtocol::listDir: " << url << endl; if(url.path().length() <= 1) { listRoot(); return; } int second_slash_idx = url.path().find('/', 1); QString root_dirname = url.path().mid(1, second_slash_idx - 1); KURL target = m_impl.findBaseURL(root_dirname); kdDebug(1220) << "possible redirection target : " << target << endl; if(target.isValid()) { target.addPath(url.path().remove(0, second_slash_idx)); redirection(target); finished(); return; } error(KIO::ERR_MALFORMED_URL, url.prettyURL()); }
void ZeroConfProtocol::resolveAndRedirect( const ZeroConfUrl& zeroConfUrl ) { if (serviceToResolve && !zeroConfUrl.matches(serviceToResolve)) { delete serviceToResolve; serviceToResolve = 0; } if (serviceToResolve == 0) { if( !knownProtocols.contains(zeroConfUrl.serviceType()) ) { error( ERR_SERVICE_NOT_AVAILABLE, zeroConfUrl.serviceType() ); return; } serviceToResolve = new RemoteService( zeroConfUrl.serviceName(), zeroConfUrl.serviceType(), zeroConfUrl.domain() ); if (!serviceToResolve->resolve()) { error( ERR_DOES_NOT_EXIST, zeroConfUrl.serviceName() ); return; } } if( !knownProtocols.contains(zeroConfUrl.serviceType()) ) return; // action const ProtocolData& protocolData = knownProtocols[zeroConfUrl.serviceType()]; KUrl destUrl; protocolData.feedUrl( &destUrl, serviceToResolve ); redirection( destUrl ); finished(); }
void RemoteProtocol::listDir(const KUrl &url) { kDebug(1220) << "RemoteProtocol::listDir: " << url; if ( url.path().length() <= 1 ) { listRoot(); return; } int second_slash_idx = url.path().indexOf( '/', 1 ); const QString root_dirname = url.path().mid( 1, second_slash_idx-1 ); KUrl target = m_impl.findBaseURL( root_dirname ); kDebug(1220) << "possible redirection target : " << target; if( target.isValid() ) { if ( second_slash_idx < 0 ) { second_slash_idx = url.path().size(); } target.addPath( url.path().remove(0, second_slash_idx) ); kDebug(1220) << "complete redirection target : " << target; redirection(target); finished(); return; } error(KIO::ERR_MALFORMED_URL, url.prettyUrl()); }
DolphinTabPage::DolphinTabPage(const QUrl &primaryUrl, const QUrl &secondaryUrl, QWidget* parent) : QWidget(parent), m_primaryViewActive(true), m_splitViewEnabled(false) { QVBoxLayout* layout = new QVBoxLayout(this); layout->setSpacing(0); layout->setMargin(0); m_splitter = new QSplitter(Qt::Horizontal, this); m_splitter->setChildrenCollapsible(false); layout->addWidget(m_splitter); // Create a new primary view m_primaryViewContainer = createViewContainer(primaryUrl); connect(m_primaryViewContainer->view(), SIGNAL(urlChanged(QUrl)), this, SIGNAL(activeViewUrlChanged(QUrl))); connect(m_primaryViewContainer->view(), SIGNAL(redirection(QUrl,QUrl)), this, SLOT(slotViewUrlRedirection(QUrl,QUrl))); m_splitter->addWidget(m_primaryViewContainer); m_primaryViewContainer->show(); if (secondaryUrl.isValid() || GeneralSettings::splitView()) { // Provide a secondary view, if the given secondary url is valid or if the // startup settings are set this way (use the url of the primary view). m_splitViewEnabled = true; const QUrl& url = secondaryUrl.isValid() ? secondaryUrl : primaryUrl; m_secondaryViewContainer = createViewContainer(url); m_splitter->addWidget(m_secondaryViewContainer); m_secondaryViewContainer->show(); } m_primaryViewContainer->setActive(true); }
void RedirectScheduler::cancel(bool newLoadInProgress) { m_timer.stop(); OwnPtr<ScheduledRedirection> redirection(m_scheduledRedirection.release()); if (redirection && redirection->toldClient) m_frame->loader()->clientRedirectCancelledOrFinished(newLoadInProgress); }
void RemoteProtocol::stat(const KURL &url) { kdDebug(1220) << "RemoteProtocol::stat: " << url << endl; QString path = url.path(); if(path.isEmpty() || path == "/") { // The root is "virtual" - it's not a single physical directory KIO::UDSEntry entry; m_impl.createTopLevelEntry(entry); statEntry(entry); finished(); return; } if(m_impl.isWizardURL(url)) { KIO::UDSEntry entry; if(m_impl.createWizardEntry(entry)) { statEntry(entry); finished(); } else { error(KIO::ERR_DOES_NOT_EXIST, url.prettyURL()); } return; } int second_slash_idx = url.path().find('/', 1); QString root_dirname = url.path().mid(1, second_slash_idx - 1); if(second_slash_idx == -1 || ((int)url.path().length()) == second_slash_idx + 1) { KIO::UDSEntry entry; if(m_impl.statNetworkFolder(entry, root_dirname)) { statEntry(entry); finished(); return; } } else { KURL target = m_impl.findBaseURL(root_dirname); kdDebug(1220) << "possible redirection target : " << target << endl; if(target.isValid()) { target.addPath(url.path().remove(0, second_slash_idx)); redirection(target); finished(); return; } } error(KIO::ERR_MALFORMED_URL, url.prettyURL()); }
int KProtocolProxyFTP::ProcessHeader() { char buffer[1024]; int len = 1; size = 0xFFFFFFF; while( len && fgets( buffer, 1024, fsocket ) ) { len = strlen(buffer); while( len && (buffer[len-1] == '\n' || buffer[len-1] == '\r')) buffer[--len] = 0; if ( strncmp( buffer, "Content-length: ", 16 ) == 0 || strncmp( buffer, "Content-Length: ", 16 ) == 0 ) size = atol( buffer + 16 ); else if ( strncmp( buffer, "Content-Type: ", 14 ) == 0 || strncmp( buffer, "Content-type: ", 14 ) == 0 ) { emit mimeType( buffer + 14 ); } else if ( strncmp( buffer, "HTTP/1.0 ", 9 ) == 0 ) { if ( (buffer[9] == '4') || (buffer[9] == '5')) { KURL u( url ); QString path = u.path(); /* When the requested URL is not a Directory, fail with 'KIO_ERROR_NotADirectory'. Kfm will try again as a file. */ if ( (path.right(1) == "/") && (path.length() != 1 ) ) { Close(); Error(KIO_ERROR_NotADirectory,"Not a directory",errno); return FAIL; } else { // A real error occured Close(); Error(KIO_ERROR_CouldNotRead,buffer+9,errno); return FAIL; } } } else if ( strncmp( buffer, "Location: ", 10 ) == 0 ) { Close(); KURL u( url ); KURL u2( u, buffer + 10 ); emit redirection( u2.url() ); return Open( &u2, currentMode ); } } bytesleft = size; return(SUCCESS); }
void ApplicationsProtocol::get( const KUrl & url ) { KService::Ptr service = KService::serviceByDesktopName(url.fileName()); if (service && service->isValid()) { KUrl redirUrl(KStandardDirs::locate("apps", service->entryPath())); redirection(redirUrl); finished(); } else { error( KIO::ERR_IS_DIRECTORY, url.prettyUrl() ); } }
void KFMJob::slotRedirection( const char *_url ) { emit redirection( _url ); if (!KURL(_url).isLocalFile()) { // disable any change if redirection on a local file. // This allows to store the "/index.html" in 'url' // without changing the url stored here and in kfmman. David. url = _url; post_data = 0; openFileOrDir(false); } }
void execpwd(Cmd c, int inPipeId, int outPipeId) { char cwd[100]; if(c->next == NULL) { redirection(c, inPipeId, outPipeId); getcwd(cwd,sizeof(cwd)); printf("%s", cwd); putchar('\n'); } else { if(fork() == 0) { redirection(c, inPipeId, outPipeId); //printf("TP"); getcwd(cwd,sizeof(cwd)); printf("%s", cwd); putchar('\n'); exit(0); } else { close((pipes+(2*outPipeId))[1]); wait(); } } }
int MTPSlave::checkUrl ( const KUrl& url, bool redirect ) { kDebug ( KIO_MTP ) << url; if ( url.path().startsWith ( QLatin1String ( "udi=" ) ) && redirect ) { QString udi = url.path( KUrl::RemoveTrailingSlash ).remove ( 0, 4 ); kDebug ( KIO_MTP ) << "udi = " << udi; Solid::Device device ( udi ); if ( !device.isValid() ) { return 2; } Solid::GenericInterface *iface = device.as<Solid::GenericInterface>(); QMap<QString, QVariant> properties = iface->allProperties(); int busnum = properties.value ( QLatin1String ( "BUSNUM" ) ).toInt(); int devnum = properties.value ( QLatin1String ( "DEVNUM" ) ).toInt(); kDebug ( KIO_MTP ) << "UDI reports BUS/DEV:" << busnum << "/" << devnum; QMap<QString, LIBMTP_raw_device_t*> devices = getRawDevices(); foreach ( const QString &deviceName, devices.keys() ) { LIBMTP_raw_device_t* rawDevice = devices.value ( deviceName ); int currentBusNum = rawDevice->bus_location; int currentDevNum = rawDevice->devnum; kDebug ( KIO_MTP ) << "LIBMTP has BUS/DEV:"<< currentBusNum << "/" << currentDevNum; if ( currentBusNum == busnum && currentDevNum == devnum ) { KUrl newUrl; newUrl.setProtocol ( QLatin1String ( "mtp" ) ); newUrl.setPath ( QLatin1Char ( '/' ) + deviceName ); redirection ( newUrl ); return 1; } } }
void RemoteProtocol::get(const KUrl &url) { kDebug(1220) << "RemoteProtocol::get: " << url; const QString file = m_impl.findDesktopFile( url.fileName() ); kDebug(1220) << "desktop file : " << file; if (!file.isEmpty()) { KUrl desktop; desktop.setPath(file); redirection(desktop); finished(); return; } error(KIO::ERR_MALFORMED_URL, url.prettyUrl()); }
void RedirectScheduler::timerFired(Timer<RedirectScheduler>*) { if (!m_frame->page()) return; if (m_frame->page()->defersLoading()) return; OwnPtr<ScheduledRedirection> redirection(m_scheduledRedirection.release()); FrameLoader* loader = m_frame->loader(); switch (redirection->type) { case ScheduledRedirection::redirection: case ScheduledRedirection::locationChange: loader->changeLocation(KURL(ParsedURLString, redirection->url), redirection->referrer, redirection->lockHistory, redirection->lockBackForwardList, redirection->wasUserGesture, redirection->wasRefresh); return; case ScheduledRedirection::historyNavigation: if (redirection->historySteps == 0) { // Special case for go(0) from a frame -> reload only the frame loader->urlSelected(loader->url(), "", 0, redirection->lockHistory, redirection->lockBackForwardList, redirection->wasUserGesture, SendReferrer); return; } // go(i!=0) from a frame navigates into the history of the frame only, // in both IE and NS (but not in Mozilla). We can't easily do that. m_frame->page()->goBackOrForward(redirection->historySteps); return; case ScheduledRedirection::formSubmission: // The submitForm function will find a target frame before using the redirection timer. // Now that the timer has fired, we need to repeat the security check which normally is done when // selecting a target, in case conditions have changed. Other code paths avoid this by targeting // without leaving a time window. If we fail the check just silently drop the form submission. if (!redirection->formState->sourceFrame()->loader()->shouldAllowNavigation(m_frame)) return; loader->loadFrameRequest(redirection->frameRequest, redirection->lockHistory, redirection->lockBackForwardList, redirection->event, redirection->formState, SendReferrer); return; } ASSERT_NOT_REACHED(); }
void testCommande(){ // Test si l'utilisateur a rediriger la sortie int i, placeFichier; for(i=0, placeFichier=0; i<nbArg; i++, placeFichier++){ if ( !strcmp(commandeParse[i], ">" ) ) { /* Test si user à rediriger la sortie */ redirection(++placeFichier); return; } } // Test si l'utilisateur a pipe la sortie int placePipe; for(placePipe=0; placePipe<nbArg; placePipe++){ if ( !strcmp(commandeParse[placePipe], "|" ) ) { /* Test si user à rediriger la sortie */ commandePipe(placePipe); return; } } if ( !commandeParse[0] ) /* Si commande null ne fais rien et relance un invite commande */ ; else if ( !strcmp(commandeParse[0], "cd" ) ) /* Test si user utilise CD */ changeDirectory(); else if ( !strcmp(commandeParse[0], "history" ) ) /* Test si user utilise HISTORY */ commandeHistory(); else if ( !strcmp(commandeParse[0], "touch" ) ) /* Test si user utilise TOUCH */ commandeTouch(); else if ( !strcmp(commandeParse[0], "exit" ) ) /* Test si user utilise EXIT */ exit(0); else if ( !strcmp(commandeParse[0], "cat" ) ) /* Test si user utilise CAT */ commandeCat(); else if ( !strcmp(commandeParse[0], "cp" ) ) /* Test si user utilise CP */ commandeCP(); else /* Exécution de commande avec exec */ executionCommande(); }
void execution(Commande *commande, Niveau *niveau){ fixDirectory(commande, niveau); insertionString(niveau->history, commande->commande); int nbArgument = nbArg(commande); int ok = 1; int redirect = 1; // printw("nb arg : %d\n", nbArgument); exceptionProcessing(niveau, commande); // Vérifie que la commande ne soit pas vide if (strlen(commande->commande) == 0){} else { // Vérifie si la commande est autorisée dans ce niveau if (!appartient(premierArg(commande->commande), niveau->charAutorise)) { printw("Commande \"%s\" interdite !!\n", premierArg(commande->commande)); printw("Liste des commandes autorisées :\n"); String *temp = niveau->charAutorise->premier; printw("\t %s\n", temp->string); while((temp = temp->suivant) != NULL){ printw("\t %s\n", temp->string); } } else { ListeString *listeArg = malloc(sizeof(ListeString)); buildArgsChain(listeArg, commande); // Gestion particulière du cd if (!strcmp(substr(commande->commande,0,2), "cd")) { // Vérifie qu'il n'y a qu'un seul argument après le cd if (nbArgument == 1) { // Vérifie que le dossier visé existe et qu'il n'est pas un fichier et qu'il n'est pas au-dessus de la racine if (dirExists(listeArg->premier->string) && accessible(commande)) { // Vérifie que ce n'est pas un fichier if(fileExists(listeArg->premier->string)) printw("\"%s\" est un fichier !!\n", listeArg->premier->string); else{ chdir(listeArg->premier->string); fixDirectory(commande, niveau); commande->niveau = commande->niveau + incrementNiveau(commande); } }else printw("Le répertoire \"%s\" n'existe pas !!\n", listeArg->premier->string); }else{ goBackRoot(commande); } } // gestion du pwd else if (!strcmp(substr(commande->commande,0,3), "pwd")) pwd(commande); // Gestion de >> else if((redirect = isRedirector(commande)) > 0) redirection(niveau, commande, redirect); // commandes autres else { printw("%s", exec(listeArg, commande, &(*niveau))); } } } }
DolphinViewContainer::DolphinViewContainer(const KUrl& url, QWidget* parent) : QWidget(parent), m_topLayout(0), m_urlNavigator(0), m_searchBox(0), m_view(0), m_filterBar(0), m_statusBar(0), m_statusBarTimer(0), m_statusBarTimestamp() { hide(); m_topLayout = new QVBoxLayout(this); m_topLayout->setSpacing(0); m_topLayout->setMargin(0); m_urlNavigator = new KUrlNavigator(DolphinSettings::instance().placesModel(), url, this); connect(m_urlNavigator, SIGNAL(urlsDropped(const KUrl&, QDropEvent*)), this, SLOT(dropUrls(const KUrl&, QDropEvent*))); connect(m_urlNavigator, SIGNAL(activated()), this, SLOT(activate())); connect(m_urlNavigator->editor(), SIGNAL(completionModeChanged(KGlobalSettings::Completion)), this, SLOT(saveUrlCompletionMode(KGlobalSettings::Completion))); const GeneralSettings* settings = DolphinSettings::instance().generalSettings(); m_urlNavigator->setUrlEditable(settings->editableUrl()); m_urlNavigator->setShowFullPath(settings->showFullPath()); m_urlNavigator->setHomeUrl(KUrl(settings->homeUrl())); KUrlComboBox* editor = m_urlNavigator->editor(); editor->setCompletionMode(KGlobalSettings::Completion(settings->urlCompletionMode())); m_searchBox = new DolphinSearchBox(this); m_searchBox->hide(); connect(m_searchBox, SIGNAL(closeRequest()), this, SLOT(closeSearchBox())); connect(m_searchBox, SIGNAL(search(QString)), this, SLOT(startSearching(QString))); connect(m_searchBox, SIGNAL(returnPressed(QString)), this, SLOT(requestFocus())); m_view = new DolphinView(url, this); connect(m_view, SIGNAL(urlChanged(const KUrl&)), m_urlNavigator, SLOT(setUrl(const KUrl&))); connect(m_view, SIGNAL(writeStateChanged(bool)), this, SIGNAL(writeStateChanged(bool))); connect(m_view, SIGNAL(requestItemInfo(KFileItem)), this, SLOT(showItemInfo(KFileItem))); connect(m_view, SIGNAL(errorMessage(const QString&)), this, SLOT(showErrorMessage(const QString&))); connect(m_view, SIGNAL(infoMessage(const QString&)), this, SLOT(showInfoMessage(const QString&))); connect(m_view, SIGNAL(itemTriggered(KFileItem)), this, SLOT(slotItemTriggered(KFileItem))); connect(m_view, SIGNAL(redirection(KUrl, KUrl)), this, SLOT(redirect(KUrl, KUrl))); connect(m_view, SIGNAL(startedPathLoading(KUrl)), this, SLOT(slotStartedPathLoading())); connect(m_view, SIGNAL(finishedPathLoading(KUrl)), this, SLOT(slotFinishedPathLoading())); connect(m_view, SIGNAL(itemCountChanged()), this, SLOT(delayedStatusBarUpdate())); connect(m_view, SIGNAL(pathLoadingProgress(int)), this, SLOT(updateProgress(int))); connect(m_view, SIGNAL(infoMessage(const QString&)), this, SLOT(showInfoMessage(const QString&))); connect(m_view, SIGNAL(errorMessage(const QString&)), this, SLOT(showErrorMessage(const QString&))); connect(m_view, SIGNAL(urlIsFileError(const KUrl&)), this, SLOT(openFile(const KUrl&))); connect(m_view, SIGNAL(selectionChanged(const KFileItemList&)), this, SLOT(delayedStatusBarUpdate())); connect(m_view, SIGNAL(operationCompletedMessage(const QString&)), this, SLOT(showOperationCompletedMessage(const QString&))); connect(m_urlNavigator, SIGNAL(urlChanged(const KUrl&)), this, SLOT(slotUrlNavigatorLocationChanged(const KUrl&))); connect(m_urlNavigator, SIGNAL(urlAboutToBeChanged(const KUrl&)), this, SLOT(saveViewState())); connect(m_urlNavigator, SIGNAL(historyChanged()), this, SLOT(slotHistoryChanged())); // initialize status bar m_statusBar = new DolphinStatusBar(this, m_view); connect(m_statusBar, SIGNAL(stopPressed()), this, SLOT(stopLoading())); m_statusBarTimer = new QTimer(this); m_statusBarTimer->setSingleShot(true); m_statusBarTimer->setInterval(300); connect(m_statusBarTimer, SIGNAL(timeout()), this, SLOT(updateStatusBar())); KIO::FileUndoManager* undoManager = KIO::FileUndoManager::self(); connect(undoManager, SIGNAL(jobRecordingFinished(CommandType)), this, SLOT(delayedStatusBarUpdate())); // initialize filter bar m_filterBar = new FilterBar(this); m_filterBar->setVisible(settings->filterBar()); connect(m_filterBar, SIGNAL(filterChanged(const QString&)), this, SLOT(setNameFilter(const QString&))); connect(m_filterBar, SIGNAL(closeRequest()), this, SLOT(closeFilterBar())); connect(m_view, SIGNAL(urlChanged(const KUrl&)), m_filterBar, SLOT(clear())); m_topLayout->addWidget(m_urlNavigator); m_topLayout->addWidget(m_searchBox); m_topLayout->addWidget(m_view); m_topLayout->addWidget(m_filterBar); m_topLayout->addWidget(m_statusBar); setSearchModeEnabled(isSearchUrl(url)); }
int main() { int per; signal(SIGCHLD,signalhandler); signal(SIGINT,signalINThandler); char x1[1000],bin; char delim[]=" \t"; char *x2; getcwd(home,100); strcpy(prehome,home); strcpy(preprehome,prehome); display(); printf("~> "); x1[0]='\0'; while(1) { scanf("%[^\n]",x1); scanf("%c",&bin); if(x1[0]=='\0') { int killcount=0; for(killcount=0; killcount<gkill; killcount++) { if(killstatus[killcount]==1) { printf("process name:%s pid:%d exited normally\n",killname[killcount],killid[killcount]); } else if(killstatus[killcount]==-1) { printf("process name:%s pid:%d exited abnormally\n",killname[killcount],killid[killcount]); } } gkill=0; displayx(prehome,home); /* if(strstr(prehome,home)!=NULL){ int j2=0; printf("~"); for(j2=strlen(home);j2<strlen(prehome);j2++){ printf("%c",prehome[j2]); } printf("> "); } else{ printf("%s> ",prehome); } */ continue; } int i=0; char *tok[100],x3[100]; strcpy(x3,x1); x2=strtok(x1,delim); while(x2!=NULL) { tok[i]=x2; x2=strtok(NULL,delim); i++; } tok[i]=NULL; char copy[100]; if(!strcmp(tok[0],"cd")) { if(i==1 || !strcmp(tok[1],"~")) { per=chdir(home); display(); printf("~> "); } else if(!strcmp(tok[1],"-")) { per=chdir(preprehome); display(); if(strstr(home,preprehome)==NULL) { printf("%s> ",prehome); } else { int j=0,k=0; copy[0]='\0'; for(j=strlen(preprehome); j<strlen(home); j++,k++) { copy[k]=prehome[j]; } copy[k]='\0'; printf("~%s> ",copy); } } else if(tok[1][0]=='~') { char current1[100]; strcpy(current1,home); int j1=0; int j2=strlen(current1); for(j1=1; j1<=strlen(tok[1]); j1++) { current1[j2+j1-1]=tok[1][j1]; } current1[j2+j1-1]='\0'; int status3=chdir(current1); if(status3==-1) { perror(NULL); } getcwd(current1,100); display(); if(strstr(current1,home)==NULL) { printf("%s> ",current1); } else { int j=0,k=0; copy[0]='\0'; for(j=strlen(home); j<strlen(current1); j++,k++) { copy[k]=current1[j]; } copy[k]='\0'; printf("~%s> ",copy); } } else if(tok[1][0]=='/') { int status1=chdir(tok[1]); if(status1==-1) { perror(NULL); } getcwd(tok[1],100); displayx(tok[1],home); } else { char current[100]; getcwd(current,100); int j=0; strcat(current,"/"); strcat(current,tok[1]); int status2=chdir(current); if(status2==-1) { perror(NULL); } getcwd(current,100); if(strstr(current,home)==NULL) { display(); printf("%s> ",current); } else { int j=0,k=0; char copy[100]; copy[0]='\0'; for(j=strlen(home); j<strlen(current); j++,k++) { copy[k]=current[j]; } copy[k]='\0'; display(); printf("~%s> ",copy); } } } else if(!strcmp(tok[0],"pid") && tok[1]==NULL) { printf("pid:./a.out process id: %d\n",getpid()); display(prehome,home); } else if(!strcmp(tok[0],"pid") && !strcmp(tok[1],"current")) { int valc=0; for(valc=0; valc<gj; valc++) { if(pidc[valc]!=0) { printf("command name:%s process id: %d\n",namec[valc],pidc[valc]); } } displayx(prehome,home); } else if(!strcmp(tok[0],"pid") && !strcmp(tok[1],"all")) { int valh=0; for(valh=0; valh<gj; valh++) { printf("command name: %s process id: %d\n",nameh[valh],pidh[valh]); } displayx(prehome,home); } else if(!strcmp(tok[0],"hist")) { history(tok[0],0); displayx(prehome,home); } else if(strstr(tok[0],"hist") && strlen(tok[0])==5) { history(tok[0],1); displayx(prehome,home); } else if(strstr(tok[0],"!hist") && strlen(tok[0])==6) { history(tok[0],2); displayx(prehome,home); } else if(!strcmp(tok[0],"quit")) { exit(1); } else if(checkpipe(tok,i)) { pipehandle(tok,i); displayx(prehome,home); } else if(strstr(x3,">") || strstr(x3,"<") || strstr(x3,"|")) { int ile=0,igt=0,countre=0,in,out,pipe[100]= {0},countp=0; for(countre=0; countre<i; countre++) { if(!strcmp(tok[countre],"<")) { ile=countre; } else if(!strcmp(tok[countre],">")) { igt=countre; } else if(!strcmp(tok[countre],"|")) { pipe[countp]=countre; countp++; } } redirection(tok,ile,igt); } else { int val=fork(); if(tok[i-1][0]=='&') { tok[i-1]=NULL; if(val==0) { if(execvp(tok[0],tok)==-1) { perror(NULL); } exit(0); } else if(val>0) { strcpy(nameh[gj],tok[0]); strcpy(namec[gj],tok[0]); pidh[gj]=val; pidc[gj]=val; gj++; } } else if(tok[0]!=NULL) { if(val==0) { if(execvp(tok[0],tok)==-1) { perror(NULL); } exit(0); } else if(val>0) { wait(NULL); } } display(); if(!strcmp(prehome,home)) { int j2=0; printf("~"); for(j2=strlen(home); j2<strlen(prehome); j2++) { printf("%c",prehome[j2]); } printf("> "); } else { printf("%s> ",prehome); } } strcpy(preprehome,prehome); getcwd(prehome,100); x1[0]='\0'; history(x3,9); if(per==-1) { printf(NULL); } } return 0; }
void execwhere(Cmd c, int inPipeId, int outPipeId) { int newfd; int i=0; char* str_path = getenv("PATH"); char* str; char* dir; char path[20]; struct stat fileStat; if(c->next == NULL) { //if(fork() == 0) // { redirection(c, inPipeId, outPipeId); str = strdup(str_path); //printf("PATH:%s\n",str); printf("%s:", c->args[1]); if(isBuiltinCommand(c->args[1])) printf(" Built-in command \n%s:",c->args[1]); while ((dir = strsep(&str, ":"))) { strcpy(path, dir); strcat(path,"/"); strcat(path,c->args[1]); //printf("dir:%s\n", path); if(stat(path, &fileStat) == 0) { printf(" %s",path); } } putchar('\n'); // exit(0); //} //else //{ // wait(); //} } else { if(fork() == 0) { redirection(c, inPipeId, outPipeId); str = strdup(str_path); //printf("PATH:%s\n",str); printf("%s:", c->args[1]); if(isBuiltinCommand(c->args[1])) printf(" Built-in command \n%s:",c->args[1]); while ((dir = strsep(&str, ":"))) { strcpy(path, dir); strcat(path,"/"); strcat(path,c->args[1]); //printf("dir:%s\n", path); if(stat(path, &fileStat) == 0) { printf(" %s",path); } } putchar('\n'); exit(0); } else { close((pipes+(2*outPipeId))[1]); wait(); } } }
//=========================================================================== void SMBSlave::get( const KURL& kurl ) { char buf[MAX_XFER_BUF_SIZE]; int filefd = 0; ssize_t bytesread = 0; // time_t curtime = 0; time_t lasttime = 0; time_t starttime = 0; KIO::filesize_t totalbytesread = 0; QByteArray filedata; SMBUrl url; kdDebug(KIO_SMB) << "SMBSlave::get on " << kurl << endl; // check (correct) URL KURL kvurl = checkURL(kurl); // if URL is not valid we have to redirect to correct URL if (kvurl != kurl) { redirection(kvurl); finished(); return; } if(!auth_initialize_smbc()) return; // Stat url = kurl; if(cache_stat(url,&st) == -1 ) { if ( errno == EACCES ) error( KIO::ERR_ACCESS_DENIED, url.prettyURL()); else error( KIO::ERR_DOES_NOT_EXIST, url.prettyURL()); return; } if ( S_ISDIR( st.st_mode ) ) { error( KIO::ERR_IS_DIRECTORY, url.prettyURL()); return; } // Set the total size totalSize( st.st_size ); // Open and read the file filefd = smbc_open(url.toSmbcUrl(),O_RDONLY,0); if(filefd >= 0) { if(buf) { bool isFirstPacket = true; lasttime = starttime = time(NULL); while(1) { bytesread = smbc_read(filefd, buf, MAX_XFER_BUF_SIZE); if(bytesread == 0) { // All done reading break; } else if(bytesread < 0) { error( KIO::ERR_COULD_NOT_READ, url.prettyURL()); return; } filedata.setRawData(buf,bytesread); if (isFirstPacket) { // We need a KMimeType::findByNameAndContent(filename,data) // For now we do: find by extension, and if not found (or extension not reliable) // then find by content. bool accurate = false; KMimeType::Ptr mime = KMimeType::findByURL( kurl, st.st_mode, false, true, &accurate ); if ( !mime || mime->name() == KMimeType::defaultMimeType() || !accurate ) { KMimeType::Ptr p_mimeType = KMimeType::findByContent(filedata); if ( p_mimeType && p_mimeType->name() != KMimeType::defaultMimeType() ) mime = p_mimeType; } mimeType(mime->name()); isFirstPacket = false; } data( filedata ); filedata.resetRawData(buf,bytesread); // increment total bytes read totalbytesread += bytesread; processedSize(totalbytesread); } } smbc_close(filefd); data( QByteArray() ); processedSize(static_cast<KIO::filesize_t>(st.st_size)); } else { error( KIO::ERR_CANNOT_OPEN_FOR_READING, url.prettyURL()); return; } finished(); }
void execunsetenv(Cmd c, int inPipeId, int outPipeId) { int newfd; int i=0; char* str; if(c->next == NULL) { //if(fork() == 0) // { redirection(c, inPipeId, outPipeId); if(c->args[1] == NULL) { perror("Variable not input"); } else{ //printf("TP"); //printf("Invoking Putenv for %s to null",c->args[1]); str = strdup(c->args[1]); unsetenv(str); } // exit(0); //} //else //{ // wait(); //} } else { if(fork() == 0) { redirection(c, inPipeId, outPipeId); if(c->args[1] == NULL) { perror("Variable not input"); } else{ //printf("TP"); //printf("Invoking Putenv for %s to null",c->args[1]); str = strdup(c->args[1]); unsetenv(str); } exit(0); } else { close((pipes+(2*outPipeId))[1]); wait(); } } }
void execcd(Cmd c, int inPipeId, int outPipeId) { int newfd; int i=0; char* path; char cwd[100]; if(c->next == NULL) { redirection(c, inPipeId, outPipeId); if(c->args[1] == NULL) { path = getenv("HOME"); //printf("Changing the directory to %s", path); if(chdir(path) != 0) { perror(""); } } else { if((c->args[1])[0] != '/') { // true for the dir in cwd getcwd(cwd,sizeof(cwd)); strcat(cwd,"/"); strcat(cwd,c->args[1]); if(chdir(cwd) != 0) { perror(""); } } else{//true for dir w.r.t. / if(chdir(c->args[1]) != 0) { perror(""); } } } //getcwd(cwd,sizeof(cwd)); //printf("The CWD is: %s", cwd); } else { if(fork() == 0) { redirection(c, inPipeId, outPipeId); //printf("TP"); if(c->args[1] == NULL) { path = getenv("HOME"); //printf("Changing the directory to %s", path); if(chdir(path) != 0) { perror(""); } } else { if((c->args[1])[0] != '/') { // true for the dir in cwd getcwd(cwd,sizeof(cwd)); strcat(cwd,"/"); strcat(cwd,c->args[1]); if(chdir(cwd) != 0) { perror(""); } } else{//true for dir w.r.t. / if(chdir(c->args[1]) != 0) { perror(""); } } } //getcwd(cwd,sizeof(cwd)); //printf("The CWD is: %s", cwd); exit(0); } else { close((pipes+(2*outPipeId))[1]); wait(); } } }
void PakProtocol::listDir(const KURL &url) { kdDebug(PAK_DEBUG_ID) << "Entering listDir()" << endl; QString path; KIO::Error errorNum; if ( !checkNewFile( url, path, errorNum ) ) { if ( errorNum == KIO::ERR_CANNOT_OPEN_FOR_READING ) { // If we cannot open, it might be a problem with the archive header (e.g. unsupported format) // Therefore give a more specific error message error( KIO::ERR_SLAVE_DEFINED, i18n( "Could not open the file, probably due to an unsupported file format.\n%1") .arg( url.prettyURL() ) ); return; } else if ( errorNum != KIO::ERR_IS_DIRECTORY ) { // We have any other error error( errorNum, url.prettyURL() ); return; } // It's a real dir -> redirect KURL redir; redir.setPath( url.path() ); kdDebug( PAK_DEBUG_ID ) << "Ok, redirection to " << redir.url() << endl; redirection( redir ); finished(); // And let go of the tar file - for people who want to unmount a cdrom after that delete _pakFile; _pakFile = 0L; return; } if ( path.isEmpty() ) { KURL redir( url.protocol() + QString::fromLatin1( ":/") ); kdDebug( PAK_DEBUG_ID ) << "url.path()==" << url.path() << endl; redir.setPath( url.path() + QString::fromLatin1("/") ); kdDebug( PAK_DEBUG_ID ) << "ArchiveProtocol::listDir: redirection " << redir.url() << endl; redirection( redir ); finished(); return; } path = QString::fromLocal8Bit(remoteEncoding()->encode(path)); kdDebug( PAK_DEBUG_ID ) << "checkNewFile done" << endl; const KArchiveDirectory* root = _pakFile->directory(); const KArchiveDirectory* dir; if (!path.isEmpty() && path != "/") { kdDebug(PAK_DEBUG_ID) << QString("Looking for entry %1").arg(path) << endl; const KArchiveEntry* e = root->entry( path ); if ( !e ) { error( KIO::ERR_DOES_NOT_EXIST, url.prettyURL() ); return; } if ( ! e->isDirectory() ) { error( KIO::ERR_IS_FILE, url.prettyURL() ); return; } dir = (KArchiveDirectory*)e; } else { dir = root; } QStringList l = dir->entries(); totalSize( l.count() ); KIO::UDSEntry entry; QStringList::Iterator it = l.begin(); for( ; it != l.end(); ++it ) { kdDebug(PAK_DEBUG_ID) << (*it) << endl; const KArchiveEntry* archiveEntry = dir->entry( (*it) ); createUDSEntry( archiveEntry, entry ); listEntry( entry, false ); } listEntry( entry, true ); // ready finished(); kdDebug( PAK_DEBUG_ID ) << "ArchiveProtocol::listDir done" << endl; /*kdDebug(PAK_DEBUG_ID) << "Entering listDir()" << endl; totalSize(1); // ONE file (Magic!!) KIO::UDSEntry entry; createUDSEntry(NULL, entry); kdDebug(PAK_DEBUG_ID) << "Giving file away" << endl; listEntry(entry, false); listEntry(entry, true); // End finished(); kdDebug(PAK_DEBUG_ID) << "-<> Exiting listDir()" << endl;*/ }
void PakProtocol::get(const KURL &url) { kdDebug(PAK_DEBUG_ID) << "ArchiveProtocol::get " << url << endl; QString path; KIO::Error errorNum; if ( !checkNewFile( url, path, errorNum ) ) { if ( errorNum == KIO::ERR_CANNOT_OPEN_FOR_READING ) { // If we cannot open, it might be a problem with the archive header (e.g. unsupported format) // Therefore give a more specific error message error( KIO::ERR_SLAVE_DEFINED, i18n( "Could not open the file, probably due to an unsupported file format.\n%1") .arg( url.prettyURL() ) ); return; } else { // We have any other error error( errorNum, url.prettyURL() ); return; } } kdDebug(PAK_DEBUG_ID) << "Continue getting" << endl; path = QString::fromLocal8Bit(remoteEncoding()->encode(path)); kdDebug(PAK_DEBUG_ID) << "Path > " << path << endl; const KArchiveDirectory* root = _pakFile->directory(); const KArchiveEntry* archiveEntry = root->entry( path ); kdDebug(PAK_DEBUG_ID) << "Check if no archiveEntry > " << archiveEntry << endl; if ( !archiveEntry ) { error( KIO::ERR_DOES_NOT_EXIST, url.prettyURL() ); return; } kdDebug(PAK_DEBUG_ID) << "archiveEntry::name > " << archiveEntry->name() << endl; if ( archiveEntry->isDirectory() ) { error( KIO::ERR_IS_DIRECTORY, url.prettyURL() ); return; } const KArchiveFile* archiveFileEntry = static_cast<const KArchiveFile *>(archiveEntry); if ( !archiveEntry->symlink().isEmpty() ) { kdDebug(7109) << "Redirection to " << archiveEntry->symlink() << endl; KURL realURL; if (archiveEntry->symlink().startsWith("/")) { // absolute path realURL.setPath(archiveEntry->symlink() ); // goes out of tar:/, back into file: } else { realURL = KURL( url, archiveEntry->symlink() ); } kdDebug(7109) << "realURL= " << realURL << endl; redirection( realURL ); finished(); return; } //kdDebug(7109) << "Preparing to get the archive data" << endl; /* * The easy way would be to get the data by calling archiveFileEntry->data() * However this has drawbacks: * - the complete file must be read into the memory * - errors are skipped, resulting in an empty file */ QIODevice* io = 0; // Getting the device is hard, as archiveFileEntry->device() is not virtual! if ( url.protocol() == "pak" ) { io = archiveFileEntry->device(); } else { // Wrong protocol? Why was this not catched by checkNewFile? kdWarning(7109) << "Protocol " << url.protocol() << " not supported by this IOSlave; " << k_funcinfo << endl; error( KIO::ERR_UNSUPPORTED_PROTOCOL, url.protocol() ); return; } if (!io) { error( KIO::ERR_SLAVE_DEFINED, i18n( "The archive file could not be opened, perhaps because the format is unsupported.\n%1" ) .arg( url.prettyURL() ) ); return; } if ( !io->open( IO_ReadOnly ) ) { error( KIO::ERR_CANNOT_OPEN_FOR_READING, url.prettyURL() ); return; } totalSize( archiveFileEntry->size() ); // Size of a QIODevice read. It must be large enough so that the mime type check will not fail const int maxSize = 0x100000; // 1MB int bufferSize = kMin( maxSize, archiveFileEntry->size() ); QByteArray buffer ( bufferSize ); if ( buffer.isEmpty() && bufferSize > 0 ) { // Something went wrong error( KIO::ERR_OUT_OF_MEMORY, url.prettyURL() ); return; } bool firstRead = true; // How much file do we still have to process? int fileSize = archiveFileEntry->size(); KIO::filesize_t processed = 0; while ( !io->atEnd() && fileSize > 0 ) { if ( !firstRead ) { bufferSize = kMin( maxSize, fileSize ); buffer.resize( bufferSize, QGArray::SpeedOptim ); } const Q_LONG read = io->readBlock( buffer.data(), buffer.size() ); // Avoid to use bufferSize here, in case something went wrong. if ( read != bufferSize ) { kdWarning(7109) << "Read " << read << " bytes but expected " << bufferSize << endl; error( KIO::ERR_COULD_NOT_READ, url.prettyURL() ); return; } if ( firstRead ) { // We use the magic one the first data read // (As magic detection is about fixed positions, we can be sure that it is enough data.) KMimeMagicResult * result = KMimeMagic::self()->findBufferFileType( buffer, path ); kdDebug(7109) << "Emitting mimetype " << result->mimeType() << endl; mimeType( result->mimeType() ); firstRead = false; } data( buffer ); processed += read; processedSize( processed ); fileSize -= bufferSize; } io->close(); delete io; data( QByteArray() ); finished(); /*kdDebug(PAK_DEBUG_ID) << "Entering get()" << endl; mimetype("text/plain"); QCString str("Hello Pak World!!"); data(str); finished(); kdDebug(PAK_DEBUG_ID) << "Exiting get()" << endl;*/ }
void execsetenv(Cmd c, int inPipeId, int outPipeId) { int newfd; int i=0; char* str; if(c->next == NULL) { //if(fork() == 0) // { redirection(c, inPipeId, outPipeId); if(c->args[1] == NULL) { i=0; while(environ[i]) { printf("%s\n", environ[i++]); } putchar('\n'); } else{ //printf("TP"); if(c->args[2] == NULL) { //printf("Invoking Putenv for %s to null",c->args[1]); str = strdup(c->args[1]); str = strcat(str, "="); putenv(str); //fprintf(stderr, "%s set to %s", c->args[1], getenv(c->args[1])); } else { //printf("Invoking Putenv for %s to %s",c->args[1],c->args[2]); str = strdup(c->args[1]); str = strcat(strcat(str,"="),c->args[2]); //printf("will execute %s",env); putenv(str); //fprintf(stderr, "%s set to %s", c->args[1], getenv(c->args[1])); //printf("The Output of the method is: %d", putenv(env)); } } // exit(0); //} //else //{ // wait(); //} } else { if(fork() == 0) { redirection(c, inPipeId, outPipeId); //printf("TP"); if(c->args[1] == NULL) { i=0; while(environ[i]) { printf("%s\n", environ[i++]); } putchar('\n'); } else{ //printf("TP"); if(c->args[2] == NULL) { //printf("Invoking Putenv for %s to null",c->args[1]); str = strdup(c->args[1]);; str = strcat(str, "="); putenv(str); //fprintf(stderr, "%s set to %s", c->args[1], getenv(c->args[1])); } else { //printf("Invoking Putenv for %s to %s",c->args[1],c->args[2]); str = strdup(c->args[1]); str = strcat(strcat(str,"="),c->args[2]); //printf("will execute %s",env); putenv(str); //fprintf(stderr, "%s set to %s", c->args[1], getenv(c->args[1])); //printf("The Output of the method is: %d", putenv(env)); } } exit(0); } else { close((pipes+(2*outPipeId))[1]); wait(); } } }
void execnice(Cmd c, int inPipeId, int outPipeId) { int newfd; int i=0; char* str; int which = PRIO_PROCESS; id_t pid; if(c->next == NULL) { //if(fork() == 0) // { redirection(c, inPipeId, outPipeId); if(c->args[1] == NULL) { pid = getpid(); if(setpriority(which, pid, 4) == -1) perror("Cannnot set priority"); //fprintf(stderr, "The priority set is: %d\n", getpriority(which, pid)); } else if(is_valid_int(c->args[1]) == 0) { pid = getpid(); if(setpriority(which, pid, 4) == -1) perror("Cannnot set priority"); //fprintf(stderr, "The priority set is: %d\n", getpriority(which, pid)); if(c->args[2] != NULL) { c->args+=1; c->nargs-=1; //fprintf(stderr, "The priority set is: %d for command: %s\n", getpriority(which, pid),c->args[0]); prCmd(c, inPipeId, outPipeId); } } else{ pid = getpid(); if(setpriority(which, pid, atoi(c->args[1])) == -1) perror("Cannnot set priority"); //fprintf(stderr, "The priority set is: %d\n", getpriority(which, pid)); if(c->args[2] != NULL) { c->args+=2; c->nargs-=2; //fprintf(stderr, "The priority set is: %d for command: %s\n", getpriority(which, pid),c->args[0]); prCmd(c, inPipeId, outPipeId); } } // exit(0); //} //else //{ // wait(); //} } else { if(fork() == 0) { redirection(c, inPipeId, outPipeId); if(c->args[1] == NULL) { pid = getpid(); if(setpriority(which, pid, 4) == -1) perror("Cannnot set priority"); //fprintf(stderr, "The priority set is: %d\n", getpriority(which, pid)); } else if(is_valid_int(c->args[1]) == 0) { pid = getpid(); if(setpriority(which, pid, 4) == -1) perror("Cannnot set priority"); //fprintf(stderr, "The priority set is: %d\n", getpriority(which, pid)); if(c->args[2] != NULL) { c->args+=1; c->nargs-=1; //fprintf(stderr, "The priority set is: %d for command: %s\n", getpriority(which, pid),c->args[0]); prCmd(c, inPipeId, outPipeId); } } else{ pid = getpid(); if(setpriority(which, pid, atoi(c->args[1])) == -1) perror("Cannnot set priority"); //fprintf(stderr, "The priority set is: %d\n", getpriority(which, pid)); if(c->args[2] != NULL) { c->args+=2; c->nargs-=2; //fprintf(stderr, "The priority set is: %d for command: %s\n", getpriority(which, pid),c->args[0]); prCmd(c, inPipeId, outPipeId); } } exit(0); } else { close((pipes+(2*outPipeId))[1]); wait(); } } }