通过TCP连接发送stdout

时间:2015-12-03 13:27:49

标签: c redirect server client stdout

我有一个客户端和服务器程序,其中服务器是shell

我需要将shell的输出重定向到客户端

根据我的理解,在将dup()复制到stdout并运行execve之后,输出应该通过流发送并打印在客户端

这是我的客户代码......

while(1){
  printf("rrsh> ");
  Fgets(buf, MAXLINE, stdin);
  int nul = p3parseline(buf, argv);
  if (!strcmp(argv[0], "quit"))
    break;
  Rio_writen(clientfd, buf, strlen(buf));
  Rio_readlineb(&rio, buf, MAXLINE);
  if (!strcmp(buf, "Command not allowed\n")){
    strcpy(buf, "Cannot execute '");
    strcat(buf, argv[0]);
    strcat(buf, "' on this server\n");
    Fputs(buf, stdout);
  }
  else if (!strcmp(buf, "Command approved\n")){
    printf("WOOHOO\n");
  }
}

...这里是服务器代码......

  while((n = Rio_readlineb(&rio, buf, MAXLINE)) != 0){ //loop until connection has been terminated
    printf("server received %zu Byte(s)\n", n);
    bg = p3parseline(buf, argv);
    temp = strcat(argv[0], "\n");

    //check if the command is allowed
    file = Fopen("rrshcommands.txt", "r");
    while (Fgets(command, MAXLINE, file) != NULL){
      if (!strcmp(temp, command)){
        flag = 1;
        strcpy(buf, "Command approved\n");
        break;
      }
    }

    strtok(argv[0], "\n");

    if (flag == 0){ //case where the command is allowed
      strcpy(buf, "Command not allowed\n");
      Rio_writen(connfd, buf, strlen(buf));
    }
    else{
      if ((pid = fork()) == 0) {   /* Child runs user job */
        Dup2(connfd, STDOUT_FILENO);
        Close(connfd);
        if (execve(argv[0], argv, environ) < 0) {
          printf("%s: Command not found.", argv[0]);
          exit(0);
        }
      }
      /* Parent waits for foreground job to terminate */
      if (!bg) {
        int status;
        if (waitpid(pid, &status, 0) < 0)
          unix_error("waitfg: waitpid error");
        Rio_writen(connfd, buf, strlen(buf)); /*this writes "Command approved to the client*/
      }
    }
  }

请注意,shell仅允许在rrshcommands.txt文件中指定的某些命令

如果您认为可以弄明白,请停在此处,以下是调试信息

奇怪的是执行和调试给了我两个不同的结果

这是执行期间客户端的输出......

Kendalls-MacBook-Pro:P4 kendallweihe$ ./rrsh-client 127.0.0.1 1024
Username: kendallweihe
Password: password
rrsh> /bin/ls
rrsh> /bin

请注意,它不会打印出无法在此服务器上执行blah命令或命令已批准

但是当我调试时,会打印语句......

   47           Fputs(buf, stdout);
   48         }
   49         else if (!strcmp(buf, "Command approved\n")){
-> 50           printf("WOOHOO\n");
   51         }
   52       }
   53     }
(lldb) n
WOOHOO

   46           strcat(buf, "' on this server\n");
-> 47           Fputs(buf, stdout);
   48         }
   49         else if (!strcmp(buf, "Command approved\n")){
   50           printf("WOOHOO\n");
(lldb) n
Cannot execute '/bin' on this server

0 个答案:

没有答案